@pi-chamber/web 0.7.1 → 0.7.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -1
- package/bin/cli.js +2 -2
- package/bin/cli.test.js +98 -1
- package/bin/lib/DOCUMENTATION.md +2 -1
- package/bin/lib/cli-args.js +8 -5
- package/bin/lib/cli-startup.js +10 -7
- package/bin/lib/cli-startup.test.js +28 -0
- package/bin/lib/commands-startup.js +152 -6
- package/dist/assets/{CommitSection-DuGkZ_bm.js → CommitSection-DfAlM30E.js} +1 -1
- package/dist/assets/{DiagramEditor-C7xe1Brl.js → DiagramEditor-TeJ1G_NN.js} +1 -1
- package/dist/assets/{DiagramView-BTqROEWP.js → DiagramView-DKLIwNth.js} +1 -1
- package/dist/assets/{DiffView-hcqXTjEc.js → DiffView-CZyqSs5W.js} +1 -1
- package/dist/assets/{FilesView-GadyKxta.js → FilesView-rftA7fEL.js} +1 -1
- package/dist/assets/{GitView-BKy-hYUN.js → GitView-D5LMTT2M.js} +3 -3
- package/dist/assets/{JsonTreeView-CGc4eTGI.js → JsonTreeView-DMI3-Smy.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-CqfEAhPM.js → MarkdownRendererImpl-gdd-5n9J.js} +1 -1
- package/dist/assets/{PatchDiff-P17-Byb8.js → PatchDiff-GNB1NlAN.js} +1 -1
- package/dist/assets/{PierreDiffViewer-BbUCO4IF.js → PierreDiffViewer-DmJv2AoJ.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-j6KFBSe0.js → SessionSwitcherContent-CWdDPll7.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-DSVeuuVL.js → SessionSwitcherDropdown-Cx-Jfmvo.js} +2 -2
- package/dist/assets/{SessionUnreadDot-BVBBEBTg.js → SessionUnreadDot-CKe4uVcf.js} +1 -1
- package/dist/assets/{SettingsView-FnmtcWZc.js → SettingsView-DaxkNy5C.js} +3 -3
- package/dist/assets/{SettingsWindow-Bascj0V3.js → SettingsWindow-D1M_rRDo.js} +1 -1
- package/dist/assets/{ToolOutputDialog-CPMzJ27S.js → ToolOutputDialog-CUKcp77A.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-BZSRKHHM.js → ToolPartDiffPreview-CkzwXAC5.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-DFx8xsmh.js → VirtualizedFileDiff-sRc4lN0B.js} +1 -1
- package/dist/assets/{WindowsWindowControls-DIqnZ2uU.js → WindowsWindowControls-CCnU0ckO.js} +121 -121
- package/dist/assets/{collapsible-DlqZyxEY.js → collapsible-B0cIItyf.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-elCbdk6U.js → computeVirtualFileMetrics-B1uVA58l.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-BmQ7Zu-L.js → contextFileOpenGuard-BuedQ5EQ.js} +1 -1
- package/dist/assets/{index-BerHSX92.js → index-BA67uOfZ.js} +1 -1
- package/dist/assets/index-CcbDTf8Q.js +8 -0
- package/dist/assets/index-Cl3XbCeC.css +1 -0
- package/dist/assets/{isDiffPlainText-CvfRfc7h.js → isDiffPlainText-DLDFLL6P.js} +1 -1
- package/dist/assets/{isFilePlainText-_vq9Ghu3.js → isFilePlainText-B2wwrpRU.js} +1 -1
- package/dist/assets/{main-DYs-nZO6.js → main-B5k0qpHJ.js} +4 -4
- package/dist/assets/{main-DTCOwPr3.js → main-Bepu8Jr9.js} +2 -2
- package/dist/assets/{markdownCore-CzWR_p3k.js → markdownCore-BfuFM7mg.js} +1 -1
- package/dist/assets/{miniChat-C2XxEA3N.js → miniChat-Co0Snpgl.js} +2 -2
- package/dist/assets/{mobile-BQhAOqV7.js → mobile-CSvL_Zyu.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-M2bY1WKA.js → renderElectronMiniChatApp-DrMJ1RXX.js} +2 -2
- package/dist/assets/{renderMobileApp-BnpHUUhY.js → renderMobileApp-B2toAnMW.js} +4 -4
- package/dist/assets/{runtimeSurface-OhCUGSKg.js → runtimeSurface-DF3VwUlO.js} +1 -1
- package/dist/assets/{useInlineCommentController-DC0iNSYX.js → useInlineCommentController-CxMP78jg.js} +1 -1
- package/dist/assets/{usePanelSlide-aeAIo1cp.js → usePanelSlide-DUuoQt5X.js} +3 -3
- package/dist/assets/{usePushVisibilityBeacon-om5Qlrt6.js → usePushVisibilityBeacon-CSPdFBaA.js} +1 -1
- package/dist/assets/{useSwitcherItems-Bln2r_Q2.js → useSwitcherItems-zOeC2Cta.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-Dv4zaHRN.js → vendor-codemirror-language-data-C7_BPMCr.js} +2 -2
- package/dist/assets/{web-components-BOt08OHk.js → web-components-BYNCGylQ.js} +1 -1
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +1 -1
- package/server/lib/package-manager.js +32 -1
- package/server/lib/package-manager.test.js +21 -0
- package/server/lib/pi/attachment-store.js +95 -22
- package/server/lib/pi/attachment-store.test.js +23 -0
- package/server/lib/pi/routes.js +120 -43
- package/server/lib/pi/routes.test.js +63 -2
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +2 -0
- package/server/lib/pi/session-daemon/session-daemon.js +7 -0
- package/dist/assets/index-ChFxkws4.js +0 -8
- package/dist/assets/index-DZ-f_hCQ.css +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
2
|
-
import{_ as Ps}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Xe,j as t,R as o}from"./vendor-react-DYyjh7Q0.js";import{a_ as $s,a$ as kc,ai as Cc,o as Xi,D as as,n as ls,q as hs,I as j,ar as Is,b0 as zo,B as Ve,ap as pn,T as st,l as nt,m as rt,b1 as Zi,b2 as Nc,b3 as Ac,b4 as Ic,b5 as Dc,g as Fe,b6 as Pc,b7 as $o,b8 as Ec,b9 as Tc,ba as Uo,bb as Rc,bc as Mc,bd as Fc,be as Lc,bf as Ir,bg as Oc,t as le,am as qt,an as Jt,ao as Xt,R as Ws,bh as Bc,bi as _c,bj as zc,bk as $c,bl as Go,W as _t,bm as Uc,bn as Gc,bo as Kc,bp as Hc,bq as Wc,br as Vc,bs as Dr,bt as ea,bu as ta,bv as Yc,bw as Qc,bx as qc,by as Jc,bz as Xc,bA as Zc,aO as Pr,r as Gs,aQ as Ts,aT as ed,aU as td,aV as sd,aW as nd,aX as ar,aY as Zs,bB as Ko,as as kt,b as $t,aJ as Ms,bC as sa,p as Ss,s as Fs,v as Ls,bD as rd,bE as nn,bF as od,bG as Qs,a2 as en,bH as lr,bI as Ho,bJ as Wo,bK as an,av as id,aK as na,aA as Vo,ay as ad,ax as ld,aN as ra,f as eo,bL as cd,e as to,w as qn,C as oa,bM as dd,bN as Wt,aF as ia,c as Er,bO as ud,bP as fd,bQ as Jn,bR as Yo,aP as aa,bS as la,bT as ca,z as hd,bU as so,bV as pd,bW as md,h as da,j as gd,bX as xd,bY as bd,i as yd,bZ as Tr,b_ as ua,b$ as vd,c0 as wd,d as Sd,c1 as jd,a as kd,aq as Cd,aS as Nd,c2 as fa,c3 as Ad,c4 as Id,aR as Dd,c5 as Pd,c6 as Ed,a8 as Td,c7 as Rd,aG as Md,c8 as Fd,c9 as Ld,ca as Nn,cb as Qo,cc as Od,cd as qo,ce as Jo,cf as Bd,aE as ha,U as _d,x as zd,cg as pa,u as $d,ch as Ud,ci as Gd,at as Vs,k as Kd,cj as Hd,ck as ma,cl as Wd,cm as ga,cn as Vd,co as Yd}from"./WindowsWindowControls-DIqnZ2uU.js";import{V as Xo,W as Qd,X as Zo,Y as qd,i as Jd,Z as Xd,P as Zd,r as es,_ as mn,b as eu,m as B,O as vs,u as ce,$ as tu,a0 as ds,a1 as no,t as ro,n as ws,a2 as Je,a3 as Rs,a4 as oo,a5 as io,a6 as su,a7 as nu,F as ru,a8 as ou,a9 as iu,aa as au,ab as lu,ac as is,ad as ei,ae as Rr,a as Xn,af as cu,ag as du,Q as ao,R as ln,ah as uu,ai as fu,aj as xa,A as hu,N as ba,G as cn,ak as Mr,e as Fr,d as An,al as pu,am as mu,an as tn,ao as cr,ap as ya,E as gu,q as xu,aq as Lr,ar as Ds,as as ti,at as Or,au as va,av as Br,aw as bu,ax as yu,ay as vu,az as wu,aA as Su,aB as ju,aC as ku,x as Cu,aD as Nu,aE as Au,aF as si}from"./index-ChFxkws4.js";import{d as Iu,g as wa,r as Du,e as Sa,h as Ln,i as ja,b as dn,c as un,s as Pu,j as Eu,k as Tu,l as ni,m as Zn,a as Ru,S as Mu,f as Fu,t as Lu,n as Ou}from"./SessionUnreadDot-BVBBEBTg.js";import{C as ka,a as Ca,M as _r,b as zr,c as $r,d as Na,S as Aa,D as Bu,e as _u,f as zu,g as $u,h as Uu,i as Gu,j as Ku,k as Hu,l as Wu}from"./vendor-base-ui-DL8r2fgQ.js";import{c as ps,d as Ia,p as lo,u as Ur,a as Vu}from"./vendor-zustand-CnsBKjP5.js";import{u as Yu}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{c as er,d as gn,P as co,D as tr,e as sr,f as Da,b as Qu,a as qu,T as Ju,M as Xu}from"./vendor-dnd-kit-core-GipZW2tY.js";import{S as uo,v as Pa,u as fo,a as Zu,h as ef}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as ho}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{usePermissionStore as tf}from"./permissionStore-BRcQ9Jgt.js";const sf="chat";function Ea(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set($s.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set($s.SETTINGS,n),s}return e.tab!==sf&&s.set($s.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set($s.FILE,e.diffFile),s}function nf(e,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,i=e.toString();return i?`${r}?${i}`:r}function rf(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=Ea(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),i=r?.[1]?decodeURIComponent(r[1].trim()):null;i&&!s.has($s.SESSION)&&s.set($s.SESSION,i);const a=[...s.entries()].sort((c,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function Gr(e,s={}){if(!(typeof window>"u")&&!(!s.force&&rf(e)))try{const n=Ea(e),r=nf(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const of=["typescript","javascript","tsx","jsx","json","markdown"],Ta={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let ri=null;const Ra=()=>(ri??=Promise.all([Ps(()=>import("./index-BerHSX92.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109])),Ps(()=>import("./workerFactory-tw7cIdmV.js"),[]),Ps(()=>import("./appThemeRegistry-BK0dHKa6.js"),__vite__mapDeps([110,111,97,98,11,82,83,84,85,86,87,88,89,90,91,92,93,94,95]))]).then(([e,s,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:s.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),ri),xn={},oi=new Set,Kr=new Set;let On={light:"pierre-light",dark:"pierre-dark"};const af=()=>{for(const e of Kr)e()},Ma=(e,s)=>{s.setRenderOptions({theme:On,lineDiffType:Ta[e].lineDiffType})},Hr=e=>{typeof window>"u"||oi.has(e)||(oi.add(e),Ra().then(s=>{if(xn[e])return;const n=Ta[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:of,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),xn[e]=r,Ma(e,r),af()}))},lf=e=>(Kr.add(e),()=>Kr.delete(e)),cf=e=>{if(!(On.light===e.light&&On.dark===e.dark)){On=e;for(const s of Object.keys(xn)){const n=xn[s];n&&Ma(s,n)}}},lx=({children:e})=>{const s=kc(),n=Xo(!1),r=Xo(!0),i=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===i)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return Xe.useEffect(()=>{let d=!1;return Ra().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),cf({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Xe.useEffect(()=>{if(typeof window>"u")return;const d=()=>{Hr("unified"),Hr("split")};if(typeof window.requestIdleCallback=="function"){const p=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(p)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},cx=(e="unified")=>{const s=Xe.useSyncExternalStore(lf,()=>xn[e],()=>{});return Xe.useEffect(()=>{Hr(e)},[e]),s};function df(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=Cc();return e}catch{return"unknown"}}function uf(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function ff(){const e=eu();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const s=(navigator.platform||"").toLowerCase();return s.includes("mac")?"macos":s.includes("win")?"windows":s.includes("linux")?"linux":"web"}function hf(e){const s=new URLSearchParams;return s.set("deviceClass",df()),s.set("arch",uf()),s.set("platform",ff()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",mn()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function dr(e,s){try{const n=hf(e);s&&n.set("currentVersion",s);const r=await es(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const i=await r.json();return{available:i.available??!1,version:i.version,currentVersion:i.currentVersion??"unknown",body:i.body,releaseUrl:i.releaseUrl,downloadUrl:i.downloadUrl,nextSuggestedCheckInSec:typeof i.nextSuggestedCheckInSec=="number"&&Number.isFinite(i.nextSuggestedCheckInSec)?i.nextSuggestedCheckInSec:void 0,packageManager:i.packageManager,updateCommand:i.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function pf(){return Jd()?"mobile":Xd()?"desktop":Zd()?"web":null}const ii={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Bn=ps()((e,s)=>({...ii,checkForUpdates:async()=>{const n=pf();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,i=null;if(n==="desktop"){const a="0.7.1",[l,c]=await Promise.allSettled([Zo(),dr("desktop",a)]),d=l.status==="fulfilled"?l.value:null;return i=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:d?.available??!1,info:d,lastChecked:Date.now(),nextCheckInSec:i}),i}else n==="web"?(r=await dr("web"),i=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await dr("mobile","0.7.1"),i=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:i}),i}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=s();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const i=await Zo();if(!i?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(l=>({info:l.info?{...l.info,...i,body:l.info.body||i.body,available:l.info.available}:i})),!await qd(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(i){e({downloading:!1,error:i instanceof Error?i.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await Qd())throw new Error("Desktop restart only works on Local instance")}catch(i){e({error:i instanceof Error?i.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(ii)}})),ai="https://github.com/RyderAsKing/PiChamber/releases";function mf(e){const s=new Date(`${e}T00:00:00`);return Number.isNaN(s.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(s)}function gf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function li(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function xf(e,s){const n=e.split(".").map(i=>Number.parseInt(i,10)),r=s.split(".").map(i=>Number.parseInt(i,10));for(let i=0;i<3;i+=1){const a=Number.isFinite(n[i])?n[i]:0,l=Number.isFinite(r[i])?r[i]:0;if(a!==l)return l-a}return 0}function bf(e){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((i,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(i.start,l).trim();return{version:i.version,date:i.date,start:i.start,end:l,raw:c}})}const ci=2e3,yf=600*1e3;async function vf(){try{const e=await es("/api/pichamber/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0,autoRestart:(await e.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await e.json().catch(()=>({}))).error||`Server error: ${e.status}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function wf(){try{return(await es("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function Sf(e,s=Math.ceil(yf/ci),n=ci){for(let r=0;r<s;r++){try{const i=await es("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((i.status===401||i.status===403)&&await wf())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const Fa=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:i,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[p,h]=Xe.useState(!1),[x,m]=Xe.useState("idle"),[f,g]=Xe.useState(null),S=n?.version?n.releaseUrl||`${ai}/tag/v${n.version}`:ai,k=n?.downloadUrl||S,_=a?.total?Math.round(a.downloaded/a.total*100):0,A=u==="web",b=u==="mobile",v=n?.updateCommand||"pichamber update";Xe.useEffect(()=>{e||(m("idle"),g(null))},[e]);const M=async()=>{(await pn(v)).ok&&(h(!0),setTimeout(()=>h(!1),2e3))},N=Xe.useCallback(async G=>{await Xi(G)},[]),C=Xe.useCallback(async()=>{m("updating"),g(null);const G=await vf();if(!G.success){m("error"),g(G.error||"Update failed");return}G.autoRestart&&(m("restarting"),await new Promise(Z=>setTimeout(Z,2e3))),m("reconnecting"),await Sf(n?.currentVersion)?window.location.reload():(m("error"),g("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),I=Xe.useCallback(()=>{N(k)},[N,k]),D=x!=="idle"&&x!=="error",P=Xe.useMemo(()=>{if(!n?.body)return null;const G=n.body.trim();if(!G)return null;const ee=bf(G);return ee.length===0?{kind:"raw",title:"What's new",content:li(G)}:{kind:"sections",title:"What's new",sections:[...ee].sort((te,U)=>xf(te.version,U.version)).map(te=>({version:te.version,dateLabel:mf(te.date),content:li(gf(te.raw)||G)}))}},[n?.body]);return t.jsx(as,{open:e,onOpenChange:D?void 0:s,children:t.jsxs(ls,{className:"max-w-4xl p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[t.jsxs("div",{className:"flex items-center mb-1",children:[t.jsxs(hs,{className:"flex items-center gap-2.5",children:[t.jsx(j,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||n?.version)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),t.jsxs("div",{className:"space-y-2",children:[A&&D&&t.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(j,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),P&&!D&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(Is,{className:"max-h-[400px] p-0",fillContainer:!1,children:P.kind==="raw"?t.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:G=>{const Z=G.target.closest("a");Z&&Z.href&&(G.preventDefault(),G.stopPropagation(),N(Z.href))},children:t.jsx(zo,{content:P.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:P.sections.map(G=>t.jsxs("div",{className:"p-4",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[t.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",G.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:G.dateLabel})]}),t.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:ee=>{const te=ee.target.closest("a");te&&te.href&&(ee.preventDefault(),ee.stopPropagation(),N(te.href))},children:t.jsx(zo,{content:G.content,disableLinkSafety:!0,enableFileReferences:!1})})]},G.version))})})}),A&&x==="error"&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(j,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:"Or update via terminal:"})]}),t.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:v}),t.jsx("button",{onClick:M,className:B("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",p&&"text-[var(--status-success)]"),title:p?"Copied!":"Copy command",children:p?t.jsx(j,{name:"check",className:"h-4 w-4"}):t.jsx(j,{name:"clipboard",className:"h-4 w-4"})})]})]}),!A&&!b&&r&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm",children:[t.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),t.jsxs("span",{className:"font-mono text-foreground",children:[_,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${_}%`}})})]}),(l||f)&&t.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:t.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||f})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:S,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(j,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!A&&!b&&!i&&!r&&t.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(j,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!A&&!b&&r&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(j,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!A&&!b&&i&&t.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[t.jsx(j,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),b&&t.jsxs(Ve,{onClick:I,size:"default",children:[t.jsx(j,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),A&&!D&&t.jsxs("button",{onClick:C,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(j,{name:"download",className:"h-4 w-4"}),"Update Now"]}),A&&D&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(j,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},jf=o.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:i,className:a,iconClassName:l}){const c=o.useCallback(u=>{u.preventDefault(),u.stopPropagation(),!r&&!s&&n()},[s,r,n]),d=o.useCallback(u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:d,disabled:r,"aria-checked":s,"aria-label":i,className:B("group/radio relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full outline-none","transition-[background-color,box-shadow] duration-200 ease-out",s?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none hover:bg-[var(--primary-base)]":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)] hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",a),children:t.jsx("span",{"aria-hidden":!0,className:B("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),bn=({children:e,className:s,contentClassName:n})=>{const[r,i]=o.useState(!1),a=o.useRef(null);return o.useEffect(()=>{if(!r)return;const l=c=>{const d=a.current;d&&c.target instanceof Node&&d.contains(c.target)||i(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(st,{open:r,onOpenChange:i,children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),i(c=>!c)},className:B("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(j,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(rt,{sideOffset:8,className:B("max-w-sm",n),children:e})]})},dx="w-full min-w-40 max-w-48",kf="settings",Cf="w-full min-w-40 max-w-48",ux="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Nf="w-full max-w-[24rem]",fx="min-w-0 flex-1",hx="flex w-full min-w-0 items-center gap-2",px="typography-meta shrink-0 text-muted-foreground tabular-nums",La="space-y-3.5",Af="space-y-1.5",mx="typography-settings-page-title text-muted-foreground",If="typography-settings-section-title text-foreground",gx="typography-settings-section-title text-foreground",Oa="typography-settings-group-title text-foreground",po="typography-settings-field-label text-foreground",Df="typography-settings-description text-muted-foreground",yn="typography-meta text-muted-foreground",xx="typography-meta font-medium text-foreground",bx="typography-settings-section-title text-foreground",Pf=({title:e,description:s,titleAccessory:n,info:r,headerAction:i,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const p=e!=null||s!=null||i!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:B("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[p?t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?t.jsx("h2",{className:If,children:e}):e,n,r!=null?t.jsx(bn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:Df,children:s}):null]}),i?t.jsx("div",{className:"shrink-0",children:i}):null]}):null,t.jsx("div",{className:B(d),children:a})]})},yx=({children:e,className:s})=>t.jsx("div",{className:B("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Ef=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:B(Oa,s),children:e}),vx=({title:e,description:s,info:n,children:r,className:i,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:B("space-y-2",i),children:[e!=null||s!=null||n!=null?t.jsxs("div",{className:"space-y-0.5",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Ef,{children:e}),n!=null?t.jsx(bn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:yn,children:s}):null]}):null,t.jsx("div",{className:B(a),children:r})]}),Us=({label:e,description:s,info:n,descriptionPlacement:r="before",children:i,settingsItem:a,className:l,controlClassName:c})=>{const d=s!=null?t.jsx("p",{className:yn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:B("space-y-2",l),children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:po,children:e}),n!=null?t.jsx(bn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:B("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:i}),r==="after"?d:null]})},wx=({label:e,description:s,info:n,children:r,settingsItem:i,className:a,controlClassName:l,alignEnd:c=!0})=>t.jsxs("div",{"data-settings-item":i,className:B("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",a),children:[t.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:po,children:e}),n!=null?t.jsx(bn,{children:n}):null]}),s!=null?t.jsx("p",{className:B(yn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:B("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),Sx=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:B("pt-4",s),children:e}),Tf=({checked:e,onChange:s,label:n,description:r,disabled:i=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const p=()=>{i||s(!e)},h=r!=null;return t.jsxs("div",{"data-settings-item":l,className:B("group flex cursor-pointer gap-2 py-0.5",h?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:i?-1:0,"aria-pressed":e,"aria-disabled":i||void 0,onClick:p,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),p())},children:[t.jsx(Zi,{checked:e,onChange:s,disabled:i,ariaLabel:a}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:po,children:n}),d,u!=null?t.jsx(bn,{children:u}):null]}),h?t.jsx("span",{className:yn,children:r}):null]})]})},jx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:i,disabled:a=!1,className:l})=>t.jsxs("div",{className:B("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",a&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:a?-1:0,"aria-pressed":e,"aria-disabled":a||void 0,onClick:()=>{a||s()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a||s())},children:[t.jsx(jf,{checked:e,onChange:s,disabled:a,ariaLabel:i,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:B("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:yn,children:r}):null]})]}),kx=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:B(Af,n),children:s});function Cx({value:e,options:s,onChange:n,className:r,"aria-label":i}){return t.jsx("div",{role:"group","aria-label":i,className:B("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Ve,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":e===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}class Rf extends o.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){this.setState({error:s,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?t.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:t.jsxs(Nc,{className:"w-full max-w-md",children:[t.jsx(Ac,{className:"text-center",children:t.jsxs(Ic,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(j,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(Dc,{className:"space-y-4",children:[t.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&t.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&t.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[t.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),t.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),t.jsx("div",{className:"flex gap-2",children:t.jsxs(Ve,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(j,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),t.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Mf(e){return t.jsx(Rf,{...e,texts:{title:"Chat Error",description:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.",sessionLabel:"Session",detailsSummary:"Error details",resetAction:"Reset Chat",persistentHint:"If the problem persists, try refreshing the page."}})}const Nx=({active:e=!0})=>{const s=Fe(n=>n.currentSessionId);return t.jsx(Mf,{sessionId:s||void 0,children:t.jsx(Pc,{active:e},s??"no-session")})};function Ff({onResizeStart:e,ariaLabel:s}){return t.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,onPointerDown:e,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:t.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const mo=Xe.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:i=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:p,endSlot:h,...x},m)=>{const f=Xe.useRef(null),g=Xe.useRef(null),[S,k]=Xe.useState(null),_=c??S,A=Xe.useCallback(v=>{const M=f.current;if(!M)return;g.current={startY:v.clientY,startHeight:M.getBoundingClientRect().height};const N=v.currentTarget;N.setPointerCapture(v.pointerId);const C=D=>{const P=g.current;if(!P)return;const G=P.startHeight+(D.clientY-P.startY),ee=Math.max(82,G);d?d(ee):k(ee)},I=()=>{g.current=null,N.removeEventListener("pointermove",C),N.removeEventListener("pointerup",I),N.removeEventListener("pointercancel",I)};N.addEventListener("pointermove",C),N.addEventListener("pointerup",I),N.addEventListener("pointercancel",I),v.preventDefault()},[d]),b=Xe.useCallback(v=>{if(v.target.closest('textarea, button, [role="separator"]'))return;const N=f.current?.querySelector("textarea");N&&document.activeElement!==N&&(v.preventDefault(),N.focus())},[]);return p?t.jsx(Is,{as:"textarea",ref:m,disableHorizontal:!0,fillContainer:r,useScrollShadow:i,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:B("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}):t.jsx("div",{ref:f,onPointerDown:b,style:_!==null?{height:`${_}px`}:void 0,className:B("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],s),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[t.jsx("textarea",{ref:m,className:B("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[h,t.jsx(Ff,{onResizeStart:A,ariaLabel:"Resize textarea"})]})]})})});mo.displayName="Textarea";const di=(e,s)=>s.updatedAtMs-e.updatedAtMs,Kn=ps((e,s)=>({instances:[],statusesById:{},importCandidates:[],isLoading:!1,isSaving:!1,isImportsLoading:!1,initialized:!1,listenerReady:!1,error:null,load:async()=>{if(!s().isLoading){e({isLoading:!0,error:null});try{const[n,r]=await Promise.all([Mc(),Uo()]),i={};for(const a of r.sort(di))i[a.id]=a;s().listenerReady||await Fc(a=>{e(l=>({statusesById:{...l.statusesById,[a.id]:a}}))}),e({instances:n.instances,statusesById:i,isLoading:!1,initialized:!0,listenerReady:!0})}catch(n){e({isLoading:!1,error:n instanceof Error?n.message:String(n)})}}},loadImports:async()=>{if(!s().isImportsLoading){e({isImportsLoading:!0,error:null});try{const n=await Rc();e({importCandidates:n,isImportsLoading:!1})}catch(n){e({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await Uo(),r={};for(const i of n.sort(di))r[i.id]=i;e({statusesById:r})}catch(n){e({error:n instanceof Error?n.message:String(n)})}},setInstances:async n=>{e({isSaving:!0,error:null});try{await Tc({instances:n}),e({instances:n,isSaving:!1}),await s().refreshStatuses()}catch(r){throw e({isSaving:!1,error:r instanceof Error?r.message:String(r)}),r}},upsertInstance:async n=>{const r=s().instances,i=r.some(a=>a.id===n.id)?r.map(a=>a.id===n.id?n:a):[n,...r];await s().setInstances(i)},createFromCommand:async(n,r,i)=>{const a=Lc(n,r);i&&i.trim()&&(a.nickname=i.trim()),await s().upsertInstance(a)},removeInstance:async n=>{await $o(n).catch(()=>{});const r=s().instances.filter(i=>i.id!==n);await s().setInstances(r),e(i=>{const a={...i.statusesById};return delete a[n],{statusesById:a}})},connect:async n=>{e({error:null});try{await Ec(n),await s().refreshStatuses()}catch(r){throw e({error:r instanceof Error?r.message:String(r)}),r}},disconnect:async n=>{e({error:null});try{await $o(n),await s().refreshStatuses()}catch(r){throw e({error:r instanceof Error?r.message:String(r)}),r}},retry:async n=>{await s().connect(n)},getStatus:n=>s().statusesById[n]||null,clearError:()=>e({error:null})})),Ba=[{key:"play",label:"Play",Icon:"play"},{key:"build",label:"Build",Icon:"hammer"},{key:"lint",label:"Lint",Icon:"checkbox-circle"},{key:"terminal",label:"Terminal",Icon:"terminal-box"},{key:"tools",label:"Tools",Icon:"tools"},{key:"bug",label:"Bug",Icon:"bug"},{key:"flask",label:"Flask",Icon:"flask"},{key:"rocket",label:"Rocket",Icon:"rocket"},{key:"code",label:"Code",Icon:"code"},{key:"server",label:"Server",Icon:"server"},{key:"branch",label:"Branch",Icon:"git-branch"},{key:"search",label:"Search",Icon:"search"},{key:"settings",label:"Settings",Icon:"settings-3"},{key:"brain",label:"Brain",Icon:"brain-ai-3"},{key:"stack",label:"Stack",Icon:"stack"},{key:"robot",label:"Robot",Icon:"robot-2"},{key:"command",label:"Command",Icon:"command"},{key:"file",label:"File",Icon:"file-text"}],fn=Object.fromEntries(Ba.map(e=>[e.key,e.Icon])),Wr="pichamber:project-actions-updated",_a=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},us=(e,s)=>`${_a(e)}::${s}`,Lf=e=>{const s=e.trim();return!s||s==="0.0.0.0"||s==="::"?"127.0.0.1":s},ui=e=>{if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.round(e);return s<1||s>65535?null:s},Of=(e,s)=>{if(!s.enabled||s.type!=="local")return null;const n=ui(s.localPort),r=ui(s.remotePort);if(!n||!r)return null;const i=Lf(s.localHost||e.localForward.bindHost||"127.0.0.1"),a=(s.remoteHost||"127.0.0.1").trim(),l=(e.nickname||e.id||"instance").trim();return{id:`${e.id}::${s.id}`,label:`${l} - ${i}:${n} -> ${a}:${r}`,url:`http://${i}:${n}`}},za=e=>{const s=[];for(const n of e)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const r of n.portForwards){const i=Of(n,r);i&&s.push(i)}return s},Bf=(e,s)=>{const n=(e||"").trim();return n&&za(s).find(a=>a.id===n)?.url||null},_f=Nf,$a=({title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(Pf,{title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),Vr=e=>e.name.trim().length>0&&e.command.trim().length>0,zf=e=>e.name.trim().length===0&&e.command.trim().length===0,$f=e=>!Vr(e)&&!zf(e),Uf=(e,s)=>e.some(r=>s.has(r.id)&&!Vr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Vr)},Gf=450,Kf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Hf=()=>({id:Kf(),name:"",command:"",icon:"play"}),Wf=({projectRef:e})=>{const s=o.useMemo(()=>vs(),[]),n=Kn(v=>v.instances),r=Kn(v=>v.load),[i,a]=o.useState([]),[l,c]=o.useState(!1),[d,u]=o.useState(null),[p,h]=o.useState(new Set),x=o.useRef(!1);o.useEffect(()=>{s&&r().catch(()=>{})},[s,r]),o.useEffect(()=>{let v=!1;return c(!0),(async()=>{try{const M=await Ir(e);if(v)return;a(M.actions),u(JSON.stringify({actions:M.actions})),h(new Set(M.actions.map(N=>N.id)))}catch{if(v)return;a([]),u(JSON.stringify({actions:[]})),h(new Set)}finally{v||c(!1)}})(),()=>{v=!0}},[e]);const m=o.useMemo(()=>s?za(n):[],[n,s]),f=o.useMemo(()=>Uf(i,p),[i,p]),g=o.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),S=d!==null&&f.canPersist&&g!==d,k=o.useCallback(async v=>await Oc(e,{actions:v,primaryActionId:null})?(u(JSON.stringify({actions:v})),h(new Set(v.map(N=>N.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Wr,{detail:{projectId:e.id}})),!0):(le.error("Failed to save actions"),!1),[e]);o.useEffect(()=>{if(!S||l||x.current)return;const v=window.setTimeout(()=>{x.current||(x.current=!0,(async()=>{try{await k(f.actions)}finally{x.current=!1}})())},Gf);return()=>{window.clearTimeout(v)}},[S,l,k,f.actions]);const _=o.useCallback(()=>{const v=Hf();a(M=>[...M,v])},[]),A=o.useCallback(v=>{a(M=>M.filter(N=>N.id!==v))},[]),b=o.useCallback((v,M)=>{a(N=>N.map(C=>C.id===v?M(C):C))},[]);return t.jsx($a,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Ve,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:_,children:[t.jsx(j,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:l?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):i.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:B("space-y-6",_f),children:i.map((v,M)=>{const N=v.icon||"play",C=fn[N]||"play",I=v.name.trim()||`Action ${M+1}`,D=$f(v);return t.jsxs("div",{className:La,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Oa,children:I}),t.jsx(Ve,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>A(v.id),"aria-label":`Delete ${I}`,children:t.jsx(j,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(Us,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:t.jsx(j,{name:C,className:"h-4 w-4"})})}),t.jsx(Xt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:Ba.map(P=>{const G=P.Icon,ee=(v.icon||"play")===P.key;return t.jsx("button",{type:"button",onClick:()=>b(v.id,Z=>({...Z,icon:P.key})),className:B("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",ee&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${P.label}`,children:t.jsx(j,{name:G,className:"h-4 w-4"})},P.key)})})})]}),t.jsx(Ws,{value:v.name,onChange:P=>b(v.id,G=>({...G,name:P.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(Us,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(mo,{value:v.command,onChange:P=>b(v.id,G=>({...G,command:P.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),D?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(Tf,{checked:v.autoOpenUrl===!0,onChange:P=>b(v.id,G=>({...G,...P?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0,desktopOpenSshForward:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${I}`}),v.autoOpenUrl===!0?t.jsxs(t.Fragment,{children:[t.jsx(Us,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(Ws,{value:v.openUrl||"",onChange:P=>b(v.id,G=>({...G,openUrl:P.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})}),s?t.jsx(Us,{label:"Desktop SSH forward",controlClassName:"w-full max-w-none",children:m.length>0?t.jsxs(Bc,{value:v.desktopOpenSshForward&&m.some(P=>P.id===v.desktopOpenSshForward)?v.desktopOpenSshForward:"__none__",onValueChange:P=>{b(v.id,G=>({...G,...P==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:P}}))},children:[t.jsx(_c,{size:kf,className:"w-full",children:t.jsx(zc,{placeholder:"Use output/manual URL"})}),t.jsxs($c,{children:[t.jsx(Go,{value:"__none__",children:"Use output/manual URL"}),m.map(P=>t.jsx(Go,{value:P.id,children:P.label},P.id))]})]}):t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No enabled local SSH forwards available."})}):null]}):null]},v.id)})})})},Vf={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",keyboardHint:"↑↓ navigate",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},Yf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:i,isModelAllowed:a,onChange:l})=>{const c=_t(D=>D.providers),d=_t(D=>D.modelsMetadata),u=ce(D=>D.hiddenModels),p=ce(D=>D.providerOrder),h=ce(D=>D.setProviderOrder),x=ce(D=>D.isFavoriteModel),m=ce(D=>D.toggleFavoriteModel),f=ce(D=>D.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:S}=Uc(),[k,_]=o.useState(!1),[A,b]=o.useState("");o.useEffect(()=>{k||b("")},[k]);const v=e?c.find(D=>D.id===e.providerId):void 0,M=e&&v?(Array.isArray(v.models)?v.models:[]).find(D=>D.id===e.modelId):void 0,N=e?Gc(M,e.modelId):s,C=o.useMemo(()=>e?u.filter(D=>!(D.providerID===e.providerId&&D.modelID===e.modelId)):u,[u,e]),I=o.useCallback(D=>{l({providerId:D.providerID,modelId:D.modelID}),_(!1)},[l]);return t.jsxs(qt,{modal:!1,open:k,onOpenChange:D=>{r||_(D)},children:[t.jsx(Jt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:B(Hc({size:"default"}),Cf,"min-w-0",i),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(Kc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:B("truncate",e?"text-foreground":"text-muted-foreground"),children:N})]}),t.jsx(j,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Xt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(Wc,{providers:c,favoriteModels:g,recentModels:S,modelsMetadata:d,searchQuery:A,onSearchQueryChange:b,onSelect:I,labels:{...Vf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:C,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),_(!1)},disabled:r,autoFocus:!0,onEscape:()=>_(!1),isFavorite:D=>x(D.providerID,D.modelID),onToggleFavorite:D=>m(D.providerID,D.modelID),onReorderFavorite:(D,P)=>f(D.providerID,D.modelID,P.providerID,P.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",providerOrder:p,onReorderProvider:h,reorderProviderTitle:"Drag to reorder provider"})})]})},ur="w-full max-w-none",Qf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:i,project:a}=e,l=_t(c=>c.loadProviders);return o.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx($a,{title:"Project",divider:!1,children:t.jsxs("div",{className:La,children:[t.jsx(Us,{label:"Name",settingsItem:"projects.name",controlClassName:ur,children:t.jsx(Ws,{value:s,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),t.jsx(Us,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:ur,children:t.jsx(Yf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:ur,onChange:c=>{if(!c){i("","");return}i(c.providerId,c.modelId)}})})]})}):null},qf=e=>{const[s,n]=o.useState(""),[r,i]=o.useState(void 0);o.useEffect(()=>{if(!e){n(""),i(void 0);return}n(e.label??""),i(e.defaultModel)},[e]);const a=o.useMemo(()=>Vc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=o.useCallback((u,p)=>{i(u&&p?`${u}/${p}`:void 0)},[]),d=o.useCallback(async()=>{if(!e)return null;const u=s.trim();return u?{label:u,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},Jf=450,Xf=(e,s)=>{const{hasChanges:n,name:r,defaultModel:i,prepareSaveData:a}=e,l=o.useRef(!1);o.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const d=await a();if(d)try{await s(d)}catch{le.error("Failed to save project settings")}}finally{l.current=!1}})())},Jf);return()=>{window.clearTimeout(c)}},[i,n,r,s,a])},Zf=({project:e,onIdentitySave:s})=>{const n=qf(e),r=o.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),i=o.useCallback(async a=>{await s(a)},[s]);return Xf(n,i),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Qf,{form:n}),t.jsx(Wf,{projectRef:r})]})};function eh({...e}){return t.jsx(ka,{...e})}function th({...e}){return t.jsx(Ca,{...e})}function sh({className:e,positionerClassName:s,children:n,style:r,...i}){return t.jsx(_r,{children:t.jsx(zr,{className:B("app-region-no-drag z-50",s),children:t.jsx($r,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:B(Dr,e),...i,children:n})})})}function fi({className:e,...s}){return t.jsx(Na,{className:B(ea,e),...s})}function nh({className:e,...s}){return t.jsx(Aa,{className:B(ta,e),...s})}const As=ps()(Ia(lo((e,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{e({selectedProfileId:n})},loadProfiles:async()=>{e({isLoading:!0});const n=s().profiles;try{const r=await Zc();return e({profiles:r,isLoading:!1}),!0}catch(r){return console.error("Failed to load git identity profiles:",r),e({profiles:n,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const n=await Xc();if(n&&n.userName&&n.userEmail){const r={id:"global",name:"Global Identity",userName:n.userName,userEmail:n.userEmail,authType:n.sshCommand?"ssh":void 0,sshKey:n.sshCommand?n.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"fingerprint"};e({globalIdentity:r})}else e({globalIdentity:null});return!0}catch(n){return console.error("Failed to load global git identity:",n),e({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const n=await Jc();return e({discoveredCredentials:n}),!0}catch(n){return console.error("Failed to discover git credentials:",n),e({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const n=r=>{if(typeof r!="string")return null;const i=r.trim();return i.length>0?i:null};try{let r=null;if(r===null){const i=ro()?.settings;if(i)try{const l=(await i.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const i=await es("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",i=r.length>0?r:"";return await no({defaultGitIdentityId:i}),e({defaultGitIdentityId:i.length>0?i:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};return ds("saving"),await qc(r),ds("saved"),await s().loadProfiles(),!0}catch(r){return ds("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const i=s().profiles.find(l=>l.id===n);if(!i)throw new Error("Profile not found");const a={...i,...r};return ds("saving"),await Qc(n,a),ds("saved"),await s().loadProfiles(),!0}catch(i){return ds("error"),console.error("Failed to update git identity profile:",i),!1}},deleteProfile:async n=>{try{return ds("saving"),await Yc(n),ds("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return ds("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:i}=s();return n==="global"?i||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(i=>!n.some(a=>a.authType==="token"&&a.host===i.host))}}),{name:"git-identities-store",storage:tu(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=As);const rh=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"magic-prompts",title:"PiChamber Utility Prompts",group:"agent",kind:"split",keywords:["prompts","templates","git","github","review","commit","pull request","utility"],isAvailable:()=>!1},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["prompt","templates","multi-run","strategy","approach"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],oh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function ih(e){const s=e.trim().toLowerCase();return rh.find(n=>n.slug===s)??null}function ah(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=oh[s];if(n)return n;const r=ih(s);return r?r.slug:"home"}function Ax(e){switch(e){case"general":return"settings-3";case"projects":return"folders";case"remote-instances":return"computer";case"appearance":return"palette";case"chat":return"chat-ai-3";case"dictation":return"mic";case"magic-prompts":return"ai-generate-2";case"snippets":return"chat-thread";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"chat-history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"book-open";case"git":return"git-branch";case"tunnel":return"home-office";case"about":return"information";case"home":return null;default:return"robot-2"}}const In=100;function Ix(){const e=ce(C=>C.isArchivePageOpen),s=ce(C=>C.setArchivePageOpen),n=ce(C=>C.setActiveMainTab),r=Fe(C=>C.setCurrentSession),i=Fe(C=>C.unarchiveSession),a=ws(C=>C.homeDirectory),l=Pr({archived:!0}),[c,d]=o.useState(""),[u,p]=o.useState(null),[h,x]=o.useState(In),m=c.trim().toLowerCase(),f=o.useMemo(()=>e?[...l].sort((C,I)=>(I.time?.archived??0)-(C.time?.archived??0)):[],[l,e]),g=o.useMemo(()=>{const C=new Map;for(const I of f){const D=Je(Gs(I))??"",P=C.get(D);if(P){P.sessions.push(I);continue}C.set(D,{directory:D,label:D?Rs(D,a)||D:"other projects",sessions:[I]})}return[...C.values()].sort((I,D)=>D.sessions.length-I.sessions.length)},[a,f]),S=o.useMemo(()=>m?f.filter(C=>(C.title??"").toLowerCase().includes(m)):u===null?f:g.find(C=>C.directory===u)?.sessions??[],[g,m,u,f]),k=S.slice(0,h),_=S.length-k.length,A=l.length,b=o.useCallback(C=>{p(C),x(In)},[]),v=o.useCallback(C=>{const I=Je(Gs(C));r(C.id,I??void 0),n("chat"),s(!1)},[n,r,s]),M=o.useCallback(C=>{i(C.id).then(I=>{I?le.success("Session restored"):le.error("Failed to restore session")})},[i]);if(!e)return null;const N=(C,I,D,P,G,ee,Z)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:G,title:ee,className:B("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Z?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",P?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:I}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:D})]}),Z?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>Ts.requestDelete({sessions:Z,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${I}`,children:t.jsx(j,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},C);return t.jsx(Bu,{open:e,onOpenChange:s,children:t.jsxs(_u,{children:[t.jsx(zu,{className:"fixed inset-0 z-50 bg-black/25 dark:bg-black/40 transition-opacity duration-150 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0"}),t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:t.jsxs($u,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[t.jsx(Uu,{className:"sr-only",children:"Archived sessions"}),t.jsx(Gu,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(Ku,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(j,{name:"close",className:"size-4"})}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[N("__all__","All directories",A,u===null,()=>b(null)),g.map(C=>N(C.directory||"__none__",C.label,C.sessions.length,u===C.directory,()=>b(C.directory),C.directory||void 0,C.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(j,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:C=>{d(C.target.value),x(In)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:S.length===1?`${S.length} archived session`:`${S.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[k.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:m?"No matching archived sessions":"No archived sessions"})}):k.map(C=>{const I=Je(Gs(C))??"",D=I?Rs(I,a)||I:null;return t.jsxs("div",{className:"group relative flex cursor-pointer items-center gap-3 rounded-md py-1 pl-2 pr-2 transition-[padding] hover:bg-interactive-hover/40 hover:pr-14 focus-within:pr-14",onClick:()=>v(C),role:"button",tabIndex:0,onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),v(C))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:C.title||"Untitled Session"}),m&&D?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:I,children:D}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Iu(C.time?.archived??C.time?.updated??C.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),M(C)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${C.title||"Untitled Session"}`,children:t.jsx(j,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),Ts.requestDelete({sessions:[C],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${C.title||"Untitled Session"}`,children:t.jsx(j,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},C.id)}),_>0?t.jsx("button",{type:"button",onClick:()=>x(C=>C+In),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const lh=()=>{const[e,s]=Xe.useState(!1),[n,r]=Xe.useState(!1);Xe.useEffect(()=>{s(vs()),r(oo())},[]);const i=Xe.useCallback(async c=>e?await io(c):{success:!0,path:c},[e]),a=Xe.useCallback(async c=>e?await su():{success:!0},[e]),l=Xe.useCallback(async c=>e?await nu():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:i,startAccessing:a,stopAccessing:l}},ch=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),dh=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:i,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=o.useState(!1),[p,h]=o.useState(""),[x,m]=o.useState(!1),[f,g]=o.useState(!1),[S,k]=o.useState(""),[_,A]=o.useState(!1),b=o.useRef(null),v=o.useCallback(U=>{U.stopPropagation()},[]),M=l.length>1,N=o.useMemo(()=>ch(S),[S]),C=o.useMemo(()=>{const U=p.toLowerCase();return U?s.filter(K=>K.toLowerCase().includes(U)):s},[p,s]),I=o.useMemo(()=>{const U=p.toLowerCase();return U?n.filter(K=>K.toLowerCase().includes(U)):n},[p,n]),D=U=>{if(U===e){u(!1);return}i(U),u(!1),h("")},P=()=>{m(!0),setTimeout(()=>b.current?.focus(),50)},G=async()=>{if(!(!N||_)){if(M){g(!0);return}A(!0);try{await a(N,l[0]),k(""),m(!1),u(!1)}finally{A(!1)}}},ee=async U=>{if(!(!N||_)){A(!0);try{await a(N,U),k(""),m(!1),g(!1),u(!1)}finally{A(!1)}}},Z=()=>{g(!1)},te=()=>{k(""),m(!1),g(!1)};return o.useEffect(()=>{d||(h(""),m(!1),g(!1),k(""))},[d]),t.jsxs(qt,{open:d,onOpenChange:u,children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsxs(Ve,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:c,children:[t.jsx(j,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:e||"Detached HEAD"}),t.jsx(j,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(rt,{sideOffset:8,children:"Current branch"})]}),t.jsx(Xt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(ed,{className:"h-full min-h-0",children:[t.jsx(td,{placeholder:"Search branches...",value:p,onValueChange:h,onKeyDown:v}),t.jsxs(sd,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(nd,{children:"No branches found."}),t.jsx(ar,{children:f?t.jsxs("div",{className:"px-2 py-1.5",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.jsx("button",{type:"button",onClick:Z,disabled:_,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(j,{name:"arrow-left",className:"size-4"})}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Push To Prefix"," ",t.jsx("span",{className:"text-foreground font-medium",children:N})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(U=>t.jsxs("button",{type:"button",onClick:()=>ee(U),disabled:_,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[t.jsxs("span",{className:"typography-ui-label text-foreground",children:[_?t.jsx(j,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,U.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:U.pushUrl})]},U.name))})]}):x?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:b,placeholder:"New branch name",value:S,onChange:U=>k(U.target.value),onClick:U=>U.stopPropagation(),onKeyDown:U=>{v(U),U.key==="Enter"?(U.preventDefault(),G()):U.key==="Escape"&&(U.preventDefault(),te())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:G,disabled:!N||_,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:_?t.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(j,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:te,disabled:_,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(j,{name:"close",className:"size-4"})})]}):t.jsxs(Zs,{onSelect:P,children:[t.jsx(j,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Ko,{}),t.jsxs(ar,{heading:"Local branches",children:[C.map(U=>t.jsxs(Zs,{onSelect:()=>D(U),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:U}),(r?.[U]?.ahead||r?.[U]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[U].ahead||0," ahead ·"," ",r[U].behind||0," behind"]})]}),e===U&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${U}`)),C.length===0&&t.jsx(Zs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Ko,{}),t.jsxs(ar,{heading:"Remote branches",children:[I.map(U=>t.jsx(Zs,{onSelect:()=>D(U),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:U})},`remote-${U}`)),I.length===0&&t.jsx(Zs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},uh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),fh=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,i]=o.useState(!1),[a,l]=o.useState(e||""),[c,d]=o.useState(!1),u=o.useRef(null),p=()=>{!e||!s||(l(e),i(!0),setTimeout(()=>u.current?.focus(),0))},h=async()=>{if(!e||!s||!a.trim())return;const f=uh(a);if(f===e){i(!1);return}d(!0);try{await s(e,f),i(!1),l("")}finally{d(!1)}},x=()=>{i(!1),l("")},m=f=>{f.key==="Enter"?(f.preventDefault(),h()):f.key==="Escape"&&(f.preventDefault(),x())};return r?t.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:t.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:f=>{f.preventDefault(),h()},children:[t.jsx(j,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:f=>l(f.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:m,autoFocus:!0}),t.jsx("button",{type:"submit",disabled:c,"aria-label":c?"Saving branch name":"Save branch name",title:c?"Saving branch name":"Save branch name",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?t.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(j,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:x,disabled:c,"aria-label":"Cancel branch rename",title:"Cancel branch rename",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(j,{name:"close",className:"size-4"})})]})}):t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[t.jsx(j,{name:"git-branch",className:"size-4 text-primary shrink-0"}),t.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:e||"Detached HEAD"}),n&&s&&e&&t.jsx(Ve,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:p,title:"Rename branch",children:t.jsx(j,{name:"edit",className:"size-4"})})]})]})},hh=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:i,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:p=!1})=>{const h=o.useRef(!1),x=!!l,m=s.find(v=>v.name===u)??s[0],f=d>0&&p,g=a||e!==null||x||!m||f,S=a||e!==null||x||s.length===0,k=c>0||d>0,_=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),A=f?"Commit or stash your changes before syncing":m?k?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",b=()=>{m&&r(m)};return t.jsxs("div",{className:"inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:f?0:void 0,children:t.jsxs("button",{type:"button",onClick:b,disabled:g,className:B("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),"aria-label":"Sync Changes",children:[e==="sync"?t.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(j,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:_})]})})}),t.jsx(rt,{sideOffset:8,children:A})]}),t.jsxs(qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:B("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:S,"aria-label":"More sync actions",children:t.jsx(j,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Xt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(v=>t.jsx(kt,{onSelect:M=>{if(h.current){M.preventDefault(),h.current=!1;return}n(v)},children:t.jsxs("div",{className:"flex w-full items-center gap-2",children:[t.jsx(j,{name:"refresh",className:"size-4 text-muted-foreground"}),t.jsx("div",{className:"min-w-0 flex-1",children:t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:`Fetch from ${v.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:v.fetchUrl})]})}),i&&v.name!==u?t.jsx(Ve,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||x,onPointerDown:M=>{h.current=!0,M.preventDefault(),M.stopPropagation()},onClick:M=>{h.current=!0,M.preventDefault(),M.stopPropagation(),i(v)},"aria-label":`Remove remote ${v.name}`,title:`Remove remote ${v.name}`,children:l===v.name?t.jsx(j,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(j,{name:"close",className:"size-3.5"})}):null]})},v.name))})]})]})},ph={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},mh={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function Ua(e){return e&&mh[e]||"var(--primary)"}const hi=({icon:e,className:s,colorToken:n})=>{const r=ph[e??"branch"]??"user-3";return t.jsx(j,{name:r,className:s,style:{color:Ua(n)}})},Ga=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:i=!1})=>{const a=r||s.length===0;return t.jsxs(qt,{children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsxs(Ve,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:{color:Ua(e?.color)},disabled:a,children:[r?t.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(hi,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!i&&t.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(j,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(rt,{sideOffset:8,children:"Git identity"})]}),t.jsx(Xt,{align:"end",className:"w-64",children:s.length===0?t.jsx("div",{className:"px-2 py-1.5",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(l=>{const c=e?.id===l.id;return t.jsx(kt,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(hi,{icon:l.icon,colorToken:l.color,className:"size-4"}),t.jsxs("span",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?t.jsx(j,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},gh=({comparison:e,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${e.remote}/${e.branch}`,i=e.ahead===0&&e.behind===0,a=s?`Compared with ${r}. Primary sync badges still reflect ${s}.`:`Compared with ${r}.`;return t.jsxs(st,{delayDuration:n,children:[t.jsx(nt,{asChild:!0,children:t.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[t.jsx(j,{name:"git-branch",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:r}),i?t.jsx("span",{className:"tabular-nums text-muted-foreground",children:"synced"}):t.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[e.ahead>0?t.jsxs("span",{className:"text-[var(--status-info)]",children:["↑",e.ahead]}):null,e.behind>0?t.jsxs("span",{className:"text-[var(--status-warning)]",children:["↓",e.behind]}):null]})]})}),t.jsx(rt,{sideOffset:8,children:a})]})},Dx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:p,onCreateBranch:h,onRenameBranch:x,activeIdentityProfile:m,availableIdentities:f,onSelectIdentity:g,isApplyingIdentity:S,isWorktreeMode:k,onOpenHistory:_,onOpenGraph:A,onOpenStashes:b,onOpenUpdateBranch:v,onOpenReintegrateCommits:M,pullRequest:N,prChecks:C,onOpenPullRequest:I})=>{if(!e)return null;const D=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:_||A||b||v?t.jsxs(qt,{children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsx(Ve,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:t.jsx(j,{name:"more-fill",className:"size-4"})})})}),t.jsx(rt,{sideOffset:8,children:"Repository views"})]}),t.jsxs(Xt,{align:"end",children:[_?t.jsxs(kt,{onSelect:_,children:[t.jsx(j,{name:"history",className:"size-4"}),"History"]}):null,A?t.jsxs(kt,{onSelect:A,children:[t.jsx(j,{name:"git-branch",className:"size-4"}),"Graph"]}):null,b?t.jsxs(kt,{onSelect:b,children:[t.jsx(j,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,v?t.jsxs(kt,{onSelect:v,children:[t.jsx(j,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,M?t.jsxs(kt,{onSelect:M,children:[t.jsx(j,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),P=C?C.state==="success"?"var(--status-success)":C.state==="failure"?"var(--status-error)":"var(--status-warning)":null,G=N?N.state==="merged"?"merged":N.state==="closed"?"closed":N.draft?"draft":C?.state==="failure"||N.mergeable===!1||N.mergeableState==="blocked"||N.mergeableState==="dirty"?"blocked":"open":null,ee=N&&I?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsxs(Ve,{variant:"ghost",size:"sm",onClick:I,className:"h-8 gap-1.5 px-2 typography-micro",children:[t.jsx(j,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${G})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${N.number}`}),P?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:P}}):null]})}),t.jsx(rt,{sideOffset:8,children:"Open pull request"})]}):null,Z=t.jsx(hh,{syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,disabled:!e,iconOnly:!0,aheadCount:e.ahead,behindCount:e.behind,trackingRemoteName:e.tracking?.split("/")[0],hasUncommittedChanges:(e.files?.length??0)>0}),te=e.upstreamComparison?t.jsx(gh,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,U=t.jsx(Ga,{activeProfile:m,identities:f,onSelect:g,isApplying:S,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:k?t.jsx(fh,{currentBranch:e.current,onRename:x}):t.jsx(dh,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:p,onCreate:h,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:U})]}),t.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[ee?t.jsx("div",{className:"shrink-0",children:ee}):null,t.jsx("div",{className:"min-w-0 flex-1"}),te?t.jsx("div",{className:"min-w-0 shrink",children:te}):null,D,t.jsx("div",{className:"shrink-0",children:Z})]})]})},xh=e=>e==="/",Ks=e=>e.replace(/\\/g,"/"),Ys=e=>{if(!e||xh(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Hs=e=>e.endsWith("/"),Hn=e=>{const s=e.trim();return!s||Hs(s)?s:`${s}/`},go=e=>e.lastIndexOf("/"),Ka=e=>{if(Hs(e))return e;const s=go(e);return s<0?e:e.slice(0,s+1)},Ha=e=>{const s=go(e);return e.slice(s+1)},Wa=e=>{const s=Ys(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=go(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},Va=e=>Hs(e)&&Wa(e)!==null,bh=e=>{if(!Va(e))return null;const s=Ys(e.trim());return Ha(s)||s},yh=(e,s)=>`${Ka(e)}${s}/`,Cs=e=>{if(!e)return null;const s=Ys(Ks(e.trim()));return s?s.toLowerCase():null},pi=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},vh=(e,s)=>{const n=Ys(Ks(e.trim())),r=Ys(Ks(s.trim()));if(!n)return"";if(!r)return Hn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const i=`${r}/`;return n.toLowerCase().startsWith(i.toLowerCase())?`~/${n.slice(r.length+1)}/`:Hn(n)},wh=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,fr=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},Sh=async()=>au(),jh=({open:e,onOpenChange:s})=>{const n=ws(F=>F.homeDirectory),r=$t(F=>F.projects),i=$t(F=>F.addProject),a=ce(F=>F.setActiveMainTab),l=ce(F=>F.setSessionSwitcherOpen),c=Fe(F=>F.openNewSessionDraft),d=As(F=>F.profiles),u=As(F=>F.globalIdentity),p=As(F=>F.defaultGitIdentityId),h=As(F=>F.loadProfiles),x=As(F=>F.loadGlobalIdentity),m=As(F=>F.loadDefaultGitIdentityId),{canRequestAccess:f,startAccessing:g}=lh(),{isMobile:S,isTablet:k}=Ms(),_=S||k,A=o.useRef(null),b=o.useRef(new Map),[v,M]=o.useState(""),[N,C]=o.useState("~/"),[I,D]=o.useState([]),[P,G]=o.useState(!1),[ee,Z]=o.useState(!1),[te,U]=o.useState(null),[K,T]=o.useState(0),[R,q]=o.useState(0),[ae,z]=o.useState(!1),[Re,Te]=o.useState(!1),[Ye,_e]=o.useState(!1),[Qe,Be]=o.useState(""),[ie,pe]=o.useState(null),[We,ke]=o.useState(!1),[ve,$e]=o.useState("right"),ot=o.useRef("~/"),ze=v||n,J=o.useMemo(()=>new Set(r.map(F=>Cs(F.path)).filter(F=>!!F)),[r]);o.useEffect(()=>{if(!e)return;C("~/"),D([]),q(0),z(!1),Te(!1),_e(!1),Be(""),pe(null),ke(!1),ot.current="~/",$e("right"),_||requestAnimationFrame(()=>fr(A.current));let F=!1;return(async()=>{const Ue=await Sh();F||(M(Ue||n||""),_||requestAnimationFrame(()=>fr(A.current)))})(),()=>{F=!0}},[n,e,_]),o.useEffect(()=>{e&&(h(),x(),m())},[m,h,x,e]);const Q=o.useMemo(()=>{const F=new Map;u&&F.set(u.id,u);for(const Ne of d)F.set(Ne.id,Ne);return Array.from(F.values())},[d,u]);o.useEffect(()=>{if(!e||!Ye||ie!==null)return;const F=typeof p=="string"?p.trim():"";if(F&&Q.some(Ue=>Ue.id===F)){pe(F);return}const Ne=Q.find(Ue=>Ue.authType==="ssh"||Ue.sshKey);Ne&&pe(Ne.id)},[Q,p,Ye,e,ie]);const ge=o.useMemo(()=>Q.find(F=>F.id===ie)??null,[Q,ie]),X=o.useMemo(()=>Ka(N),[N]),be=o.useMemo(()=>Hs(N)?"":Ha(N),[N]),Ae=o.useMemo(()=>ze?pi(X,ze):"",[X,ze]);o.useEffect(()=>{const F=ot.current;F!==X&&($e(X.length>=F.length?"right":"left"),ot.current=X)},[X]),o.useEffect(()=>{if(!e||!Ae){D([]),U(null);return}let F=!1;return G(!0),Z(!1),U(null),ru(Ae).then(Ne=>{if(F)return;Z(!1),U(null);const Ue=Ne.filter(pt=>pt.isDirectory).map(pt=>({name:pt.name,path:Ks(pt.path)})).sort((pt,L)=>pt.name.localeCompare(L.name));D(Ue)}).catch(Ne=>{if(!F){D([]);const Ue=ou(Ne)?Ne.reason:"unknown";U(Ue),Z(Ue==="not-found")}}).finally(()=>{F||G(!1)}),()=>{F=!0}},[Ae,K,e]);const je=o.useMemo(()=>{const F=be.toLowerCase(),Ne=We||be.startsWith(".");return I.filter(Ue=>Ue.name.toLowerCase().startsWith(F)&&(Ne||!Ue.name.startsWith(".")))},[be,I,We]),lt=o.useMemo(()=>bh(N),[N]),jt=o.useMemo(()=>Wa(N),[N]),it=o.useMemo(()=>{const F=[],Ne=Cs(Ae);Va(N)&<&&jt&&F.push({type:"parent",value:"browse:up",name:lt,path:jt,alreadyAdded:!!(Ne&&J.has(Ne))});for(const Ue of je){const pt=Cs(Ue.path);F.push({type:"directory",value:`browse:${Ue.path}`,name:Ue.name,path:Ue.path,alreadyAdded:!!(pt&&J.has(pt))})}return F},[J,Ae,lt,je,jt,N]);o.useEffect(()=>{q(0)},[N,it.length]);const xe=o.useMemo(()=>ze?Ys(pi(N,ze)):"",[ze,N]),Le=Cs(xe),Oe=!!(Le&&J.has(Le)),Ke=o.useMemo(()=>be?je.find(F=>F.name===be)??null:null,[be,je]),Ct=!!(xe&&!Oe&&(te===null||te==="not-found")&&(Hs(N)&&ee||!Hs(N)&&be.trim().length>0&&Ke===null)),ht=!ae&&!Re&&!Oe&&te!=="os-permission"&&te!=="invalid-response"&&te!=="unknown"&&!!xe,O=ht&&Qe.trim().length>0,Ce=it[R]??null,ye=!!Ce,w=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",Y=Oe?"Already added":Ye?ae?"Cloning...":"Clone & add":ae?"Adding...":Ct?"Create & add":"Add folder",se=Ye?O:ht;o.useLayoutEffect(()=>{const F=A.current;F&&(F.scrollLeft=F.scrollWidth)},[N]),o.useLayoutEffect(()=>{!e||_||fr(A.current)},[e,_]),o.useLayoutEffect(()=>{const F=it[R];F&&b.current.get(F.value)?.scrollIntoView({block:"nearest"})},[R,it]);const ue=o.useCallback(()=>{s(!1)},[s]),Se=o.useCallback((F,Ne)=>{a("chat"),S&&l(!1),c({selectedProjectId:F,directoryOverride:Ne}),ue()},[ue,S,c,a,l]),Pe=o.useCallback(async F=>{if(!F||ae)return;const Ne=Cs(F);if(Ne&&J.has(Ne))return;let Ue=F;z(!0);try{const pt=!Ye&&Ct&&Cs(F)===Cs(xe);if(Ye){const re=Qe.trim();if(!re){le.error("Enter a repository URL before cloning.");return}const me=await es("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:re,destinationPath:F,gitIdentityId:ge?.id??null})});if(!me.ok)throw new Error("Failed to clone git repository");Ue=(await me.json()).path||F}else if(pt&&!(await es("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:Ae?{directory:Ae}:void 0,body:JSON.stringify({path:F})})).ok)throw new Error("Failed to select directory");const L=i(Ue);if(!L){le.error("Failed to add folder",{description:"Please select a valid directory path."});return}Se(L.id,L.path)}catch(pt){le.error("Failed to select directory",{description:pt instanceof Error?pt.message:"Unknown error occurred."})}finally{z(!1)}},[i,J,Ae,Qe,Ye,ae,Se,ge?.id,Ct,xe]),He=o.useCallback(F=>{C(Hn(F))},[]),mt=o.useCallback(F=>{C(yh(N,F.name))},[N]),bt=o.useCallback(F=>{if(F){if(F.type==="parent"){He(F.path);return}mt(F)}},[He,mt]),qe=o.useCallback(async F=>{const Ne=await g(F);if(!Ne.success)return le.error("Failed to open directory",{description:Ne.error||"Desktop could not grant file access."}),!1;const Ue=ze?vh(F,ze):Hn(Ks(F));return He(Ue),!0},[He,ze,g]),dt=o.useCallback(async()=>{if(!Re){Te(!0);try{if(oo()){const Ne=await io(xe);if(!Ne.success||!Ne.path){Ne.error&&Ne.error!=="Directory selection cancelled"&&le.error("Failed to select directory",{description:Ne.error});return}await qe(Ne.path);return}const F=await iu(xe);if(F.status==="cancelled")return;if(F.status!=="picked"){le.error("Couldn't open a folder picker",{description:F.error});return}await qe(F.path)}catch(F){le.error("Failed to select directory",{description:F instanceof Error?F.message:"Unknown error occurred."})}finally{Te(!1)}}},[qe,Re,xe]),xt=o.useCallback(F=>{if(F.key==="ArrowDown"){F.preventDefault(),q(Ne=>Math.min(it.length-1,Ne+1));return}if(F.key==="ArrowUp"){F.preventDefault(),q(Ne=>Math.max(0,Ne-1));return}if(F.key==="Enter"){if(F.preventDefault(),wh(F)){Pe(xe);return}ye&&bt(Ce);return}F.key==="Backspace"&&N===""&&(F.preventDefault(),ue())},[bt,Pe,ue,ye,Ce,N,it.length,xe]),Me=t.jsxs("button",{type:"button",onClick:()=>ke(F=>!F),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[We?t.jsx(j,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(j,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),Ze=t.jsx("div",{className:"py-1.5",children:t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(j,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),t.jsx(Ws,{ref:A,value:N,onChange:F=>C(Ks(F.target.value)),onKeyDown:xt,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),t.jsxs(Ve,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:ae||Re,onMouseDown:F=>F.preventDefault(),onClick:()=>{dt()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(j,{name:"folder-open",className:"h-3.5 w-3.5"}),Re?"Opening...":"Browse"]})]})}),yt=it.some(F=>F.type==="parent"),Nt=t.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:t.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[t.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),t.jsxs(Ve,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":Ye,disabled:ae||Re,onClick:()=>_e(F=>!F),children:[t.jsx(j,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),Ye?t.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Ws,{value:Qe,onChange:F=>Be(F.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),t.jsx(Ga,{activeProfile:ge,identities:Q,onSelect:F=>pe(F.id),isApplying:ae,iconOnly:!0})]})]}):null,Oe?t.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,t.jsx("div",{className:B("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",ve==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:P?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):te&&te!=="not-found"?t.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[t.jsx("div",{className:"typography-ui-label text-status-error",children:te==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[te==="os-permission"&&f?t.jsx(Ve,{size:"xs",onClick:()=>{dt()},disabled:Re,children:"Grant access"}):null,t.jsx(Ve,{variant:"outline",size:"xs",onClick:()=>T(F=>F+1),children:"Try again"})]})]}):it.length===0?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):t.jsx("div",{className:"space-y-0.5",children:it.map((F,Ne)=>{const Ue=Ne===R,pt=F.type==="directory"&&yt;return t.jsxs("button",{ref:L=>{L?b.current.set(F.value,L):b.current.delete(F.value)},type:"button","aria-label":F.type==="parent"?F.alreadyAdded?`Go back from ${F.name}, already added`:`Go back from ${F.name}`:F.alreadyAdded?`Open ${F.name}, already added`:`Open ${F.name}`,onMouseEnter:()=>q(Ne),onMouseDown:L=>L.preventDefault(),onClick:()=>bt(F),className:B("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Ue&&"bg-interactive-selection text-interactive-selection-foreground",!Ue&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:B("flex min-w-0 flex-1 items-center gap-2",pt&&"pl-4"),children:[F.type==="parent"?t.jsx(j,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(j,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:F.name})]}),F.alreadyAdded?t.jsx("span",{className:B("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Ue?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,F.type==="parent"?t.jsx(j,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(j,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},F.value)})})},X)]})}),Pt=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[Ze,Nt]}),Et=t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(j,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(j,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(j,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{children:w}),t.jsx(j,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),It=t.jsx(Ve,{size:S?"xs":"default",onClick:()=>{Pe(xe)},disabled:!se,className:B(S&&"w-full flex-1"),children:Y}),At=()=>t.jsxs(t.Fragment,{children:[S?null:Et,t.jsx("div",{className:B("flex w-full flex-row justify-end gap-2 sm:w-auto",S&&"justify-stretch"),children:It})]});return S?t.jsx(sa,{open:e,onClose:ue,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:At()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:Me}),Pt]})}):t.jsx(as,{open:e,onOpenChange:s,children:t.jsxs(ls,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(Ss,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(hs,{children:"Add folder"}),t.jsx(Fs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Me]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:Pt}),t.jsx(Ls,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:At()})]})})},Dn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Px=()=>{const[e,s]=o.useState(!1),[n,r]=o.useState(null),[i,a]=o.useState(!1),l=rd,c=Fe(M=>M.deleteSessions),d=ce(M=>M.showDeletionDialog),u=ce(M=>M.setShowDeletionDialog),{isMobile:p,isTablet:h,hasTouchInput:x}=Ms(),m=p||h||x;o.useEffect(()=>lu(()=>{s(!1)}),[]);const f=o.useCallback(M=>{r({sessions:M.sessions,dateLabel:M.dateLabel})},[]),g=o.useCallback(()=>{r(null),a(!1)},[]),S=o.useCallback(async M=>{if(M.sessions.length===0)return;if(M.sessions.length===1){const D=M.sessions[0];await l(D.id)?le.success("Session deleted"):le.error("Failed to delete session");return}const N=M.sessions.map(D=>D.id),{deletedIds:C,failedIds:I}=await c(N);if(C.length>0){const D=I.length>0?I.length===1?`${I.length} session could not be deleted.`:`${I.length} sessions could not be deleted.`:M.dateLabel?`Removed all sessions from ${M.dateLabel}.`:void 0;le.success(C.length===1?"Deleted {count} session":`Deleted ${C.length} sessions`,{description:Dn(D)})}I.length>0&&le.error(I.length===1?`Failed to delete ${I.length} session`:`Failed to delete ${I.length} sessions`,{description:Dn("Please try again in a moment.")})},[l,c]);o.useEffect(()=>Ts.onDeleteRequest(M=>{if(!d){S(M);return}f(M)}),[f,d,S]),o.useEffect(()=>Ts.onDirectoryRequest(()=>{s(!0)}),[]);const k=o.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const M=n.sessions[0];if(!await l(M.id)){le.error("Failed to delete session"),a(!1);return}le.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const M=n.sessions.map(D=>D.id),N=await c(M),C=N.deletedIds,I=N.failedIds;if(C.length>0){const D=I.length>0?I.length===1?`${I.length} session could not be deleted.`:`${I.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;le.success(C.length===1?"Deleted {count} session":`Deleted ${C.length} sessions`,{description:Dn(D),action:{label:"OK",onClick:()=>{}}})}if(I.length>0&&(le.error(I.length===1?`Failed to delete ${I.length} session`:`Failed to delete ${I.length} sessions`,{description:Dn("Please try again in a moment.")}),C.length===0)){a(!1);return}}g()}finally{a(!1)}}},[n,l,c,g]),_=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",A=n?t.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&t.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(M=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:M.title||"Untitled Session"})},M.id)),n.sessions.length>5&&t.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),t.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,b=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?t.jsx(j,{name:"checkbox-blank",className:"size-4"}):t.jsx(j,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ve,{variant:"ghost",onClick:g,disabled:i,children:"Cancel"}),t.jsx(Ve,{variant:"destructive",onClick:k,disabled:i,children:i?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),v=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[m?t.jsx(sa,{open:!!n,onClose:()=>{i||g()},title:v,footer:t.jsx("div",{className:"flex justify-end gap-2",children:b}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[_&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:_}),A]})}):t.jsx(as,{open:!!n,onOpenChange:M=>{if(!M){if(i)return;g()}},children:t.jsxs(ls,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(Ss,{children:[t.jsx(hs,{children:v}),_&&t.jsx(Fs,{children:_})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:A}),t.jsx(Ls,{className:"mt-2 gap-2 pt-1 pb-1",children:b})]})}),t.jsx(jh,{open:e,onOpenChange:s})]})},Ex=()=>{const e=nn(d=>d.entries),s=ce(d=>d.isMobile),n=ce(d=>d.activeMainTab),r=Fe(d=>d.newSessionDraft),i=Fe(d=>d.openNewSessionDraft),a=Fe(d=>d.setNewSessionDraftTarget),l=n==="chat",c=o.useMemo(()=>{const d=od(r?.worktreeIntent),u=!!r?.open,p=[];for(const h of e.values()){const x=u&&h.key===d,m=x&&l;if(h.state){m||p.push(h);continue}h.receipt&&!x&&p.push(h)}return p},[e,r?.worktreeIntent,r?.open,l]);return c.length===0?null:t.jsx("div",{className:B("pointer-events-none fixed inset-x-0 z-40 flex justify-center px-3",s?"bottom-[calc(var(--oc-safe-area-bottom,0px)+5.5rem)]":"bottom-4"),"aria-live":"polite",children:t.jsx("div",{className:"pointer-events-auto flex w-full max-w-[640px] flex-col gap-2",children:c.map(d=>t.jsx(kh,{entry:d,onDismissFailed:()=>nn.getState().dismissFailed(d.key),onDismissCompleted:()=>nn.getState().clearEntry(d.key),onOpenWorktree:()=>{const u=d.receipt;u&&(r?.open?a({directoryOverride:u.path,worktreeIntent:null}):i({directoryOverride:u.path}),nn.getState().clearEntry(d.key),ce.getState().setActiveMainTab("chat"))}},d.key))})})},kh=({entry:e,onDismissFailed:s,onDismissCompleted:n,onOpenWorktree:r})=>{const i=e.state?.phase==="failed",a=!!(e.state&&!i),l=!e.state&&!!e.receipt,c=i?e.state?.label??"Worktree creation failed":a?e.state?.label??"Creating worktree...":e.receipt?`Worktree ready: ${e.receipt.branch??e.path??"new worktree"}`:"",d=i?e.state?.error:l?e.receipt?.path:null;return t.jsxs("div",{className:B("flex items-center gap-3 rounded-xl border px-3 py-2.5 shadow-lg backdrop-blur",i?"border-[var(--status-error-border)] bg-[var(--status-error-background)] text-[var(--status-error-foreground)]":l?"border-[var(--border)] bg-[var(--surface-elevated)] text-foreground":"border-[var(--border)] bg-[var(--surface-muted)] text-muted-foreground"),role:i?"alert":"status",children:[a?t.jsx(Qs,{variant:"inline",text:null,animationType:"spinner"}):l?t.jsx(j,{name:"git-branch",className:"h-4 w-4 shrink-0 text-[var(--status-success)]"}):t.jsx(j,{name:"alert",className:"h-4 w-4 shrink-0"}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("p",{className:"typography-ui-label truncate",children:c}),d?t.jsx("p",{className:"mt-0.5 break-words text-xs opacity-80 line-clamp-2",children:d}):null,a&&e.branch?t.jsx("p",{className:"mt-0.5 truncate text-xs opacity-60",children:e.branch}):null]}),i?t.jsx(Ve,{type:"button",variant:"ghost",size:"xs",onClick:s,"aria-label":"Dismiss error",children:"Dismiss"}):null,l?t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Ve,{type:"button",size:"xs",onClick:r,children:"Open"}),t.jsx(Ve,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Dismiss",children:t.jsx(j,{name:"close",className:"h-3.5 w-3.5"})})]}):null,a?t.jsx("span",{className:"hidden shrink-0 text-xs opacity-60 sm:inline",children:"In background"}):null]})};function Tx(){const e=o.useRef(!1),s=o.useRef(!1),n=Fe(p=>p.setCurrentSession),r=ce(p=>p.setActiveMainTab),i=ce(p=>p.setSettingsDialogOpen),a=ce(p=>p.setSettingsPage),l=ce(p=>p.navigateToDiff),c=o.useCallback(async p=>{if(!s.current){s.current=!0;try{if(p.sessionId){const h=Fe.getState().currentSessionId,x=en().getState().selectedSessionId;if(p.sessionId!==h||p.sessionId!==x){const m=Fe.getState().getDirectoryForSession(p.sessionId);n(p.sessionId,m)}}if(p.settingsPath){a(ah(p.settingsPath)),i(!0);return}ce.getState().isSettingsDialogOpen&&i(!1),p.tab&&r(p.tab),p.diffFile&&(p.tab==="diff"||!p.tab)&&l(p.diffFile)}finally{s.current=!1}}},[n,r,i,a,l]),d=o.useCallback(()=>{const p=Fe.getState(),h=en().getState(),x=ce.getState();return{sessionId:lr({currentSessionId:p.currentSessionId,piSelectedSessionId:h.selectedSessionId,draft:p.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),u=o.useCallback((p={})=>{if(s.current)return;const h=d();Gr(h,p)},[d]);o.useEffect(()=>{if(e.current||(e.current=!0,!Ho()))return;const p=Wo();(async()=>(await c(p),Gr({...d(),sessionId:p.sessionId??lr({currentSessionId:Fe.getState().currentSessionId,piSelectedSessionId:en().getState().selectedSessionId,draft:Fe.getState().newSessionDraft}),tab:p.tab??ce.getState().activeMainTab,settingsPath:p.settingsPath??ce.getState().settingsPage,diffFile:p.diffFile??ce.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),o.useEffect(()=>{const p=()=>{const S=Fe.getState(),k=en().getState();return lr({currentSessionId:S.currentSessionId,piSelectedSessionId:k.selectedSessionId,draft:S.newSessionDraft})};let h=p(),x=Fe.getState().newSessionDraft?.open===!0;const m=()=>{const S=Fe.getState(),k=p(),_=S.newSessionDraft?.open===!0;k===h&&_===x||s.current||(h=k,x=_,u({replace:!0}))},f=Fe.subscribe(()=>{m()}),g=en().subscribe(()=>{m()});return()=>{f(),g()}},[u]),o.useEffect(()=>{let p=ce.getState().activeMainTab,h=ce.getState().isSettingsDialogOpen,x=ce.getState().settingsPage,m=ce.getState().pendingDiffFile;return ce.subscribe(g=>{if(s.current)return;const S=g.activeMainTab!==p,k=g.isSettingsDialogOpen!==h,_=g.settingsPage!==x,A=g.pendingDiffFile!==m&&g.activeMainTab==="diff";p=g.activeMainTab,h=g.isSettingsDialogOpen,x=g.settingsPage,m=g.pendingDiffFile,(S||k||_||A)&&u()})},[u]),o.useEffect(()=>{if(typeof window>"u")return;const p=()=>{const h=Wo();if(Ho())c(h);else{const x=ce.getState();x.isSettingsDialogOpen&&i(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",p),()=>{window.removeEventListener("popstate",p)}},[c,r,i])}function Ch(e=!0){const s=Bn(r=>r.checkForUpdates),n=o.useRef(s);o.useEffect(()=>{n.current=s},[s]),o.useEffect(()=>{if(!e)return;const r=3e3,i=3600*1e3,a=300*1e3,l=1440*60*1e3;let c=!1,d=null;const u=h=>{const x=Math.round(h*1e3);return Math.max(a,Math.min(l,x))},p=h=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),m=typeof x=="number"&&Number.isFinite(x)?u(x):i;p(m)},h))};return p(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function Rx(){const e=an(s=>s.connection==="ready",void 0,"chrome");return Ch(e),null}const mi=12,Nh=[{id:"left",x:22,y:58,delay:0,radius:120,colorVar:"--status-success"},{id:"center",x:50,y:42,delay:120,radius:150,colorVar:"--primary-base"},{id:"right",x:78,y:55,delay:200,radius:130,colorVar:"--status-info"}],Ah=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:i=Nh,onComplete:a})=>{const l=Xe.useRef(!1);Xe.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Xe.useMemo(()=>Array.from({length:mi},(d,u)=>{const p=Math.PI*2*u/mi;return{x:Math.cos(p),y:Math.sin(p),delay:u*18}}),[]);return e?t.jsx("div",{className:B("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:i.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:u,children:c.map((p,h)=>{const x=p.x*d.radius,m=p.y*d.radius,f={"--translate-x":`${x}px`,"--translate-y":`${m}px`,"--particle-delay":`${p.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:f},`${d.id}-${h}-${s}`)})},`${d.id}-${s}`)})}):null},Ih=({durationMs:e=3400}={})=>{const[s,n]=Xe.useState({isActive:!1,cycle:0}),r=Xe.useRef(null),i=Xe.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Xe.useCallback(()=>{i(),n(c=>c.isActive?{...c,isActive:!1}:c)},[i]),l=Xe.useCallback(()=>{i(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[i,e]);return Xe.useEffect(()=>()=>i(),[i]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},Ya=o.createContext(void 0),Mx=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:i}=Ih(),a=o.useMemo(()=>({triggerFireworks:r,dismissFireworks:i}),[r,i]);return t.jsxs(Ya.Provider,{value:a,children:[e,t.jsx(Ah,{isActive:s,burstKey:n})]})},Dh={triggerFireworks:()=>{},dismissFireworks:()=>{}},Fx=()=>o.useContext(Ya)??Dh,gi=380,xi=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},Wn=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Pn=({icon:e,iconNode:s,label:n,children:r})=>t.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[t.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:s??(e?t.jsx(j,{name:e,className:"size-[18px]"}):null)}),t.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),Ph=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const i=o.useRef(null),[a,l]=o.useState(e),[c,d]=o.useState(!1),{enabled:u}=eo(),p=o.useRef(null),[h,x]=o.useState(null);o.useLayoutEffect(()=>{if(!e||!u||!a)return;const f=()=>{const k=n.current?.getBoundingClientRect(),_=p.current?.getBoundingClientRect();if(!k||!_){x(null);return}const A=k.left-_.left,b=Math.min(Math.max(A,8),Math.max(8,_.width-gi-8));x(b)};f();const g=p.current;if(typeof ResizeObserver>"u"||!g)return;const S=new ResizeObserver(f);return S.observe(g),()=>S.disconnect()},[n,u,e,a]);const m=u&&h!==null;return o.useEffect(()=>{if(e){l(!0),d(!1);return}if(!a)return;d(!0);const f=window.setTimeout(()=>{l(!1),d(!1)},140);return()=>window.clearTimeout(f)},[e,a]),o.useEffect(()=>{if(!e)return;const f=g=>{g.key==="Escape"&&s()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[s,e]),o.useEffect(()=>{if(!e)return;const f=g=>{const S=g.target;if(!(S instanceof Node)){s();return}i.current?.contains(S)||n.current?.contains(S)||s()};return document.addEventListener("pointerdown",f,!0),document.addEventListener("wheel",f,!0),()=>{document.removeEventListener("pointerdown",f,!0),document.removeEventListener("wheel",f,!0)}},[n,s,e]),a?t.jsxs("div",{ref:p,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[t.jsx("div",{ref:i,role:"tooltip","aria-label":"Context usage for current conversation",className:B("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",m?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...m?{top:8,left:h??8,width:`min(${gi}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(Pn,{iconNode:t.jsx(ra,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:B("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),t.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?t.jsxs(t.Fragment,{children:[t.jsx(Pn,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:Wn(r.cacheRead)})}),t.jsx(Pn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:Wn(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(Pn,{icon:"check",label:"Cache hit",children:t.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):t.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),t.jsx("style",{children:`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BA67uOfZ.js","assets/WindowsWindowControls-CCnU0ckO.js","assets/index-CcbDTf8Q.js","assets/vendor-zustand-CnsBKjP5.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-Cl3XbCeC.css","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-base-ui-DL8r2fgQ.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-react-dom-sVFnuruh.js","assets/vendor-floating-ui-dom-Bkw82kL9.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-use-sync-external-store-B7OScDIw.js","assets/runtimeSurface-DF3VwUlO.js","assets/vendor-dnd-kit-core-GipZW2tY.js","assets/vendor-dnd-kit-utilities-CrOcp0Bp.js","assets/vendor-dnd-kit-accessibility-Cv52zwWT.js","assets/vendor-dnd-kit-sortable-Ct2QxIHb.js","assets/vendor-cmdk-BCEUzcHE.js","assets/vendor-radix-ui-react-dialog-jX3Dld8c.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-D1GnwnP9.js","assets/vendor-radix-ui-react-context-CM4yFQ2I.js","assets/vendor-radix-ui-react-id-BcxRjnbX.js","assets/vendor-radix-ui-react-use-layout-effect-0fyGwS2_.js","assets/vendor-radix-ui-react-use-controllable-state-C_ecoh35.js","assets/vendor-radix-ui-react-dismissable-layer-M7LsH3yL.js","assets/vendor-radix-ui-react-primitive-CfpW6_IT.js","assets/vendor-radix-ui-react-slot-BxUc3Pvz.js","assets/vendor-radix-ui-react-use-callback-ref-UKEWHtoP.js","assets/vendor-radix-ui-react-use-escape-keydown-Co13lHGj.js","assets/vendor-radix-ui-react-focus-scope-C2K7lNPv.js","assets/vendor-radix-ui-react-portal-xlJWBfDg.js","assets/vendor-radix-ui-react-presence-Btn-Dp7L.js","assets/vendor-radix-ui-react-focus-guards-D5MZ0nQs.js","assets/vendor-react-remove-scroll-CfeMe0DL.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-C9YRs2nU.js","assets/vendor-react-style-singleton-B1H4bWSG.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-C-AuTczP.js","assets/vendor-use-callback-ref-CJB0R85I.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-E2vgV9K3.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-codemirror-view-DSzLbZiS.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-BUlYhQ3o.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-BS2SpSAZ.js","assets/vendor-codemirror-lang-json-CqayksDf.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-Ba8JZ6fp.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-DK27qQri.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-CvO36Y1p.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-C7_BPMCr.js","assets/vendor-codemirror-lang-python-_2bIYTiJ.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-RrgJ8H_6.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/vendor-tanstack-react-virtual-IrbCBGJ4.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-DJASDzNt.js","assets/vendor-motion-dom-DJLgZh4Q.js","assets/vendor-motion-utils-BGh8QBgx.js","assets/vendor-sonner-CW8w438f.js","assets/computeVirtualFileMetrics-B1uVA58l.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-BmJyTmjJ.js","assets/vendor-pierre-theming-C6Z4M5_u.js","assets/vendor-shikijs-engine-javascript-Cme4830A.js","assets/vendor-oniguruma-to-es-DLBnFDCE.js","assets/vendor-oniguruma-parser-C0D4_9rT.js","assets/vendor-regex-BBWcyTkg.js","assets/vendor-regex-utilities-2BQyy0xI.js","assets/vendor-regex-recursion-JU4mF-dD.js","assets/vendor-shikijs-transformers-CZWsLLKm.js","assets/isFilePlainText-B2wwrpRU.js","assets/isDiffPlainText-DLDFLL6P.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-B-cPXHXW.js","assets/appThemeRegistry-BK0dHKa6.js","assets/registerCustomTheme-BBXUCRnG.js","assets/vendor-ghostty-web-CrxinGGH.js","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/SessionSwitcherDropdown-Cx-Jfmvo.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as Ps}from"./vendor-vite-runtime-DD1OZmLC.js";import{r as Xe,j as t,R as o}from"./vendor-react-DYyjh7Q0.js";import{a_ as $s,a$ as kc,ai as Cc,o as Xi,D as as,n as ls,q as hs,I as j,ar as Is,b0 as zo,B as Ve,ap as pn,T as st,l as nt,m as rt,b1 as Zi,b2 as Nc,b3 as Ac,b4 as Ic,b5 as Dc,g as Fe,b6 as Pc,b7 as $o,b8 as Ec,b9 as Tc,ba as Uo,bb as Rc,bc as Mc,bd as Fc,be as Lc,bf as Ir,bg as Oc,t as le,am as qt,an as Jt,ao as Xt,R as Ws,bh as Bc,bi as _c,bj as zc,bk as $c,bl as Go,W as _t,bm as Uc,bn as Gc,bo as Kc,bp as Hc,bq as Wc,br as Vc,bs as Dr,bt as ea,bu as ta,bv as Yc,bw as Qc,bx as qc,by as Jc,bz as Xc,bA as Zc,aO as Pr,r as Gs,aQ as Ts,aT as ed,aU as td,aV as sd,aW as nd,aX as ar,aY as Zs,bB as Ko,as as kt,b as $t,aJ as Ms,bC as sa,p as Ss,s as Fs,v as Ls,bD as rd,bE as nn,bF as od,bG as Qs,a2 as en,bH as lr,bI as Ho,bJ as Wo,bK as an,av as id,aK as na,aA as Vo,ay as ad,ax as ld,aN as ra,f as eo,bL as cd,e as to,w as qn,C as oa,bM as dd,bN as Wt,aF as ia,c as Er,bO as ud,bP as fd,bQ as Jn,bR as Yo,aP as aa,bS as la,bT as ca,z as hd,bU as so,bV as pd,bW as md,h as da,j as gd,bX as xd,bY as bd,i as yd,bZ as Tr,b_ as ua,b$ as vd,c0 as wd,d as Sd,c1 as jd,a as kd,aq as Cd,aS as Nd,c2 as fa,c3 as Ad,c4 as Id,aR as Dd,c5 as Pd,c6 as Ed,a8 as Td,c7 as Rd,aG as Md,c8 as Fd,c9 as Ld,ca as Nn,cb as Qo,cc as Od,cd as qo,ce as Jo,cf as Bd,aE as ha,U as _d,x as zd,cg as pa,u as $d,ch as Ud,ci as Gd,at as Vs,k as Kd,cj as Hd,ck as ma,cl as Wd,cm as ga,cn as Vd,co as Yd}from"./WindowsWindowControls-CCnU0ckO.js";import{V as Xo,W as Qd,X as Zo,Y as qd,i as Jd,Z as Xd,P as Zd,r as es,_ as mn,b as eu,m as B,O as vs,u as ce,$ as tu,a0 as ds,a1 as no,t as ro,n as ws,a2 as Je,a3 as Rs,a4 as oo,a5 as io,a6 as su,a7 as nu,F as ru,a8 as ou,a9 as iu,aa as au,ab as lu,ac as is,ad as ei,ae as Rr,a as Xn,af as cu,ag as du,Q as ao,R as ln,ah as uu,ai as fu,aj as xa,A as hu,N as ba,G as cn,ak as Mr,e as Fr,d as An,al as pu,am as mu,an as tn,ao as cr,ap as ya,E as gu,q as xu,aq as Lr,ar as Ds,as as ti,at as Or,au as va,av as Br,aw as bu,ax as yu,ay as vu,az as wu,aA as Su,aB as ju,aC as ku,x as Cu,aD as Nu,aE as Au,aF as si}from"./index-CcbDTf8Q.js";import{d as Iu,g as wa,r as Du,e as Sa,h as Ln,i as ja,b as dn,c as un,s as Pu,j as Eu,k as Tu,l as ni,m as Zn,a as Ru,S as Mu,f as Fu,t as Lu,n as Ou}from"./SessionUnreadDot-CKe4uVcf.js";import{C as ka,a as Ca,M as _r,b as zr,c as $r,d as Na,S as Aa,D as Bu,e as _u,f as zu,g as $u,h as Uu,i as Gu,j as Ku,k as Hu,l as Wu}from"./vendor-base-ui-DL8r2fgQ.js";import{c as ps,d as Ia,p as lo,u as Ur,a as Vu}from"./vendor-zustand-CnsBKjP5.js";import{u as Yu}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{c as er,d as gn,P as co,D as tr,e as sr,f as Da,b as Qu,a as qu,T as Ju,M as Xu}from"./vendor-dnd-kit-core-GipZW2tY.js";import{S as uo,v as Pa,u as fo,a as Zu,h as ef}from"./vendor-dnd-kit-sortable-Ct2QxIHb.js";import{C as ho}from"./vendor-dnd-kit-utilities-CrOcp0Bp.js";import{usePermissionStore as tf}from"./permissionStore-BRcQ9Jgt.js";const sf="chat";function Ea(e){const s=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&s.set($s.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return s.set($s.SETTINGS,n),s}return e.tab!==sf&&s.set($s.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&s.set($s.FILE,e.diffFile),s}function nf(e,s){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,i=e.toString();return i?`${r}?${i}`:r}function rf(e){if(typeof window>"u")return!0;try{const s=new URLSearchParams(window.location.search),n=Ea(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),i=r?.[1]?decodeURIComponent(r[1].trim()):null;i&&!s.has($s.SESSION)&&s.set($s.SESSION,i);const a=[...s.entries()].sort((c,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(a.length!==l.length)return!1;for(let c=0;c<a.length;c++)if(a[c][0]!==l[c][0]||a[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function Gr(e,s={}){if(!(typeof window>"u")&&!(!s.force&&rf(e)))try{const n=Ea(e),r=nf(n);s.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const of=["typescript","javascript","tsx","jsx","json","markdown"],Ta={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let ri=null;const Ra=()=>(ri??=Promise.all([Ps(()=>import("./index-BA67uOfZ.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109])),Ps(()=>import("./workerFactory-tw7cIdmV.js"),[]),Ps(()=>import("./appThemeRegistry-BK0dHKa6.js"),__vite__mapDeps([110,111,97,98,11,82,83,84,85,86,87,88,89,90,91,92,93,94,95]))]).then(([e,s,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:s.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),ri),xn={},oi=new Set,Kr=new Set;let On={light:"pierre-light",dark:"pierre-dark"};const af=()=>{for(const e of Kr)e()},Ma=(e,s)=>{s.setRenderOptions({theme:On,lineDiffType:Ta[e].lineDiffType})},Hr=e=>{typeof window>"u"||oi.has(e)||(oi.add(e),Ra().then(s=>{if(xn[e])return;const n=Ta[e],r=new s.WorkerPoolManager({workerFactory:s.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:of,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),xn[e]=r,Ma(e,r),af()}))},lf=e=>(Kr.add(e),()=>Kr.delete(e)),cf=e=>{if(!(On.light===e.light&&On.dark===e.dark)){On=e;for(const s of Object.keys(xn)){const n=xn[s];n&&Ma(s,n)}}},lx=({children:e})=>{const s=kc(),n=Xo(!1),r=Xo(!0),i=s?.lightThemeId??n.metadata.id,a=s?.darkThemeId??r.metadata.id,l=s?.availableThemes.find(d=>d.metadata.id===i)??n,c=s?.availableThemes.find(d=>d.metadata.id===a)??r;return Xe.useEffect(()=>{let d=!1;return Ra().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),cf({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Xe.useEffect(()=>{if(typeof window>"u")return;const d=()=>{Hr("unified"),Hr("split")};if(typeof window.requestIdleCallback=="function"){const p=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(p)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),t.jsx(t.Fragment,{children:e})},cx=(e="unified")=>{const s=Xe.useSyncExternalStore(lf,()=>xn[e],()=>{});return Xe.useEffect(()=>{Hr(e)},[e]),s};function df(){if(typeof window>"u")return"unknown";try{const{deviceType:e}=Cc();return e}catch{return"unknown"}}function uf(){const e=typeof window<"u"?window.__PICHAMBER_ELECTRON__?.arch?.toLowerCase?.():void 0;if(e==="arm64"||e==="aarch64")return"arm64";if(e==="x64"||e==="amd64"||e==="x86_64")return"x64";const n=(typeof navigator<"u"?navigator.userAgentData:void 0)?.architecture?.toLowerCase?.();if(n==="arm"||n==="arm64"||n==="aarch64")return"arm64";if(n==="x86"||n==="x64"||n==="amd64")return"x64";const r=typeof navigator<"u"?navigator.userAgent.toLowerCase():"";return r.includes("aarch64")||r.includes("arm64")||r.includes("armv")?"arm64":r.includes("x86_64")||r.includes("x64")||r.includes("amd64")||r.includes("win64")?"x64":"unknown"}function ff(){const e=eu();if(e==="android"||e==="ios")return e;if(typeof navigator>"u")return"web";const s=(navigator.platform||"").toLowerCase();return s.includes("mac")?"macos":s.includes("win")?"windows":s.includes("linux")?"linux":"web"}function hf(e){const s=new URLSearchParams;return s.set("deviceClass",df()),s.set("arch",uf()),s.set("platform",ff()),e==="desktop"?(s.set("appType","desktop-electron"),s.set("instanceMode",mn()?"local":"remote"),s):e==="mobile"?(s.set("appType","mobile-capacitor"),s.set("instanceMode","remote"),s):(s.set("appType","web"),s.set("instanceMode","unknown"),s)}async function dr(e,s){try{const n=hf(e);s&&n.set("currentVersion",s);const r=await es(`/api/pi/update-check?${n.toString()}`,{method:"GET",headers:{Accept:"application/json"},priority:"low"});if(!r.ok)throw new Error(`Server responded with ${r.status}`);const i=await r.json();return{available:i.available??!1,version:i.version,currentVersion:i.currentVersion??"unknown",body:i.body,releaseUrl:i.releaseUrl,downloadUrl:i.downloadUrl,nextSuggestedCheckInSec:typeof i.nextSuggestedCheckInSec=="number"&&Number.isFinite(i.nextSuggestedCheckInSec)?i.nextSuggestedCheckInSec:void 0,packageManager:i.packageManager,updateCommand:i.updateCommand}}catch(n){return console.warn("Failed to check for updates:",n),null}}function pf(){return Jd()?"mobile":Xd()?"desktop":Zd()?"web":null}const ii={checking:!1,available:!1,downloading:!1,downloaded:!1,info:null,progress:null,error:null,runtimeType:null,lastChecked:null,nextCheckInSec:null},Bn=ps()((e,s)=>({...ii,checkForUpdates:async()=>{const n=pf();if(!n)return null;e({checking:!0,error:null,runtimeType:n});try{let r=null,i=null;if(n==="desktop"){const a="0.7.2",[l,c]=await Promise.allSettled([Zo(),dr("desktop",a)]),d=l.status==="fulfilled"?l.value:null;return i=c.status==="fulfilled"?c.value?.nextSuggestedCheckInSec??null:null,e({checking:!1,available:d?.available??!1,info:d,lastChecked:Date.now(),nextCheckInSec:i}),i}else n==="web"?(r=await dr("web"),i=r?.nextSuggestedCheckInSec??null):n==="mobile"&&(r=await dr("mobile","0.7.2"),i=r?.nextSuggestedCheckInSec??null);return e({checking:!1,available:r?.available??!1,info:r,lastChecked:Date.now(),nextCheckInSec:i}),i}catch(r){return e({checking:!1,error:r instanceof Error?r.message:"Failed to check for updates"}),null}},downloadUpdate:async()=>{const{available:n,runtimeType:r}=s();if(!(r!=="desktop"||!n)){e({downloading:!0,error:null,progress:null});try{const i=await Zo();if(!i?.available)throw new Error("Update detected, but desktop package is not ready yet. Retry in a moment.");if(e(l=>({info:l.info?{...l.info,...i,body:l.info.body||i.body,available:l.info.available}:i})),!await qd(l=>{e({progress:l})}))throw new Error("Desktop update only works on Local instance");e({downloading:!1,downloaded:!0})}catch(i){e({downloading:!1,error:i instanceof Error?i.message:"Failed to download update"})}}},restartToUpdate:async()=>{const{downloaded:n,runtimeType:r}=s();if(!(r!=="desktop"||!n))try{if(!await Qd())throw new Error("Desktop restart only works on Local instance")}catch(i){e({error:i instanceof Error?i.message:"Failed to restart"})}},dismiss:()=>{e({available:!1,downloaded:!1,info:null})},reset:()=>{e(ii)}})),ai="https://github.com/RyderAsKing/PiChamber/releases";function mf(e){const s=new Date(`${e}T00:00:00`);return Number.isNaN(s.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(s)}function gf(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function li(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function xf(e,s){const n=e.split(".").map(i=>Number.parseInt(i,10)),r=s.split(".").map(i=>Number.parseInt(i,10));for(let i=0;i<3;i+=1){const a=Number.isFinite(n[i])?n[i]:0,l=Number.isFinite(r[i])?r[i]:0;if(a!==l)return l-a}return 0}function bf(e){const s=/^## \[(\d+\.\d+\.\d+)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=s.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((i,a)=>{const l=n[a+1]?.start??e.length,c=e.slice(i.start,l).trim();return{version:i.version,date:i.date,start:i.start,end:l,raw:c}})}const ci=2e3,yf=600*1e3;async function vf(){try{const e=await es("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});return e.ok?{success:!0,autoRestart:(await e.json().catch(()=>({}))).autoRestart!==!1}:{success:!1,error:(await e.json().catch(()=>({}))).error||`Server error: ${e.status}`}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function wf(){try{return(await es("/health",{method:"GET",headers:{Accept:"application/json"}})).ok}catch{return!1}}async function Sf(e,s=Math.ceil(yf/ci),n=ci){for(let r=0;r<s;r++){try{const i=await es("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);if(a&&a.available===!1||a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.currentVersion!==e)return!0}else if((i.status===401||i.status===403)&&await wf())return!0}catch{}await new Promise(i=>setTimeout(i,n))}return!1}const Fa=({open:e,onOpenChange:s,info:n,downloading:r,downloaded:i,progress:a,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[p,h]=Xe.useState(!1),[x,m]=Xe.useState("idle"),[f,g]=Xe.useState(null),S=n?.version?n.releaseUrl||`${ai}/tag/v${n.version}`:ai,k=n?.downloadUrl||S,_=a?.total?Math.round(a.downloaded/a.total*100):0,A=u==="web",b=u==="mobile",v=n?.updateCommand||"pichamber update";Xe.useEffect(()=>{e||(m("idle"),g(null))},[e]);const M=async()=>{(await pn(v)).ok&&(h(!0),setTimeout(()=>h(!1),2e3))},N=Xe.useCallback(async G=>{await Xi(G)},[]),C=Xe.useCallback(async()=>{m("updating"),g(null);const G=await vf();if(!G.success){m("error"),g(G.error||"Update failed");return}G.autoRestart&&(m("restarting"),await new Promise(Z=>setTimeout(Z,2e3))),m("reconnecting"),await Sf(n?.currentVersion)?window.location.reload():(m("error"),g("Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update"))},[n?.currentVersion]),I=Xe.useCallback(()=>{N(k)},[N,k]),D=x!=="idle"&&x!=="error",P=Xe.useMemo(()=>{if(!n?.body)return null;const G=n.body.trim();if(!G)return null;const ee=bf(G);return ee.length===0?{kind:"raw",title:"What's new",content:li(G)}:{kind:"sections",title:"What's new",sections:[...ee].sort((te,U)=>xf(te.version,U.version)).map(te=>({version:te.version,dateLabel:mf(te.date),content:li(gf(te.raw)||G)}))}},[n?.body]);return t.jsx(as,{open:e,onOpenChange:D?void 0:s,children:t.jsxs(ls,{className:"max-w-4xl p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[t.jsxs("div",{className:"flex items-center mb-1",children:[t.jsxs(hs,{className:"flex items-center gap-2.5",children:[t.jsx(j,{name:"download-cloud",className:"h-5 w-5 text-[var(--primary-base)]"}),t.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="reconnecting"?"Updating PiChamber...":"Update Available"})]}),(n?.currentVersion||n?.version)&&t.jsxs("div",{className:"flex items-center gap-2 font-mono text-sm ml-3",children:[n?.currentVersion&&t.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&n?.version&&t.jsx("span",{className:"text-muted-foreground/50",children:"→"}),n?.version&&t.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:n.version})]})]}),t.jsxs("div",{className:"space-y-2",children:[A&&D&&t.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(j,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),t.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="reconnecting"&&"Waiting for server..."]})]}),t.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),P&&!D&&t.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:t.jsx(Is,{className:"max-h-[400px] p-0",fillContainer:!1,children:P.kind==="raw"?t.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:G=>{const Z=G.target.closest("a");Z&&Z.href&&(G.preventDefault(),G.stopPropagation(),N(Z.href))},children:t.jsx(zo,{content:P.content,disableLinkSafety:!0,enableFileReferences:!1})}):t.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:P.sections.map(G=>t.jsxs("div",{className:"p-4",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[t.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",G.version]}),t.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:G.dateLabel})]}),t.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:ee=>{const te=ee.target.closest("a");te&&te.href&&(ee.preventDefault(),ee.stopPropagation(),N(te.href))},children:t.jsx(zo,{content:G.content,disableLinkSafety:!0,enableFileReferences:!1})})]},G.version))})})}),A&&x==="error"&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[t.jsx(j,{name:"terminal",className:"h-4 w-4"}),t.jsx("span",{children:"Or update via terminal:"})]}),t.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[t.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:v}),t.jsx("button",{onClick:M,className:B("flex items-center justify-center p-2 rounded","text-muted-foreground hover:text-foreground hover:bg-[var(--interactive-hover)]","transition-colors",p&&"text-[var(--status-success)]"),title:p?"Copied!":"Copy command",children:p?t.jsx(j,{name:"check",className:"h-4 w-4"}):t.jsx(j,{name:"clipboard",className:"h-4 w-4"})})]})]}),!A&&!b&&r&&t.jsxs("div",{className:"space-y-2 mt-4",children:[t.jsxs("div",{className:"flex items-center justify-between text-sm",children:[t.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),t.jsxs("span",{className:"font-mono text-foreground",children:[_,"%"]})]}),t.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${_}%`}})})]}),(l||f)&&t.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:t.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||f})})]}),t.jsxs("div",{className:"mt-4 flex items-center justify-between gap-4",children:[t.jsxs("a",{href:S,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[t.jsx(j,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),t.jsxs("div",{className:"flex-1 flex justify-end",children:[!A&&!b&&!i&&!r&&t.jsxs("button",{onClick:c,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(j,{name:"download",className:"h-4 w-4"}),"Download Update"]}),!A&&!b&&r&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(j,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!A&&!b&&i&&t.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[t.jsx(j,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),b&&t.jsxs(Ve,{onClick:I,size:"default",children:[t.jsx(j,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),A&&!D&&t.jsxs("button",{onClick:C,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)] text-[var(--primary-foreground)] hover:opacity-90 transition-opacity",children:[t.jsx(j,{name:"download",className:"h-4 w-4"}),"Update Now"]}),A&&D&&t.jsxs("button",{disabled:!0,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--primary-base)]/50 text-[var(--primary-foreground)] cursor-not-allowed",children:[t.jsx(j,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},jf=o.memo(function({checked:s,onChange:n,disabled:r=!1,ariaLabel:i,className:a,iconClassName:l}){const c=o.useCallback(u=>{u.preventDefault(),u.stopPropagation(),!r&&!s&&n()},[s,r,n]),d=o.useCallback(u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),!r&&!s&&n())},[s,r,n]);return t.jsx("button",{type:"button",role:"radio",onClick:c,onKeyDown:d,disabled:r,"aria-checked":s,"aria-label":i,className:B("group/radio relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full outline-none","transition-[background-color,box-shadow] duration-200 ease-out",s?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none hover:bg-[var(--primary-base)]":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)] hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",a),children:t.jsx("span",{"aria-hidden":!0,className:B("block h-[5px] w-[5px] rounded-full bg-white",!s&&"opacity-0",l)})})}),bn=({children:e,className:s,contentClassName:n})=>{const[r,i]=o.useState(!1),a=o.useRef(null);return o.useEffect(()=>{if(!r)return;const l=c=>{const d=a.current;d&&c.target instanceof Node&&d.contains(c.target)||i(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),t.jsxs(st,{open:r,onOpenChange:i,children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{ref:a,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),i(c=>!c)},className:B("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",s),children:t.jsx(j,{name:"information",className:"h-3.5 w-3.5"})})}),t.jsx(rt,{sideOffset:8,className:B("max-w-sm",n),children:e})]})},dx="w-full min-w-40 max-w-48",kf="settings",Cf="w-full min-w-40 max-w-48",ux="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",Nf="w-full max-w-[24rem]",fx="min-w-0 flex-1",hx="flex w-full min-w-0 items-center gap-2",px="typography-meta shrink-0 text-muted-foreground tabular-nums",La="space-y-3.5",Af="space-y-1.5",mx="typography-settings-page-title text-muted-foreground",If="typography-settings-section-title text-foreground",gx="typography-settings-section-title text-foreground",Oa="typography-settings-group-title text-foreground",po="typography-settings-field-label text-foreground",Df="typography-settings-description text-muted-foreground",yn="typography-meta text-muted-foreground",xx="typography-meta font-medium text-foreground",bx="typography-settings-section-title text-foreground",Pf=({title:e,description:s,titleAccessory:n,info:r,headerAction:i,children:a,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const p=e!=null||s!=null||i!=null||r!=null;return t.jsxs("section",{"data-settings-item":u,className:B("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[p?t.jsxs("div",{className:"flex items-start justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?t.jsx("h2",{className:If,children:e}):e,n,r!=null?t.jsx(bn,{children:r}):null]}):null,s!=null?t.jsx("div",{className:Df,children:s}):null]}),i?t.jsx("div",{className:"shrink-0",children:i}):null]}):null,t.jsx("div",{className:B(d),children:a})]})},yx=({children:e,className:s})=>t.jsx("div",{className:B("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",s),children:e}),Ef=({children:e,className:s,as:n="h3"})=>t.jsx(n,{className:B(Oa,s),children:e}),vx=({title:e,description:s,info:n,children:r,className:i,contentClassName:a,settingsItem:l})=>t.jsxs("div",{"data-settings-item":l,className:B("space-y-2",i),children:[e!=null||s!=null||n!=null?t.jsxs("div",{className:"space-y-0.5",children:[e!=null?t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Ef,{children:e}),n!=null?t.jsx(bn,{children:n}):null]}):null,s!=null?t.jsx("p",{className:yn,children:s}):null]}):null,t.jsx("div",{className:B(a),children:r})]}),Us=({label:e,description:s,info:n,descriptionPlacement:r="before",children:i,settingsItem:a,className:l,controlClassName:c})=>{const d=s!=null?t.jsx("p",{className:yn,children:s}):null;return t.jsxs("div",{"data-settings-item":a,className:B("space-y-2",l),children:[t.jsxs("div",{className:"space-y-0.5",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:po,children:e}),n!=null?t.jsx(bn,{children:n}):null]}),r==="before"?d:null]}),t.jsx("div",{className:B("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:i}),r==="after"?d:null]})},wx=({label:e,description:s,info:n,children:r,settingsItem:i,className:a,controlClassName:l,alignEnd:c=!0})=>t.jsxs("div",{"data-settings-item":i,className:B("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",a),children:[t.jsxs("div",{className:"min-w-0 @xl:w-56 @xl:shrink-0",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("div",{className:po,children:e}),n!=null?t.jsx(bn,{children:n}):null]}),s!=null?t.jsx("p",{className:B(yn,"mt-0.5"),children:s}):null]}),t.jsx("div",{className:B("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",c&&"@xl:justify-end",l),children:r})]}),Sx=({children:e,className:s,settingsItem:n})=>t.jsx("div",{"data-settings-item":n,className:B("pt-4",s),children:e}),Tf=({checked:e,onChange:s,label:n,description:r,disabled:i=!1,ariaLabel:a,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const p=()=>{i||s(!e)},h=r!=null;return t.jsxs("div",{"data-settings-item":l,className:B("group flex cursor-pointer gap-2 py-0.5",h?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:i?-1:0,"aria-pressed":e,"aria-disabled":i||void 0,onClick:p,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),p())},children:[t.jsx(Zi,{checked:e,onChange:s,disabled:i,ariaLabel:a}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[t.jsx("span",{className:po,children:n}),d,u!=null?t.jsx(bn,{children:u}):null]}),h?t.jsx("span",{className:yn,children:r}):null]})]})},jx=({selected:e,onSelect:s,label:n,description:r,ariaLabel:i,disabled:a=!1,className:l})=>t.jsxs("div",{className:B("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",a&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:a?-1:0,"aria-pressed":e,"aria-disabled":a||void 0,onClick:()=>{a||s()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),a||s())},children:[t.jsx(jf,{checked:e,onChange:s,disabled:a,ariaLabel:i,className:r!=null?"mt-0.5":void 0}),t.jsxs("div",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:B("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?t.jsx("span",{className:yn,children:r}):null]})]}),kx=({"aria-label":e,children:s,className:n})=>t.jsx("div",{role:"radiogroup","aria-label":e,className:B(Af,n),children:s});function Cx({value:e,options:s,onChange:n,className:r,"aria-label":i}){return t.jsx("div",{role:"group","aria-label":i,className:B("flex flex-wrap items-center gap-1",r),children:s.map(a=>t.jsx(Ve,{type:"button",variant:"chip",size:"xs",disabled:a.disabled,"aria-pressed":e===a.value,className:"!font-normal",onClick:()=>n(a.value),children:a.label},a.value))})}class Rf extends o.Component{constructor(s){super(s),this.state={hasError:!1}}static getDerivedStateFromError(s){return{hasError:!0,error:s}}componentDidCatch(s,n){this.setState({error:s,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?t.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:t.jsxs(Nc,{className:"w-full max-w-md",children:[t.jsx(Ac,{className:"text-center",children:t.jsxs(Ic,{className:"flex items-center justify-center gap-2 text-destructive",children:[t.jsx(j,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),t.jsxs(Dc,{className:"space-y-4",children:[t.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&t.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&t.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[t.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),t.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),t.jsx("div",{className:"flex gap-2",children:t.jsxs(Ve,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[t.jsx(j,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),t.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Mf(e){return t.jsx(Rf,{...e,texts:{title:"Chat Error",description:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.",sessionLabel:"Session",detailsSummary:"Error details",resetAction:"Reset Chat",persistentHint:"If the problem persists, try refreshing the page."}})}const Nx=({active:e=!0})=>{const s=Fe(n=>n.currentSessionId);return t.jsx(Mf,{sessionId:s||void 0,children:t.jsx(Pc,{active:e},s??"no-session")})};function Ff({onResizeStart:e,ariaLabel:s}){return t.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":s,onPointerDown:e,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:t.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:t.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const mo=Xe.forwardRef(({className:e,outerClassName:s,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:i=!1,scrollShadowSize:a,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:p,endSlot:h,...x},m)=>{const f=Xe.useRef(null),g=Xe.useRef(null),[S,k]=Xe.useState(null),_=c??S,A=Xe.useCallback(v=>{const M=f.current;if(!M)return;g.current={startY:v.clientY,startHeight:M.getBoundingClientRect().height};const N=v.currentTarget;N.setPointerCapture(v.pointerId);const C=D=>{const P=g.current;if(!P)return;const G=P.startHeight+(D.clientY-P.startY),ee=Math.max(82,G);d?d(ee):k(ee)},I=()=>{g.current=null,N.removeEventListener("pointermove",C),N.removeEventListener("pointerup",I),N.removeEventListener("pointercancel",I)};N.addEventListener("pointermove",C),N.addEventListener("pointerup",I),N.addEventListener("pointercancel",I),v.preventDefault()},[d]),b=Xe.useCallback(v=>{if(v.target.closest('textarea, button, [role="separator"]'))return;const N=f.current?.querySelector("textarea");N&&document.activeElement!==N&&(v.preventDefault(),N.focus())},[]);return p?t.jsx(Is,{as:"textarea",ref:m,disableHorizontal:!0,fillContainer:r,useScrollShadow:i,scrollShadowSize:a,outerClassName:s,scrollbarClassName:n,className:B("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}):t.jsx("div",{ref:f,onPointerDown:b,style:_!==null?{height:`${_}px`}:void 0,className:B("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],s),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[t.jsx("textarea",{ref:m,className:B("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}),t.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[h,t.jsx(Ff,{onResizeStart:A,ariaLabel:"Resize textarea"})]})]})})});mo.displayName="Textarea";const di=(e,s)=>s.updatedAtMs-e.updatedAtMs,Kn=ps((e,s)=>({instances:[],statusesById:{},importCandidates:[],isLoading:!1,isSaving:!1,isImportsLoading:!1,initialized:!1,listenerReady:!1,error:null,load:async()=>{if(!s().isLoading){e({isLoading:!0,error:null});try{const[n,r]=await Promise.all([Mc(),Uo()]),i={};for(const a of r.sort(di))i[a.id]=a;s().listenerReady||await Fc(a=>{e(l=>({statusesById:{...l.statusesById,[a.id]:a}}))}),e({instances:n.instances,statusesById:i,isLoading:!1,initialized:!0,listenerReady:!0})}catch(n){e({isLoading:!1,error:n instanceof Error?n.message:String(n)})}}},loadImports:async()=>{if(!s().isImportsLoading){e({isImportsLoading:!0,error:null});try{const n=await Rc();e({importCandidates:n,isImportsLoading:!1})}catch(n){e({isImportsLoading:!1,error:n instanceof Error?n.message:String(n)})}}},refreshStatuses:async()=>{try{const n=await Uo(),r={};for(const i of n.sort(di))r[i.id]=i;e({statusesById:r})}catch(n){e({error:n instanceof Error?n.message:String(n)})}},setInstances:async n=>{e({isSaving:!0,error:null});try{await Tc({instances:n}),e({instances:n,isSaving:!1}),await s().refreshStatuses()}catch(r){throw e({isSaving:!1,error:r instanceof Error?r.message:String(r)}),r}},upsertInstance:async n=>{const r=s().instances,i=r.some(a=>a.id===n.id)?r.map(a=>a.id===n.id?n:a):[n,...r];await s().setInstances(i)},createFromCommand:async(n,r,i)=>{const a=Lc(n,r);i&&i.trim()&&(a.nickname=i.trim()),await s().upsertInstance(a)},removeInstance:async n=>{await $o(n).catch(()=>{});const r=s().instances.filter(i=>i.id!==n);await s().setInstances(r),e(i=>{const a={...i.statusesById};return delete a[n],{statusesById:a}})},connect:async n=>{e({error:null});try{await Ec(n),await s().refreshStatuses()}catch(r){throw e({error:r instanceof Error?r.message:String(r)}),r}},disconnect:async n=>{e({error:null});try{await $o(n),await s().refreshStatuses()}catch(r){throw e({error:r instanceof Error?r.message:String(r)}),r}},retry:async n=>{await s().connect(n)},getStatus:n=>s().statusesById[n]||null,clearError:()=>e({error:null})})),Ba=[{key:"play",label:"Play",Icon:"play"},{key:"build",label:"Build",Icon:"hammer"},{key:"lint",label:"Lint",Icon:"checkbox-circle"},{key:"terminal",label:"Terminal",Icon:"terminal-box"},{key:"tools",label:"Tools",Icon:"tools"},{key:"bug",label:"Bug",Icon:"bug"},{key:"flask",label:"Flask",Icon:"flask"},{key:"rocket",label:"Rocket",Icon:"rocket"},{key:"code",label:"Code",Icon:"code"},{key:"server",label:"Server",Icon:"server"},{key:"branch",label:"Branch",Icon:"git-branch"},{key:"search",label:"Search",Icon:"search"},{key:"settings",label:"Settings",Icon:"settings-3"},{key:"brain",label:"Brain",Icon:"brain-ai-3"},{key:"stack",label:"Stack",Icon:"stack"},{key:"robot",label:"Robot",Icon:"robot-2"},{key:"command",label:"Command",Icon:"command"},{key:"file",label:"File",Icon:"file-text"}],fn=Object.fromEntries(Ba.map(e=>[e.key,e.Icon])),Wr="pichamber:project-actions-updated",_a=e=>{const s=(e||"").trim().replace(/\\/g,"/");return s?s==="/"?"/":s.length>1?s.replace(/\/+$/,""):s:""},us=(e,s)=>`${_a(e)}::${s}`,Lf=e=>{const s=e.trim();return!s||s==="0.0.0.0"||s==="::"?"127.0.0.1":s},ui=e=>{if(typeof e!="number"||!Number.isFinite(e))return null;const s=Math.round(e);return s<1||s>65535?null:s},Of=(e,s)=>{if(!s.enabled||s.type!=="local")return null;const n=ui(s.localPort),r=ui(s.remotePort);if(!n||!r)return null;const i=Lf(s.localHost||e.localForward.bindHost||"127.0.0.1"),a=(s.remoteHost||"127.0.0.1").trim(),l=(e.nickname||e.id||"instance").trim();return{id:`${e.id}::${s.id}`,label:`${l} - ${i}:${n} -> ${a}:${r}`,url:`http://${i}:${n}`}},za=e=>{const s=[];for(const n of e)if(!(!n?.id||!Array.isArray(n.portForwards)))for(const r of n.portForwards){const i=Of(n,r);i&&s.push(i)}return s},Bf=(e,s)=>{const n=(e||"").trim();return n&&za(s).find(a=>a.id===n)?.url||null},_f=Nf,$a=({title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,children:l,className:c,contentClassName:d,divider:u=!0})=>t.jsx(Pf,{title:e,description:s,info:n,settingsItem:r,titleAccessory:i,headerAction:a,divider:u,className:c,contentClassName:d,children:l}),Vr=e=>e.name.trim().length>0&&e.command.trim().length>0,zf=e=>e.name.trim().length===0&&e.command.trim().length===0,$f=e=>!Vr(e)&&!zf(e),Uf=(e,s)=>e.some(r=>s.has(r.id)&&!Vr(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(Vr)},Gf=450,Kf=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Hf=()=>({id:Kf(),name:"",command:"",icon:"play"}),Wf=({projectRef:e})=>{const s=o.useMemo(()=>vs(),[]),n=Kn(v=>v.instances),r=Kn(v=>v.load),[i,a]=o.useState([]),[l,c]=o.useState(!1),[d,u]=o.useState(null),[p,h]=o.useState(new Set),x=o.useRef(!1);o.useEffect(()=>{s&&r().catch(()=>{})},[s,r]),o.useEffect(()=>{let v=!1;return c(!0),(async()=>{try{const M=await Ir(e);if(v)return;a(M.actions),u(JSON.stringify({actions:M.actions})),h(new Set(M.actions.map(N=>N.id)))}catch{if(v)return;a([]),u(JSON.stringify({actions:[]})),h(new Set)}finally{v||c(!1)}})(),()=>{v=!0}},[e]);const m=o.useMemo(()=>s?za(n):[],[n,s]),f=o.useMemo(()=>Uf(i,p),[i,p]),g=o.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),S=d!==null&&f.canPersist&&g!==d,k=o.useCallback(async v=>await Oc(e,{actions:v,primaryActionId:null})?(u(JSON.stringify({actions:v})),h(new Set(v.map(N=>N.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(Wr,{detail:{projectId:e.id}})),!0):(le.error("Failed to save actions"),!1),[e]);o.useEffect(()=>{if(!S||l||x.current)return;const v=window.setTimeout(()=>{x.current||(x.current=!0,(async()=>{try{await k(f.actions)}finally{x.current=!1}})())},Gf);return()=>{window.clearTimeout(v)}},[S,l,k,f.actions]);const _=o.useCallback(()=>{const v=Hf();a(M=>[...M,v])},[]),A=o.useCallback(v=>{a(M=>M.filter(N=>N.id!==v))},[]),b=o.useCallback((v,M)=>{a(N=>N.map(C=>C.id===v?M(C):C))},[]);return t.jsx($a,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:t.jsxs(Ve,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:_,children:[t.jsx(j,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:l?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):i.length===0?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):t.jsx("div",{className:B("space-y-6",_f),children:i.map((v,M)=>{const N=v.icon||"play",C=fn[N]||"play",I=v.name.trim()||`Action ${M+1}`,D=$f(v);return t.jsxs("div",{className:La,children:[t.jsxs("div",{className:"flex items-center justify-between gap-2",children:[t.jsx("h3",{className:Oa,children:I}),t.jsx(Ve,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>A(v.id),"aria-label":`Delete ${I}`,children:t.jsx(j,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),t.jsxs(Us,{label:"Name",controlClassName:"w-full max-w-none",children:[t.jsxs(qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:t.jsx(j,{name:C,className:"h-4 w-4"})})}),t.jsx(Xt,{align:"start",className:"w-56 p-2",children:t.jsx("div",{className:"grid grid-cols-6 gap-1",children:Ba.map(P=>{const G=P.Icon,ee=(v.icon||"play")===P.key;return t.jsx("button",{type:"button",onClick:()=>b(v.id,Z=>({...Z,icon:P.key})),className:B("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",ee&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${P.label}`,children:t.jsx(j,{name:G,className:"h-4 w-4"})},P.key)})})})]}),t.jsx(Ws,{value:v.name,onChange:P=>b(v.id,G=>({...G,name:P.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),t.jsx(Us,{label:"Command",controlClassName:"w-full max-w-none",children:t.jsx(mo,{value:v.command,onChange:P=>b(v.id,G=>({...G,command:P.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),D?t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,t.jsx(Tf,{checked:v.autoOpenUrl===!0,onChange:P=>b(v.id,G=>({...G,...P?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0,desktopOpenSshForward:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${I}`}),v.autoOpenUrl===!0?t.jsxs(t.Fragment,{children:[t.jsx(Us,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:t.jsx(Ws,{value:v.openUrl||"",onChange:P=>b(v.id,G=>({...G,openUrl:P.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})}),s?t.jsx(Us,{label:"Desktop SSH forward",controlClassName:"w-full max-w-none",children:m.length>0?t.jsxs(Bc,{value:v.desktopOpenSshForward&&m.some(P=>P.id===v.desktopOpenSshForward)?v.desktopOpenSshForward:"__none__",onValueChange:P=>{b(v.id,G=>({...G,...P==="__none__"?{desktopOpenSshForward:void 0}:{desktopOpenSshForward:P}}))},children:[t.jsx(_c,{size:kf,className:"w-full",children:t.jsx(zc,{placeholder:"Use output/manual URL"})}),t.jsxs($c,{children:[t.jsx(Go,{value:"__none__",children:"Use output/manual URL"}),m.map(P=>t.jsx(Go,{value:P.id,children:P.label},P.id))]})]}):t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No enabled local SSH forwards available."})}):null]}):null]},v.id)})})})},Vf={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",keyboardHint:"↑↓ navigate",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},Yf=({value:e,noneLabel:s,ariaLabel:n,disabled:r=!1,className:i,isModelAllowed:a,onChange:l})=>{const c=_t(D=>D.providers),d=_t(D=>D.modelsMetadata),u=ce(D=>D.hiddenModels),p=ce(D=>D.providerOrder),h=ce(D=>D.setProviderOrder),x=ce(D=>D.isFavoriteModel),m=ce(D=>D.toggleFavoriteModel),f=ce(D=>D.reorderFavoriteModel),{favoriteModelsList:g,recentModelsList:S}=Uc(),[k,_]=o.useState(!1),[A,b]=o.useState("");o.useEffect(()=>{k||b("")},[k]);const v=e?c.find(D=>D.id===e.providerId):void 0,M=e&&v?(Array.isArray(v.models)?v.models:[]).find(D=>D.id===e.modelId):void 0,N=e?Gc(M,e.modelId):s,C=o.useMemo(()=>e?u.filter(D=>!(D.providerID===e.providerId&&D.modelID===e.modelId)):u,[u,e]),I=o.useCallback(D=>{l({providerId:D.providerID,modelId:D.modelID}),_(!1)},[l]);return t.jsxs(qt,{modal:!1,open:k,onOpenChange:D=>{r||_(D)},children:[t.jsx(Jt,{asChild:!0,disabled:r,children:t.jsxs("button",{type:"button","aria-label":n,disabled:r,className:B(Hc({size:"default"}),Cf,"min-w-0",i),children:[t.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?t.jsx(Kc,{providerId:e.providerId,className:"size-4 shrink-0"}):null,t.jsx("span",{className:B("truncate",e?"text-foreground":"text-muted-foreground"),children:N})]}),t.jsx(j,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),t.jsx(Xt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:t.jsx(Wc,{providers:c,favoriteModels:g,recentModels:S,modelsMetadata:d,searchQuery:A,onSearchQueryChange:b,onSelect:I,labels:{...Vf,notSelected:s},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:C,isModelAllowed:a,includeNotSelected:!0,onSelectNone:()=>{l(null),_(!1)},disabled:r,autoFocus:!0,onEscape:()=>_(!1),isFavorite:D=>x(D.providerID,D.modelID),onToggleFavorite:D=>m(D.providerID,D.modelID),onReorderFavorite:(D,P)=>f(D.providerID,D.modelID,P.providerID,P.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite",providerOrder:p,onReorderProvider:h,reorderProviderTitle:"Drag to reorder provider"})})]})},ur="w-full max-w-none",Qf=({form:e})=>{const{name:s,setName:n,parsedDefaultModel:r,handleDefaultModelChange:i,project:a}=e,l=_t(c=>c.loadProviders);return o.useEffect(()=>{l({source:"projectSettings"})},[l]),a?t.jsx($a,{title:"Project",divider:!1,children:t.jsxs("div",{className:La,children:[t.jsx(Us,{label:"Name",settingsItem:"projects.name",controlClassName:ur,children:t.jsx(Ws,{value:s,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),t.jsx(Us,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:ur,children:t.jsx(Yf,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:ur,onChange:c=>{if(!c){i("","");return}i(c.providerId,c.modelId)}})})]})}):null},qf=e=>{const[s,n]=o.useState(""),[r,i]=o.useState(void 0);o.useEffect(()=>{if(!e){n(""),i(void 0);return}n(e.label??""),i(e.defaultModel)},[e]);const a=o.useMemo(()=>Vc(r),[r]),l=!!e&&(s.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=o.useCallback((u,p)=>{i(u&&p?`${u}/${p}`:void 0)},[]),d=o.useCallback(async()=>{if(!e)return null;const u=s.trim();return u?{label:u,defaultModel:r??null}:null},[r,s,e]);return{name:s,setName:n,defaultModel:r,parsedDefaultModel:a,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},Jf=450,Xf=(e,s)=>{const{hasChanges:n,name:r,defaultModel:i,prepareSaveData:a}=e,l=o.useRef(!1);o.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const d=await a();if(d)try{await s(d)}catch{le.error("Failed to save project settings")}}finally{l.current=!1}})())},Jf);return()=>{window.clearTimeout(c)}},[i,n,r,s,a])},Zf=({project:e,onIdentitySave:s})=>{const n=qf(e),r=o.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),i=o.useCallback(async a=>{await s(a)},[s]);return Xf(n,i),!e||!r?null:t.jsxs("div",{className:"space-y-0",children:[t.jsx(Qf,{form:n}),t.jsx(Wf,{projectRef:r})]})};function eh({...e}){return t.jsx(ka,{...e})}function th({...e}){return t.jsx(Ca,{...e})}function sh({className:e,positionerClassName:s,children:n,style:r,...i}){return t.jsx(_r,{children:t.jsx(zr,{className:B("app-region-no-drag z-50",s),children:t.jsx($r,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:B(Dr,e),...i,children:n})})})}function fi({className:e,...s}){return t.jsx(Na,{className:B(ea,e),...s})}function nh({className:e,...s}){return t.jsx(Aa,{className:B(ta,e),...s})}const As=ps()(Ia(lo((e,s)=>({selectedProfileId:null,defaultGitIdentityId:null,profiles:[],globalIdentity:null,discoveredCredentials:[],isLoading:!1,setSelectedProfile:n=>{e({selectedProfileId:n})},loadProfiles:async()=>{e({isLoading:!0});const n=s().profiles;try{const r=await Zc();return e({profiles:r,isLoading:!1}),!0}catch(r){return console.error("Failed to load git identity profiles:",r),e({profiles:n,isLoading:!1}),!1}},loadGlobalIdentity:async()=>{try{const n=await Xc();if(n&&n.userName&&n.userEmail){const r={id:"global",name:"Global Identity",userName:n.userName,userEmail:n.userEmail,authType:n.sshCommand?"ssh":void 0,sshKey:n.sshCommand?n.sshCommand.replace("ssh -i ",""):null,color:"info",icon:"fingerprint"};e({globalIdentity:r})}else e({globalIdentity:null});return!0}catch(n){return console.error("Failed to load global git identity:",n),e({globalIdentity:null}),!1}},loadDiscoveredCredentials:async()=>{try{const n=await Jc();return e({discoveredCredentials:n}),!0}catch(n){return console.error("Failed to discover git credentials:",n),e({discoveredCredentials:[]}),!1}},loadDefaultGitIdentityId:async()=>{const n=r=>{if(typeof r!="string")return null;const i=r.trim();return i.length>0?i:null};try{let r=null;if(r===null){const i=ro()?.settings;if(i)try{const l=(await i.load())?.settings||{};r=n(l.defaultGitIdentityId)}catch{}}if(r===null)try{const i=await es("/api/pi/ui-settings",{method:"GET",headers:{Accept:"application/json"}});if(i.ok){const a=await i.json().catch(()=>null);r=n(a?.defaultGitIdentityId)}}catch{}return e({defaultGitIdentityId:r}),!0}catch(r){return console.error("Failed to load default git identity setting:",r),!1}},setDefaultGitIdentityId:async n=>{try{const r=typeof n=="string"?n.trim():"",i=r.length>0?r:"";return await no({defaultGitIdentityId:i}),e({defaultGitIdentityId:i.length>0?i:null}),!0}catch(r){return console.error("Failed to save default git identity setting:",r),!1}},createProfile:async n=>{try{const r={...n,id:n.id||`profile-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,color:n.color||"keyword",icon:n.icon||"branch"};return ds("saving"),await qc(r),ds("saved"),await s().loadProfiles(),!0}catch(r){return ds("error"),console.error("Failed to create git identity profile:",r),!1}},updateProfile:async(n,r)=>{try{const i=s().profiles.find(l=>l.id===n);if(!i)throw new Error("Profile not found");const a={...i,...r};return ds("saving"),await Qc(n,a),ds("saved"),await s().loadProfiles(),!0}catch(i){return ds("error"),console.error("Failed to update git identity profile:",i),!1}},deleteProfile:async n=>{try{return ds("saving"),await Yc(n),ds("saved"),s().selectedProfileId===n&&e({selectedProfileId:null}),await s().loadProfiles(),!0}catch(r){return ds("error"),console.error("Failed to delete git identity profile:",r),!1}},getProfileById:n=>{const{profiles:r,globalIdentity:i}=s();return n==="global"?i||void 0:r.find(a=>a.id===n)},getUnimportedCredentials:()=>{const{profiles:n,discoveredCredentials:r}=s();return r.filter(i=>!n.some(a=>a.authType==="token"&&a.host===i.host))}}),{name:"git-identities-store",storage:tu(),partialize:e=>({selectedProfileId:e.selectedProfileId})}),{name:"git-identities-store"}));typeof window<"u"&&(window.__zustand_git_identities_store__=As);const rh=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"]},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","identity","identities","ssh","profiles","credentials","keys","commit","gitmoji","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"magic-prompts",title:"PiChamber Utility Prompts",group:"agent",kind:"split",keywords:["prompts","templates","git","github","review","commit","pull request","utility"],isAvailable:()=>!1},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["prompt","templates","multi-run","strategy","approach"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],oh={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function ih(e){const s=e.trim().toLowerCase();return rh.find(n=>n.slug===s)??null}function ah(e){const s=(e??"").trim().toLowerCase();if(!s)return"home";const n=oh[s];if(n)return n;const r=ih(s);return r?r.slug:"home"}function Ax(e){switch(e){case"general":return"settings-3";case"projects":return"folders";case"remote-instances":return"computer";case"appearance":return"palette";case"chat":return"chat-ai-3";case"dictation":return"mic";case"magic-prompts":return"ai-generate-2";case"snippets":return"chat-thread";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"chat-history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"book-open";case"git":return"git-branch";case"tunnel":return"home-office";case"about":return"information";case"home":return null;default:return"robot-2"}}const In=100;function Ix(){const e=ce(C=>C.isArchivePageOpen),s=ce(C=>C.setArchivePageOpen),n=ce(C=>C.setActiveMainTab),r=Fe(C=>C.setCurrentSession),i=Fe(C=>C.unarchiveSession),a=ws(C=>C.homeDirectory),l=Pr({archived:!0}),[c,d]=o.useState(""),[u,p]=o.useState(null),[h,x]=o.useState(In),m=c.trim().toLowerCase(),f=o.useMemo(()=>e?[...l].sort((C,I)=>(I.time?.archived??0)-(C.time?.archived??0)):[],[l,e]),g=o.useMemo(()=>{const C=new Map;for(const I of f){const D=Je(Gs(I))??"",P=C.get(D);if(P){P.sessions.push(I);continue}C.set(D,{directory:D,label:D?Rs(D,a)||D:"other projects",sessions:[I]})}return[...C.values()].sort((I,D)=>D.sessions.length-I.sessions.length)},[a,f]),S=o.useMemo(()=>m?f.filter(C=>(C.title??"").toLowerCase().includes(m)):u===null?f:g.find(C=>C.directory===u)?.sessions??[],[g,m,u,f]),k=S.slice(0,h),_=S.length-k.length,A=l.length,b=o.useCallback(C=>{p(C),x(In)},[]),v=o.useCallback(C=>{const I=Je(Gs(C));r(C.id,I??void 0),n("chat"),s(!1)},[n,r,s]),M=o.useCallback(C=>{i(C.id).then(I=>{I?le.success("Session restored"):le.error("Failed to restore session")})},[i]);if(!e)return null;const N=(C,I,D,P,G,ee,Z)=>t.jsxs("div",{className:"group/dir relative",children:[t.jsxs("button",{type:"button",onClick:G,title:ee,className:B("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Z?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",P?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[t.jsx("span",{className:"min-w-0 flex-1 truncate",children:I}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:D})]}),Z?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>Ts.requestDelete({sessions:Z,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${I}`,children:t.jsx(j,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),t.jsx(rt,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},C);return t.jsx(Bu,{open:e,onOpenChange:s,children:t.jsxs(_u,{children:[t.jsx(zu,{className:"fixed inset-0 z-50 bg-black/25 dark:bg-black/40 transition-opacity duration-150 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0"}),t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:t.jsxs($u,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[t.jsx(Uu,{className:"sr-only",children:"Archived sessions"}),t.jsx(Gu,{className:"sr-only",children:"Browse and restore archived sessions."}),t.jsx(Ku,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(j,{name:"close",className:"size-4"})}),t.jsxs("div",{className:"flex min-h-0 flex-1",children:[t.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:t.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[N("__all__","All directories",A,u===null,()=>b(null)),g.map(C=>N(C.directory||"__none__",C.label,C.sessions.length,u===C.directory,()=>b(C.directory),C.directory||void 0,C.sessions))]})}),t.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(j,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),t.jsx("input",{value:c,onChange:C=>{d(C.target.value),x(In)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),t.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:S.length===1?`${S.length} archived session`:`${S.length} archived sessions`})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:t.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[k.length===0?t.jsx("div",{className:"py-10 text-center text-muted-foreground",children:t.jsx("p",{className:"typography-ui-label font-semibold",children:m?"No matching archived sessions":"No archived sessions"})}):k.map(C=>{const I=Je(Gs(C))??"",D=I?Rs(I,a)||I:null;return t.jsxs("div",{className:"group relative flex cursor-pointer items-center gap-3 rounded-md py-1 pl-2 pr-2 transition-[padding] hover:bg-interactive-hover/40 hover:pr-14 focus-within:pr-14",onClick:()=>v(C),role:"button",tabIndex:0,onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),v(C))},children:[t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:C.title||"Untitled Session"}),m&&D?t.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:I,children:D}):null,t.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:Iu(C.time?.archived??C.time?.updated??C.time?.created??Date.now())}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),M(C)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${C.title||"Untitled Session"}`,children:t.jsx(j,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),t.jsx("button",{type:"button",onClick:P=>{P.stopPropagation(),Ts.requestDelete({sessions:[C],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${C.title||"Untitled Session"}`,children:t.jsx(j,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},C.id)}),_>0?t.jsx("button",{type:"button",onClick:()=>x(C=>C+In),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const lh=()=>{const[e,s]=Xe.useState(!1),[n,r]=Xe.useState(!1);Xe.useEffect(()=>{s(vs()),r(oo())},[]);const i=Xe.useCallback(async c=>e?await io(c):{success:!0,path:c},[e]),a=Xe.useCallback(async c=>e?await su():{success:!0},[e]),l=Xe.useCallback(async c=>e?await nu():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:i,startAccessing:a,stopAccessing:l}},ch=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),dh=({currentBranch:e,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:i,onCreate:a,remotes:l=[],disabled:c=!1})=>{const[d,u]=o.useState(!1),[p,h]=o.useState(""),[x,m]=o.useState(!1),[f,g]=o.useState(!1),[S,k]=o.useState(""),[_,A]=o.useState(!1),b=o.useRef(null),v=o.useCallback(U=>{U.stopPropagation()},[]),M=l.length>1,N=o.useMemo(()=>ch(S),[S]),C=o.useMemo(()=>{const U=p.toLowerCase();return U?s.filter(K=>K.toLowerCase().includes(U)):s},[p,s]),I=o.useMemo(()=>{const U=p.toLowerCase();return U?n.filter(K=>K.toLowerCase().includes(U)):n},[p,n]),D=U=>{if(U===e){u(!1);return}i(U),u(!1),h("")},P=()=>{m(!0),setTimeout(()=>b.current?.focus(),50)},G=async()=>{if(!(!N||_)){if(M){g(!0);return}A(!0);try{await a(N,l[0]),k(""),m(!1),u(!1)}finally{A(!1)}}},ee=async U=>{if(!(!N||_)){A(!0);try{await a(N,U),k(""),m(!1),g(!1),u(!1)}finally{A(!1)}}},Z=()=>{g(!1)},te=()=>{k(""),m(!1),g(!1)};return o.useEffect(()=>{d||(h(""),m(!1),g(!1),k(""))},[d]),t.jsxs(qt,{open:d,onOpenChange:u,children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsxs(Ve,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1",disabled:c,children:[t.jsx(j,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:e||"Detached HEAD"}),t.jsx(j,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(rt,{sideOffset:8,children:"Current branch"})]}),t.jsx(Xt,{align:"start",className:"w-72 p-0 max-h-[60vh] flex flex-col",children:t.jsxs(ed,{className:"h-full min-h-0",children:[t.jsx(td,{placeholder:"Search branches...",value:p,onValueChange:h,onKeyDown:v}),t.jsxs(sd,{scrollbarClassName:"overlay-scrollbar--flush overlay-scrollbar--dense overlay-scrollbar--zero",disableHorizontal:!0,children:[t.jsx(nd,{children:"No branches found."}),t.jsx(ar,{children:f?t.jsxs("div",{className:"px-2 py-1.5",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[t.jsx("button",{type:"button",onClick:Z,disabled:_,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(j,{name:"arrow-left",className:"size-4"})}),t.jsxs("span",{className:"typography-meta text-muted-foreground",children:["Push To Prefix"," ",t.jsx("span",{className:"text-foreground font-medium",children:N})," ","Push To Suffix"]})]}),t.jsx("div",{className:"flex flex-col gap-1",children:l.map(U=>t.jsxs("button",{type:"button",onClick:()=>ee(U),disabled:_,className:"flex flex-col items-start gap-0.5 px-2 py-1.5 rounded-md text-left hover:bg-accent disabled:opacity-50",children:[t.jsxs("span",{className:"typography-ui-label text-foreground",children:[_?t.jsx(j,{name:"loader-4",className:"inline size-3 mr-1.5 animate-spin"}):null,U.name]}),t.jsx("span",{className:"typography-micro text-muted-foreground truncate max-w-full",children:U.pushUrl})]},U.name))})]}):x?t.jsxs("div",{className:"flex items-center gap-2 px-2 py-1.5 rounded-lg",children:[t.jsx("input",{ref:b,placeholder:"New branch name",value:S,onChange:U=>k(U.target.value),onClick:U=>U.stopPropagation(),onKeyDown:U=>{v(U),U.key==="Enter"?(U.preventDefault(),G()):U.key==="Escape"&&(U.preventDefault(),te())},className:"flex-1 min-w-0 bg-transparent typography-meta outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"button",onClick:G,disabled:!N||_,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:_?t.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(j,{name:"add",className:"size-4"})}),t.jsx("button",{type:"button",onClick:te,disabled:_,className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(j,{name:"close",className:"size-4"})})]}):t.jsxs(Zs,{onSelect:P,children:[t.jsx(j,{name:"add",className:"size-4"}),t.jsx("span",{children:"Create new branch..."})]})}),t.jsx(Ko,{}),t.jsxs(ar,{heading:"Local branches",children:[C.map(U=>t.jsxs(Zs,{onSelect:()=>D(U),children:[t.jsxs("span",{className:"flex flex-1 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:U}),(r?.[U]?.ahead||r?.[U]?.behind)&&t.jsxs("span",{className:"typography-micro text-muted-foreground",children:[r[U].ahead||0," ahead ·"," ",r[U].behind||0," behind"]})]}),e===U&&t.jsx("span",{className:"typography-micro text-primary",children:"Current"})]},`local-${U}`)),C.length===0&&t.jsx(Zs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No local branches"})})]}),t.jsx(Ko,{}),t.jsxs(ar,{heading:"Remote branches",children:[I.map(U=>t.jsx(Zs,{onSelect:()=>D(U),children:t.jsx("span",{className:"typography-ui-label text-foreground",children:U})},`remote-${U}`)),I.length===0&&t.jsx(Zs,{disabled:!0,className:"justify-center",children:t.jsx("span",{className:"typography-meta text-muted-foreground",children:"No remote branches"})})]})]})]})})]})},uh=e=>e.trim().replace(/\s+/g,"-").replace(/[^A-Za-z0-9._/-]/g,"-").replace(/-+/g,"-").replace(/\/{2,}/g,"/").replace(/\/-+/g,"/").replace(/-+\//g,"/").replace(/^[-/]+/,"").replace(/[-/]+$/,""),fh=({currentBranch:e,onRename:s,showEditButton:n=!0})=>{const[r,i]=o.useState(!1),[a,l]=o.useState(e||""),[c,d]=o.useState(!1),u=o.useRef(null),p=()=>{!e||!s||(l(e),i(!0),setTimeout(()=>u.current?.focus(),0))},h=async()=>{if(!e||!s||!a.trim())return;const f=uh(a);if(f===e){i(!1);return}d(!0);try{await s(e,f),i(!1),l("")}finally{d(!1)}},x=()=>{i(!1),l("")},m=f=>{f.key==="Enter"?(f.preventDefault(),h()):f.key==="Escape"&&(f.preventDefault(),x())};return r?t.jsx("div",{className:"flex items-center gap-2 rounded-md bg-primary/12 px-2 py-1 h-8",children:t.jsxs("form",{className:"flex w-full items-center gap-2",onSubmit:f=>{f.preventDefault(),h()},children:[t.jsx(j,{name:"git-branch",className:"size-4 text-primary"}),t.jsx("input",{ref:u,value:a,onChange:f=>l(f.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",placeholder:"Branch name",onKeyDown:m,autoFocus:!0}),t.jsx("button",{type:"submit",disabled:c,"aria-label":c?"Saving branch name":"Save branch name",title:c?"Saving branch name":"Save branch name",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:c?t.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(j,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:x,disabled:c,"aria-label":"Cancel branch rename",title:"Cancel branch rename",className:"shrink-0 text-muted-foreground hover:text-foreground disabled:opacity-50",children:t.jsx(j,{name:"close",className:"size-4"})})]})}):t.jsxs("div",{className:"flex w-full min-w-0 items-center gap-1.5 px-2 py-1 h-8",children:[t.jsx(j,{name:"git-branch",className:"size-4 text-primary shrink-0"}),t.jsxs("div",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[t.jsx("span",{className:"truncate typography-ui-label font-normal text-foreground",children:e||"Detached HEAD"}),n&&s&&e&&t.jsx(Ve,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 shrink-0",onClick:p,title:"Rename branch",children:t.jsx(j,{name:"edit",className:"size-4"})})]})]})},hh=({syncAction:e,remotes:s=[],onFetch:n,onSync:r,onRemoveRemote:i,disabled:a,removingRemoteName:l=null,aheadCount:c=0,behindCount:d=0,trackingRemoteName:u,hasUncommittedChanges:p=!1})=>{const h=o.useRef(!1),x=!!l,m=s.find(v=>v.name===u)??s[0],f=d>0&&p,g=a||e!==null||x||!m||f,S=a||e!==null||x||s.length===0,k=c>0||d>0,_=["sync",d>0?`↓${d}`:null,c>0?`↑${c}`:null].filter(Boolean).join(" "),A=f?"Commit or stash your changes before syncing":m?k?`Sync Changes (${d} down, ${c} up)`:"Sync Changes":"No remotes configured",b=()=>{m&&r(m)};return t.jsxs("div",{className:"inline-flex items-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] border border-border/60 bg-[var(--surface-elevated)] overflow-hidden",children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("span",{className:"inline-flex",tabIndex:f?0:void 0,children:t.jsxs("button",{type:"button",onClick:b,disabled:g,className:B("inline-flex h-7 items-center gap-1.5 px-2 typography-ui-label font-medium text-foreground","transition-colors hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),"aria-label":"Sync Changes",children:[e==="sync"?t.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(j,{name:"refresh",className:"size-4"}),t.jsx("span",{className:"whitespace-nowrap tabular-nums",children:_})]})})}),t.jsx(rt,{sideOffset:8,children:A})]}),t.jsxs(qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:B("inline-flex h-7 w-6 items-center justify-center border-l border-[var(--interactive-border)] text-muted-foreground","transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50"),disabled:S,"aria-label":"More sync actions",children:t.jsx(j,{name:"arrow-down-s",className:"size-4"})})}),t.jsx(Xt,{align:"start",alignOffset:-40,className:"w-[min(360px,calc(100vw-2rem))] max-h-[320px] overflow-y-auto",children:s.map(v=>t.jsx(kt,{onSelect:M=>{if(h.current){M.preventDefault(),h.current=!1;return}n(v)},children:t.jsxs("div",{className:"flex w-full items-center gap-2",children:[t.jsx(j,{name:"refresh",className:"size-4 text-muted-foreground"}),t.jsx("div",{className:"min-w-0 flex-1",children:t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:`Fetch from ${v.name}`}),t.jsx("span",{className:"typography-meta text-muted-foreground truncate",children:v.fetchUrl})]})}),i&&v.name!==u?t.jsx(Ve,{type:"button",variant:"destructive",size:"xs",className:"h-6 w-6 px-0",disabled:e!==null||x,onPointerDown:M=>{h.current=!0,M.preventDefault(),M.stopPropagation()},onClick:M=>{h.current=!0,M.preventDefault(),M.stopPropagation(),i(v)},"aria-label":`Remove remote ${v.name}`,title:`Remove remote ${v.name}`,children:l===v.name?t.jsx(j,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(j,{name:"close",className:"size-3.5"})}):null]})},v.name))})]})]})},ph={branch:"git-branch",briefcase:"briefcase",house:"home",graduation:"graduation-cap",code:"code",heart:"heart",user:"user-3",fingerprint:"fingerprint"},mh={keyword:"var(--syntax-keyword)",error:"var(--status-error)",string:"var(--syntax-string)",function:"var(--syntax-function)",type:"var(--syntax-type)",success:"var(--status-success)",info:"var(--status-info)",warning:"var(--status-warning)"};function Ua(e){return e&&mh[e]||"var(--primary)"}const hi=({icon:e,className:s,colorToken:n})=>{const r=ph[e??"branch"]??"user-3";return t.jsx(j,{name:r,className:s,style:{color:Ua(n)}})},Ga=({activeProfile:e,identities:s,onSelect:n,isApplying:r,iconOnly:i=!1})=>{const a=r||s.length===0;return t.jsxs(qt,{children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsxs(Ve,{variant:"ghost",size:"sm",className:"h-8 min-w-0 max-w-[15rem] justify-start gap-1.5 px-2 py-1 typography-ui-label",style:{color:Ua(e?.color)},disabled:a,children:[r?t.jsx(j,{name:"loader-4",className:"size-4 animate-spin"}):t.jsx(hi,{icon:e?.icon,colorToken:e?.color,className:"size-4"}),!i&&t.jsx("span",{className:"git-identity-label min-w-0 flex-1 truncate text-left",children:e?.name||"No identity"}),t.jsx(j,{name:"arrow-down-s",className:"size-4 opacity-60"})]})})}),t.jsx(rt,{sideOffset:8,children:"Git identity"})]}),t.jsx(Xt,{align:"end",className:"w-64",children:s.length===0?t.jsx("div",{className:"px-2 py-1.5",children:t.jsx("p",{className:"typography-meta text-muted-foreground",children:"No profiles available to apply."})}):s.map(l=>{const c=e?.id===l.id;return t.jsx(kt,{onSelect:()=>n(l),children:t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(hi,{icon:l.icon,colorToken:l.color,className:"size-4"}),t.jsxs("span",{className:"flex min-w-0 flex-col",children:[t.jsx("span",{className:"typography-ui-label text-foreground",children:l.name}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:l.userEmail})]}),c?t.jsx(j,{name:"check",className:"ml-auto size-4 text-foreground"}):null]})},l.id)})})]})},gh=({comparison:e,trackingBranch:s,tooltipDelayMs:n=1e3})=>{const r=`${e.remote}/${e.branch}`,i=e.ahead===0&&e.behind===0,a=s?`Compared with ${r}. Primary sync badges still reflect ${s}.`:`Compared with ${r}.`;return t.jsxs(st,{delayDuration:n,children:[t.jsx(nt,{asChild:!0,children:t.jsxs("div",{className:"inline-flex h-8 max-w-full items-center gap-1.5 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-2 typography-micro text-muted-foreground",children:[t.jsx(j,{name:"git-branch",className:"size-3.5 shrink-0"}),t.jsx("span",{className:"min-w-0 truncate text-foreground/80",children:r}),i?t.jsx("span",{className:"tabular-nums text-muted-foreground",children:"synced"}):t.jsxs("span",{className:"inline-flex items-center gap-1 tabular-nums",children:[e.ahead>0?t.jsxs("span",{className:"text-[var(--status-info)]",children:["↑",e.ahead]}):null,e.behind>0?t.jsxs("span",{className:"text-[var(--status-warning)]",children:["↓",e.behind]}):null]})]})}),t.jsx(rt,{sideOffset:8,children:a})]})},Dx=({status:e,localBranches:s,remoteBranches:n,branchInfo:r,syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,onCheckoutBranch:p,onCreateBranch:h,onRenameBranch:x,activeIdentityProfile:m,availableIdentities:f,onSelectIdentity:g,isApplyingIdentity:S,isWorktreeMode:k,onOpenHistory:_,onOpenGraph:A,onOpenStashes:b,onOpenUpdateBranch:v,onOpenReintegrateCommits:M,pullRequest:N,prChecks:C,onOpenPullRequest:I})=>{if(!e)return null;const D=t.jsx("div",{className:"flex items-center gap-1 shrink-0",children:_||A||b||v?t.jsxs(qt,{children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsx(Ve,{variant:"ghost",size:"sm",className:"h-8 w-8 px-0","aria-label":"Repository views",children:t.jsx(j,{name:"more-fill",className:"size-4"})})})}),t.jsx(rt,{sideOffset:8,children:"Repository views"})]}),t.jsxs(Xt,{align:"end",children:[_?t.jsxs(kt,{onSelect:_,children:[t.jsx(j,{name:"history",className:"size-4"}),"History"]}):null,A?t.jsxs(kt,{onSelect:A,children:[t.jsx(j,{name:"git-branch",className:"size-4"}),"Graph"]}):null,b?t.jsxs(kt,{onSelect:b,children:[t.jsx(j,{name:"archive-stack",className:"size-4"}),"Stashes"]}):null,v?t.jsxs(kt,{onSelect:v,children:[t.jsx(j,{name:"git-merge",className:"size-4"}),"Update branch"]}):null,M?t.jsxs(kt,{onSelect:M,children:[t.jsx(j,{name:"split-cells-horizontal",className:"size-4"}),"Re-integrate commits"]}):null]})]}):null}),P=C?C.state==="success"?"var(--status-success)":C.state==="failure"?"var(--status-error)":"var(--status-warning)":null,G=N?N.state==="merged"?"merged":N.state==="closed"?"closed":N.draft?"draft":C?.state==="failure"||N.mergeable===!1||N.mergeableState==="blocked"||N.mergeableState==="dirty"?"blocked":"open":null,ee=N&&I?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsxs(Ve,{variant:"ghost",size:"sm",onClick:I,className:"h-8 gap-1.5 px-2 typography-micro",children:[t.jsx(j,{name:"git-pull-request",className:"size-3.5",style:{color:`var(--pr-${G})`}}),t.jsx("span",{className:"tabular-nums text-foreground/80",children:`PR #${N.number}`}),P?t.jsx("span",{"aria-hidden":"true",className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:P}}):null]})}),t.jsx(rt,{sideOffset:8,children:"Open pull request"})]}):null,Z=t.jsx(hh,{syncAction:i,remotes:a,onFetch:l,onSync:c,onRemoveRemote:d,removingRemoteName:u,disabled:!e,iconOnly:!0,aheadCount:e.ahead,behindCount:e.behind,trackingRemoteName:e.tracking?.split("/")[0],hasUncommittedChanges:(e.files?.length??0)>0}),te=e.upstreamComparison?t.jsx(gh,{comparison:e.upstreamComparison,trackingBranch:e.tracking,tooltipDelayMs:1e3}):null,U=t.jsx(Ga,{activeProfile:m,identities:f,onSelect:g,isApplying:S,iconOnly:!0});return t.jsxs("header",{className:"@container/git-header px-3 py-2 bg-transparent",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 min-w-0",children:[t.jsx("div",{className:"min-w-0 flex-1",children:k?t.jsx(fh,{currentBranch:e.current,onRename:x}):t.jsx(dh,{currentBranch:e.current,localBranches:s,remoteBranches:n,branchInfo:r,onCheckout:p,onCreate:h,remotes:a})}),t.jsx("div",{className:"flex shrink-0 items-center gap-1",children:U})]}),t.jsxs("div",{className:"mt-3 flex h-8 min-w-0 items-center gap-2",children:[ee?t.jsx("div",{className:"shrink-0",children:ee}):null,t.jsx("div",{className:"min-w-0 flex-1"}),te?t.jsx("div",{className:"min-w-0 shrink",children:te}):null,D,t.jsx("div",{className:"shrink-0",children:Z})]})]})},xh=e=>e==="/",Ks=e=>e.replace(/\\/g,"/"),Ys=e=>{if(!e||xh(e))return e;let s=e;for(;s.length>1&&s.endsWith("/");)s=s.slice(0,-1);return s},Hs=e=>e.endsWith("/"),Hn=e=>{const s=e.trim();return!s||Hs(s)?s:`${s}/`},go=e=>e.lastIndexOf("/"),Ka=e=>{if(Hs(e))return e;const s=go(e);return s<0?e:e.slice(0,s+1)},Ha=e=>{const s=go(e);return e.slice(s+1)},Wa=e=>{const s=Ys(e.trim());if(!s||s==="~"||s==="~/"||s==="/")return null;const n=go(s);return n<0?null:s.startsWith("~/")&&n<=1?"~/":n===0?"/":`${s.slice(0,n)}/`},Va=e=>Hs(e)&&Wa(e)!==null,bh=e=>{if(!Va(e))return null;const s=Ys(e.trim());return Ha(s)||s},yh=(e,s)=>`${Ka(e)}${s}/`,Cs=e=>{if(!e)return null;const s=Ys(Ks(e.trim()));return s?s.toLowerCase():null},pi=(e,s)=>{const n=e.trim();return n==="~"?s:n.startsWith("~/")?`${s}${n.slice(1)}`:n},vh=(e,s)=>{const n=Ys(Ks(e.trim())),r=Ys(Ks(s.trim()));if(!n)return"";if(!r)return Hn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const i=`${r}/`;return n.toLowerCase().startsWith(i.toLowerCase())?`~/${n.slice(r.length+1)}/`:Hn(n)},wh=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,fr=e=>{if(!e)return;e.focus({preventScroll:!0});const s=e.value.length;e.setSelectionRange(s,s),e.scrollLeft=e.scrollWidth},Sh=async()=>au(),jh=({open:e,onOpenChange:s})=>{const n=ws(F=>F.homeDirectory),r=$t(F=>F.projects),i=$t(F=>F.addProject),a=ce(F=>F.setActiveMainTab),l=ce(F=>F.setSessionSwitcherOpen),c=Fe(F=>F.openNewSessionDraft),d=As(F=>F.profiles),u=As(F=>F.globalIdentity),p=As(F=>F.defaultGitIdentityId),h=As(F=>F.loadProfiles),x=As(F=>F.loadGlobalIdentity),m=As(F=>F.loadDefaultGitIdentityId),{canRequestAccess:f,startAccessing:g}=lh(),{isMobile:S,isTablet:k}=Ms(),_=S||k,A=o.useRef(null),b=o.useRef(new Map),[v,M]=o.useState(""),[N,C]=o.useState("~/"),[I,D]=o.useState([]),[P,G]=o.useState(!1),[ee,Z]=o.useState(!1),[te,U]=o.useState(null),[K,T]=o.useState(0),[R,q]=o.useState(0),[ae,z]=o.useState(!1),[Re,Te]=o.useState(!1),[Ye,_e]=o.useState(!1),[Qe,Be]=o.useState(""),[ie,pe]=o.useState(null),[We,ke]=o.useState(!1),[ve,$e]=o.useState("right"),ot=o.useRef("~/"),ze=v||n,J=o.useMemo(()=>new Set(r.map(F=>Cs(F.path)).filter(F=>!!F)),[r]);o.useEffect(()=>{if(!e)return;C("~/"),D([]),q(0),z(!1),Te(!1),_e(!1),Be(""),pe(null),ke(!1),ot.current="~/",$e("right"),_||requestAnimationFrame(()=>fr(A.current));let F=!1;return(async()=>{const Ue=await Sh();F||(M(Ue||n||""),_||requestAnimationFrame(()=>fr(A.current)))})(),()=>{F=!0}},[n,e,_]),o.useEffect(()=>{e&&(h(),x(),m())},[m,h,x,e]);const Q=o.useMemo(()=>{const F=new Map;u&&F.set(u.id,u);for(const Ne of d)F.set(Ne.id,Ne);return Array.from(F.values())},[d,u]);o.useEffect(()=>{if(!e||!Ye||ie!==null)return;const F=typeof p=="string"?p.trim():"";if(F&&Q.some(Ue=>Ue.id===F)){pe(F);return}const Ne=Q.find(Ue=>Ue.authType==="ssh"||Ue.sshKey);Ne&&pe(Ne.id)},[Q,p,Ye,e,ie]);const ge=o.useMemo(()=>Q.find(F=>F.id===ie)??null,[Q,ie]),X=o.useMemo(()=>Ka(N),[N]),be=o.useMemo(()=>Hs(N)?"":Ha(N),[N]),Ae=o.useMemo(()=>ze?pi(X,ze):"",[X,ze]);o.useEffect(()=>{const F=ot.current;F!==X&&($e(X.length>=F.length?"right":"left"),ot.current=X)},[X]),o.useEffect(()=>{if(!e||!Ae){D([]),U(null);return}let F=!1;return G(!0),Z(!1),U(null),ru(Ae).then(Ne=>{if(F)return;Z(!1),U(null);const Ue=Ne.filter(pt=>pt.isDirectory).map(pt=>({name:pt.name,path:Ks(pt.path)})).sort((pt,L)=>pt.name.localeCompare(L.name));D(Ue)}).catch(Ne=>{if(!F){D([]);const Ue=ou(Ne)?Ne.reason:"unknown";U(Ue),Z(Ue==="not-found")}}).finally(()=>{F||G(!1)}),()=>{F=!0}},[Ae,K,e]);const je=o.useMemo(()=>{const F=be.toLowerCase(),Ne=We||be.startsWith(".");return I.filter(Ue=>Ue.name.toLowerCase().startsWith(F)&&(Ne||!Ue.name.startsWith(".")))},[be,I,We]),lt=o.useMemo(()=>bh(N),[N]),jt=o.useMemo(()=>Wa(N),[N]),it=o.useMemo(()=>{const F=[],Ne=Cs(Ae);Va(N)&<&&jt&&F.push({type:"parent",value:"browse:up",name:lt,path:jt,alreadyAdded:!!(Ne&&J.has(Ne))});for(const Ue of je){const pt=Cs(Ue.path);F.push({type:"directory",value:`browse:${Ue.path}`,name:Ue.name,path:Ue.path,alreadyAdded:!!(pt&&J.has(pt))})}return F},[J,Ae,lt,je,jt,N]);o.useEffect(()=>{q(0)},[N,it.length]);const xe=o.useMemo(()=>ze?Ys(pi(N,ze)):"",[ze,N]),Le=Cs(xe),Oe=!!(Le&&J.has(Le)),Ke=o.useMemo(()=>be?je.find(F=>F.name===be)??null:null,[be,je]),Ct=!!(xe&&!Oe&&(te===null||te==="not-found")&&(Hs(N)&&ee||!Hs(N)&&be.trim().length>0&&Ke===null)),ht=!ae&&!Re&&!Oe&&te!=="os-permission"&&te!=="invalid-response"&&te!=="unknown"&&!!xe,O=ht&&Qe.trim().length>0,Ce=it[R]??null,ye=!!Ce,w=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl",Y=Oe?"Already added":Ye?ae?"Cloning...":"Clone & add":ae?"Adding...":Ct?"Create & add":"Add folder",se=Ye?O:ht;o.useLayoutEffect(()=>{const F=A.current;F&&(F.scrollLeft=F.scrollWidth)},[N]),o.useLayoutEffect(()=>{!e||_||fr(A.current)},[e,_]),o.useLayoutEffect(()=>{const F=it[R];F&&b.current.get(F.value)?.scrollIntoView({block:"nearest"})},[R,it]);const ue=o.useCallback(()=>{s(!1)},[s]),Se=o.useCallback((F,Ne)=>{a("chat"),S&&l(!1),c({selectedProjectId:F,directoryOverride:Ne}),ue()},[ue,S,c,a,l]),Pe=o.useCallback(async F=>{if(!F||ae)return;const Ne=Cs(F);if(Ne&&J.has(Ne))return;let Ue=F;z(!0);try{const pt=!Ye&&Ct&&Cs(F)===Cs(xe);if(Ye){const re=Qe.trim();if(!re){le.error("Enter a repository URL before cloning.");return}const me=await es("/api/git/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:re,destinationPath:F,gitIdentityId:ge?.id??null})});if(!me.ok)throw new Error("Failed to clone git repository");Ue=(await me.json()).path||F}else if(pt&&!(await es("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:Ae?{directory:Ae}:void 0,body:JSON.stringify({path:F})})).ok)throw new Error("Failed to select directory");const L=i(Ue);if(!L){le.error("Failed to add folder",{description:"Please select a valid directory path."});return}Se(L.id,L.path)}catch(pt){le.error("Failed to select directory",{description:pt instanceof Error?pt.message:"Unknown error occurred."})}finally{z(!1)}},[i,J,Ae,Qe,Ye,ae,Se,ge?.id,Ct,xe]),He=o.useCallback(F=>{C(Hn(F))},[]),mt=o.useCallback(F=>{C(yh(N,F.name))},[N]),bt=o.useCallback(F=>{if(F){if(F.type==="parent"){He(F.path);return}mt(F)}},[He,mt]),qe=o.useCallback(async F=>{const Ne=await g(F);if(!Ne.success)return le.error("Failed to open directory",{description:Ne.error||"Desktop could not grant file access."}),!1;const Ue=ze?vh(F,ze):Hn(Ks(F));return He(Ue),!0},[He,ze,g]),dt=o.useCallback(async()=>{if(!Re){Te(!0);try{if(oo()){const Ne=await io(xe);if(!Ne.success||!Ne.path){Ne.error&&Ne.error!=="Directory selection cancelled"&&le.error("Failed to select directory",{description:Ne.error});return}await qe(Ne.path);return}const F=await iu(xe);if(F.status==="cancelled")return;if(F.status!=="picked"){le.error("Couldn't open a folder picker",{description:F.error});return}await qe(F.path)}catch(F){le.error("Failed to select directory",{description:F instanceof Error?F.message:"Unknown error occurred."})}finally{Te(!1)}}},[qe,Re,xe]),xt=o.useCallback(F=>{if(F.key==="ArrowDown"){F.preventDefault(),q(Ne=>Math.min(it.length-1,Ne+1));return}if(F.key==="ArrowUp"){F.preventDefault(),q(Ne=>Math.max(0,Ne-1));return}if(F.key==="Enter"){if(F.preventDefault(),wh(F)){Pe(xe);return}ye&&bt(Ce);return}F.key==="Backspace"&&N===""&&(F.preventDefault(),ue())},[bt,Pe,ue,ye,Ce,N,it.length,xe]),Me=t.jsxs("button",{type:"button",onClick:()=>ke(F=>!F),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[We?t.jsx(j,{name:"checkbox",className:"h-4 w-4 text-primary"}):t.jsx(j,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),Ze=t.jsx("div",{className:"py-1.5",children:t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsxs("div",{className:"relative min-w-0 flex-1",children:[t.jsx(j,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),t.jsx(Ws,{ref:A,value:N,onChange:F=>C(Ks(F.target.value)),onKeyDown:xt,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),t.jsxs(Ve,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:ae||Re,onMouseDown:F=>F.preventDefault(),onClick:()=>{dt()},title:"Browse location","aria-label":"Browse location",children:[t.jsx(j,{name:"folder-open",className:"h-3.5 w-3.5"}),Re?"Opening...":"Browse"]})]})}),yt=it.some(F=>F.type==="parent"),Nt=t.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:t.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[t.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[t.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),t.jsxs(Ve,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":Ye,disabled:ae||Re,onClick:()=>_e(F=>!F),children:[t.jsx(j,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),Ye?t.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[t.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Ws,{value:Qe,onChange:F=>Be(F.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"}),t.jsx(Ga,{activeProfile:ge,identities:Q,onSelect:F=>pe(F.id),isApplying:ae,iconOnly:!0})]})]}):null,Oe?t.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,t.jsx("div",{className:B("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",ve==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:P?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):te&&te!=="not-found"?t.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[t.jsx("div",{className:"typography-ui-label text-status-error",children:te==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),t.jsxs("div",{className:"flex items-center gap-2",children:[te==="os-permission"&&f?t.jsx(Ve,{size:"xs",onClick:()=>{dt()},disabled:Re,children:"Grant access"}):null,t.jsx(Ve,{variant:"outline",size:"xs",onClick:()=>T(F=>F+1),children:"Try again"})]})]}):it.length===0?t.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):t.jsx("div",{className:"space-y-0.5",children:it.map((F,Ne)=>{const Ue=Ne===R,pt=F.type==="directory"&&yt;return t.jsxs("button",{ref:L=>{L?b.current.set(F.value,L):b.current.delete(F.value)},type:"button","aria-label":F.type==="parent"?F.alreadyAdded?`Go back from ${F.name}, already added`:`Go back from ${F.name}`:F.alreadyAdded?`Open ${F.name}, already added`:`Open ${F.name}`,onMouseEnter:()=>q(Ne),onMouseDown:L=>L.preventDefault(),onClick:()=>bt(F),className:B("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",Ue&&"bg-interactive-selection text-interactive-selection-foreground",!Ue&&"hover:bg-interactive-hover/50"),children:[t.jsxs("span",{className:B("flex min-w-0 flex-1 items-center gap-2",pt&&"pl-4"),children:[F.type==="parent"?t.jsx(j,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):t.jsx(j,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:F.name})]}),F.alreadyAdded?t.jsx("span",{className:B("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",Ue?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,F.type==="parent"?t.jsx(j,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):t.jsx(j,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},F.value)})})},X)]})}),Pt=t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[Ze,Nt]}),Et=t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(j,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),t.jsx(j,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx(j,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),t.jsxs("span",{className:"inline-flex items-center gap-1",children:[t.jsx("span",{children:w}),t.jsx(j,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),It=t.jsx(Ve,{size:S?"xs":"default",onClick:()=>{Pe(xe)},disabled:!se,className:B(S&&"w-full flex-1"),children:Y}),At=()=>t.jsxs(t.Fragment,{children:[S?null:Et,t.jsx("div",{className:B("flex w-full flex-row justify-end gap-2 sm:w-auto",S&&"justify-stretch"),children:It})]});return S?t.jsx(sa,{open:e,onClose:ue,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:t.jsx("div",{className:"flex flex-col gap-2",children:At()}),children:t.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[t.jsx("div",{className:"flex justify-end",children:Me}),Pt]})}):t.jsx(as,{open:e,onOpenChange:s,children:t.jsxs(ls,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[t.jsx(Ss,{className:"px-5 pb-2 pt-5",children:t.jsxs("div",{className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{children:[t.jsx(hs,{children:"Add folder"}),t.jsx(Fs,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),Me]})}),t.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:Pt}),t.jsx(Ls,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:At()})]})})},Dn=e=>e?t.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Px=()=>{const[e,s]=o.useState(!1),[n,r]=o.useState(null),[i,a]=o.useState(!1),l=rd,c=Fe(M=>M.deleteSessions),d=ce(M=>M.showDeletionDialog),u=ce(M=>M.setShowDeletionDialog),{isMobile:p,isTablet:h,hasTouchInput:x}=Ms(),m=p||h||x;o.useEffect(()=>lu(()=>{s(!1)}),[]);const f=o.useCallback(M=>{r({sessions:M.sessions,dateLabel:M.dateLabel})},[]),g=o.useCallback(()=>{r(null),a(!1)},[]),S=o.useCallback(async M=>{if(M.sessions.length===0)return;if(M.sessions.length===1){const D=M.sessions[0];await l(D.id)?le.success("Session deleted"):le.error("Failed to delete session");return}const N=M.sessions.map(D=>D.id),{deletedIds:C,failedIds:I}=await c(N);if(C.length>0){const D=I.length>0?I.length===1?`${I.length} session could not be deleted.`:`${I.length} sessions could not be deleted.`:M.dateLabel?`Removed all sessions from ${M.dateLabel}.`:void 0;le.success(C.length===1?"Deleted {count} session":`Deleted ${C.length} sessions`,{description:Dn(D)})}I.length>0&&le.error(I.length===1?`Failed to delete ${I.length} session`:`Failed to delete ${I.length} sessions`,{description:Dn("Please try again in a moment.")})},[l,c]);o.useEffect(()=>Ts.onDeleteRequest(M=>{if(!d){S(M);return}f(M)}),[f,d,S]),o.useEffect(()=>Ts.onDirectoryRequest(()=>{s(!0)}),[]);const k=o.useCallback(async()=>{if(n){a(!0);try{if(n.sessions.length===1){const M=n.sessions[0];if(!await l(M.id)){le.error("Failed to delete session"),a(!1);return}le.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const M=n.sessions.map(D=>D.id),N=await c(M),C=N.deletedIds,I=N.failedIds;if(C.length>0){const D=I.length>0?I.length===1?`${I.length} session could not be deleted.`:`${I.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;le.success(C.length===1?"Deleted {count} session":`Deleted ${C.length} sessions`,{description:Dn(D),action:{label:"OK",onClick:()=>{}}})}if(I.length>0&&(le.error(I.length===1?`Failed to delete ${I.length} session`:`Failed to delete ${I.length} sessions`,{description:Dn("Please try again in a moment.")}),C.length===0)){a(!1);return}}g()}finally{a(!1)}}},[n,l,c,g]),_=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",A=n?t.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&t.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(M=>t.jsx("li",{className:"typography-micro text-muted-foreground/80",children:t.jsx("span",{className:"truncate",children:M.title||"Untitled Session"})},M.id)),n.sessions.length>5&&t.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),t.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,b=t.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[t.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?t.jsx(j,{name:"checkbox-blank",className:"size-4"}):t.jsx(j,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Ve,{variant:"ghost",onClick:g,disabled:i,children:"Cancel"}),t.jsx(Ve,{variant:"destructive",onClick:k,disabled:i,children:i?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),v=n?.sessions.length===1?"Delete session":"Delete sessions";return t.jsxs(t.Fragment,{children:[m?t.jsx(sa,{open:!!n,onClose:()=>{i||g()},title:v,footer:t.jsx("div",{className:"flex justify-end gap-2",children:b}),children:t.jsxs("div",{className:"space-y-2 pb-2",children:[_&&t.jsx("p",{className:"typography-meta text-muted-foreground/80",children:_}),A]})}):t.jsx(as,{open:!!n,onOpenChange:M=>{if(!M){if(i)return;g()}},children:t.jsxs(ls,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[t.jsxs(Ss,{children:[t.jsx(hs,{children:v}),_&&t.jsx(Fs,{children:_})]}),t.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:A}),t.jsx(Ls,{className:"mt-2 gap-2 pt-1 pb-1",children:b})]})}),t.jsx(jh,{open:e,onOpenChange:s})]})},Ex=()=>{const e=nn(d=>d.entries),s=ce(d=>d.isMobile),n=ce(d=>d.activeMainTab),r=Fe(d=>d.newSessionDraft),i=Fe(d=>d.openNewSessionDraft),a=Fe(d=>d.setNewSessionDraftTarget),l=n==="chat",c=o.useMemo(()=>{const d=od(r?.worktreeIntent),u=!!r?.open,p=[];for(const h of e.values()){const x=u&&h.key===d,m=x&&l;if(h.state){m||p.push(h);continue}h.receipt&&!x&&p.push(h)}return p},[e,r?.worktreeIntent,r?.open,l]);return c.length===0?null:t.jsx("div",{className:B("pointer-events-none fixed inset-x-0 z-40 flex justify-center px-3",s?"bottom-[calc(var(--oc-safe-area-bottom,0px)+5.5rem)]":"bottom-4"),"aria-live":"polite",children:t.jsx("div",{className:"pointer-events-auto flex w-full max-w-[640px] flex-col gap-2",children:c.map(d=>t.jsx(kh,{entry:d,onDismissFailed:()=>nn.getState().dismissFailed(d.key),onDismissCompleted:()=>nn.getState().clearEntry(d.key),onOpenWorktree:()=>{const u=d.receipt;u&&(r?.open?a({directoryOverride:u.path,worktreeIntent:null}):i({directoryOverride:u.path}),nn.getState().clearEntry(d.key),ce.getState().setActiveMainTab("chat"))}},d.key))})})},kh=({entry:e,onDismissFailed:s,onDismissCompleted:n,onOpenWorktree:r})=>{const i=e.state?.phase==="failed",a=!!(e.state&&!i),l=!e.state&&!!e.receipt,c=i?e.state?.label??"Worktree creation failed":a?e.state?.label??"Creating worktree...":e.receipt?`Worktree ready: ${e.receipt.branch??e.path??"new worktree"}`:"",d=i?e.state?.error:l?e.receipt?.path:null;return t.jsxs("div",{className:B("flex items-center gap-3 rounded-xl border px-3 py-2.5 shadow-lg backdrop-blur",i?"border-[var(--status-error-border)] bg-[var(--status-error-background)] text-[var(--status-error-foreground)]":l?"border-[var(--border)] bg-[var(--surface-elevated)] text-foreground":"border-[var(--border)] bg-[var(--surface-muted)] text-muted-foreground"),role:i?"alert":"status",children:[a?t.jsx(Qs,{variant:"inline",text:null,animationType:"spinner"}):l?t.jsx(j,{name:"git-branch",className:"h-4 w-4 shrink-0 text-[var(--status-success)]"}):t.jsx(j,{name:"alert",className:"h-4 w-4 shrink-0"}),t.jsxs("div",{className:"min-w-0 flex-1",children:[t.jsx("p",{className:"typography-ui-label truncate",children:c}),d?t.jsx("p",{className:"mt-0.5 break-words text-xs opacity-80 line-clamp-2",children:d}):null,a&&e.branch?t.jsx("p",{className:"mt-0.5 truncate text-xs opacity-60",children:e.branch}):null]}),i?t.jsx(Ve,{type:"button",variant:"ghost",size:"xs",onClick:s,"aria-label":"Dismiss error",children:"Dismiss"}):null,l?t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[t.jsx(Ve,{type:"button",size:"xs",onClick:r,children:"Open"}),t.jsx(Ve,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:n,"aria-label":"Dismiss",children:t.jsx(j,{name:"close",className:"h-3.5 w-3.5"})})]}):null,a?t.jsx("span",{className:"hidden shrink-0 text-xs opacity-60 sm:inline",children:"In background"}):null]})};function Tx(){const e=o.useRef(!1),s=o.useRef(!1),n=Fe(p=>p.setCurrentSession),r=ce(p=>p.setActiveMainTab),i=ce(p=>p.setSettingsDialogOpen),a=ce(p=>p.setSettingsPage),l=ce(p=>p.navigateToDiff),c=o.useCallback(async p=>{if(!s.current){s.current=!0;try{if(p.sessionId){const h=Fe.getState().currentSessionId,x=en().getState().selectedSessionId;if(p.sessionId!==h||p.sessionId!==x){const m=Fe.getState().getDirectoryForSession(p.sessionId);n(p.sessionId,m)}}if(p.settingsPath){a(ah(p.settingsPath)),i(!0);return}ce.getState().isSettingsDialogOpen&&i(!1),p.tab&&r(p.tab),p.diffFile&&(p.tab==="diff"||!p.tab)&&l(p.diffFile)}finally{s.current=!1}}},[n,r,i,a,l]),d=o.useCallback(()=>{const p=Fe.getState(),h=en().getState(),x=ce.getState();return{sessionId:lr({currentSessionId:p.currentSessionId,piSelectedSessionId:h.selectedSessionId,draft:p.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),u=o.useCallback((p={})=>{if(s.current)return;const h=d();Gr(h,p)},[d]);o.useEffect(()=>{if(e.current||(e.current=!0,!Ho()))return;const p=Wo();(async()=>(await c(p),Gr({...d(),sessionId:p.sessionId??lr({currentSessionId:Fe.getState().currentSessionId,piSelectedSessionId:en().getState().selectedSessionId,draft:Fe.getState().newSessionDraft}),tab:p.tab??ce.getState().activeMainTab,settingsPath:p.settingsPath??ce.getState().settingsPage,diffFile:p.diffFile??ce.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),o.useEffect(()=>{const p=()=>{const S=Fe.getState(),k=en().getState();return lr({currentSessionId:S.currentSessionId,piSelectedSessionId:k.selectedSessionId,draft:S.newSessionDraft})};let h=p(),x=Fe.getState().newSessionDraft?.open===!0;const m=()=>{const S=Fe.getState(),k=p(),_=S.newSessionDraft?.open===!0;k===h&&_===x||s.current||(h=k,x=_,u({replace:!0}))},f=Fe.subscribe(()=>{m()}),g=en().subscribe(()=>{m()});return()=>{f(),g()}},[u]),o.useEffect(()=>{let p=ce.getState().activeMainTab,h=ce.getState().isSettingsDialogOpen,x=ce.getState().settingsPage,m=ce.getState().pendingDiffFile;return ce.subscribe(g=>{if(s.current)return;const S=g.activeMainTab!==p,k=g.isSettingsDialogOpen!==h,_=g.settingsPage!==x,A=g.pendingDiffFile!==m&&g.activeMainTab==="diff";p=g.activeMainTab,h=g.isSettingsDialogOpen,x=g.settingsPage,m=g.pendingDiffFile,(S||k||_||A)&&u()})},[u]),o.useEffect(()=>{if(typeof window>"u")return;const p=()=>{const h=Wo();if(Ho())c(h);else{const x=ce.getState();x.isSettingsDialogOpen&&i(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",p),()=>{window.removeEventListener("popstate",p)}},[c,r,i])}function Ch(e=!0){const s=Bn(r=>r.checkForUpdates),n=o.useRef(s);o.useEffect(()=>{n.current=s},[s]),o.useEffect(()=>{if(!e)return;const r=3e3,i=3600*1e3,a=300*1e3,l=1440*60*1e3;let c=!1,d=null;const u=h=>{const x=Math.round(h*1e3);return Math.max(a,Math.min(l,x))},p=h=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),m=typeof x=="number"&&Number.isFinite(x)?u(x):i;p(m)},h))};return p(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function Rx(){const e=an(s=>s.connection==="ready",void 0,"chrome");return Ch(e),null}const mi=12,Nh=[{id:"left",x:22,y:58,delay:0,radius:120,colorVar:"--status-success"},{id:"center",x:50,y:42,delay:120,radius:150,colorVar:"--primary-base"},{id:"right",x:78,y:55,delay:200,radius:130,colorVar:"--status-info"}],Ah=({isActive:e,burstKey:s=0,className:n,durationMs:r=900,bursts:i=Nh,onComplete:a})=>{const l=Xe.useRef(!1);Xe.useEffect(()=>{!e&&l.current&&a?.(),e&&(l.current=!0)},[e,a]);const c=Xe.useMemo(()=>Array.from({length:mi},(d,u)=>{const p=Math.PI*2*u/mi;return{x:Math.cos(p),y:Math.sin(p),delay:u*18}}),[]);return e?t.jsx("div",{className:B("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":s,children:i.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return t.jsx("div",{className:"firework-burst",style:u,children:c.map((p,h)=>{const x=p.x*d.radius,m=p.y*d.radius,f={"--translate-x":`${x}px`,"--translate-y":`${m}px`,"--particle-delay":`${p.delay}ms`,color:`var(${d.colorVar})`};return t.jsx("span",{className:"firework-particle",style:f},`${d.id}-${h}-${s}`)})},`${d.id}-${s}`)})}):null},Ih=({durationMs:e=3400}={})=>{const[s,n]=Xe.useState({isActive:!1,cycle:0}),r=Xe.useRef(null),i=Xe.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),a=Xe.useCallback(()=>{i(),n(c=>c.isActive?{...c,isActive:!1}:c)},[i]),l=Xe.useCallback(()=>{i(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[i,e]);return Xe.useEffect(()=>()=>i(),[i]),{isActive:s.isActive,burstKey:s.cycle,triggerFireworks:l,dismissFireworks:a}},Ya=o.createContext(void 0),Mx=({children:e})=>{const{isActive:s,burstKey:n,triggerFireworks:r,dismissFireworks:i}=Ih(),a=o.useMemo(()=>({triggerFireworks:r,dismissFireworks:i}),[r,i]);return t.jsxs(Ya.Provider,{value:a,children:[e,t.jsx(Ah,{isActive:s,burstKey:n})]})},Dh={triggerFireworks:()=>{},dismissFireworks:()=>{}},Fx=()=>o.useContext(Ya)??Dh,gi=380,xi=(e,s)=>{if(!e||typeof e!="object")return;const n=e[s];return typeof n=="number"&&Number.isFinite(n)?n:void 0},Wn=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Pn=({icon:e,iconNode:s,label:n,children:r})=>t.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[t.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:s??(e?t.jsx(j,{name:e,className:"size-[18px]"}):null)}),t.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),t.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),Ph=({open:e,onClose:s,anchorRef:n,contextDisplay:r})=>{const i=o.useRef(null),[a,l]=o.useState(e),[c,d]=o.useState(!1),{enabled:u}=eo(),p=o.useRef(null),[h,x]=o.useState(null);o.useLayoutEffect(()=>{if(!e||!u||!a)return;const f=()=>{const k=n.current?.getBoundingClientRect(),_=p.current?.getBoundingClientRect();if(!k||!_){x(null);return}const A=k.left-_.left,b=Math.min(Math.max(A,8),Math.max(8,_.width-gi-8));x(b)};f();const g=p.current;if(typeof ResizeObserver>"u"||!g)return;const S=new ResizeObserver(f);return S.observe(g),()=>S.disconnect()},[n,u,e,a]);const m=u&&h!==null;return o.useEffect(()=>{if(e){l(!0),d(!1);return}if(!a)return;d(!0);const f=window.setTimeout(()=>{l(!1),d(!1)},140);return()=>window.clearTimeout(f)},[e,a]),o.useEffect(()=>{if(!e)return;const f=g=>{g.key==="Escape"&&s()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[s,e]),o.useEffect(()=>{if(!e)return;const f=g=>{const S=g.target;if(!(S instanceof Node)){s();return}i.current?.contains(S)||n.current?.contains(S)||s()};return document.addEventListener("pointerdown",f,!0),document.addEventListener("wheel",f,!0),()=>{document.removeEventListener("pointerdown",f,!0),document.removeEventListener("wheel",f,!0)}},[n,s,e]),a?t.jsxs("div",{ref:p,className:"fixed inset-x-0 bottom-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px))] z-20 pointer-events-none",children:[t.jsx("div",{ref:i,role:"tooltip","aria-label":"Context usage for current conversation",className:B("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",m?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...m?{top:8,left:h??8,width:`min(${gi}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"space-y-1",children:r?t.jsxs(t.Fragment,{children:[t.jsx(Pn,{iconNode:t.jsx(ra,{percentage:r.percentage}),label:"Context",children:t.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[t.jsxs("span",{className:B("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),t.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?t.jsxs(t.Fragment,{children:[t.jsx(Pn,{icon:"stack",label:"Cache read",children:t.jsx("span",{className:"tabular-nums",children:Wn(r.cacheRead)})}),t.jsx(Pn,{icon:"edit",label:"Cache write",children:t.jsx("span",{className:"tabular-nums",children:Wn(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?t.jsx(Pn,{icon:"check",label:"Cache hit",children:t.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):t.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),t.jsx("style",{children:`
|
|
3
3
|
@keyframes session-metadata-in {
|
|
4
4
|
from { opacity: 0; transform: translateY(-8px) scale(0.985); }
|
|
5
5
|
to { opacity: 1; transform: translateY(0) scale(1); }
|
|
@@ -53,4 +53,4 @@ ${w}
|
|
|
53
53
|
`):we.slice(0,-1).join(`
|
|
54
54
|
`);if(jt.current=tt.endsWith(`
|
|
55
55
|
`)?"":(we[we.length-1]??"").slice(-1024),!et)return;const ut=cg(et);if(!ut||it.current.has(ut))return;const Ot=xe.current;it.current.add(ut),dg(ut).then(Ut=>{if(it.current.delete(ut),!Ut||xe.current!==Ot)return;const Rt=Ee.getState().getDirectoryState(L)?.tabs.find(Gt=>Gt.id===re);!Rt||Rt.previewUrlLocked||Rt.previewUrl===ut||U(L,re,ut,{locked:!1,autoOpened:!1})})},[U]),se=o.useCallback((L,re,me)=>{if(Q.current===me)return;w(),Q.current=me;const tt=s.connect(me,{onEvent:we=>{if(Q.current===me)switch(we.type){case"snapshot":{ee(L,re,!1),Be(null),pe(!1),ke(!1),Oe(),te(L,re,we.data??"",we.sequence??0),Y(L,re,we.data??""),we.status==="exited"&&G(L,re,"exited");break}case"reconnecting":{Be(null),pe(!1),ke(!0);break}case"data":{we.data&&(Z(L,re,we.data,we.sequence,we.replayData),Y(L,re,we.data));break}case"exit":{const et=typeof we.exitCode=="number"?we.exitCode:null,ut=typeof we.signal=="number"?we.signal:null,Ut=!!Ee.getState().getDirectoryState(L)?.tabs.find(Rt=>Rt.id===re)?.label?.startsWith("Action:");Z(L,re,`\\r\\n[Process exited${et!==null?` with code ${et}`:""}${ut!==null?` (signal ${ut})`:""}]\\r\\n`),G(L,re,"exited"),ee(L,re,!1),Be(Ut?null:"Terminal session ended"),pe(!1),ke(!1),w();break}}},onError:(we,et)=>{if(Q.current===me){if(!et){Be(null),pe(!1);return}if(ke(!1),we.code==="SESSION_NOT_FOUND"&&!Ee.getState().getDirectoryState(L)?.tabs.find(Ot=>Ot.id===re)?.label?.startsWith("Action:")){Be(null),pe(!1),ee(L,re,!1),P(L,re,null),G(L,re,"idle"),w();return}Be(`Connection failed: ${we.message}`),pe(!0),ee(L,re,!1),G(L,re,"exited"),P(L,re,null),w()}}});J.current=()=>{tt.close(),Q.current=null}},[Z,te,w,Oe,Y,ee,G,P,s]);o.useEffect(()=>{let L=!1;if(!M||!Ce)return;if(!b){Be(A?"No working directory available for terminal.":"Select a session to open the terminal."),w();return}return(async()=>{const me=b;if(!be.current||be.current!==me)return;if(!Ee.getState().getDirectoryState(me)){N(me);return}const we=Ee.getState().getDirectoryState(me);if(!we||we.tabs.length===0)return;const et=we.activeTabId??we.tabs[0]?.id??null;if(!et)return;const ut=we.tabs.find(gt=>gt.id===et)??we.tabs[0],Ot=ut?.terminalSessionId??null,Ut=ut?.lifecycle??"idle",Rt=!!ut?.label?.startsWith("Action:"),Gt=Ee.getState().getBuffer(me,et),Ft=Gt.byteLength>0||Gt.chunks.length>0;if(!Ot){if(Ut==="exited"){ee(me,et,!1);return}if(Rt&&Ft){ee(me,et,!1);return}const gt=`${me}\0${et}`;if(lt.current.has(gt))return;const Bt=je.current??Hi;lt.current.add(gt),Be(null),pe(!1),ke(!1),ee(me,et,!0);try{const H=await s.createSession({cwd:me,sessionId:et,cols:Bt.cols,rows:Bt.rows,shell:c,loginShell:d,...i.current}),ne=!L&&be.current===me&&ge.current===et;if(!Ee.getState().getDirectoryState(me)?.tabs.find(he=>he.id===et)){try{await s.close(H.sessionId)}catch{}return}if(P(me,et,H.sessionId),!ne)return;const de=je.current;de&&(de.cols!==Bt.cols||de.rows!==Bt.rows)&&s.resize({sessionId:H.sessionId,...de}).catch(()=>{});return}catch(H){const ne=Ee.getState().getDirectoryState(me)?.tabs.find(oe=>oe.id===et);if(!ne||ne.terminalSessionId||(ee(me,et,!1),be.current!==me||ge.current!==et))return;Be(H instanceof Error?H.message:"Failed to start terminal session"),pe(!0),ke(!1);return}finally{lt.current.delete(gt)}}!Ot||L||(X.current=Ot,se(me,et,Ot))})(),()=>{L=!0,X.current=null,w()}},[A,b,z,Re,R,Ce,f,M,N,ee,G,P,se,w,s,d,c]),o.useEffect(()=>{if(!O||m)return;if(typeof window>"u"){Oe();return}const L=window.requestAnimationFrame(()=>{Oe()});return()=>{window.cancelAnimationFrame(L)}},[R,Oe,O,m]);const ue=o.useCallback(async()=>{if(!b||ot)return;const L=Ee.getState().getDirectoryState(b),re=R??L?.activeTabId??L?.tabs[0]?.id??null;if(!re)return;const me=L?.tabs.find(tt=>tt.id===re)?.terminalSessionId??null;if(!(!me||!s.restartSession)){ze(!0),Be(null),pe(!1),ke(!1),w(),Le();try{const tt=je.current??Hi,we=await s.restartSession(me,{cwd:b,shell:c,loginShell:d,...tt,...i.current});if(Ee.getState().getDirectoryState(b)?.tabs.find(ut=>ut.id===re)?.terminalSessionId!==me||(P(b,re,we.sessionId),G(b,re,"running"),be.current!==b||ge.current!==re))return;X.current=we.sessionId,se(b,re,we.sessionId)}catch(tt){if(Ee.getState().getDirectoryState(b)?.tabs.find(et=>et.id===re)?.terminalSessionId!==me||be.current!==b||ge.current!==re)return;Be(tt instanceof Error?tt.message:"Failed to restart terminal"),pe(!1),ke(!1),X.current=me,se(b,re,me)}finally{ze(!1)}}},[R,w,b,f,ot,Le,G,P,se,s,d,c]),Se=o.useCallback(async()=>{await ue()},[ue]),Pe=o.useCallback(()=>{if(!b)return;const L=C(b);I(b,L),Be(null),pe(!1),ke(!1),w()},[C,w,b,I]),He=o.useCallback(()=>{const L=Ae.current?.getSelection(),re=k??(_?.open?"draft":null);!L||!re||!q||!b||K({directory:b,sessionKey:re},{source:"terminal",fileLabel:q.label,startLine:L.startLine,endLine:L.endLine,code:L.text,language:q.terminalSessionId??q.id,text:""})},[q,K,k,b,_?.open]),mt=o.useCallback(L=>{b&&(I(b,L),Be(null),pe(!1),ke(!1),w())},[w,b,I]),bt=o.useCallback(L=>{if(!b)return;L===R&&w(),Be(null),pe(!1),ke(!1);const re=Ee.getState().getDirectoryState(b)?.tabs.find(me=>me.id===L)?.terminalSessionId;(async()=>{re&&await s.close(re),D(b,L)})().catch(me=>Be(me instanceof Error?me.message:"Terminal session ended"))},[R,D,w,b,s]),qe=o.useCallback(L=>{if(!L||We)return;let re=L,me=!1;ve&&L.length>0&&(re=hg(L,ve),me=!0);const tt=X.current;tt&&(s.sendInput(tt,re).catch(we=>{We||Be(we instanceof Error?we.message:"Failed to send input")}),me&&($e(null),Ke()))},[ve,Ke,We,$e,s]),dt=o.useCallback((L,re)=>{const me=je.current;if((!me||me.cols!==L||me.rows!==re)&&(je.current={cols:L,rows:re}),!O)return;const tt=X.current;tt&&s.resize({sessionId:tt,cols:L,rows:re}).catch(()=>{})},[O,s]),xt=o.useCallback(L=>{$e(re=>re===L?null:L),Ke()},[Ke,$e]),Me=o.useCallback(L=>{const re=fg(L,ve);re&&(qe(re),$e(null),Ke())},[ve,Ke,qe,$e]),Ze=o.useMemo(()=>({Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"}),[]),yt=o.useCallback(L=>{if(L.repeat)return;const re=L.key;if(!re||re==="Control"||re==="Meta"||re==="Alt"||re==="Shift")return;const me=re.length===1?re.toLowerCase():re;if(me in Ze){L.preventDefault(),L.stopPropagation(),Me(Ze[me]);return}if(ve!=="ctrl")return;const tt=L.code??"",we=re.length===1&&/[a-zA-Z]/.test(re)?re.toUpperCase():tt.startsWith("Key")&&tt.length===4?tt.slice(3).toUpperCase():null;if(we&&we.length===1&&we>="A"&&we<="Z"){const et=dl(we);if(!et)return;L.preventDefault(),L.stopPropagation(),qe(et),$e(null),Ke()}},[ve,Ke,Me,qe,Ze,$e]);o.useEffect(()=>{if(!(!S||!ve||!z))return window.addEventListener("keydown",yt),()=>window.removeEventListener("keydown",yt)},[ve,yt,S,z]);const Nt=o.useMemo(()=>{const L=tn[cr].stack;if(typeof window>"u")return(tn[a]??tn[cr]).stack;const me=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return me&&me.trim().length>0?me.trim():(tn[a]??tn[cr]).stack??L},[a]),Pt=o.useMemo(()=>zm(r),[r]),Et=`${b??"no-dir"}::${R??"no-tab"}`;if(o.useEffect(()=>{if(!O||m)return;const L=Ae.current;if(!L)return;const re=()=>{L.fit()};if(typeof window<"u"){const me=window.requestAnimationFrame(()=>{re(),Oe()}),tt=[220,400].map(we=>window.setTimeout(re,we));return()=>{window.cancelAnimationFrame(me),tt.forEach(we=>window.clearTimeout(we))}}re()},[Oe,O,m,Et,z]),o.useEffect(()=>{if(!O||!m)return;let L=null;const re=()=>{L!==null&&window.cancelAnimationFrame(L),L=window.requestAnimationFrame(()=>{L=null,Ae.current?.fit()})};return window.addEventListener("oc:keyboard-settled",re),()=>{window.removeEventListener("oc:keyboard-settled",re),L!==null&&window.cancelAnimationFrame(L)}},[O,Et,m]),!A)return t.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:"Select a session to open the terminal."});if(!b)return t.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[t.jsx("p",{children:"No working directory available for this session."}),t.jsx("button",{onClick:ue,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const It=!z||Ye||ot||We,At=Ce,F=x?"lg":"xs",Ne=x?"w-10 p-0":"w-9 p-0",Ue=L=>{x&&L.preventDefault()},pt=t.jsxs(t.Fragment,{children:[t.jsx(Ve,{type:"button",size:F,variant:"outline",onPointerDown:Ue,onClick:()=>Me("esc"),disabled:It,children:"Esc"}),t.jsxs(Ve,{type:"button",size:F,variant:"outline",className:Ne,onPointerDown:Ue,onClick:()=>Me("tab"),disabled:It,children:[t.jsx(j,{name:"arrow-right",className:"h-4 w-4"}),t.jsx("span",{className:"sr-only",children:"Tab"})]}),t.jsxs(Ve,{type:"button",size:F,variant:"chip","aria-pressed":ve==="ctrl",className:x?"px-3":"px-2",onPointerDown:Ue,onClick:()=>xt("ctrl"),disabled:It,children:[t.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),t.jsx("span",{className:"sr-only",children:"Control modifier"})]}),t.jsxs(Ve,{type:"button",size:F,variant:"chip","aria-pressed":ve==="alt",className:x?"px-3":"px-2",onPointerDown:Ue,onClick:()=>xt("alt"),disabled:It,children:[t.jsx("span",{className:"text-xs font-medium",children:"Alt"}),t.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),t.jsxs(Ve,{type:"button",size:F,variant:"outline",className:Ne,onPointerDown:Ue,onClick:()=>Me("arrow-up"),disabled:It,children:[t.jsx(j,{name:"arrow-up"}),t.jsx("span",{className:"sr-only",children:"Arrow up"})]}),t.jsxs(Ve,{type:"button",size:F,variant:"outline",className:Ne,onPointerDown:Ue,onClick:()=>Me("arrow-left"),disabled:It,children:[t.jsx(j,{name:"arrow-left"}),t.jsx("span",{className:"sr-only",children:"Arrow left"})]}),t.jsxs(Ve,{type:"button",size:F,variant:"outline",className:Ne,onPointerDown:Ue,onClick:()=>Me("arrow-down"),disabled:It,children:[t.jsx(j,{name:"arrow-down"}),t.jsx("span",{className:"sr-only",children:"Arrow down"})]}),t.jsxs(Ve,{type:"button",size:F,variant:"outline",className:Ne,onPointerDown:Ue,onClick:()=>Me("arrow-right"),disabled:It,children:[t.jsx(j,{name:"arrow-right"}),t.jsx("span",{className:"sr-only",children:"Arrow right"})]}),t.jsxs(Ve,{type:"button",size:F,variant:"outline",className:Ne,onPointerDown:Ue,onClick:()=>Me("enter"),disabled:It,children:[t.jsx(j,{name:"arrow-go-back"}),t.jsx("span",{className:"sr-only",children:"Enter"})]})]});return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-[var(--surface-background)]",children:[t.jsxs("div",{className:B("app-region-no-drag sticky top-0 z-20 shrink-0 bg-[var(--surface-background)] text-xs",x?"px-3 py-1.5":"pl-3 pr-1.5 py-1"),children:[v?t.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[t.jsx("div",{className:B("min-w-0 flex-1",x?"h-8":"h-7"),children:t.jsx(tg,{items:ae,activeId:R,onSelect:mt,onClose:bt,layoutMode:"scrollable",variant:"default",className:"h-full bg-transparent"})}),t.jsx(Ve,{type:"button",size:"xs",variant:"ghost",className:B("shrink-0",x?"h-8 w-8 p-0":"h-7 w-7 p-0"),onClick:Pe,title:"New tab",children:t.jsx(j,{name:"add",className:`${x?"h-[18px] w-[18px]":"h-4 w-4"}`})}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[t.jsx(Ve,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{ue()},disabled:ot,title:"Restart terminal","aria-label":"Restart terminal",children:t.jsx(j,{name:"restart",className:"h-4 w-4"})}),t.jsx(Ve,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 p-0",onClick:He,title:"Attach selected output","aria-label":"Attach selected output",children:t.jsx(j,{name:"attachment-2",className:"h-4 w-4"})}),_e?t.jsxs(Ve,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{b&&T(b,_e)},title:"Open preview pane",children:[t.jsx(j,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),t.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,!x&&S&&f&&v?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:pt}):null,!x&&S&&!v?t.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:pt}):null]}),t.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:Pt.background},children:[t.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:At?t.jsx(cl,{ref:L=>{Ae.current=L},sessionKey:Et,chunks:Te,onInput:qe,onResize:dt,theme:Pt,fontFamily:Nt,fontSize:l,enableTouchScroll:m,autoFocus:O,isVisible:O},Et):null}),!We&&Qe&&t.jsxs("div",{className:"absolute inset-x-0 bottom-0 bg-[var(--status-error-background)] px-3 py-2 text-xs text-[var(--status-error-foreground)] flex items-center justify-between gap-2",children:[t.jsx("span",{children:Qe}),ie&&x&&t.jsx(Ve,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:Se,disabled:ot,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),x&&S?t.jsx("div",{className:"shrink-0 overflow-x-auto border-t border-border/40 bg-[var(--surface-background)] px-2 pt-1.5 pb-[max(0.375rem,calc(var(--oc-app-bottom-safe,0px)-var(--oc-keyboard-inset,0px)))] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:pt})}):null]})},pg=ps(()=>({statusById:new Map})),Ux=()=>{ya(),pa()},Gx=e=>{Fe.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ce.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ya(),Ee.getState().clearAll(),ws.getState().resetForRuntimeSwitch(),_t.setState({providers:[],agents:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),$t.getState().resetForRuntimeSwitch(),$d.getState().resetForRuntimeSwitch(),pg.setState({statusById:new Map}),Ud(),Gd(),tf.getState().reset(),gu.getState().resetForRuntimeSwitch(),oa.getState().resetForRuntimeSwitch(e.runtimeKey),fa.getState().resetForRuntimeSwitch(e.runtimeKey),nn.getState().resetForRuntimeSwitch(e.runtimeKey),yp.getState().resetForRuntimeSwitch(),Wt.getState().resetForRuntimeSwitch(e.runtimeKey),xu.getState().resetForRuntimeSwitch(e.runtimeKey),Fe.getState().restoreForRuntimeSwitch(e.runtimeKey),ce.getState().restoreForRuntimeSwitch(e.runtimeKey);const s=ce.getState();Gr({sessionId:Fe.getState().currentSessionId,tab:s.activeMainTab,isSettingsOpen:s.isSettingsDialogOpen,settingsPath:s.settingsPage,diffFile:s.pendingDiffFile},{replace:!0,force:!0}),pa()},mg=48,gg=96,Qt=(e,...s)=>{try{e?.(...s)}catch{}},kr=(e,s)=>{if(typeof e=="function"){const n=e();return n>0?n:s}return typeof e=="number"&&e>0?e:s},Kx=(e,s)=>{const n=o.useRef(s);n.current=s;const r=s.enabled;o.useEffect(()=>{const i=e.current;if(!i||r===!1)return;const a=i.style.touchAction;i.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?gg:mg;let d=!1,u=!1,p=!1,h=null,x=!1,m=0,f=0,g=0,S=0;const k=()=>{d=!1,u=!1,p=!1,h=null},_=()=>{const I=n.current,D=h,P=x;u&&D&&(Qt(D==="left"?I.onLeftProgress:I.onRightProgress,P?1:0),Qt(I.onDragEnd,D,P)),k()},A=()=>{_(),u||k()},b=I=>{const D=n.current;if(D.enabled===!1){u&&h?_():k();return}if(I.touches.length!==1){u&&h?_():k();return}const P=I.touches[0],G=i.getBoundingClientRect(),ee=i.clientWidth,Z=!!D.leftOpen,te=!!D.rightOpen,U=K=>km(K,i);if(Z||te){if(U(I.target)){k();return}if(Z&&te){const K=P.clientX<=G.left+c;P.clientX>=G.right-c?(h="right",x=!0):K?(h="left",x=!0):(h=Z?"left":"right",x=!0)}else Z?(h="left",x=!0):(h="right",x=!0);S=kr(h==="left"?D.leftWidth:D.rightWidth,ee),S<10&&(S=ee||window.innerWidth||320),S<10&&(S=320),d=!0}else{if(U(I.target)){k();return}h=null,x=!1,S=0,d=!0}m=P.clientX,f=P.clientY,g=Date.now(),u=!1,p=!1},v=I=>{if(!d)return;if(I.touches.length!==1){A();return}const D=I.touches[0],P=D.clientX-m,G=D.clientY-f;if(!p){if(Math.abs(P)<Fi&&Math.abs(G)<Fi)return;if(Math.abs(G)>Math.abs(P)*rn){k();return}if(!h){const te=n.current;h=P>0?"left":"right",S=kr(h==="left"?te.leftWidth:te.rightWidth,i.clientWidth),S<10&&(S=window.innerWidth||320)}if(h==="left"){if(!x&&P<=0){k();return}if(x&&P>=0){k();return}}else{if(!x&&P>=0){k();return}if(x&&P<=0){k();return}}p=!0,u=!0,Qt(n.current.onDragStart,h)}if(!u)return;I.cancelable&&I.preventDefault();const ee=n.current,Z=Li(h,x,P,S);Qt(h==="left"?ee.onLeftProgress:ee.onRightProgress,Z)},M=(I,D)=>{if(!d){k();return}const P=I-m,G=D-f;if(!h&&!x&&Math.abs(P)>=$n&&Math.abs(G)<=Math.abs(P)*rn){const T=n.current;h=P>0?"left":"right",S=kr(h==="left"?T.leftWidth:T.rightWidth,i.clientWidth),S<10&&(S=window.innerWidth||320)}if(!h){k();return}const ee=Math.max(1,Date.now()-g),Z=n.current;if(!u){const T=Math.abs(P),R=Math.abs(G);T>=$n&&R<=T*rn?h==="left"&&!x&&P>0?(Qt(Z.onLeftProgress,1),Qt(Z.onLeftOpen)):h==="right"&&!x&&P<0?(Qt(Z.onRightProgress,1),Qt(Z.onRightOpen)):Qt(h==="left"?Z.onLeftProgress:Z.onRightProgress,x?1:0):Qt(h==="left"?Z.onLeftProgress:Z.onRightProgress,x?1:0);const q=h;k(),Qt(Z.onDragEnd,q);return}const te=Li(h,x,P,S),U=Sm({side:h,isOpenAtStart:x,dx:P,dt:ee,progress:te}),K=h;Qt(K==="left"?U?Z.onLeftOpen:Z.onLeftClose:U?Z.onRightOpen:Z.onRightClose),k(),Qt(Z.onDragEnd,K,U)},N=I=>{const D=I.changedTouches[0];if(!D){k();return}const P=D.clientX-m,G=D.clientY-f;d&&(u||Math.abs(P)>=$n&&Math.abs(G)<=Math.abs(P)*rn)&&I.cancelable&&I.preventDefault(),M(D.clientX,D.clientY)},C=()=>{A()};return i.addEventListener("touchstart",b,{passive:!0}),i.addEventListener("touchmove",v,{passive:!1}),i.addEventListener("touchend",N,{passive:!1}),i.addEventListener("touchcancel",C,{passive:!0}),()=>{try{u&&h&&_()}catch{}i.style.touchAction=a,i.removeEventListener("touchstart",b),i.removeEventListener("touchmove",v),i.removeEventListener("touchend",N),i.removeEventListener("touchcancel",C)}},[e,r])};function Hx({className:e="h-5 w-5"}){return t.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[t.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),t.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),t.jsx(j,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function Wi({size:e,className:s,style:n,...r}){return t.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:s,style:{width:typeof e=="number"?`${e}px`:e,height:typeof e=="number"?`${e}px`:e,...n},...r,children:t.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"})})}const xg=({sessionDirectory:e,draftDirectory:s,isNewSessionDraftOpen:n})=>n?s:e,bg=({activeProjectLabel:e,openDirectory:s,homeDirectory:n})=>Jn(s,n)?null:e,Cr=()=>Ds.filter(e=>Or.has(e.id)).map(e=>({...va(e)})),yg=()=>{if(typeof window>"u")return Br;const e=window.localStorage.getItem("openInAppId");return e&&Lr(e)?e:Br};let Nr=!1,zs=!1,bs=!1,ys=0,hn=null;const Vi=()=>{hn&&(clearTimeout(hn),hn=null)},Ns=ps()((e,s)=>({selectedAppId:yg(),availableApps:Cr(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Nr||typeof window>"u")return;Nr=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:Cr(),hasLoadedApps:u});return}const p=new Set(d.map(f=>f.name)),h=new Map(d.map(f=>[f.name,f.iconDataUrl??void 0])),m=Ds.filter(f=>p.has(f.appName)||Or.has(f.id)).map(f=>({...va(f),iconDataUrl:h.get(f.appName)}));e({availableApps:m,hasLoadedApps:!0})},r=async d=>{if(!vs()||!mn()||zs||s().hasLoadedApps&&!d)return;const p=Ds.map(h=>h.appName);Vi(),zs=!0,bs=!1,e({isScanning:!0});try{const{apps:h,success:x,hasCache:m,isCacheStale:f}=await ti(p,d),g=x&&!m&&h.length===0&&ys<3;if(e({isCacheStale:m?f:!1}),n(h,x?!g:!1),x){if(g){const k=[800,1600,3200][ys]??3200;ys+=1,bs=!0,hn=setTimeout(()=>{r()},k);return}ys=0,bs=!1;return}if(ys<3){const k=[1e3,3e3,7e3][ys]??7e3;ys+=1,bs=!0,hn=setTimeout(()=>{r()},k)}}finally{zs=!1,bs||e({isScanning:!1})}};r();const i=d=>{const u=d.detail,p=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&Lr(u.openInAppId)?u.openInAppId:null;p&&(window.localStorage.setItem("openInAppId",p),e({selectedAppId:p}))},a=()=>{r()},l=d=>{const u=d.detail;Array.isArray(u)&&(ys=3,bs=!1,e({isScanning:!1,isCacheStale:!1}),n(u))};window.addEventListener("pichamber:settings-synced",i),window.addEventListener("pichamber:app-ready",a),window.addEventListener("pichamber:installed-apps-updated",l),window.__pichamberAppReady&&r(),window.setTimeout(()=>{s().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(Nr||s().initialize(),!vs()||!mn()||zs||s().hasLoadedApps&&!n)return;const i=Ds.map(a=>a.appName);Vi(),n&&e({hasLoadedApps:!1}),zs=!0,bs=!1,e({isScanning:!0});try{const{apps:a,hasCache:l,isCacheStale:c}=await ti(i,n),d=new Set(a.map(x=>x.name)),u=new Map(a.map(x=>[x.name,x.iconDataUrl??void 0])),h=Ds.filter(x=>d.has(x.appName)||Or.has(x.id)).map(x=>({...x,iconDataUrl:u.get(x.appName)}));e({availableApps:h.length>0?h:Cr(),hasLoadedApps:h.length>0,isCacheStale:l?c:!1})}finally{zs=!1,bs||e({isScanning:!1})}},selectApp:async n=>{Lr(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await no({openInAppId:n}))}})),vg="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAXaSURBVFgJ7VddbBRVFP5mdme6dOnu2tZawOAPjfxU+bGQYCRAsvw8qNGEQPTRJ0I0amL0wfjgA/HBR8KLD8YgDxJEUkVFxSYYTSRii6DQQCMGIQqlW7p0u+zMzo/fuTuzO9Nt0Td94CRn7pl7z5zznZ977y5wh/7jDGiz+T979qD5Ujbfd90xlll+stOF1uI40B1+4HhkjnZk9CgLQ9iXp2/BdcbgVc/h0sAgduywudJEMwLY9Of4ugtW5p3CpL7W1jTN88VmjdQYvnDKF1mczkYuNZLeCVg3X8fa9u+nqzUB2HRpdN2pSseRQknPoUL1Jo2ICTrPGcCzdwPdHENcAnicKRqcAk7cpL5J1r0JlAtPYV1XDETM/FtH3m19r+f5by+XjNX/xnmCX3/cCzydi4CKiC7lw+PArhGgoPPFq/6E0+9vwM6d5VBNpuv03cLNfeNTRh9KnJIiV2/PvSngycC5RD+dE5zb3g7s6QESzAZc2l6wuY9SnWIAxv10r81uU85Vt1FvtpEtlc/SMFUkUofeZ2IBta0DWDmXgkfbyTRz1qAYAMczOz3p1elOxYPyEllj421hdELViPO6Kudk3ia3UGe5ABDbvtnJZ52SdYmCZ3stdeexBabFdeAbYopEowtagVUZqFapBrtAGqpiVaFrGgyjZlrmTD5yEqoEJj4iFMuA62i6L3WPZkAiuHgarZ/vbWSBkTzO2rfTR4XOJVJhjfX44MBn+OTocVWbcF5MalxXPeVL6zYonoGo44YOtDI7qHC1lkL5nHnOc+tJRi3K6iygLNGMjt1A1XVV6iUzOvVtAvMlS2I/yBYlRf8MgA6szmXQ1jDfKhSgjft6DRtrkgarAiAw5nI9v2WDSn+Zxfd9DawGxIlPPQUg0A2HGABfEIYlCDU4+q0d8O+jRzHCCFYy+nu4BaeYAoksBCDrPYsXQQ6iitgiSQaS1FHHtMzFil4DpxTl4UhORSn4WOaaiGsbu4iFRkMnYQlEV0oSJQGQ4FyYgSRDjpqPZcCR6EOOWonIEsBqArAIQOMLzw0VXRRERF2VoA6Atk1+MzsASekMJYgaFEeHR4Cr85lNGntYzgKCYd/NSNIDCXr0ZJ2jwTsjSvEMzFQCCVmKHBRahn2DNb4rDRx8pnbXOOIg0JELLMHOF1AUkaRj1V8c2TookkMS83WK9QCVpRwtf5wCykQWRKDyJ44Ytc452QUV6inmN9IDIv/6y2+YLDuqTywBEHxv8rsoxQC4Fpf4cZ2pbJ4/huxXr0EvFmoRCrAIVymLQ3Eid0GJYPsPfISBLwdwi79YQnCqBNS7LQDP5qYSAKEDypOrX4WVWYLsFy+i9cwh6CUmUKIJI2Gq5cSbnLLw849D2Ld3L4olC1u3P0c1ow5Ozgixa3puWChONG1D3eLZUQOglvng+Vp5dBfseesx5/yHyI4cBTL3wsssRGs2g6/ppHijiMLoNSSMNHofy6Nn6SPsAR02nUoTtrDTSrdoi8CTni55rlOsCf1ypaDxlFMNU1epCV5XL6Y6dmOq+BeS48NIlq7Anpjg5dOFbPdDWLQyj/aubnUKSkMKi3NhkUd4kieYtbRbYS0bFAOQKI8NO363z1RJHmamtnlwhGksxV2w/gl29WRtm8kWtWUnRShLnQvXgDOXmLg2HzlvbDiyHD8Y517YP2i4FtueFPbB9FFqKcyobk4A5y7zquUFa7IXojyHoeXmAFcY755vaI6A56Xsofm/7+cmblBTpOldQ5vs3PJDVS+RVSAaus2SpJTO80t4NTNSOQfCDrtFkBevA0ME6HGvPdDpFlekzm7rf3nFQNRQEwBZTL9warObWfx21Uv1+fx1ERqVNampGoOHpF1tsdp07RnoGMxK1vT97rbK4IP6+Tc+fWXVsahaYGL6VO09d//GXHXr7jVeqmuppqU6ff4x0RO6lqRxgxHJpWKSlcw5eWfjq5rq/CdhaL5l6JWxjDc6bP7w5sn+/uMs2B36H2bgb6v9raK0+o9IAAAAAElFTkSuQmCC",wg="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAQzSURBVFgJ7VZNbBNHFH67Xv9RxwnBDqlUoQglcZK6qSIEJIQWAYJQoVY9IE5RTzn20FMvqdpDesq9B24+NdwthAJCkZChJg1JSOXYQIwQKQIaBdtENbs73t2+N8miGWOcpFHUHniyd97OvJ9v3nv7ZgDe038cAeVd/jOZjC94sKdfU+Bj24G9igpexwYPyiu2bauKqqqirkOTqmrjnIOyFsoyUKDocSCj/7mU7ujoMER5l68JYOFZ4YSiwPjd9O0jjx7ch1KhAJZVAcdx0LxDv3XetYKjggr4I4bzHo8G4aYmONjZBYf6+2dUzfd9PNowJajUZmef/PX5zcWl0rmvvnbQHrra+f/M+S+dqYXs2t3Hz09Ve5UicCmZ3NPb1Zv66btv+65dSULA64WGxkbw+Xx8V9XK9d4pWowxeFUqgW6acHroC/j5l0sLD/PZY98MDf3t6mouQ+On3X1H7/2e7rtOztHpgbY2+CAUgperq+D3+7cNgtLSEA7D0+VluDF5FS7cSff2HT56DF1dd/3KhQTWJ/lclsc8jIrk9IfRURgZGQEvRqNSWa8D2t1W/liXXK8Ro0i0lF0ExaPEXec0SgAqhrm3VCzwdS9GQNd1GBsbg0AgAIlEAlpbW7EYLVF/U56AagieiGwbuhERlSQApmEE8c/XKXxU0fF4HNowFfPz81Aul7edBjLGbeHITANsZga4g42HVAM2Y74KM/kSIQ/izgcHB2FiYgJmZmZ4MZpYULRG5PF4+Bx/2cLDxuhhYUqFLwGoWCaQEBGhNjAa4+Pj/J3SQA6pHpqbm/kcNitIJpOgaZIZvlbrQbZNJvcjSZOZDKhwRKLic4l2Pjc3B8FgkE+trKxAVUN0RWuOZNtCHyJJACj/bgREIZcnA9PT029SQM63unuywSOwUWOuTQmAhfmnlluPxIjUk6u1RrbJh0jyV0Ap2OZnJhrbjOcRqEqBBMDCAtltAORDJAkAVj2mWS5CUXinPDUx+oxFkgBYjO0qANu2wKoqQgkAfgW7C4AiYMmfoQSgwpjj7GYRUh/Q66SAmdisNxql227FfP1bXrRlVExdtCNHwDRLdPkgwmi8OUREhe3y1NLJFpEfbWMNvBRtSI2o+KqYi+zbx4NQwptMCO8E1HjEHYjKm/HknG5FZIsCG4lEoLS2lhP1JAB3bt1KH//s+GJPd3dPJpvlN5kwXiYIhHukisr1eAItXsm6YzGItrTcn5+dvS3qSQBSqVQhFouNnj039CsaCC7mcqDjgbNT6op1AtrU8Wo3Ojk5KaVAOptdR8PDwxf3t7SMvXjxvJNOPP31a35Krt8CXKl3j2SUDip/IAjRaBRaP9z/cHW18GMikbhcrVUTAAm1t7d/NDAwcDIUCvVqmtqkyLe3ajtvvTtg4x3SLpbLa3+kUr9N5fP55beE3k/8HyLwDx2/HIx7q3WfAAAAAElFTkSuQmCC",Ar=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?vg:e.id==="terminal"?wg:void 0}),Yi=({label:e,iconDataUrl:s,fallbackIconDataUrl:n})=>{const[r,i]=o.useState(!1),a=e.trim().slice(0,1).toUpperCase()||"?",l=s||n;return l&&!r?t.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>i(!0)}):t.jsx("span",{className:B("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:a})},Sg=({directory:e,className:s})=>{const n=Ns(f=>f.selectedAppId),r=Ns(f=>f.availableApps),i=Ns(f=>f.isCacheStale),a=Ns(f=>f.isScanning),l=Ns(f=>f.initialize),c=Ns(f=>f.loadInstalledApps),d=Ns(f=>f.selectApp);o.useEffect(()=>{l()},[l]);const u=vs()&&mn(),p=o.useMemo(()=>{const f=r.find(g=>g.id===n)??r.find(g=>g.id===Br)??r[0]??Ds[0];return Ar(f||Ds[0])},[r,n]);if(!u||!e||r.length===0)return null;const h=async f=>{await bu(e,f.id,f.appName)||await xa(e,f.appName)},x=async f=>{await d(f.id),await h(f)},m=async()=>{(await pn(e)).ok&&le.success("Path copied to clipboard")};return t.jsxs("div",{className:B("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",s),children:[t.jsx("button",{type:"button",onClick:()=>{h(p)},className:B("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",a&&"animate-pulse"),"aria-label":`Open in ${p.label}`,children:t.jsx(Yi,{label:p.label,iconDataUrl:p.iconDataUrl,fallbackIconDataUrl:p.fallbackIconDataUrl})}),t.jsxs(qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:B("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:t.jsx(j,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Xt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[t.jsxs(kt,{className:"flex items-center gap-2",onClick:()=>{m()},children:[t.jsx(j,{name:"file-copy",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),t.jsx(Vs,{}),r.map(f=>{const g=Ar(f);return t.jsxs(kt,{className:"flex items-center gap-2",onClick:()=>{x(f)},children:[t.jsx(Yi,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:g.fallbackIconDataUrl}),t.jsx("span",{className:"typography-ui-label text-foreground",children:f.label}),p.id===f.id?t.jsx(j,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},f.id)}),i?t.jsxs(kt,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[t.jsx(j,{name:"refresh",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},jg=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],kg=["dev","start","preview","serve"];async function Cg(e,s,n){if(!e)return null;const r=Ig(s);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const i=Dg(n);if(i){const a=await Pg(e);return{command:`${a==="npm"?"npm run":a==="yarn"?"yarn":a==="pnpm"?"pnpm":a==="bun"?"bun run --shell=bun":"npm run"} ${i}`,label:`Start (${i})`}}}if(await Ng(e)){const i=await Ag(),a=typeof i=="number"&&Number.isFinite(i)&&i>0?i:8e3;return{command:`python3 -m http.server ${a}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${a}/`}}return null}async function Ng(e){const s=`${e}/index.html`,n=await Qn(s,e);return typeof n=="string"&&n.trim().length>0}async function Ag(){try{const e=await es("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const s=await e.json().catch(()=>null),n=typeof s?.port=="number"?s.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function Ig(e){for(const s of e){const n=`${s.name} ${s.command}`.toLowerCase();if(kg.some(i=>n.includes(i)))return s}return null}function Dg(e){for(const{pattern:s}of jg)for(const n of Object.keys(e))if(s.test(n))return n;return null}async function Pg(e){const s=await Qn(`${e}/package.json`,e);if(s)try{const r=JSON.parse(s),i=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(i.startsWith("bun@"))return"bun";if(i.startsWith("pnpm@"))return"pnpm";if(i.startsWith("yarn@"))return"yarn";if(i.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,i]of n){const a=await Qn(`${e}/${r}`,e);if(typeof a=="string"&&a.trim().length>0)return i}return"npm"}async function Qn(e,s){if(s?.trim())try{const r=new URLSearchParams({path:e,directory:s,optional:"true"}),i=await es(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(i.ok)return i.text()}catch{}const n=ro()?.files;if(n?.readFile)try{const r=await n.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await es(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function Eg(e){try{const s=await Qn(`${e}/package.json`,e);if(s==null)return null;const r=JSON.parse(s).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Tg=(e,s,n)=>new Promise(r=>{let i=!1,a=null,l=null;const c=d=>{i||(i=!0,l&&clearTimeout(l),a?.close(),r(d))};a=e.connect(s,{onEvent:d=>{(d.type==="exit"||d.type==="snapshot"&&d.status==="exited")&&c(!0)},onError:(d,u)=>{u&&c(!0)}}),i?a.close():l=setTimeout(()=>c(!1),n)}),Rg="\x1B",Mg=new RegExp(`${Rg}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Fg=/https?:\/\/[^\s<>'"`]+/gi,Zt="__pichamber_auto_discover_preview__",Lg=15e3,Og=e=>{let s="";for(let n=0;n<e.length;n+=1){const r=e.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(s+=e[n])}return s},Bg=e=>{const s=(e||"").trim();if(!s)return null;const n=/^https?:\/\//i.test(s)?s:`http://${s}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},_g=e=>{const n=e.replace(Mg,"").match(Fg);if(!n||n.length===0)return null;const r=n.map(a=>a.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const i=[];for(const a of r)try{const l=new URL(a);l.port&&l.port.length>0&&i.push({raw:a,parsed:l})}catch{}if(i.length>0){const a=l=>{const{parsed:c}=l,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",p=c.pathname||"/",h=p.split("/").filter(Boolean).length,x=p==="/"||p==="",m=!!(c.search||c.hash);let f=0;return u&&(f+=50),x&&(f+=30),f-=Math.min(h*5,20),m&&(f-=10),f};return i.sort((l,c)=>a(c)-a(l)),i[0]?.parsed.origin??i[0]?.raw??null}return r[0]??null},Qi=({projectRef:e,directory:s,className:n,compact:r=!1,allowMobile:i=!1})=>{const{currentTheme:a}=ha(),{terminal:l}=qn(),{isMobile:c}=Ms(),d=o.useMemo(()=>vs(),[]),u=Kn(O=>O.instances),p=Kn(O=>O.load),h=ce(O=>O.terminalShell),x=ce(O=>O.terminalLoginShells.includes(O.terminalShell)),m=ce(O=>O.setSettingsPage),f=ce(O=>O.setSettingsDialogOpen),g=ce(O=>O.setSettingsProjectsSelectedId),S=ce(O=>O.openContextPreview),k=Ee(O=>O.ensureDirectory),_=Ee(O=>O.setTabLabel),A=Ee(O=>O.setTabIconKey),b=Ee(O=>O.setActiveTab),v=Ee(O=>O.setConnecting),M=Ee(O=>O.setTabSessionId),N=Ee(O=>O.setTabPreviewUrl),C=Ee(O=>O.projectActionRuns),I=Ee(O=>O.setProjectActionRun),D=Ee(O=>O.updateProjectActionRunStatus),P=Ee(O=>O.removeProjectActionRun),[G,ee]=o.useState([]),[Z,te]=o.useState(null),[U,K]=o.useState(!1),T=o.useRef({}),R=o.useRef({}),q=o.useRef({}),ae=o.useRef({}),z=o.useRef(new Set),Re=o.useRef(0),Te=e?.id??null,Ye=e?.path??"",_e=o.useMemo(()=>Te?{id:Te,path:Ye}:null,[Te,Ye]);o.useEffect(()=>{d&&p().catch(()=>{})},[d,p]);const Qe=o.useCallback(async O=>{await Xi(O)},[]),Be=o.useCallback(async()=>{if(!_e)return;const O=Re.current+1;Re.current=O,K(!0);try{const Ce=await Ir(_e);if(Re.current!==O)return;const ye=Ce.actions;ee(ye),te(w=>w===Zt||w&&ye.some(Y=>Y.id===w)?w:null)}catch{if(Re.current!==O)return}finally{Re.current===O&&K(!1)}},[_e]),ie=o.useMemo(()=>_a(s||_e?.path||""),[s,_e?.path]),pe=o.useMemo(()=>Z?G.find(O=>O.id===Z)??null:null,[G,Z]),We=o.useMemo(()=>({id:Zt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),ke=!c,ve=o.useMemo(()=>ke?[We,...G]:G,[G,We,ke]);o.useEffect(()=>{Be()},[Be]),o.useEffect(()=>{if(typeof window>"u")return;const O=Ce=>{const ye=Ce.detail;Te&&(ye?.projectId&&ye.projectId!==Te||Be())};return window.addEventListener(Wr,O),()=>{window.removeEventListener(Wr,O)}},[Be,Te]),o.useEffect(()=>{Z&&(Z===Zt&&ke||G.some(O=>O.id===Z)||te(null))},[G,ke,Z]),o.useEffect(()=>{const O=()=>{const Ce=Ee.getState(),ye=Ce.sessions,w=Ce.projectActionRuns;for(const[Y,se]of Object.entries(w)){const Se=ye.get(se.directory)?.tabs.find(Ze=>Ze.id===se.tabId);if(!Se||Se.terminalSessionId!==se.sessionId){P(Y);continue}const Pe=R.current[Y]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};R.current[Y]=Pe;const He=ve.find(Ze=>Ze.id===se.actionId),mt=Ce.getBuffer(se.directory,se.tabId).chunks;if(!He||mt.length===0)continue;const bt=mt.filter(Ze=>Pe.lastSeenChunkId===null||Ze.id>Pe.lastSeenChunkId);if(bt.length===0)continue;const qe=bt.map(Ze=>Ze.data).join(""),dt=`${Pe.tail}${qe}`,xt=!Pe.openedUrl&&He.autoOpenUrl===!0?_g(dt):null,Me=bt[bt.length-1]?.id??Pe.lastSeenChunkId;if(Pe.lastSeenChunkId=Me,Pe.tail=dt.slice(-512),xt)if(Pe.openedUrl=!0,Pe.openInPreview){const Ze=w[Y];Ze&&(N(Ze.directory,Ze.tabId,xt,{locked:!1,autoOpened:!1}),Ze.status==="waiting-for-preview"&&D(Y,"running"),window.clearTimeout(ae.current[Y]),delete ae.current[Y],S(Ze.directory,xt))}else Qe(xt),le.success("Opened URL from action output");R.current[Y]=Pe}for(const Y of Object.keys(R.current))w[Y]||(delete R.current[Y],window.clearTimeout(ae.current[Y]),delete ae.current[Y])};return O(),Ee.subscribe((Ce,ye)=>{(Ce.sessions!==ye.sessions||Ce.buffers!==ye.buffers)&&O()})},[ve,S,Qe,C,P,N,D]);const $e=o.useCallback(async(O,Ce={})=>{if(!ie)throw new Error("No active directory");const ye=us(ie,O.id);k(ie);const w=Ee.getState(),Y=w.getDirectoryState(ie);let se=T.current[ye]||null;const ue=se?!!Y?.tabs.some(He=>He.id===se):!1;(!se||!ue)&&(se=w.createTab(ie),T.current[ye]=se),_(ie,se,`Action: ${O.name}`),A(ie,se,O.icon||"play"),b(ie,se),Ce.revealTerminal!==!1&&ce.getState().openContextPanelTab(ie,{mode:"terminal"});const Pe=Ee.getState().getDirectoryState(ie)?.tabs.find(He=>He.id===se);return{key:ye,tabId:se,sessionId:Pe?.terminalSessionId??null}},[k,ie,b,A,_]),ot=o.useCallback(async O=>{if(!i&&c)return;if(!ie){le.error("No active directory for action");return}const Ce=us(ie,O.id),ye=C[Ce];if(!(ye&&ye.status==="running")&&!z.current.has(Ce)){z.current.add(Ce);try{const w=O.id===Zt?await(async()=>{const[Me,Ze]=await Promise.all([Ir({id:_e?.id??"",path:ie}),Eg(ie)]),yt=await Cg(ie,Me.actions,Ze);if(!yt)throw new Error('No dev server command found. Configure a project action or add a \\"dev\\" script to package.json.');return{id:Zt,name:"Auto-discover",command:yt.command,icon:"scan-2",autoOpenUrl:!0,openUrl:yt.previewUrlHint||""}})():O,Y=w.autoOpenUrl===!0&&(w.openUrl||"").trim().length>0,se=!Y&&O.id!==Zt,{key:ue,tabId:Se,sessionId:Pe}=await $e(w,{revealTerminal:se});let He=Pe;if(!He){v(ie,Se,!0);try{He=(await l.createSession({cwd:ie,sessionId:Se,shell:h,loginShell:x,themeMode:a.metadata.variant==="light"?"light":"dark",terminalBackground:a.colors.surface.background,terminalForeground:a.colors.syntax.base.foreground})).sessionId,M(ie,Se,He)}finally{v(ie,Se,!1)}}if(!He)throw new Error("Failed to create terminal session");q.current[ue]?.(),v(ie,Se,!0);const mt=l.connect(He,{onEvent:Me=>{Me.type==="snapshot"&&(Ee.getState().replaceBuffer(ie,Se,Me.data??"",Me.sequence??0),Ee.getState().setConnecting(ie,Se,!1)),Me.type==="data"&&typeof Me.data=="string"&&Me.data.length>0&&Ee.getState().appendToBuffer(ie,Se,Me.data,Me.sequence,Me.replayData),Me.type==="exit"&&(Ee.getState().setTabLifecycle(ie,Se,"exited"),Ee.getState().setConnecting(ie,Se,!1),Ee.getState().removeProjectActionRun(ue),delete R.current[ue],q.current[ue]?.(),delete q.current[ue],window.clearTimeout(ae.current[ue]),delete ae.current[ue])},onError:(Me,Ze)=>{Ee.getState().setConnecting(ie,Se,!1),Ze&&(Ee.getState().setTabLifecycle(ie,Se,"exited"),Ee.getState().setTabSessionId(ie,Se,null),Ee.getState().removeProjectActionRun(ue))}});q.current[ue]=mt.close;const bt=w.autoOpenUrl===!0&&d&&(w.desktopOpenSshForward||"").trim().length>0,qe=w.autoOpenUrl?Bg(w.openUrl):null,dt=w.autoOpenUrl&&d?Bf(w.desktopOpenSshForward,u):null;I({key:ue,directory:ie,actionId:w.id,tabId:Se,sessionId:He,status:w.id===Zt&&!qe?"waiting-for-preview":"running"}),window.clearTimeout(ae.current[ue]),delete ae.current[ue],w.id===Zt&&!qe&&(ae.current[ue]=window.setTimeout(()=>{const Me=Ee.getState(),Ze=Me.projectActionRuns[ue];Me.updateProjectActionRunStatus(ue,"running"),Ze&&(Me.setActiveTab(Ze.directory,Ze.tabId),ce.getState().openContextPanelTab(Ze.directory,{mode:"terminal"})),delete ae.current[ue]},Lg)),R.current[ue]={lastSeenChunkId:null,openedUrl:!!dt||!!qe||Y,tail:"",openInPreview:w.id===Zt};const xt=Og(w.command.trim().replace(/\r\n|\r/g,`
|
|
56
|
-
`));await l.sendInput(He,`${xt}\r`),dt?(N(ie,Se,null,{locked:!0}),Qe(dt),le.success("Opened forwarded URL")):qe?(N(ie,Se,qe,{locked:!0,autoOpened:!0}),S(ie,qe),le.success("Opened action URL")):Y?(N(ie,Se,null,{locked:!0}),le.error("Invalid custom URL format")):bt?(N(ie,Se,null,{locked:!0}),le.error("Selected desktop SSH forward is unavailable")):N(ie,Se,null,{locked:!1,autoOpened:!1})}catch(w){P(Ce),delete R.current[Ce],q.current[Ce]?.(),delete q.current[Ce],window.clearTimeout(ae.current[Ce]),delete ae.current[Ce],le.error(w instanceof Error?w.message:"Failed to run action")}finally{z.current.delete(Ce)}}},[a.colors.surface.background,a.colors.syntax.base.foreground,a.metadata.variant,u,$e,i,c,d,ie,x,h,Qe,S,C,P,v,I,N,M,_e?.id,l]),ze=o.useCallback(async O=>{const Ce=us(ie,O.id),ye=C[Ce];if(!ye)return;D(Ce,"stopping");const w=Tg(l,ye.sessionId,1e3);try{await l.sendInput(ye.sessionId,"")}catch{}const Y=await w;if(Ee.getState().getDirectoryState(ye.directory)?.tabs.find(Se=>Se.id===ye.tabId)?.terminalSessionId===ye.sessionId&&!Y){if(typeof l.forceKill=="function")try{await l.forceKill({sessionId:ye.sessionId})}catch{}else try{await l.close(ye.sessionId)}catch{}M(ye.directory,ye.tabId,null)}P(Ce),delete R.current[Ce],q.current[Ce]?.(),delete q.current[Ce],window.clearTimeout(ae.current[Ce]),delete ae.current[Ce]},[ie,C,P,M,l,D]),J=o.useCallback(()=>{const O=pe??ve[0];if(!O)return;const Ce=us(ie,O.id),ye=C[Ce];if(ye?.status!=="stopping"){if(ye){ze(O);return}ot(O)}},[ve,ie,ot,C,pe,ze]),Q=o.useCallback((O,Ce=!1)=>{if(te(O.id),!Ce){ot(O);return}const ye=us(ie,O.id),w=C[ye];if(w?.status!=="stopping"){if(w){ze(O);return}ot(O)}},[ie,ot,C,ze]),ge=o.useCallback(()=>{_e?.id&&(g(_e.id),m("projects"),f(!0))},[f,m,g,_e?.id]),X=pe??ve[0]??null,be=X?C[us(ie,X.id)]:null,Ae=Ee(O=>be?O.sessions.get(be.directory)?.tabs.find(Ce=>Ce.id===be.tabId)?.previewUrl??null:null);if(!i&&c||!_e||!ie)return null;const je=pe??ve[0]??null;if(!je)return null;const lt=je.icon||"play",jt=je.id===Zt?"scan-2":fn[lt]||"play",it=us(ie,je.id),xe=C[it],Le=xe?.status==="stopping",Oe=xe?.status==="waiting-for-preview",Ke=!!(xe&&Ae),Ct=()=>{!xe||!Ae||S(xe.directory,Ae)},ht=je.id===Zt;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",disabled:U||Le,className:B("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:J,"aria-label":xe?`Stop ${je.name}`:`Run ${je.name}`,children:Le||Oe?t.jsx(j,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):xe?t.jsx(j,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(j,{name:jt,className:"h-5 w-5"})})}),ht?t.jsx(rt,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),Ke?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:Ct,children:t.jsx(j,{name:"global",className:"h-4 w-4"})})}),t.jsx(rt,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:t.jsx(j,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Xt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(kt,{className:"flex items-center gap-2",onClick:ge,children:[t.jsx(j,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Vs,{}),ve.map(O=>{const Ce=O.icon||"play",ye=O.id===Zt?"scan-2":fn[Ce]||"play",w=us(ie,O.id),Y=C[w],se=!!Y,ue=Y?.status==="stopping";return t.jsxs(kt,{className:"flex items-center gap-2",onClick:()=>{Q(O,!0)},children:[t.jsx(j,{name:ye,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:O.name}),ue||Y?.status==="waiting-for-preview"?t.jsx(j,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):se?t.jsx(j,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},O.id)})]})]})]}):t.jsxs("div",{className:B("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:J,disabled:U||Le,className:B("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":xe?`Stop ${je.name}`:`Run ${je.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:Le||Oe?t.jsx(j,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):xe?t.jsx(j,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(j,{name:jt,className:"h-4 w-4"})})})}),ht?t.jsx(rt,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),Ke?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:Ct,className:B(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:t.jsx(j,{name:"global",className:"h-4 w-4"})})}),t.jsx(rt,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:B(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:t.jsx(j,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Xt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(kt,{className:"flex items-center gap-2",onClick:ge,children:[t.jsx(j,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Vs,{}),ve.map(O=>{const Ce=O.icon||"play",ye=O.id===Zt?"scan-2":fn[Ce]||"play",w=us(ie,O.id),Y=C[w],se=!!Y,ue=Y?.status==="stopping";return t.jsxs(kt,{className:"flex items-center gap-2",onClick:()=>{Q(O,!0)},children:[t.jsx(j,{name:ye,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:O.name}),ue||Y?.status==="waiting-for-preview"?t.jsx(j,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):se?t.jsx(j,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},O.id)})]})]})]})},zg=o.lazy(()=>Ps(()=>import("./SessionSwitcherDropdown-DSVeuuVL.js"),__vite__mapDeps([115,11,4,5,1,2,3,6,7,8,9,10,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79])).then(e=>({default:e.SessionSwitcherDropdown}))),nr="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",$g="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",Ug=o.memo(function({visible:s=!0,title:n,ariaLabel:r,onClick:i,className:a,Icon:l,iconClassName:c,pressed:d=!1}){return s?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,"aria-label":r,"aria-pressed":d,className:B(a??nr,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(j,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(rt,{children:t.jsx("p",{children:n})})]}):null}),Gg=o.memo(function({isMobile:s,githubAuthStatus:n,githubAccounts:r,githubAvatarUrl:i,githubLogin:a,isSwitchingGitHubAccount:l,handleGitHubAccountSwitch:c}){return!n?.connected||s?null:r.length>1?t.jsxs(qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:B(nr,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),title:a?`GitHub: ${a}`:"GitHub connected",disabled:l,children:i?t.jsx("img",{src:i,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(j,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Xt,{align:"end",className:"w-64",children:[t.jsx(Yd,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(Vs,{}),r.map(d=>{const u=d.user,p=!!d.current,h=d.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(kt,{className:"gap-2",disabled:l,onSelect:()=>{p||c(d.id)},children:[u?.avatarUrl?t.jsx("img",{src:u.avatarUrl,alt:u.login?`${u.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:t.jsx(j,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),t.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:u?.name?.trim()||u?.login||"GitHub"}),u?.login?t.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[t.jsx("span",{className:"font-mono",children:u.login}),t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{children:h})]}):null]}),p?t.jsx(j,{name:"check",className:"h-4 w-4 text-primary"}):null]},d.id)})]})]}):t.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:a?`GitHub: ${a}`:"GitHub connected",children:i?t.jsx("img",{src:i,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(j,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),Kg=o.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:d,remoteUpdateInfo:u,remoteUpdateChecking:p,remoteUpdateError:h,onOpenRemoteUpdate:x}){return t.jsxs(qt,{open:a,onOpenChange:m=>{l(m),m&&c()},children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:B(nr,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(j,{name:"server",className:"h-[18px] w-[18px]"}),s?t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),t.jsx(rt,{children:t.jsx("p",{children:`Current instance: ${n} (${d("toggle_services_menu")})`})})]}),t.jsx(Xt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:s?t.jsxs("div",{children:[i?null:t.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),t.jsx("div",{className:"typography-micro text-muted-foreground",children:u?.available?`Version ${u.version||""} is available for this instance.`:p?"Looking for updates...":h||"This instance is up to date."})]}),u?.available?t.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:x,children:"Update"}):null]})}),t.jsx(Vd,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Hg=e=>{const s=e.trim();if(!s)return"";const n=s.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],i=n[1].slice(0,3),a=`${r} ${i}`.trim();return n.length>2||a.length<s.length?`${a}...`:a}return s.length>12?`${s.slice(0,9).trimEnd()}...`:s},sn=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Wx=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:i,onSelectTabletWorkspaceTab:a})=>{is("ui.header.render");const l=ce(E=>E.setSessionSwitcherOpen),c=ce(E=>E.toggleSidebar),d=ce(E=>E.isSidebarOpen),u=ce(E=>E.activeMainTab),p=ce(E=>E.setActiveMainTab),h=ce(E=>E.shortcutOverrides);ce(E=>E.timeFormatPreference),qn();const x=Fe(E=>!!E.newSessionDraft?.open),m=Fe(E=>E.currentSessionId),f=da(m??""),g=Kd(m),S=o.useMemo(()=>{if(!g)return null;const E=g;return{title:g.title??null,directory:E.directory??null,created:g.time?.created??null,slug:E.slug??null,shareUrl:g.share?.url??null,parentId:g.parentID??null}},[g]),k=$t(Ur(E=>{if(!E.activeProjectId)return null;const fe=E.projects.find(Ie=>Ie.id===E.activeProjectId);return fe?{id:fe.id,path:fe.path,label:fe.label}:null})),_=ws(E=>E.homeDirectory),A=o.useMemo(()=>{if(!k)return null;const E=k.label?.trim();if(E)return E;const fe=k.path.split(/[\\/]/).filter(Boolean);return fe[fe.length-1]??null},[k]),{isMobile:b}=Ms(),{enabled:v}=eo(),M=!!(v&&a&&i!==void 0),N=o.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"notes",label:"Notes",icon:"sticky-note"}],[]),[C,I]=o.useState(!1),D=null,P=o.useRef(null),[G,ee]=o.useState(()=>typeof window>"u"?!1:vs()),Z=o.useMemo(()=>ba(),[]),te=Hd(),[U,K]=o.useState(!1),T=o.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:R,side:q}=ma(),ae=o.useMemo(()=>{if(typeof window>"u")return null;const E=window.__PICHAMBER_MACOS_MAJOR__;if(typeof E=="number"&&Number.isFinite(E)&&E>0)return E;if(typeof navigator>"u")return null;const fe=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!fe)return null;const Ie=Number.parseInt(fe[1],10),$=Number.parseInt(fe[2],10);return Number.isNaN(Ie)?null:Ie===10?$:Ie},[]);Xe.useEffect(()=>{typeof window>"u"||ee(vs())},[]);const z=ce(E=>E.isSessionSwitcherOpen),Re=null,Te=null,Ye=[],[_e,Qe]=o.useState(!1),[Be,ie]=o.useState(!1),[pe,We]=o.useState("Local"),[ke,ve]=o.useState(!0),[$e,ot]=o.useState(!1),[ze,J]=o.useState(null),[Q,ge]=o.useState(!1),[X,be]=o.useState(null),Ae=o.useMemo(()=>Hg(pe),[pe]),je=o.useCallback(async()=>{if(!(typeof window>"u"||!G))try{if(mn()){We("Local"),ve(!0);return}ve(!1);const E=await yu(),fe=vu(),Ie=wu([Su(fe),...E.hosts]);if(Ie.id===ju){We("Local"),ve(!0);return}We(ku(Ie.label.trim()||"Instance"))}catch{We("Local"),ve(!0)}},[G]);Xe.useEffect(()=>(je(),Cu(()=>{je()})),[je]);const lt=o.useCallback(async()=>{if(ke){J(null),be(null);return}ge(!0),be(null);try{const E=new URLSearchParams({appType:"web",instanceMode:"remote"}),fe=await es(`/api/pi/update-check?${E.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!fe.ok)throw new Error(`Server responded with ${fe.status}`);const Ie=await fe.json();J({available:Ie.available??!1,version:Ie.version,currentVersion:Ie.currentVersion??"unknown",body:Ie.body,nextSuggestedCheckInSec:typeof Ie.nextSuggestedCheckInSec=="number"?Ie.nextSuggestedCheckInSec:void 0,packageManager:Ie.packageManager,updateCommand:Ie.updateCommand})}catch(E){J(null),be(E instanceof Error?E.message:"Failed to check remote instance updates")}finally{ge(!1)}},[ke]);o.useEffect(()=>{J(null),be(null),ot(!1)},[ke,pe]),o.useEffect(()=>{if(!G||ke)return;const E=3e3,fe=3600*1e3;let Ie=!1,$=null;const Ge=at=>{$=window.setTimeout(()=>{if(Ie||typeof document<"u"&&document.visibilityState!=="visible"){Ge(fe);return}lt().finally(()=>{Ie||Ge(fe)})},at)};return Ge(E),()=>{Ie=!0,$!==null&&window.clearTimeout($)}},[lt,ke,pe,G]);const jt=o.useCallback(()=>{if(ze?.available){ot(!0);return}lt()},[lt,ze?.available]),it=m?S??null:null,xe=o.useRef(null),[Le,Oe]=o.useState(0);o.useEffect(()=>{if(!m){xe.current&&(xe.current=null,Oe($=>$+1));return}if(it){xe.current={sessionId:m,session:it,expiresAt:Date.now()+2e3};return}const E=xe.current;if(!E||E.sessionId!==m)return;const fe=E.expiresAt-Date.now();if(fe<=0){xe.current=null,Oe($=>$+1);return}const Ie=window.setTimeout(()=>{xe.current?.sessionId===m&&(xe.current=null),Oe($=>$+1)},fe);return()=>{window.clearTimeout(Ie)}},[m,it]);const Ke=(()=>{if(it)return it;if(!m)return null;const E=xe.current;return E&&E.sessionId===m&&E.expiresAt>Date.now()?E.session:null})(),Ct=o.useMemo(()=>{const E=typeof Ke?.directory=="string"?Ke.directory:"";return sn(E||"")},[Ke?.directory]),ht=Fe(E=>E.newSessionDraft?.open?sn(E.newSessionDraft.directoryOverride??""):""),O=o.useMemo(()=>xg({sessionDirectory:Ct,draftDirectory:ht,isNewSessionDraftOpen:x}),[ht,x,Ct]),ye=ca(O||null),w=o.useMemo(()=>bg({activeProjectLabel:A,openDirectory:O,homeDirectory:_}),[A,_,O]),Y=!!(w||ye),se=o.useMemo(()=>{if(!m)return w??"PiChamber";const E=Ke?.title?.trim();return E&&E.length>0?E:"Untitled Session"},[Ke?.title,m,w]),ue=ua(),Se=so(),Pe=Fe(E=>E.updateSessionTitle),He=Fe(E=>E.archiveSessions),mt=Fe(E=>E.deleteSessions),[bt,qe]=o.useState(!1),[dt,xt]=o.useState(!1),Me=o.useRef(!1),[Ze,yt]=o.useState(""),[Nt,Pt]=o.useState(null),Et=o.useRef(null);o.useEffect(()=>{Me.current=!1,xt(!1),qe(!1),yt(""),Pt(null)},[m]);const It=o.useCallback(()=>{m&&(yt(Ke?.title?.trim()||se),qe(!0))},[Ke?.title,m,se]),At=o.useCallback(async()=>{if(!m)return;const E=Ze.trim();E&&E!==Ke?.title?.trim()&&await Pe(m,E),qe(!1)},[Ke?.title,m,Ze,Pe]);o.useEffect(()=>{if(!bt)return;const E=fe=>{const Ie=fe.target;(!Ie||!Et.current?.contains(Ie))&&At()};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[bt,At]);const F=o.useCallback(()=>{m&&pn(m).then(E=>{le[E.ok?"success":"error"](E.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>le.error("Failed to copy session ID"))},[m]),Ne=o.useCallback(async()=>{if(!m||!O){le.error("Nothing to export");return}try{await Se.syncSession(m)}catch{le.error("Failed to load the complete session history");return}const E=Tr(ue.getState()).list;if(E.length===0){le.error("Nothing to export");return}const fe=rl(E,Ke?.title??null),Ie=al(Ke?.title??null);await il(fe,Ie)||ol(fe,Ie),le.success("Session exported")},[Ke?.title,m,ue,O,Se]);f?.type==="busy"||f?.type;const Ue=o.useCallback(async()=>{if(!m||!Nt)return;const E=Wd(),fe=[m];for(let at=0;at<fe.length;at+=1){const wt=fe[at];for(const St of E)St.parentID===wt&&!fe.includes(St.id)&&fe.push(St.id)}const Ie=Nt;if(Pt(null),(Ie==="archive"?await He(fe):await mt(fe)).failedIds.length>0){le.error(Ie==="archive"?"Failed to archive session":"Failed to delete session");return}le.success(Ie==="archive"?"Session archived":"Session deleted")},[He,m,mt,Nt]),pt=ce(E=>E.isArchivePageOpen),L=o.useMemo(()=>pt?{title:"Archive",subtitle:null}:null,[pt]),re=o.useMemo(()=>sn(O||k?.path||""),[k?.path,O]),me=o.useMemo(()=>k?{id:k.id,path:k.path}:null,[k]),tt=o.useRef(null);o.useEffect(()=>{!me||!re||(tt.current={projectRef:me,directory:re})},[re,me]);const we=o.useMemo(()=>me&&re?{projectRef:me,directory:re}:tt.current,[re,me]),et=o.useCallback(async E=>{},[]),ut=o.useCallback(()=>{if(typeof document>"u")return;const E=document.activeElement;if(!E)return;const fe=E.tagName;(fe==="INPUT"||fe==="TEXTAREA"||fe==="SELECT"||E.isContentEditable)&&E.blur()},[]),Ot=o.useCallback(()=>{if(b){ut(),l(!z);return}c()},[ut,b,z,l,c]),Ut=o.useCallback(()=>{cn("desktop_open_draft_mini_chat_window",{directory:sn(O||k?.path||""),projectId:k?.id??null,apiBaseUrl:Fr(),clientToken:Mr()}).catch(E=>{console.warn("[header] failed to open draft mini chat window",E)})},[k?.id,k?.path,O]),Rt=o.useCallback(()=>{if(x){Ut();return}m&&cn("desktop_open_session_mini_chat_window",{sessionId:m,directory:sn(O||k?.path||""),apiBaseUrl:Fr(),clientToken:Mr()}).catch(E=>{console.warn("[header] failed to open session mini chat window",E)})},[k?.path,m,Ut,x,O]),Gt=nr,Ft=$g,gt=o.useMemo(()=>n?"sessions":M?r&&i?i:null:r?"git":u,[u,M,n,r,i]),Bt=o.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&z&&l(!1)},[z,n,e,s,r,l]),H=o.useCallback(()=>{e?.()},[e]),ne=o.useCallback(()=>{s?.()},[s]),oe=o.useMemo(()=>G&&T&&!U?"5.5rem":te?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!G||R?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[G,U,T,te,R]);Xe.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",oe)},[oe]);const de=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",he=d?"0px":G&&R?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":v?"2.75rem":"2.5rem";Xe.useEffect(()=>{if(!G||!T){K(!1);return}let E=!1;const fe=async()=>{try{const $=await cn("desktop_is_window_fullscreen");E||K($===!0)}catch{E||K(!1)}},Ie=()=>{fe()};return fe(),window.addEventListener("pichamber:window-resized",Ie),()=>{E=!0,window.removeEventListener("pichamber:window-resized",Ie)}},[G,T]);const ft=o.useMemo(()=>!G||!T||ae===null?"":ae>=26?"h-12":ae<=15?"h-14":"",[G,T,ae]),Mt=o.useMemo(()=>{if(!(G&&!R))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[G,R]),vt=o.useCallback(()=>{if(typeof document>"u")return;const E=P.current?.getBoundingClientRect().height;E&&document.documentElement.style.setProperty("--oc-header-height",`${E}px`)},[]);Xe.useEffect(()=>{if(typeof window>"u")return;vt();const E=P.current;if(!E||typeof ResizeObserver>"u")return()=>{};let fe=0;const Ie=()=>{fe||(fe=requestAnimationFrame(()=>{fe=0,vt()}))},$=new ResizeObserver(Ie);return $.observe(E),window.addEventListener("resize",Ie),window.addEventListener("orientationchange",Ie),()=>{fe&&cancelAnimationFrame(fe),$.disconnect(),window.removeEventListener("resize",Ie),window.removeEventListener("orientationchange",Ie)}},[vt]),Xe.useEffect(()=>{vt()},[vt,b,ft]);const Kt=o.useCallback(async E=>{const fe=E.target;fe.closest(".app-region-no-drag")||fe.closest("button, a, input, select, textarea")||E.button===0&&G&&await Nu()},[G]),Ht=o.useMemo(()=>b?[{id:"chat",label:"Chat",icon:"chat-4"},{id:"diff",label:"Diff",icon:"diff"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"context",label:"Context",icon:"file-list-2"},{id:"diagram",label:"Diagram",icon:"file"}]:[],[b]),Tt=o.useCallback(E=>ao(ln(E,h)),[h]);Xe.useEffect(()=>{!b&&u!=="chat"&&u!=="terminal"&&u!=="diagram"&&p("chat")},[u,b,p]);const ns=o.useMemo(()=>{const E=[];return G&&E.push({value:"instance",label:"Instance",icon:t.jsx(j,{name:"server",className:"h-3.5 w-3.5"})}),E},[G]);Xe.useEffect(()=>{const E=fe=>{if(Au(fe)&&!fe.shiftKey&&!fe.altKey){const Ie=parseInt(fe.key,10);Ie>=1&&Ie<=Ht.length&&(fe.preventDefault(),b&&(ut(),Bt()),p(Ht[Ie-1].id))}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[ut,Bt,b,p,Ht]),Xe.useEffect(()=>{const E=fe=>{const Ie=ln("toggle_services_menu",h);if(si(fe,Ie)){fe.preventDefault(),Be?ie(!1):(ie(!0),je());return}const $=ln("cycle_services_tab",h);if(si(fe,$)){if(fe.preventDefault(),ns.length===0)return;ie(!0),je();return}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[h,Be,ns,je]);const cs=E=>{const fe=u===E.id,Ie=E.icon==="diff",$=Ie?null:E.icon,Ge=E.id==="chat",at=St=>Ie?t.jsx(Wi,{size:St}):$?t.jsx(j,{name:$,className:`h-${St/4} w-${St/4}`}):null,wt=t.jsxs("button",{type:"button",onClick:()=>p(E.id),className:B("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",fe?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"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",Ge&&!b&&"min-w-[100px] justify-center"),"aria-label":E.label,"aria-selected":fe,role:"tab",children:[b?at(20):t.jsxs(t.Fragment,{children:[at(16),t.jsx("span",{className:"header-tab-label",children:E.label})]}),E.badge!==void 0&&E.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:E.badge})]});return t.jsx(o.Fragment,{children:wt},E.id)},ms=t.jsxs(t.Fragment,{children:[t.jsx(Sg,{directory:re,className:"mr-1"}),G?t.jsx(Kg,{isDesktopApp:G,currentInstanceLabel:pe,compactCurrentInstanceLabel:Ae,currentInstanceIsLocal:ke,isDesktopServicesOpen:Be,setIsDesktopServicesOpen:ie,refreshCurrentInstanceLabel:je,shortcutLabel:Tt,remoteUpdateInfo:ze,remoteUpdateChecking:Q,remoteUpdateError:X,onOpenRemoteUpdate:jt}):null,t.jsx(Gg,{isMobile:b,githubAuthStatus:D,githubAccounts:Ye,githubAvatarUrl:Re,githubLogin:Te,isSwitchingGitHubAccount:_e,handleGitHubAccountSwitch:et})]}),qs=Z&&(x||!!m),Js=()=>t.jsxs("div",{onMouseDown:Kt,className:B("app-region-drag relative flex h-12 select-none items-center pr-3",ft),style:Mt,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:de}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:he}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[L?t.jsxs("div",{className:"mr-3 flex min-w-0 flex-col items-start px-1 py-0.5 -my-0.5 text-left",children:[t.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:L.title}),L.subtitle?t.jsx("span",{className:"truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75 max-w-full",children:L.subtitle}):null]}):t.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[d?null:t.jsx(o.Suspense,{fallback:t.jsx("button",{type:"button",className:Gt,"aria-label":"Open session switcher",children:t.jsx(j,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(zg,{align:"start",children:t.jsx("button",{type:"button",className:Gt,"aria-label":"Open session switcher",children:t.jsx(j,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 flex-col justify-center px-1",children:[bt?t.jsxs("form",{ref:Et,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:E=>{E.preventDefault(),At()},children:[t.jsx("input",{value:Ze,onChange:E=>yt(E.target.value),autoFocus:!0,onKeyDown:E=>{E.stopPropagation(),E.key==="Escape"&&qe(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(j,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>qe(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(j,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-foreground max-w-full",children:x?"New session":se}),Y?t.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[w?t.jsx("span",{className:"truncate",children:w}):null,ye?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(j,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:ye})]}):null]}):null]}),t.jsx("div",{className:B("flex h-[18px] shrink-0 items-center justify-center",Y?"self-start":"self-center"),children:m&&!x&&!bt?t.jsxs(qt,{open:dt,onOpenChange:xt,onOpenChangeComplete:E=>{!E&&Me.current&&(Me.current=!1,It())},children:[t.jsx(Jt,{asChild:!0,children:t.jsx(Ve,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:t.jsx(j,{name:"more",className:"size-4"})})}),t.jsxs(Xt,{align:"end",className:"min-w-[190px]",children:[t.jsxs(kt,{onClick:()=>{Me.current=!0},children:[t.jsx(j,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(kt,{onClick:F,children:[t.jsx(j,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsx(Vs,{}),t.jsxs(kt,{onClick:()=>{Ne()},children:[t.jsx(j,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(Vs,{}),t.jsxs(kt,{onClick:()=>Pt("archive"),children:[t.jsx(j,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(kt,{className:"text-destructive focus:text-destructive",onClick:()=>Pt("delete"),children:[t.jsx(j,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),Ht.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Ht.map(E=>cs(E))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[we?t.jsx(Qi,{projectRef:we.projectRef,directory:we.directory,className:"mr-1"}):null,t.jsx(Ug,{visible:qs,title:x?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:x?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:Rt,className:B(Gt,"mr-1"),Icon:"picture-in-picture-2"}),ms,t.jsx(ga,{visible:R&&q==="right",position:"right"})]})]})]}),gs=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[v&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:de}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:he}})]}),!v&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:H,className:B(Ft,gt==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(j,{name:"layout-left",className:"h-5 w-5"})}):z?t.jsx("button",{type:"button",onClick:()=>l(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:t.jsx(j,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:Ot,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:t.jsx(j,{name:"play-list-add",className:"h-5 w-5"})}),!e&&z&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!z||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!M&&t.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Main navigation",children:Ht.map(E=>{const fe=u===E.id,Ie=E.icon==="diff",$=Ie?null:E.icon;return t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{b&&(ut(),Bt()),p(E.id)},"aria-label":E.label,"aria-selected":fe,role:"tab",className:B(Ft,"relative rounded-lg",gt===E.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[Ie?t.jsx(Wi,{className:"h-5 w-5"}):$?t.jsx(j,{name:$,className:"h-5 w-5"}):null,E.badge!==void 0&&E.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:E.badge}),E.showDot&&t.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),t.jsx(rt,{children:t.jsx("p",{children:E.label})})]},E.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[M&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:N.map(E=>{const fe=r&&i===E.id;return t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{b&&(ut(),Bt()),I(!1),a?.(E.id)},"aria-label":E.label,"aria-selected":fe,role:"tab",className:B(Ft,"relative rounded-lg",fe&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(j,{name:E.icon,className:"h-5 w-5"})})}),t.jsx(rt,{children:t.jsx("p",{children:E.label})})]},E.id)})}),t.jsx(Eh,{open:C,onOpenChange:I,currentSessionId:m,effectiveDirectory:O||null,isNewSessionDraftOpen:x})]}),we&&t.jsx(Qi,{projectRef:we.projectRef,directory:we.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!M?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:ne,className:B(Ft,"relative",gt==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(j,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(rt,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),js=B("header-safe-area relative z-10 bg-background",b&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:P,className:js,style:{"--padding-scale":"1"},children:b?gs():Js()}),t.jsx(as,{open:Nt!==null,onOpenChange:E=>{E||Pt(null)},children:t.jsxs(ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Ss,{children:[t.jsx(hs,{children:Nt==="delete"?"Delete session?":"Archive session?"}),t.jsx(Fs,{children:Nt==="delete"?`\\"${se}\\" will be permanently deleted.`:`\\"${se}\\" will be archived.`})]}),t.jsxs(Ls,{children:[t.jsx(Ve,{variant:"outline",size:"sm",onClick:()=>Pt(null),children:"Cancel"}),t.jsx(Ve,{variant:"destructive",size:"sm",onClick:()=>{Ue()},children:Nt==="delete"?"Delete":"Archive"})]})]})}),t.jsx(Fa,{open:$e,onOpenChange:ot,info:ze,downloading:!1,downloaded:!1,progress:null,error:X,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},qi="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",Wg="app-region-no-drag flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50",Vx=()=>{const e=ce(g=>g.isSidebarOpen),s=ce(g=>g.toggleSidebar),n=ce(g=>g.shortcutOverrides),r=o.useRef(null),i=o.useRef(null),a=ao(ln("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=ma(),{enabled:d}=eo(),u=!e,p=l&&c==="left",h=l,x=u||p||h,m=p||h,f=o.useCallback(()=>{cn("desktop_show_app_menu").catch(g=>{console.warn("[titlebar] failed to open app menu",g)})},[]);return o.useEffect(()=>{if(typeof document>"u")return;const g=v=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(v)}px`)},S=v=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(v)}px`)};if(!m)return;const k=i.current,_=r.current;if(!k||!_){g(0),S(0);return}const A=()=>{const v=Math.max(k.getBoundingClientRect().width,k.scrollWidth);g(v),S(_.getBoundingClientRect().width)};if(A(),typeof ResizeObserver>"u")return;const b=new ResizeObserver(A);return b.observe(k),b.observe(_),()=>{b.disconnect()}},[m]),x?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:i,className:"flex items-center gap-2",children:[p?t.jsx(ga,{visible:!0,position:"left"}):null,h?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:f,"aria-label":"Open PiChamber menu",className:B(qi,"shrink-0"),children:t.jsx(j,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(rt,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,u?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:B(d?Wg:qi,"shrink-0"),children:t.jsx(j,{name:"layout-left",className:d?"size-[18px]":"h-[18px] w-[18px]"})})}),t.jsx(rt,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},Ji=200,Vg="cubic-bezier(0.22, 1, 0.36, 1)",Yx=e=>{const s=o.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=o.useState(e),[i,a]=o.useState(e);return o.useLayoutEffect(()=>{if(s){a(e),r(e);return}if(e){a(!0),r(!1);let c=0;const d=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(d),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>a(!1),Ji);return()=>window.clearTimeout(l)},[e,s]),{slidIn:n,layoutVisible:i,prefersReducedMotion:s,transition:s?"none":`transform ${Ji}ms ${Vg}`}};export{Us as $,Ix as A,Ax as B,Nx as C,Fi as D,Ns as E,Mx as F,Ex as G,Wx as H,bx as I,Pf as J,po as K,mx as L,Eh as M,Df as N,mo as O,zx as P,Zf as Q,Kn as R,Lx as S,$x as T,Fa as U,Ef as V,bn as W,jf as X,kf as Y,La as Z,yn as _,rn as a,Nf as a0,ux as a1,wx as a2,Cf as a3,gx as a4,Af as a5,vx as a6,kx as a7,jx as a8,Tf as a9,As as aa,yx as ab,Sx as ac,Cx as ad,dx as ae,fx as af,hx as ag,px as ah,Yf as ai,xx as aj,ih as ak,ah as al,If as am,cx as an,Fx as ao,Dx as ap,wm as b,Ox as c,$n as d,hh as e,Gx as f,Bx as g,Tx as h,km as i,Rx as j,Px as k,Yx as l,Kx as m,Vx as n,lx as o,eh as p,th as q,Ux as r,_x as s,sh as t,Bn as u,fi as v,nh as w,tg as x,Hx as y,rh as z};
|
|
56
|
+
`));await l.sendInput(He,`${xt}\r`),dt?(N(ie,Se,null,{locked:!0}),Qe(dt),le.success("Opened forwarded URL")):qe?(N(ie,Se,qe,{locked:!0,autoOpened:!0}),S(ie,qe),le.success("Opened action URL")):Y?(N(ie,Se,null,{locked:!0}),le.error("Invalid custom URL format")):bt?(N(ie,Se,null,{locked:!0}),le.error("Selected desktop SSH forward is unavailable")):N(ie,Se,null,{locked:!1,autoOpened:!1})}catch(w){P(Ce),delete R.current[Ce],q.current[Ce]?.(),delete q.current[Ce],window.clearTimeout(ae.current[Ce]),delete ae.current[Ce],le.error(w instanceof Error?w.message:"Failed to run action")}finally{z.current.delete(Ce)}}},[a.colors.surface.background,a.colors.syntax.base.foreground,a.metadata.variant,u,$e,i,c,d,ie,x,h,Qe,S,C,P,v,I,N,M,_e?.id,l]),ze=o.useCallback(async O=>{const Ce=us(ie,O.id),ye=C[Ce];if(!ye)return;D(Ce,"stopping");const w=Tg(l,ye.sessionId,1e3);try{await l.sendInput(ye.sessionId,"")}catch{}const Y=await w;if(Ee.getState().getDirectoryState(ye.directory)?.tabs.find(Se=>Se.id===ye.tabId)?.terminalSessionId===ye.sessionId&&!Y){if(typeof l.forceKill=="function")try{await l.forceKill({sessionId:ye.sessionId})}catch{}else try{await l.close(ye.sessionId)}catch{}M(ye.directory,ye.tabId,null)}P(Ce),delete R.current[Ce],q.current[Ce]?.(),delete q.current[Ce],window.clearTimeout(ae.current[Ce]),delete ae.current[Ce]},[ie,C,P,M,l,D]),J=o.useCallback(()=>{const O=pe??ve[0];if(!O)return;const Ce=us(ie,O.id),ye=C[Ce];if(ye?.status!=="stopping"){if(ye){ze(O);return}ot(O)}},[ve,ie,ot,C,pe,ze]),Q=o.useCallback((O,Ce=!1)=>{if(te(O.id),!Ce){ot(O);return}const ye=us(ie,O.id),w=C[ye];if(w?.status!=="stopping"){if(w){ze(O);return}ot(O)}},[ie,ot,C,ze]),ge=o.useCallback(()=>{_e?.id&&(g(_e.id),m("projects"),f(!0))},[f,m,g,_e?.id]),X=pe??ve[0]??null,be=X?C[us(ie,X.id)]:null,Ae=Ee(O=>be?O.sessions.get(be.directory)?.tabs.find(Ce=>Ce.id===be.tabId)?.previewUrl??null:null);if(!i&&c||!_e||!ie)return null;const je=pe??ve[0]??null;if(!je)return null;const lt=je.icon||"play",jt=je.id===Zt?"scan-2":fn[lt]||"play",it=us(ie,je.id),xe=C[it],Le=xe?.status==="stopping",Oe=xe?.status==="waiting-for-preview",Ke=!!(xe&&Ae),Ct=()=>{!xe||!Ae||S(xe.directory,Ae)},ht=je.id===Zt;return r?t.jsxs("div",{className:"inline-flex items-center",children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",disabled:U||Le,className:B("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:J,"aria-label":xe?`Stop ${je.name}`:`Run ${je.name}`,children:Le||Oe?t.jsx(j,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):xe?t.jsx(j,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):t.jsx(j,{name:jt,className:"h-5 w-5"})})}),ht?t.jsx(rt,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),Ke?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:Ct,children:t.jsx(j,{name:"global",className:"h-4 w-4"})})}),t.jsx(rt,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:t.jsx(j,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),t.jsxs(Xt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(kt,{className:"flex items-center gap-2",onClick:ge,children:[t.jsx(j,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Vs,{}),ve.map(O=>{const Ce=O.icon||"play",ye=O.id===Zt?"scan-2":fn[Ce]||"play",w=us(ie,O.id),Y=C[w],se=!!Y,ue=Y?.status==="stopping";return t.jsxs(kt,{className:"flex items-center gap-2",onClick:()=>{Q(O,!0)},children:[t.jsx(j,{name:ye,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:O.name}),ue||Y?.status==="waiting-for-preview"?t.jsx(j,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):se?t.jsx(j,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},O.id)})]})]})]}):t.jsxs("div",{className:B("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:J,disabled:U||Le,className:B("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":xe?`Stop ${je.name}`:`Run ${je.name}`,children:t.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:Le||Oe?t.jsx(j,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):xe?t.jsx(j,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):t.jsx(j,{name:jt,className:"h-4 w-4"})})})}),ht?t.jsx(rt,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),Ke?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:Ct,className:B(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:t.jsx(j,{name:"global",className:"h-4 w-4"})})}),t.jsx(rt,{sideOffset:6,children:"Open Preview"})]}):null,t.jsxs(qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:B(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:t.jsx(j,{name:"arrow-down-s",className:"h-4 w-4"})})}),t.jsxs(Xt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[t.jsxs(kt,{className:"flex items-center gap-2",onClick:ge,children:[t.jsx(j,{name:"add",className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),t.jsx(Vs,{}),ve.map(O=>{const Ce=O.icon||"play",ye=O.id===Zt?"scan-2":fn[Ce]||"play",w=us(ie,O.id),Y=C[w],se=!!Y,ue=Y?.status==="stopping";return t.jsxs(kt,{className:"flex items-center gap-2",onClick:()=>{Q(O,!0)},children:[t.jsx(j,{name:ye,className:"h-4 w-4"}),t.jsx("span",{className:"typography-ui-label text-foreground truncate",children:O.name}),ue||Y?.status==="waiting-for-preview"?t.jsx(j,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):se?t.jsx(j,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},O.id)})]})]})]})},zg=o.lazy(()=>Ps(()=>import("./SessionSwitcherDropdown-Cx-Jfmvo.js"),__vite__mapDeps([115,11,4,5,1,2,3,6,7,8,9,10,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79])).then(e=>({default:e.SessionSwitcherDropdown}))),nr="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",$g="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",Ug=o.memo(function({visible:s=!0,title:n,ariaLabel:r,onClick:i,className:a,Icon:l,iconClassName:c,pressed:d=!1}){return s?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:i,"aria-label":r,"aria-pressed":d,className:B(a??nr,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(j,{name:l,className:c??"h-[18px] w-[18px]"})})}),t.jsx(rt,{children:t.jsx("p",{children:n})})]}):null}),Gg=o.memo(function({isMobile:s,githubAuthStatus:n,githubAccounts:r,githubAvatarUrl:i,githubLogin:a,isSwitchingGitHubAccount:l,handleGitHubAccountSwitch:c}){return!n?.connected||s?null:r.length>1?t.jsxs(qt,{children:[t.jsx(Jt,{asChild:!0,children:t.jsx("button",{type:"button",className:B(nr,"h-7 w-7 overflow-hidden rounded-full border border-border/60 bg-muted/80 p-0"),title:a?`GitHub: ${a}`:"GitHub connected",disabled:l,children:i?t.jsx("img",{src:i,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(j,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),t.jsxs(Xt,{align:"end",className:"w-64",children:[t.jsx(Yd,{className:"typography-ui-header font-semibold text-foreground",children:"GitHub Accounts"}),t.jsx(Vs,{}),r.map(d=>{const u=d.user,p=!!d.current,h=d.source==="gh-cli"?"CLI":"OAuth";return t.jsxs(kt,{className:"gap-2",disabled:l,onSelect:()=>{p||c(d.id)},children:[u?.avatarUrl?t.jsx("img",{src:u.avatarUrl,alt:u.login?`${u.login} avatar`:"GitHub avatar",className:"h-6 w-6 rounded-full border border-border/60 bg-muted object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-full border border-border/60 bg-muted",children:t.jsx(j,{name:"github-fill",className:"h-3 w-3 text-muted-foreground"})}),t.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsx("span",{className:"truncate typography-ui-label text-foreground",children:u?.name?.trim()||u?.login||"GitHub"}),u?.login?t.jsxs("span",{className:"truncate typography-micro text-muted-foreground",children:[t.jsx("span",{className:"font-mono",children:u.login}),t.jsx("span",{className:"mx-1 opacity-50",children:"·"}),t.jsx("span",{children:h})]}):null]}),p?t.jsx(j,{name:"check",className:"h-4 w-4 text-primary"}):null]},d.id)})]})]}):t.jsx("div",{className:"app-region-no-drag flex h-7 w-7 items-center justify-center overflow-hidden rounded-full border border-border/60 bg-muted/80",title:a?`GitHub: ${a}`:"GitHub connected",children:i?t.jsx("img",{src:i,alt:a?`${a} avatar`:"GitHub avatar",className:"h-full w-full object-cover",loading:"lazy",referrerPolicy:"no-referrer"}):t.jsx(j,{name:"github-fill",className:"h-3.5 w-3.5 text-foreground"})})}),Kg=o.memo(function({isDesktopApp:s,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:l,refreshCurrentInstanceLabel:c,shortcutLabel:d,remoteUpdateInfo:u,remoteUpdateChecking:p,remoteUpdateError:h,onOpenRemoteUpdate:x}){return t.jsxs(qt,{open:a,onOpenChange:m=>{l(m),m&&c()},children:[t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx(Jt,{asChild:!0,children:t.jsxs("button",{type:"button","aria-label":s?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:B(nr,s?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[t.jsx(j,{name:"server",className:"h-[18px] w-[18px]"}),s?t.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),t.jsx(rt,{children:t.jsx("p",{children:`Current instance: ${n} (${d("toggle_services_menu")})`})})]}),t.jsx(Xt,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:s?t.jsxs("div",{children:[i?null:t.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),t.jsx("div",{className:"typography-micro text-muted-foreground",children:u?.available?`Version ${u.version||""} is available for this instance.`:p?"Looking for updates...":h||"This instance is up to date."})]}),u?.available?t.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:x,children:"Update"}):null]})}),t.jsx(Vd,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>l(!1)})]}):null})]})}),Hg=e=>{const s=e.trim();if(!s)return"";const n=s.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],i=n[1].slice(0,3),a=`${r} ${i}`.trim();return n.length>2||a.length<s.length?`${a}...`:a}return s.length>12?`${s.slice(0,9).trimEnd()}...`:s},sn=e=>{if(!e)return"";const s=e.replace(/\\/g,"/");return s==="/"?"/":s.replace(/\/+$/,"")},Wx=({onToggleLeftDrawer:e,onToggleRightDrawer:s,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:i,onSelectTabletWorkspaceTab:a})=>{is("ui.header.render");const l=ce(E=>E.setSessionSwitcherOpen),c=ce(E=>E.toggleSidebar),d=ce(E=>E.isSidebarOpen),u=ce(E=>E.activeMainTab),p=ce(E=>E.setActiveMainTab),h=ce(E=>E.shortcutOverrides);ce(E=>E.timeFormatPreference),qn();const x=Fe(E=>!!E.newSessionDraft?.open),m=Fe(E=>E.currentSessionId),f=da(m??""),g=Kd(m),S=o.useMemo(()=>{if(!g)return null;const E=g;return{title:g.title??null,directory:E.directory??null,created:g.time?.created??null,slug:E.slug??null,shareUrl:g.share?.url??null,parentId:g.parentID??null}},[g]),k=$t(Ur(E=>{if(!E.activeProjectId)return null;const fe=E.projects.find(Ie=>Ie.id===E.activeProjectId);return fe?{id:fe.id,path:fe.path,label:fe.label}:null})),_=ws(E=>E.homeDirectory),A=o.useMemo(()=>{if(!k)return null;const E=k.label?.trim();if(E)return E;const fe=k.path.split(/[\\/]/).filter(Boolean);return fe[fe.length-1]??null},[k]),{isMobile:b}=Ms(),{enabled:v}=eo(),M=!!(v&&a&&i!==void 0),N=o.useMemo(()=>[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"notes",label:"Notes",icon:"sticky-note"}],[]),[C,I]=o.useState(!1),D=null,P=o.useRef(null),[G,ee]=o.useState(()=>typeof window>"u"?!1:vs()),Z=o.useMemo(()=>ba(),[]),te=Hd(),[U,K]=o.useState(!1),T=o.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),{usesFramelessChrome:R,side:q}=ma(),ae=o.useMemo(()=>{if(typeof window>"u")return null;const E=window.__PICHAMBER_MACOS_MAJOR__;if(typeof E=="number"&&Number.isFinite(E)&&E>0)return E;if(typeof navigator>"u")return null;const fe=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!fe)return null;const Ie=Number.parseInt(fe[1],10),$=Number.parseInt(fe[2],10);return Number.isNaN(Ie)?null:Ie===10?$:Ie},[]);Xe.useEffect(()=>{typeof window>"u"||ee(vs())},[]);const z=ce(E=>E.isSessionSwitcherOpen),Re=null,Te=null,Ye=[],[_e,Qe]=o.useState(!1),[Be,ie]=o.useState(!1),[pe,We]=o.useState("Local"),[ke,ve]=o.useState(!0),[$e,ot]=o.useState(!1),[ze,J]=o.useState(null),[Q,ge]=o.useState(!1),[X,be]=o.useState(null),Ae=o.useMemo(()=>Hg(pe),[pe]),je=o.useCallback(async()=>{if(!(typeof window>"u"||!G))try{if(mn()){We("Local"),ve(!0);return}ve(!1);const E=await yu(),fe=vu(),Ie=wu([Su(fe),...E.hosts]);if(Ie.id===ju){We("Local"),ve(!0);return}We(ku(Ie.label.trim()||"Instance"))}catch{We("Local"),ve(!0)}},[G]);Xe.useEffect(()=>(je(),Cu(()=>{je()})),[je]);const lt=o.useCallback(async()=>{if(ke){J(null),be(null);return}ge(!0),be(null);try{const E=new URLSearchParams({appType:"web",instanceMode:"remote"}),fe=await es(`/api/pi/update-check?${E.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!fe.ok)throw new Error(`Server responded with ${fe.status}`);const Ie=await fe.json();J({available:Ie.available??!1,version:Ie.version,currentVersion:Ie.currentVersion??"unknown",body:Ie.body,nextSuggestedCheckInSec:typeof Ie.nextSuggestedCheckInSec=="number"?Ie.nextSuggestedCheckInSec:void 0,packageManager:Ie.packageManager,updateCommand:Ie.updateCommand})}catch(E){J(null),be(E instanceof Error?E.message:"Failed to check remote instance updates")}finally{ge(!1)}},[ke]);o.useEffect(()=>{J(null),be(null),ot(!1)},[ke,pe]),o.useEffect(()=>{if(!G||ke)return;const E=3e3,fe=3600*1e3;let Ie=!1,$=null;const Ge=at=>{$=window.setTimeout(()=>{if(Ie||typeof document<"u"&&document.visibilityState!=="visible"){Ge(fe);return}lt().finally(()=>{Ie||Ge(fe)})},at)};return Ge(E),()=>{Ie=!0,$!==null&&window.clearTimeout($)}},[lt,ke,pe,G]);const jt=o.useCallback(()=>{if(ze?.available){ot(!0);return}lt()},[lt,ze?.available]),it=m?S??null:null,xe=o.useRef(null),[Le,Oe]=o.useState(0);o.useEffect(()=>{if(!m){xe.current&&(xe.current=null,Oe($=>$+1));return}if(it){xe.current={sessionId:m,session:it,expiresAt:Date.now()+2e3};return}const E=xe.current;if(!E||E.sessionId!==m)return;const fe=E.expiresAt-Date.now();if(fe<=0){xe.current=null,Oe($=>$+1);return}const Ie=window.setTimeout(()=>{xe.current?.sessionId===m&&(xe.current=null),Oe($=>$+1)},fe);return()=>{window.clearTimeout(Ie)}},[m,it]);const Ke=(()=>{if(it)return it;if(!m)return null;const E=xe.current;return E&&E.sessionId===m&&E.expiresAt>Date.now()?E.session:null})(),Ct=o.useMemo(()=>{const E=typeof Ke?.directory=="string"?Ke.directory:"";return sn(E||"")},[Ke?.directory]),ht=Fe(E=>E.newSessionDraft?.open?sn(E.newSessionDraft.directoryOverride??""):""),O=o.useMemo(()=>xg({sessionDirectory:Ct,draftDirectory:ht,isNewSessionDraftOpen:x}),[ht,x,Ct]),ye=ca(O||null),w=o.useMemo(()=>bg({activeProjectLabel:A,openDirectory:O,homeDirectory:_}),[A,_,O]),Y=!!(w||ye),se=o.useMemo(()=>{if(!m)return w??"PiChamber";const E=Ke?.title?.trim();return E&&E.length>0?E:"Untitled Session"},[Ke?.title,m,w]),ue=ua(),Se=so(),Pe=Fe(E=>E.updateSessionTitle),He=Fe(E=>E.archiveSessions),mt=Fe(E=>E.deleteSessions),[bt,qe]=o.useState(!1),[dt,xt]=o.useState(!1),Me=o.useRef(!1),[Ze,yt]=o.useState(""),[Nt,Pt]=o.useState(null),Et=o.useRef(null);o.useEffect(()=>{Me.current=!1,xt(!1),qe(!1),yt(""),Pt(null)},[m]);const It=o.useCallback(()=>{m&&(yt(Ke?.title?.trim()||se),qe(!0))},[Ke?.title,m,se]),At=o.useCallback(async()=>{if(!m)return;const E=Ze.trim();E&&E!==Ke?.title?.trim()&&await Pe(m,E),qe(!1)},[Ke?.title,m,Ze,Pe]);o.useEffect(()=>{if(!bt)return;const E=fe=>{const Ie=fe.target;(!Ie||!Et.current?.contains(Ie))&&At()};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[bt,At]);const F=o.useCallback(()=>{m&&pn(m).then(E=>{le[E.ok?"success":"error"](E.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>le.error("Failed to copy session ID"))},[m]),Ne=o.useCallback(async()=>{if(!m||!O){le.error("Nothing to export");return}try{await Se.syncSession(m)}catch{le.error("Failed to load the complete session history");return}const E=Tr(ue.getState()).list;if(E.length===0){le.error("Nothing to export");return}const fe=rl(E,Ke?.title??null),Ie=al(Ke?.title??null);await il(fe,Ie)||ol(fe,Ie),le.success("Session exported")},[Ke?.title,m,ue,O,Se]);f?.type==="busy"||f?.type;const Ue=o.useCallback(async()=>{if(!m||!Nt)return;const E=Wd(),fe=[m];for(let at=0;at<fe.length;at+=1){const wt=fe[at];for(const St of E)St.parentID===wt&&!fe.includes(St.id)&&fe.push(St.id)}const Ie=Nt;if(Pt(null),(Ie==="archive"?await He(fe):await mt(fe)).failedIds.length>0){le.error(Ie==="archive"?"Failed to archive session":"Failed to delete session");return}le.success(Ie==="archive"?"Session archived":"Session deleted")},[He,m,mt,Nt]),pt=ce(E=>E.isArchivePageOpen),L=o.useMemo(()=>pt?{title:"Archive",subtitle:null}:null,[pt]),re=o.useMemo(()=>sn(O||k?.path||""),[k?.path,O]),me=o.useMemo(()=>k?{id:k.id,path:k.path}:null,[k]),tt=o.useRef(null);o.useEffect(()=>{!me||!re||(tt.current={projectRef:me,directory:re})},[re,me]);const we=o.useMemo(()=>me&&re?{projectRef:me,directory:re}:tt.current,[re,me]),et=o.useCallback(async E=>{},[]),ut=o.useCallback(()=>{if(typeof document>"u")return;const E=document.activeElement;if(!E)return;const fe=E.tagName;(fe==="INPUT"||fe==="TEXTAREA"||fe==="SELECT"||E.isContentEditable)&&E.blur()},[]),Ot=o.useCallback(()=>{if(b){ut(),l(!z);return}c()},[ut,b,z,l,c]),Ut=o.useCallback(()=>{cn("desktop_open_draft_mini_chat_window",{directory:sn(O||k?.path||""),projectId:k?.id??null,apiBaseUrl:Fr(),clientToken:Mr()}).catch(E=>{console.warn("[header] failed to open draft mini chat window",E)})},[k?.id,k?.path,O]),Rt=o.useCallback(()=>{if(x){Ut();return}m&&cn("desktop_open_session_mini_chat_window",{sessionId:m,directory:sn(O||k?.path||""),apiBaseUrl:Fr(),clientToken:Mr()}).catch(E=>{console.warn("[header] failed to open session mini chat window",E)})},[k?.path,m,Ut,x,O]),Gt=nr,Ft=$g,gt=o.useMemo(()=>n?"sessions":M?r&&i?i:null:r?"git":u,[u,M,n,r,i]),Bt=o.useCallback(()=>{n&&e&&e(),r&&s&&s(),!e&&z&&l(!1)},[z,n,e,s,r,l]),H=o.useCallback(()=>{e?.()},[e]),ne=o.useCallback(()=>{s?.()},[s]),oe=o.useMemo(()=>G&&T&&!U?"5.5rem":te?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!G||R?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[G,U,T,te,R]);Xe.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",oe)},[oe]);const de=d?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",he=d?"0px":G&&R?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":v?"2.75rem":"2.5rem";Xe.useEffect(()=>{if(!G||!T){K(!1);return}let E=!1;const fe=async()=>{try{const $=await cn("desktop_is_window_fullscreen");E||K($===!0)}catch{E||K(!1)}},Ie=()=>{fe()};return fe(),window.addEventListener("pichamber:window-resized",Ie),()=>{E=!0,window.removeEventListener("pichamber:window-resized",Ie)}},[G,T]);const ft=o.useMemo(()=>!G||!T||ae===null?"":ae>=26?"h-12":ae<=15?"h-14":"",[G,T,ae]),Mt=o.useMemo(()=>{if(!(G&&!R))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[G,R]),vt=o.useCallback(()=>{if(typeof document>"u")return;const E=P.current?.getBoundingClientRect().height;E&&document.documentElement.style.setProperty("--oc-header-height",`${E}px`)},[]);Xe.useEffect(()=>{if(typeof window>"u")return;vt();const E=P.current;if(!E||typeof ResizeObserver>"u")return()=>{};let fe=0;const Ie=()=>{fe||(fe=requestAnimationFrame(()=>{fe=0,vt()}))},$=new ResizeObserver(Ie);return $.observe(E),window.addEventListener("resize",Ie),window.addEventListener("orientationchange",Ie),()=>{fe&&cancelAnimationFrame(fe),$.disconnect(),window.removeEventListener("resize",Ie),window.removeEventListener("orientationchange",Ie)}},[vt]),Xe.useEffect(()=>{vt()},[vt,b,ft]);const Kt=o.useCallback(async E=>{const fe=E.target;fe.closest(".app-region-no-drag")||fe.closest("button, a, input, select, textarea")||E.button===0&&G&&await Nu()},[G]),Ht=o.useMemo(()=>b?[{id:"chat",label:"Chat",icon:"chat-4"},{id:"diff",label:"Diff",icon:"diff"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"context",label:"Context",icon:"file-list-2"},{id:"diagram",label:"Diagram",icon:"file"}]:[],[b]),Tt=o.useCallback(E=>ao(ln(E,h)),[h]);Xe.useEffect(()=>{!b&&u!=="chat"&&u!=="terminal"&&u!=="diagram"&&p("chat")},[u,b,p]);const ns=o.useMemo(()=>{const E=[];return G&&E.push({value:"instance",label:"Instance",icon:t.jsx(j,{name:"server",className:"h-3.5 w-3.5"})}),E},[G]);Xe.useEffect(()=>{const E=fe=>{if(Au(fe)&&!fe.shiftKey&&!fe.altKey){const Ie=parseInt(fe.key,10);Ie>=1&&Ie<=Ht.length&&(fe.preventDefault(),b&&(ut(),Bt()),p(Ht[Ie-1].id))}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[ut,Bt,b,p,Ht]),Xe.useEffect(()=>{const E=fe=>{const Ie=ln("toggle_services_menu",h);if(si(fe,Ie)){fe.preventDefault(),Be?ie(!1):(ie(!0),je());return}const $=ln("cycle_services_tab",h);if(si(fe,$)){if(fe.preventDefault(),ns.length===0)return;ie(!0),je();return}};return window.addEventListener("keydown",E),()=>window.removeEventListener("keydown",E)},[h,Be,ns,je]);const cs=E=>{const fe=u===E.id,Ie=E.icon==="diff",$=Ie?null:E.icon,Ge=E.id==="chat",at=St=>Ie?t.jsx(Wi,{size:St}):$?t.jsx(j,{name:$,className:`h-${St/4} w-${St/4}`}):null,wt=t.jsxs("button",{type:"button",onClick:()=>p(E.id),className:B("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",fe?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"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",Ge&&!b&&"min-w-[100px] justify-center"),"aria-label":E.label,"aria-selected":fe,role:"tab",children:[b?at(20):t.jsxs(t.Fragment,{children:[at(16),t.jsx("span",{className:"header-tab-label",children:E.label})]}),E.badge!==void 0&&E.badge>0&&t.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:E.badge})]});return t.jsx(o.Fragment,{children:wt},E.id)},ms=t.jsxs(t.Fragment,{children:[t.jsx(Sg,{directory:re,className:"mr-1"}),G?t.jsx(Kg,{isDesktopApp:G,currentInstanceLabel:pe,compactCurrentInstanceLabel:Ae,currentInstanceIsLocal:ke,isDesktopServicesOpen:Be,setIsDesktopServicesOpen:ie,refreshCurrentInstanceLabel:je,shortcutLabel:Tt,remoteUpdateInfo:ze,remoteUpdateChecking:Q,remoteUpdateError:X,onOpenRemoteUpdate:jt}):null,t.jsx(Gg,{isMobile:b,githubAuthStatus:D,githubAccounts:Ye,githubAvatarUrl:Re,githubLogin:Te,isSwitchingGitHubAccount:_e,handleGitHubAccountSwitch:et})]}),qs=Z&&(x||!!m),Js=()=>t.jsxs("div",{onMouseDown:Kt,className:B("app-region-drag relative flex h-12 select-none items-center pr-3",ft),style:Mt,role:"tablist","aria-label":"Main navigation",children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:de}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:he}}),t.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[L?t.jsxs("div",{className:"mr-3 flex min-w-0 flex-col items-start px-1 py-0.5 -my-0.5 text-left",children:[t.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:L.title}),L.subtitle?t.jsx("span",{className:"truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75 max-w-full",children:L.subtitle}):null]}):t.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[d?null:t.jsx(o.Suspense,{fallback:t.jsx("button",{type:"button",className:Gt,"aria-label":"Open session switcher",children:t.jsx(j,{name:"history",className:"h-[18px] w-[18px]"})}),children:t.jsx(zg,{align:"start",children:t.jsx("button",{type:"button",className:Gt,"aria-label":"Open session switcher",children:t.jsx(j,{name:"history",className:"h-[18px] w-[18px]"})})})}),t.jsxs("div",{className:"flex min-w-0 flex-col justify-center px-1",children:[bt?t.jsxs("form",{ref:Et,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:E=>{E.preventDefault(),At()},children:[t.jsx("input",{value:Ze,onChange:E=>yt(E.target.value),autoFocus:!0,onKeyDown:E=>{E.stopPropagation(),E.key==="Escape"&&qe(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),t.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(j,{name:"check",className:"size-4"})}),t.jsx("button",{type:"button",onClick:()=>qe(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:t.jsx(j,{name:"close",className:"size-4"})})]}):t.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-foreground max-w-full",children:x?"New session":se}),Y?t.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[w?t.jsx("span",{className:"truncate",children:w}):null,ye?t.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[t.jsx(j,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),t.jsx("span",{className:"truncate",children:ye})]}):null]}):null]}),t.jsx("div",{className:B("flex h-[18px] shrink-0 items-center justify-center",Y?"self-start":"self-center"),children:m&&!x&&!bt?t.jsxs(qt,{open:dt,onOpenChange:xt,onOpenChangeComplete:E=>{!E&&Me.current&&(Me.current=!1,It())},children:[t.jsx(Jt,{asChild:!0,children:t.jsx(Ve,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:t.jsx(j,{name:"more",className:"size-4"})})}),t.jsxs(Xt,{align:"end",className:"min-w-[190px]",children:[t.jsxs(kt,{onClick:()=>{Me.current=!0},children:[t.jsx(j,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),t.jsxs(kt,{onClick:F,children:[t.jsx(j,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),t.jsx(Vs,{}),t.jsxs(kt,{onClick:()=>{Ne()},children:[t.jsx(j,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),t.jsx(Vs,{}),t.jsxs(kt,{onClick:()=>Pt("archive"),children:[t.jsx(j,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),t.jsxs(kt,{className:"text-destructive focus:text-destructive",onClick:()=>Pt("delete"),children:[t.jsx(j,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),Ht.length>0&&t.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:Ht.map(E=>cs(E))}),t.jsx("div",{className:"flex-1"}),t.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[we?t.jsx(Qi,{projectRef:we.projectRef,directory:we.directory,className:"mr-1"}):null,t.jsx(Ug,{visible:qs,title:x?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:x?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:Rt,className:B(Gt,"mr-1"),Icon:"picture-in-picture-2"}),ms,t.jsx(ga,{visible:R&&q==="right",position:"right"})]})]})]}),gs=()=>t.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[v&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:de}}),t.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:he}})]}),!v&&t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?t.jsx("button",{type:"button",onClick:H,className:B(Ft,gt==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:t.jsx(j,{name:"layout-left",className:"h-5 w-5"})}):z?t.jsx("button",{type:"button",onClick:()=>l(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:t.jsx(j,{name:"arrow-left-s",className:"h-5 w-5"})}):t.jsx("button",{type:"button",onClick:Ot,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:t.jsx(j,{name:"play-list-add",className:"h-5 w-5"})}),!e&&z&&t.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!z||!!e)&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!M&&t.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain","data-no-drawer-swipe":"true",children:t.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Main navigation",children:Ht.map(E=>{const fe=u===E.id,Ie=E.icon==="diff",$=Ie?null:E.icon;return t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsxs("button",{type:"button",onClick:()=>{b&&(ut(),Bt()),p(E.id)},"aria-label":E.label,"aria-selected":fe,role:"tab",className:B(Ft,"relative rounded-lg",gt===E.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[Ie?t.jsx(Wi,{className:"h-5 w-5"}):$?t.jsx(j,{name:$,className:"h-5 w-5"}):null,E.badge!==void 0&&E.badge>0&&t.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:E.badge}),E.showDot&&t.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),t.jsx(rt,{children:t.jsx("p",{children:E.label})})]},E.id)})})})})}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[M&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:N.map(E=>{const fe=r&&i===E.id;return t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:()=>{b&&(ut(),Bt()),I(!1),a?.(E.id)},"aria-label":E.label,"aria-selected":fe,role:"tab",className:B(Ft,"relative rounded-lg",fe&&"bg-interactive-selection text-interactive-selection-foreground"),children:t.jsx(j,{name:E.icon,className:"h-5 w-5"})})}),t.jsx(rt,{children:t.jsx("p",{children:E.label})})]},E.id)})}),t.jsx(Eh,{open:C,onOpenChange:I,currentSessionId:m,effectiveDirectory:O||null,isNewSessionDraftOpen:x})]}),we&&t.jsx(Qi,{projectRef:we.projectRef,directory:we.directory,compact:!0,allowMobile:!0,className:"h-9"}),s&&!M?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:ne,className:B(Ft,"relative",gt==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:t.jsx(j,{name:"layout-right",className:"h-5 w-5"})})}),t.jsx(rt,{children:t.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),js=B("header-safe-area relative z-10 bg-background",b&&"border-b border-border/50");return t.jsxs(t.Fragment,{children:[t.jsx("header",{ref:P,className:js,style:{"--padding-scale":"1"},children:b?gs():Js()}),t.jsx(as,{open:Nt!==null,onOpenChange:E=>{E||Pt(null)},children:t.jsxs(ls,{showCloseButton:!1,className:"max-w-sm gap-5",children:[t.jsxs(Ss,{children:[t.jsx(hs,{children:Nt==="delete"?"Delete session?":"Archive session?"}),t.jsx(Fs,{children:Nt==="delete"?`\\"${se}\\" will be permanently deleted.`:`\\"${se}\\" will be archived.`})]}),t.jsxs(Ls,{children:[t.jsx(Ve,{variant:"outline",size:"sm",onClick:()=>Pt(null),children:"Cancel"}),t.jsx(Ve,{variant:"destructive",size:"sm",onClick:()=>{Ue()},children:Nt==="delete"?"Delete":"Archive"})]})]})}),t.jsx(Fa,{open:$e,onOpenChange:ot,info:ze,downloading:!1,downloaded:!1,progress:null,error:X,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},qi="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",Wg="app-region-no-drag flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50",Vx=()=>{const e=ce(g=>g.isSidebarOpen),s=ce(g=>g.toggleSidebar),n=ce(g=>g.shortcutOverrides),r=o.useRef(null),i=o.useRef(null),a=ao(ln("toggle_sidebar",n)),{usesFramelessChrome:l,side:c}=ma(),{enabled:d}=eo(),u=!e,p=l&&c==="left",h=l,x=u||p||h,m=p||h,f=o.useCallback(()=>{cn("desktop_show_app_menu").catch(g=>{console.warn("[titlebar] failed to open app menu",g)})},[]);return o.useEffect(()=>{if(typeof document>"u")return;const g=v=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(v)}px`)},S=v=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(v)}px`)};if(!m)return;const k=i.current,_=r.current;if(!k||!_){g(0),S(0);return}const A=()=>{const v=Math.max(k.getBoundingClientRect().width,k.scrollWidth);g(v),S(_.getBoundingClientRect().width)};if(A(),typeof ResizeObserver>"u")return;const b=new ResizeObserver(A);return b.observe(k),b.observe(_),()=>{b.disconnect()}},[m]),x?t.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:t.jsxs("div",{ref:i,className:"flex items-center gap-2",children:[p?t.jsx(ga,{visible:!0,position:"left"}):null,h?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:f,"aria-label":"Open PiChamber menu",className:B(qi,"shrink-0"),children:t.jsx(j,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),t.jsx(rt,{children:t.jsx("p",{children:"PiChamber menu"})})]}):null,u?t.jsxs(st,{children:[t.jsx(nt,{asChild:!0,children:t.jsx("button",{type:"button",onClick:s,"aria-label":"Open sessions",className:B(d?Wg:qi,"shrink-0"),children:t.jsx(j,{name:"layout-left",className:d?"size-[18px]":"h-[18px] w-[18px]"})})}),t.jsx(rt,{children:t.jsx("p",{children:`Open sessions (${a})`})})]}):null]})}):null},Ji=200,Vg="cubic-bezier(0.22, 1, 0.36, 1)",Yx=e=>{const s=o.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=o.useState(e),[i,a]=o.useState(e);return o.useLayoutEffect(()=>{if(s){a(e),r(e);return}if(e){a(!0),r(!1);let c=0;const d=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(d),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>a(!1),Ji);return()=>window.clearTimeout(l)},[e,s]),{slidIn:n,layoutVisible:i,prefersReducedMotion:s,transition:s?"none":`transform ${Ji}ms ${Vg}`}};export{Us as $,Ix as A,Ax as B,Nx as C,Fi as D,Ns as E,Mx as F,Ex as G,Wx as H,bx as I,Pf as J,po as K,mx as L,Eh as M,Df as N,mo as O,zx as P,Zf as Q,Kn as R,Lx as S,$x as T,Fa as U,Ef as V,bn as W,jf as X,kf as Y,La as Z,yn as _,rn as a,Nf as a0,ux as a1,wx as a2,Cf as a3,gx as a4,Af as a5,vx as a6,kx as a7,jx as a8,Tf as a9,As as aa,yx as ab,Sx as ac,Cx as ad,dx as ae,fx as af,hx as ag,px as ah,Yf as ai,xx as aj,ih as ak,ah as al,If as am,cx as an,Fx as ao,Dx as ap,wm as b,Ox as c,$n as d,hh as e,Gx as f,Bx as g,Tx as h,km as i,Rx as j,Px as k,Yx as l,Kx as m,Vx as n,lx as o,eh as p,th as q,Ux as r,_x as s,sh as t,Bn as u,fi as v,nh as w,tg as x,Hx as y,rh as z};
|