@pi-chamber/web 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{CommitSection-DLIvjYbM.js → CommitSection-BAYzLtBf.js} +1 -1
- package/dist/assets/{DiagramEditor-Tw3ZWHML.js → DiagramEditor-D1yc4joK.js} +1 -1
- package/dist/assets/{DiagramView-CK6R7taL.js → DiagramView-CAlJiG11.js} +1 -1
- package/dist/assets/{DiffView-vrxi5oWp.js → DiffView-DGD9DMS7.js} +1 -1
- package/dist/assets/{FilesView-BD_h3EVr.js → FilesView-DB5VI7EN.js} +1 -1
- package/dist/assets/{GitView-BwNKqK0K.js → GitView-CFlPcSn9.js} +3 -3
- package/dist/assets/{JsonTreeView-CmY7QgEX.js → JsonTreeView-CoX1ZscV.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-CpI-25Xk.js → MarkdownRendererImpl-V1HMFCjr.js} +1 -1
- package/dist/assets/{PatchDiff-CrIWbYj7.js → PatchDiff-D6Gs7K5B.js} +1 -1
- package/dist/assets/{PierreDiffViewer-B410mdbq.js → PierreDiffViewer-COYd5Qr-.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-DROjbyIu.js → SessionSwitcherDropdown-o1RjhCfF.js} +8 -8
- package/dist/assets/{SettingsView-CsJItYZh.js → SettingsView-BYqvfMTS.js} +3 -3
- package/dist/assets/{SettingsWindow-C9s4AX72.js → SettingsWindow-CtNS0tQn.js} +1 -1
- package/dist/assets/{ToolOutputDialog-b_R4tAZu.js → ToolOutputDialog-2zKUdGYL.js} +1 -1
- package/dist/assets/{ToolPartDiffPreview-CfnliaE9.js → ToolPartDiffPreview-CBFC9min.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-CQz2fSZI.js → VirtualizedFileDiff-UMgLcO4Q.js} +1 -1
- package/dist/assets/{collapsible-CR4U9tjw.js → collapsible-Kx4bmsQM.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-C7vXPUYT.js → computeVirtualFileMetrics-DdOCbMyK.js} +1 -1
- package/dist/assets/{contextFileOpenGuard-DtTHRnq1.js → contextFileOpenGuard-BRldMp0d.js} +1 -1
- package/dist/assets/{index-DZG82DE1.js → index-CuSNEV7s.js} +1 -1
- package/dist/assets/{isDiffPlainText-zTq-4A04.js → isDiffPlainText-CGIf0q8p.js} +1 -1
- package/dist/assets/{isFilePlainText-CLgIdzE5.js → isFilePlainText-D4hgTRxT.js} +1 -1
- package/dist/assets/{main-BVWtJYSk.js → main-By_pvk90.js} +2 -2
- package/dist/assets/{main-DXYHsqzA.js → main-CmkRaMOR.js} +4 -4
- package/dist/assets/{markdownCore-CN0pApQE.js → markdownCore-CAVCyFnI.js} +1 -1
- package/dist/assets/{miniChat-BrbRq5NQ.js → miniChat-_XK2gGZE.js} +2 -2
- package/dist/assets/{mobile-DTPtCn5N.js → mobile-B4E4JqAf.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-CM8qBaye.js → renderElectronMiniChatApp-Ca4hZgIz.js} +1 -1
- package/dist/assets/{renderMobileApp-KS_pt-qc.js → renderMobileApp-ClA5Cnmw.js} +4 -4
- package/dist/assets/{useInlineCommentController-CwNNjgc7.js → useInlineCommentController-DD31jQNC.js} +1 -1
- package/dist/assets/{usePanelSlide-DkorgQJ5.js → usePanelSlide-a4c67FIY.js} +2 -2
- package/dist/assets/{useWindowTitle-B9wt_3ZQ.js → useWindowTitle-DoHrUC5r.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-x89A7Wy0.js → vendor-codemirror-language-data-Dp_Z-0GD.js} +2 -2
- package/dist/assets/{web-components-BEPfE4kU.js → web-components-Cct1r-wn.js} +1 -1
- package/dist/index.html +1 -1
- package/dist/mini-chat.html +1 -1
- package/dist/mobile.html +1 -1
- package/package.json +1 -1
- package/server/lib/pi/session-daemon/session-daemon.js +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiffView-
|
|
2
|
-
import{r as De,j as t,R as a,b as We,e as vs}from"./vendor-react-DYyjh7Q0.js";import"./vendor-katex-CHD9BdDO.js";import{u as de,a as rt,b as _n,d as Wt,i as le,e as Se,s as $e,f as tt,r as Mn,h as ws,j as ks,k as zn,p as js,l as Ss,m as On,n as Cs,o as Es,q as Et,t as Ns,v as Vt,w as Rs,x as $n,y as Ts}from"./index-BAqpUCjs.js";import{u as Ps,a as As,b as Is,s as Ds,c as Ls,d as _s}from"./useWindowTitle-B9wt_3ZQ.js";import{u as Ue,M as Ms,i as zs,D as Kt,a as Gt,b as Xt,g as Os,c as qt,d as $s,s as Us,S as Bs,e as Fs,T as Hs,P as Ws,r as Vs,f as Ks,h as Gs,F as Xs,j as qs,k as Ys,l as Js,m as Qs,n as Zs,H as er,A as tr,C as nr,o as sr}from"./usePanelSlide-DkorgQJ5.js";import{u as rr,a as ar,b as Un,c as or,d as ir,r as At,e as lr,t as oe,o as cr,I as V,P as Ce,B as re,f as K,g as Bn,h as ge,i as ur,j as dr,k as fr,l as hr,m as mr,S as pr,n as gr,p as yr,F as Fn,T as br,q as xr,s as vr,v as It,O as wr,D as Yt,w as Jt,x as Qt,y as Zt,z as en,A as tn,C as Hn,E as Dt,G as kr,H as jr,J as Sr,K as ke,L as Cr,M as Er,N as Nr,Q as Rr,R as Tr,U as Pr,V as Ar,W as Ir,X as pe,Y as Dr,Z as Wn,_ as Nt,$ as Vn,a0 as Lr,a1 as nn,a2 as _r,a3 as Mr,a4 as zr,a5 as je,a6 as Or,a7 as $r,a8 as Ur,a9 as Br,aa as Fr,ab as Hr,ac as Wr,ad as Vr,ae as Kr,af as Gr,ag as Xr,ah as qr,ai as Yr,aj as Jr,ak as Qr,al as Zr,am as ea,an as ta,ao as na,ap as sa,aq as ra,ar as aa}from"./SessionSwitcherDropdown-DROjbyIu.js";import{S as oa,A as ia}from"./SettingsView-CsJItYZh.js";import{_ as be}from"./vendor-vite-runtime-DD1OZmLC.js";import{p as la}from"./vendor-aparajita-capacitor-secure-storage-5IShChL0.js";import{Capacitor as ca}from"./vendor-capacitor-core-B4EWRrHz.js";import{u as ua}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{C as da}from"./CommitSection-DLIvjYbM.js";import{P as fa}from"./PierreDiffViewer-B410mdbq.js";import{K as sn,P as ha,d as ma,p as pa,U as ga,Z as ya,Q as ba,r as xa}from"./vendor-remixicon-react-CzPq62YO.js";let Kn=null,rn=!1;const va=new Promise(e=>{Kn=e});function wa(){rn||(rn=!0,Kn?.())}const ka=6,ja=e=>e.parentID??null,an=e=>{const n=e.replace(/\/+$/,"");return n.slice(n.lastIndexOf("/")+1)||n},Sa=e=>e.replace(/\\/g,"/").replace(/\/+$/,""),Ca=(e,n)=>{if(!e)return"";let s=null,r=-1;for(const o of n){const i=Sa(o.path);(e===i||e.startsWith(`${i}/`))&&i.length>r&&(s=o,r=i.length)}return s?s.label?.trim()||an(s.path):an(e)},Ea=()=>{const e=rr.getState().activeSessions,n=ar.getState().index.session.unseenCount,s=de.getState().notifyOnSubtasks,r=Un.getState().projects,o=or.getState().ids,i=ir.getState().rankById;let l=0;const c=[];for(const d of e){const m=ja(d)!==null,k=(n[d.id]??0)>0&&(!m||s);k&&(l+=1),m||c.push({session:d,unread:k,project:Ca(At(d),r)})}c.sort((d,m)=>lr(d.session,m.session,o,i));const u=c.slice(0,ka).map(({session:d,unread:m,project:x})=>({id:d.id,title:d.title??"",unread:m,project:x}));return{runtimeKey:rt(),attentionCount:l,recentSessions:u}},Na="__PICHAMBER_WIDGET_SNAPSHOT__",Ra=()=>{typeof window>"u"||(window[Na]=()=>{try{return JSON.stringify(Ea())}catch{return null}})},vt="mobile-app-update-available",on="mobile-app-update-toast-dismissed-version",Ta=()=>{const e=Ue(i=>i.available),n=Ue(i=>i.runtimeType),s=Ue(i=>i.info?.version),r=Ue(i=>i.info?.downloadUrl),o=De.useRef(new Set);return De.useEffect(()=>{if(_n()!=="android"||n!=="mobile"||!e||!s||!r){oe.dismiss(vt);return}Wt().getItem(on)!==s&&(o.current.has(s)||(o.current.add(s),oe.info("PiChamber update available",{id:vt,description:`Version ${s} is ready for Android.`,duration:1/0,icon:t.jsx(V,{name:"download",className:"h-4 w-4 text-muted-foreground"}),action:{label:"Download",onClick:()=>{cr(r)}},cancel:{label:"Dismiss",onClick:()=>{Wt().setItem(on,s),oe.dismiss(vt)}}})))},[e,r,n,s]),null},Pa="Updating OpenCode configuration...",Gn=0,Xn=Pa,ln=new Set;function Aa(e){return ln.add(e),e({isUpdating:Gn>0,message:Xn}),()=>{ln.delete(e)}}function Ia(){return{isUpdating:Gn>0,message:Xn}}const Da=()=>{const[{isUpdating:e},n]=a.useState(()=>Ia());return a.useEffect(()=>Aa(n),[]),e?t.jsx("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-background/90",children:t.jsx(Ce,{width:80,height:80,isAnimated:!0})}):null},ft="pichamber.mobile.connections.v1",La="pichamber.mobile.",cn="pichamber.mobile.deviceId",_a=()=>{try{const e=window.localStorage.getItem(cn);if(e&&e.trim())return e.trim();const n=crypto.randomUUID();return window.localStorage.setItem(cn,n),n}catch{return crypto.randomUUID()}},un=()=>`mobile:${_a()}`,dn=()=>{try{const e=ca.getPlatform();return e==="ios"||e==="android"?e:void 0}catch{return}},qn=12,Ma=8e3,za=2500,Oa=3e3,ht=2500,Yn=()=>{let e=0;return{begin:()=>(e+=1,e),cancel:()=>{e+=1},isCurrent:n=>n===e}},ze=e=>{const n=e.trim();if(!n)return"";const s=/^https?:\/\//i.test(n)?n:`http://${n}`,r=new URL(s);return r.hash="",r.search="",r.pathname=r.pathname.replace(/\/+$/,""),r.toString().replace(/\/+$/,"")},Qe=e=>{try{return new URL(e).host}catch{return e}},Ve=e=>{try{return ze(e)}catch{return e.trim().replace(/\/+$/g,"")}},Lt=(e,n)=>Ve(e)===Ve(n),_t=e=>`relay:${e.serverId}@${e.relayUrl.trim()}`,$a=e=>`relay://${e.serverId}`,gt=e=>e.candidates.filter(n=>n.kind==="direct"),_e=e=>{const n=e.candidates.find(s=>s.kind==="relay");return n&&n.kind==="relay"?n.relay:null},xe=e=>{const n=gt(e)[0];if(n)return n.url;const s=_e(e);return s?$a(s):""},ie=e=>{const n=_e(e);if(n)return _t(n);const s=gt(e)[0];return s?Ve(s.url):""},mt=(e,n)=>{const s=e.find(i=>i.kind==="relay"),r=s&&s.kind==="relay"?s.relay.serverId:null,o=new Set(e.filter(i=>i.kind==="direct").map(i=>Ve(i.url)));return n.some(i=>i.kind==="relay"?r!==null&&i.relay.serverId===r:o.has(Ve(i.url)))},Mt=e=>{const n=(()=>{try{return ze(e)}catch{return""}})();return n?[{kind:"direct",url:n}]:[]},fn=e=>{if(e.candidates&&e.candidates.length>0)return e.candidates;const n=[];return typeof e.url=="string"&&e.url.trim()&&!/^relay:\/\//i.test(e.url.trim())&&n.push(...Mt(e.url)),e.relay&&n.push({kind:"relay",relay:e.relay}),n},zt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e;if(typeof n.relayUrl!="string"||!n.relayUrl.trim()||typeof n.serverId!="string"||!n.serverId.trim())return null;const s=n.hostEncPubJwk;if(!s||typeof s!="object"||Array.isArray(s))return null;const r=s;return r.kty!=="EC"||r.crv!=="P-256"||typeof r.x!="string"||!r.x||typeof r.y!="string"||!r.y?null:{relayUrl:n.relayUrl,serverId:n.serverId,hostEncPubJwk:{kty:"EC",crv:"P-256",x:r.x,y:r.y}}},yt=e=>{try{return JSON.stringify(e)}catch{return String(e)}},ce=(e,n={})=>{console.info("[mobile-connect]",e,yt(n)),ks("connect",{code:e,status:typeof n.status=="number"?n.status:void 0,detail:typeof n.reason=="string"?n.reason:typeof n.result=="string"?n.result:void 0})},Ke=(e,n={})=>{console.info("[mobile-storage]",e,yt(n))},Ua=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},Ba=e=>{if(typeof e!="string")return e??void 0;try{return JSON.parse(e)}catch{return e}},Fa=async(e,n)=>{if(!le())return null;try{const{CapacitorHttp:s}=await be(async()=>{const{CapacitorHttp:i}=await import("./vendor-capacitor-core-B4EWRrHz.js");return{CapacitorHttp:i}},[]),r=Object.fromEntries(new Headers(n?.headers).entries()),o=await s.request({url:e,method:n?.method||"GET",headers:r,data:Ba(n?.body)});return{ok:o.status>=200&&o.status<300,status:o.status,source:"native-http",json:async()=>Ua(o.data)}}catch(s){return console.warn("[mobile-connect]","native-http failed",yt({url:e,error:s instanceof Error?s.message:String(s)})),null}},Ha=async(e,n)=>{const s=await fetch(e,n).catch(r=>(console.warn("[mobile-connect]","browser-fetch failed",yt({url:e,error:r instanceof Error?r.message:String(r)})),null));return s?{ok:s.ok,status:s.status,source:"browser-fetch",json:()=>s.json()}:null},Ne=async(e,n,s)=>{let r;const o=new Promise(i=>{r=window.setTimeout(()=>{s?.(),i(null)},e)});try{return await Promise.race([n,o])}catch{return null}finally{r!==void 0&&window.clearTimeout(r)}},Me=async(e,n,s)=>{const r=s?.totalTimeoutMs??Ma,o=Date.now(),i=await Ne(Math.min(za,r),Fa(e,n));if(i)return i;const l=new AbortController,c=Math.max(500,r-(Date.now()-o));return Ne(c,Ha(e,{...n,signal:l.signal}),()=>l.abort())},bt=async e=>{if(!e)return null;const n=await e.json().catch(()=>null);if(!n||typeof n!="object")return null;const s=n;return{authenticated:typeof s.authenticated=="boolean"?s.authenticated:void 0,disabled:typeof s.disabled=="boolean"?s.disabled:void 0,scope:typeof s.scope=="string"?s.scope:void 0}},Ge=15e3,Wa=async(e,n,s,r=Ge,o)=>{const i=zn({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),l=c=>c==="ok"&&o?.keepTunnel?{outcome:c,tunnel:i}:(i.close(),{outcome:c});try{const c=n?{Authorization:`Bearer ${n}`}:void 0,u=await Ne(r,i.fetch("/auth/session",{headers:c}).catch(()=>null));if(ce("relay:session",{ok:u?.ok===!0,status:u?.status??null,hasToken:!!n}),!u)return l("unreachable");if(u.status===401)return l(n?"auth-failed":"needs-login");if(!u.ok&&u.status!==404)return l("auth-failed");const d=await bt(u);return d&&d.disabled!==!0&&d.authenticated===!1?l(n?"auth-failed":"needs-login"):l("ok")}catch(c){throw i.close(),c}},Va=(e,n,s,r,o)=>{const i=typeof window<"u"?window.location.origin:"",l={relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk,...s?{grant:s}:{}};o&&ws(l,o),$e({apiBaseUrl:i,clientToken:n,runtimeKey:r??_t(e),relay:l})},Ka=e=>{if(!e||typeof e!="object")return null;const n=e;if(n.kind==="direct")return typeof n.url=="string"&&n.url.trim()?{kind:"direct",url:n.url}:null;if(n.kind==="relay"){const s=zt(n.relay);return s?{kind:"relay",relay:s}:null}return null},Ga=e=>{if(e.mode==="relay"){const n=zt(e.relay);return n?[{kind:"relay",relay:n}]:[]}return typeof e.url=="string"?Mt(e.url):[]},Oe=()=>{if(typeof window>"u")return[];let e;try{e=JSON.parse(window.localStorage.getItem(ft)||"[]")}catch{return[]}if(!Array.isArray(e))return[];const n=le();return e.flatMap(s=>{if(!s||typeof s!="object")return[];const r=s;if(typeof r.id!="string")return[];const o=Array.isArray(r.candidates)?r.candidates.map(Ka).filter(u=>!!u):Ga(r);if(o.length===0)return[];const i=typeof r.clientToken=="string"&&r.clientToken.trim()?r.clientToken:void 0,l=typeof r.label=="string"&&r.label.trim()?r.label:Qe(xe({candidates:o})),c={id:r.id,label:l,candidates:o,lastUsedAt:typeof r.lastUsedAt=="number"?r.lastUsedAt:0};return n?[{...c,hasToken:!!r.hasToken||!!i}]:[{...c,clientToken:i,hasToken:!!i}]}).sort((s,r)=>r.lastUsedAt-s.lastUsedAt)},Rt=e=>e.kind==="relay"?{kind:"relay",relay:{relayUrl:e.relay.relayUrl,serverId:e.relay.serverId,hostEncPubJwk:e.relay.hostEncPubJwk}}:{kind:"direct",url:e.url},Ot=e=>{if(typeof window>"u")return;const n=le(),s=e.slice(0,qn).map(r=>{const o={id:r.id,label:r.label,candidates:r.candidates.map(Rt),lastUsedAt:r.lastUsedAt};return n?{...o,hasToken:!!(r.hasToken||r.clientToken)}:{...o,clientToken:r.clientToken}});try{window.localStorage.setItem(ft,JSON.stringify(s))}catch(r){console.warn("[mobile-storage] failed to persist connection metadata",r)}},Jn=(e,n)=>{const s=e.find(i=>n.id&&i.id===n.id||mt(i.candidates,n.candidates)),r=le(),o={id:n.id||s?.id||crypto.randomUUID(),label:n.label,candidates:n.candidates,lastUsedAt:Date.now(),...r?{hasToken:n.hasToken??(!!n.clientToken||s?.hasToken||!1)}:{clientToken:n.clientToken??s?.clientToken,hasToken:!!(n.clientToken??s?.clientToken)}};return[o,...e.filter(i=>i.id!==o.id&&!mt(i.candidates,n.candidates))].slice(0,qn)},$t=la,Xa=0,Ut=e=>`${La}token.${encodeURIComponent(e)}`,qa=async(e,n)=>{let s;const r=new Promise(o=>{s=window.setTimeout(()=>o(n),Oa)});try{return await Promise.race([e.catch(()=>n),r])}finally{s!==void 0&&window.clearTimeout(s)}},Bt=async(e,n,s)=>le()?qa(n().catch(r=>(console.warn(`[mobile-storage] ${e} failed`,r),s)),s):s,nt=async e=>{Ke("secure:read-start",{key:e});const n=await Bt("secure:read",async()=>(await $t.internalGetItem({prefixedKey:Ut(e),sync:!1})).data,null),s=typeof n=="string"&&n.trim()?n:void 0;return Ke("secure:read",{key:e,hasToken:!!s}),s},Ie=async(e,n)=>{Ke("secure:write-start",{key:e});const s=await Bt("secure:write",async()=>(await $t.internalSetItem({prefixedKey:Ut(e),data:n,sync:!1,access:Xa}),!0),!1);return Ke("secure:write",{key:e,ok:s}),s},Ya=async e=>{await Bt("secure:delete",async()=>(await $t.internalRemoveItem({prefixedKey:Ut(e),sync:!1}),!0),!1)},Qn=async(e,n)=>{let s=0,r=0;return{records:await Promise.all(e.map(async i=>{if(!i||typeof i!="object")return i;const l=i,c=typeof l.url=="string"?l.url:null,u=typeof l.clientToken=="string"?l.clientToken.trim():"";if(!c||!u)return i;if(!await n(c,u))return r+=1,i;s+=1;const{clientToken:d,...m}=l;return{...m,hasToken:!0}})),migrated:s,failed:r}},Zn=async()=>{if(typeof window>"u"||!le())return;let e;try{e=JSON.parse(window.localStorage.getItem(ft)||"[]")}catch{return}if(!Array.isArray(e))return;const n=e.filter(r=>!!r&&typeof r=="object"&&typeof r.url=="string"&&typeof r.clientToken=="string"&&!!r.clientToken.trim());if(n.length===0)return;Ke("secure:migrate-start",{count:n.length});const s=await Qn(e,async(r,o)=>{const i=Ve(r);return await Ie(i,o)?await nt(i)===o:!1});if(s.migrated>0)try{window.localStorage.setItem(ft,JSON.stringify(s.records))}catch(r){console.warn("[mobile-storage] failed to finalize secure token migration",r);return}Ke("secure:migrate-done",{migrated:s.migrated,failed:s.failed})},es=async()=>(await Zn(),Oe()),st=async e=>{const n=Jn(Oe(),e);return Ot(n),le()&&e.clientToken&&await Ie(ie({candidates:e.candidates}),e.clientToken),n},ts=async e=>{const n=Oe(),s=n.find(o=>o.id===e)??null,r=n.filter(o=>o.id!==e);return Ot(r),s&&le()&&await Ya(ie(s)),r},Ja=1500,pt=async(e,n,s)=>{const r=s?.fast?{totalTimeoutMs:ht}:void 0,o=_e({candidates:e})?.serverId??null,i=e.find(d=>d.kind==="relay")??null,l=e.filter(d=>d.kind==="direct"),c=async()=>{for(const d of l){const m=ze(d.url)||d.url,x=n?{Authorization:`Bearer ${n}`}:void 0,k=await Me(`${m}/health`,{method:"GET"},r);if(!k?.ok)continue;if(o){const U=await k.json().catch(()=>null),F=U&&typeof U=="object"?U.serverId:null;if(typeof F=="string"&&F&&F!==o){ce("probe:server-id-mismatch",{url:m});continue}}const N=await Me(`${m}/auth/session`,{method:"GET",credentials:n?"omit":"include",headers:x},r);if(N?.status===401)return{status:"needs-login"};if(!N||!N.ok&&N.status!==404)continue;const P=await bt(N);if(P&&P.disabled!==!0&&P.authenticated===!1)return{status:"needs-login"};const R=P?.disabled===!0;return!n&&le()&&!R&&P?.scope!=="client"?{status:"needs-login"}:{status:"ok",transport:{kind:"direct",url:m}}}return{status:"unreachable"}},u=async()=>{if(!i)return{status:"unreachable"};const{outcome:d,tunnel:m}=await Wa(i.relay,n,void 0,s?.fast?ht:void 0,{keepTunnel:!0});return d==="ok"?{status:"ok",transport:{kind:"relay",relay:i.relay,tunnel:m}}:d==="needs-login"||d==="auth-failed"?{status:"needs-login"}:{status:"unreachable"}};return i?l.length===0?u():new Promise(d=>{let m=!1,x=!1,k,N=null,P=null;const R=h=>{h?.status==="ok"&&h.transport.kind==="relay"&&h.transport.tunnel?.close()},U=h=>{m||(m=!0,d(h))},F=()=>{x||m||(k!==void 0&&(window.clearTimeout(k),k=void 0),u().then(h=>{if(P=h,m||x){R(h);return}if(h.status==="ok"||h.status==="needs-login"){U(h);return}N&&U(N)}))};c().then(h=>{if(N=h,!m){if(h.status==="ok"||h.status==="needs-login"){x=!0,k!==void 0&&window.clearTimeout(k),R(P),U(h);return}if(P){U(P);return}F()}}),k=window.setTimeout(F,Ja)}):c()},Le=(e,n,s)=>{e.kind==="relay"?Va(e.relay,n,s?.grant,s?.runtimeKey,e.tunnel):$e({apiBaseUrl:e.url,clientToken:n,runtimeKey:s?.runtimeKey}),os()},Be=()=>{const e=Oe()[0];return e?.label?.trim()?e.label:null},dt=async()=>{await Zn();const e=Oe()[0];if(!e)return{status:"no-candidate"};let n;if(le()){if(!e.hasToken)return{status:"no-candidate"};if(n=await nt(ie(e)),!n)return{status:"no-candidate"}}else if(n=e.clientToken,!n)return{status:"no-candidate"};const s=await pt(e.candidates,n,{fast:!0});return s.status==="needs-login"?{status:"needs-login",label:e.label}:s.status!=="ok"?{status:"unreachable",label:e.label}:(await st({id:e.id,label:e.label,candidates:e.candidates}),Le(s.transport,n,{runtimeKey:ie(e)}),{status:"connected"})},ns=async(e,n)=>{let s="";try{s=ze(e.url)}catch{return!1}if(!s)return!1;const r=e.clientToken?.trim()||void 0,o=r?{Authorization:`Bearer ${r}`}:void 0,i=n?.fast?{totalTimeoutMs:ht}:void 0;if(!(await Me(`${s}/health`,{method:"GET",headers:o},i))?.ok)return!1;const c=await Me(`${s}/auth/session`,{method:"GET",credentials:r?"omit":"include",headers:o},i);if(!c||!c.ok&&c.status!==404)return!1;const u=await bt(c);return!(u&&u.disabled!==!0&&u.authenticated===!1)},Qa=e=>[...e].sort((n,s)=>{const r=(n.priority??100)-(s.priority??100);if(r!==0)return r;const o=i=>i.type==="relay"?2:i.url.startsWith("https://")?0:1;return o(n)-o(s)}).flatMap(n=>{if(n.type==="relay"){const s=zt({relayUrl:n.relayUrl,serverId:n.serverId,hostEncPubJwk:n.hostEncPubJwk});return s?[{kind:"relay",relay:s}]:[]}return Mt(n.url)}),hn=async e=>{const n=_e({candidates:e})?.serverId??null;for(const s of e){if(s.kind==="relay"){const i=zn(s.relay),l=await Ne(Ge,i.fetch("/health").catch(()=>null));if(ce("establish:relay:health",{ok:l?.ok===!0,status:l?.status??null}),l?.ok)return{kind:"relay",relay:s.relay,tunnel:i};i.close();continue}const r=ze(s.url)||s.url,o=await Me(`${r}/health`,{method:"GET"});if(ce("establish:direct:health",{ok:o?.ok===!0,status:o?.status??null}),!!o?.ok){if(n){const i=await o.json().catch(()=>null),l=i&&typeof i=="object"?i.serverId:null;if(typeof l=="string"&&l&&l!==n){ce("establish:server-id-mismatch",{url:r});continue}}return{kind:"direct",url:r}}}return null},ss=async(e,n)=>{if(!tt())return ns(e,n);const s=await Ne(n?.fast?ht:Ge,Mn("/auth/session").then(o=>o).catch(()=>null));if(!s)return!0;if(s.status===401)return!1;if(!s.ok&&s.status!==404)return!0;const r=await bt(s);return!(r&&r.disabled!==!0&&r.authenticated===!1)},Za=e=>e.kind==="relay"?tt():!tt()&&Lt(e.url,Se()),rs=()=>{const e=rt();return e?Oe().find(n=>ie(n)===e)??null:null},Tt=e=>{const n=rt();return!!n&&ie(e)===n},Ze=async()=>{const e=rs();if(!e)return"no-connection";let n;if(le()?n=e.hasToken?await nt(ie(e)):void 0:n=e.clientToken,!n)return"unreachable";const s=e.candidates.findIndex(c=>Za(c.kind==="relay"?{kind:"relay",relay:c.relay}:{kind:"direct",url:c.url})),r=s>=0?e.candidates.slice(0,s):e.candidates,o=await pt(r,n,{fast:!0});if(o.status==="ok")return await st({id:e.id,label:e.label,candidates:e.candidates}),Le(o.transport,n,{runtimeKey:ie(e)}),"switched";if(o.status==="needs-login")return"needs-login";if(s>=0&&await ss({url:Se(),clientToken:n},{fast:!0}))return os(),"unchanged";const i=s>=0?e.candidates.slice(s+1):[],l=await pt(i,n,{fast:!0});return l.status==="ok"?(await st({id:e.id,label:e.label,candidates:e.candidates}),Le(l.transport,n,{runtimeKey:ie(e)}),"switched"):l.status==="needs-login"?"needs-login":"unreachable"},eo=5e3;let wt=!1;const as=async()=>{if(wt)return"skipped";const e=rs();if(!e)return ce("candidates:refresh-skip",{reason:"no-active-connection"}),"skipped";const n=_e(e);if(!n)return ce("candidates:refresh-skip",{reason:"no-relay-candidate"}),"skipped";wt=!0;try{const s=await Ne(Ge,Mn("/api/client-auth/connection/candidates").then(d=>d).catch(()=>null));if(!s?.ok)return ce("candidates:refresh-skip",{reason:"fetch-failed",status:s?.status??null}),"skipped";const r=await s.json().catch(()=>null);if(!r||r.serverId!==n.serverId)return ce("candidates:refresh-skip",{reason:"server-id-mismatch"}),"skipped";const o=Array.isArray(r.candidates)?r.candidates:[],i=[];for(const d of o){if(!d||typeof d!="object")continue;const m=d;if(!(m.type!=="lan"||typeof m.url!="string"))try{const x=ze(m.url);x&&!i.includes(x)&&i.push(x)}catch{}}if(i.length===0)return ce("candidates:refresh-skip",{reason:"no-lan-reported"}),"skipped";const l=gt(e).filter(d=>d.url.startsWith("https://")),c=[...i.map(d=>({kind:"direct",url:d})),...l,{kind:"relay",relay:n}];return JSON.stringify(e.candidates.map(Rt))===JSON.stringify(c.map(Rt))?"unchanged":(ce("candidates:refreshed",{lanCount:i.length}),await st({id:e.id,label:e.label,candidates:c}),"updated")}finally{wt=!1}},os=()=>{typeof window>"u"||window.setTimeout(()=>{(async()=>{const e=await as().catch(()=>"skipped");ce("candidates:refresh-result",{result:e}),e==="updated"&&tt()&&await Ze().catch(()=>null)})()},eo)},Ft=e=>{const[n,s]=a.useState(()=>Oe()),[r,o]=a.useState(null),[i,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(n),m=a.useRef(null),x=a.useRef(Yn()),k=a.useCallback(b=>{d.current=b,s(b)},[]),N=a.useCallback(b=>{m.current=b,o(b)},[]),P=a.useCallback(b=>{m.current===b&&(m.current=null,o(null))},[]);a.useEffect(()=>{let b=!1;return es().then(S=>{b||k(S)}),()=>{b=!0}},[k]);const R=a.useCallback(b=>{const S=Jn(d.current,b);return k(S),Ot(S),S},[k]),U=a.useCallback(async b=>{l(null),N("connect");try{const S=fn(b);if(S.length===0){l("Enter a server URL.");return}const y=b.id?d.current.find(p=>p.id===b.id):d.current.find(p=>mt(p.candidates,S)),B=b.label?.trim()||y?.label||Qe(xe({candidates:S})),g=b.relayGrant;let I=b.clientToken?.trim()||void 0;const w=!!I;I||(le()?y?.hasToken&&(I=await nt(ie({candidates:S}))):I=y?.clientToken),ce("connect:start",{candidates:S.map(p=>p.kind),hasToken:!!I});const E=await pt(S,I);if(ce("connect:probe",{status:E.status}),E.status==="unreachable"){l("Could not reach that PiChamber server.");return}if(E.status==="needs-login"){R({id:y?.id,label:B,candidates:S}),u({id:y?.id??crypto.randomUUID(),label:B,candidates:S,relay:_e({candidates:S})??void 0,relayGrant:g});return}I&&w&&le()&&await Ie(ie({candidates:S}),I),R({id:y?.id,label:B,candidates:S,clientToken:I}),Le(E.transport,I??null,{runtimeKey:ie({candidates:S}),grant:g}),e()}catch(S){console.warn("[mobile-connect] connect threw",S),l("That server URL is not valid.")}finally{P("connect")}},[N,P,e,R]),F=a.useCallback(async b=>{if(m.current==="pairing")return;l(null),N("pairing");const S=Qa(b.candidates);let y=null,B=!1;try{if(y=await hn(S),!y){l("Could not reach that PiChamber server.");return}const g=JSON.stringify({pairingId:b.pairingId,secret:b.secret,clientLabel:"PiChamber Mobile",clientKind:"mobile",deviceName:"PiChamber Mobile",devicePlatform:dn(),dedupeKey:un()}),I={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:g},w=y.kind==="relay"?await Ne(Ge,y.tunnel.fetch("/api/client-auth/pairing/redeem",I).catch(()=>null)):await Me(`${y.url}/api/client-auth/pairing/redeem`,I);if(!w?.ok){l("This server needs a password or client token.");return}const E=await w.json().catch(()=>null),p=typeof E?.clientToken=="string"?E.clientToken.trim():"";if(!p){l("This server needs a password or client token.");return}const C=typeof E?.server?.label=="string"?E.server.label:"",O=b.label||C||Qe(xe({candidates:S}));if(le()&&!await Ie(ie({candidates:S}),p)){l("This server needs a password or client token.");return}R({label:O,candidates:S,clientToken:p}),Le(y.kind==="relay"?{kind:"relay",relay:y.relay,tunnel:y.tunnel}:{kind:"direct",url:y.url},p,{runtimeKey:ie({candidates:S})}),B=y.kind==="relay",e()}catch(g){console.warn("[mobile-connect] pairing threw",g),l("This server needs a password or client token.")}finally{!B&&y?.kind==="relay"&&y.tunnel.close(),P("pairing")}},[N,P,e,R]),h=a.useCallback(async b=>{if(!c||!b.trim()||m.current==="password")return;l(null),N("password");const S=x.current.begin(),y=()=>x.current.isCurrent(S),{id:B,label:g,candidates:I}=c;let w=null,E=!1;try{if(w=await hn(I),!y())return;if(!w){l("Could not reach that PiChamber server.");return}const p={method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:b,trustDevice:!0,issueClientToken:!0,clientLabel:"PiChamber Mobile",clientKind:"mobile",devicePlatform:dn(),dedupeKey:un()})};ce("password:start",{transport:w.kind});const C=w.kind==="relay"?await Ne(Ge,w.tunnel.fetch("/auth/session",p).catch(()=>null)):await Me(`${w.url}/auth/session`,p);if(!y())return;if(ce("password:done",{ok:C?.ok===!0,status:C?.status??null}),!C?.ok){l("Could not unlock that server. Check the password.");return}const O=await C.json().catch(()=>null);if(!y())return;const q=typeof O?.clientToken=="string"?O.clientToken.trim():"";if(ce("password:token",{issued:!!q}),!q){if(w.kind==="direct"&&!le()){R({id:B,label:g,candidates:I}),u(null),Le({kind:"direct",url:w.url},null,{runtimeKey:ie({candidates:I})}),e();return}l("This server needs a password or client token.");return}if(le()&&(!y()||(await Ie(ie({candidates:I}),q),!y()))||!y()||(R({id:B,label:g,candidates:I,clientToken:q}),u(null),Le(w.kind==="relay"?{kind:"relay",relay:w.relay,tunnel:w.tunnel}:{kind:"direct",url:w.url},q,{runtimeKey:ie({candidates:I})}),E=w.kind==="relay",!y()))return;e()}catch(p){if(!y())return;console.warn("[mobile-connect] password threw",p),l("Could not unlock that server. Check the password.")}finally{!E&&w?.kind==="relay"&&w.tunnel.close(),y()&&P("password")}},[N,P,e,c,R]),v=a.useCallback(()=>{x.current.cancel(),P("password"),u(null),l(null)},[P]),L=a.useCallback(async b=>{l(null);let S=fn(b);const y=b.id?d.current.find(w=>w.id===b.id)??null:null;if(y){const w=S.filter(C=>C.kind==="direct"),E=gt(y).filter(C=>C.url.startsWith("https://")&&!w.some(O=>Lt(O.url,C.url))),p=_e(y);S=[...w,...E,...p?[{kind:"relay",relay:p}]:[]]}if(S.length===0)return l("Enter a server URL."),null;const B=b.clientToken?.trim()||void 0,g=b.label?.trim()||Qe(xe({candidates:S}));if(le()){const w=ie({candidates:S});if(B)await Ie(w,B);else if(y?.hasToken){const E=ie(y);if(E&&w&&E!==w){const p=await nt(E);p&&await Ie(w,p)}}}return R({id:b.id,label:g,candidates:S,clientToken:B}).find(w=>mt(w.candidates,S))??null},[R]),$=a.useCallback(async b=>{const S=d.current.find(B=>B.id===b)??null,y=await ts(b);return k(y),S},[k]);return{connections:n,isBusy:r!==null,isPasswordBusy:r==="password",error:i,pendingConnection:c,connect:U,redeemPairingConnection:F,submitPassword:h,cancelPassword:v,saveConnection:L,removeConnection:$,setError:l}},vi=Object.freeze(Object.defineProperty({__proto__:null,autoConnectLastInstance:dt,connectionDisplayUrl:xe,createMobilePasswordOperationTracker:Yn,deleteMobileConnection:ts,getAutoConnectTargetLabel:Be,getConnectionLabel:Qe,isActiveRuntimeConnection:Tt,isSameConnectionUrl:Lt,loadMobileConnections:es,migrateLegacyInlineTokenRecords:Qn,normalizeConnectionUrl:ze,refreshActiveConnectionCandidates:as,relayConnectionRuntimeKey:_t,reprobeActiveConnection:Ze,upsertMobileConnection:st,useMobileConnection:Ft,validateActiveRuntimeSession:ss,validateMobileConnectionSession:ns},Symbol.toStringTag,{value:"Module"})),is=()=>{if(typeof window>"u")return null;const n=window.Capacitor?.Plugins?.BarcodeScanner;return n&&(typeof n.scan=="function"||typeof n.startScan=="function")?n:null},to=()=>window.Capacitor?.getPlatform?.()==="android",ls=e=>{const n=e.trim();if(!n)return null;if(/^pichamber:\/\//i.test(n)){const s=js(n);return s?{pairing:s}:null}return/^https?:\/\//i.test(n)?{url:n}:null},cs=(e,n)=>{const s=ls(e);if(!s&&n?.pairingStringFallback){const r=Ss(e);if(r)return{status:"pairing",pairing:r}}return s?"pairing"in s?{status:"pairing",...s}:{status:"ok",...s}:{status:"invalid"}},no=async(e,n)=>{if(!e.startScan||!e.stopScan||!e.addListener)return{status:"unsupported"};if(n?.aborted)return{status:"cancelled"};let s,r,o=!1,i=()=>{};const l=new Promise(d=>{i=d}),c=d=>{o||(o=!0,i(d))},u=()=>c({status:"cancelled"});n?.addEventListener("abort",u,{once:!0});try{return(await Promise.allSettled([Promise.resolve(e.addListener("barcodesScanned",({barcodes:m})=>{const x=m?.[0],k=(x?.rawValue??x?.displayValue??"").trim();k&&c(cs(k,{pairingStringFallback:!0}))})).then(m=>{s=m}),Promise.resolve(e.addListener("scanError",()=>c({status:"failed"}))).then(m=>{r=m})])).some(({status:m})=>m==="rejected")?c({status:"failed"}):o||e.startScan({formats:["QR_CODE"]}).catch(()=>c({status:"failed"})),await l}finally{n?.removeEventListener("abort",u),await Promise.allSettled([Promise.resolve(s?.remove()),Promise.resolve(r?.remove()),e.stopScan()])}},Pt=()=>is()!==null,us=async e=>{const n=is();if(!n)return{status:"unsupported"};try{if(n.requestPermissions){const l=(await n.requestPermissions())?.camera;if(l&&l!=="granted"&&l!=="limited")return{status:"permission-denied"}}if(e?.signal?.aborted)return{status:"cancelled"};if(to())return no(n,e?.signal);if(!n.scan)return{status:"unsupported"};const r=(await n.scan({formats:["QR_CODE"]}))?.barcodes?.[0],o=(r?.rawValue??r?.displayValue??"").trim();return o?cs(o):{status:"cancelled"}}catch{return{status:"failed"}}},He={autoComplete:"off",autoCorrect:"off",spellCheck:!1},Ye="h-12 w-full rounded-[16px] border border-border/70 bg-surface-elevated px-4 text-[16px] text-foreground outline-none transition-colors placeholder:text-muted-foreground focus:border-primary focus:ring-2 focus:ring-primary/20",ds=({onCancel:e})=>{const n=a.useRef(null);return a.useLayoutEffect(()=>{const s={value:document.documentElement.style.getPropertyValue("background-color"),priority:document.documentElement.style.getPropertyPriority("background-color")},r={value:document.body.style.getPropertyValue("background-color"),priority:document.body.style.getPropertyPriority("background-color")};document.documentElement.style.setProperty("background-color","rgba(0, 0, 0, 0)","important"),document.body.style.setProperty("background-color","rgba(0, 0, 0, 0)","important");const o=new Map,i=c=>{!(c instanceof HTMLElement)||c===n.current||o.has(c)||(o.set(c,{opacity:c.style.opacity,pointerEvents:c.style.pointerEvents}),c.style.setProperty("opacity","0"),c.style.setProperty("pointer-events","none"))};Array.from(document.body.children).forEach(i);const l=new MutationObserver(c=>{c.forEach(u=>u.addedNodes.forEach(i))});return l.observe(document.body,{childList:!0}),()=>{l.disconnect(),o.forEach((c,u)=>{u.style.opacity=c.opacity,u.style.pointerEvents=c.pointerEvents}),s.value?document.documentElement.style.setProperty("background-color",s.value,s.priority):document.documentElement.style.removeProperty("background-color"),r.value?document.body.style.setProperty("background-color",r.value,r.priority):document.body.style.removeProperty("background-color")}},[]),a.useEffect(()=>{const s=()=>{document.visibilityState==="hidden"&&e()};return document.addEventListener("visibilitychange",s),()=>document.removeEventListener("visibilitychange",s)},[e]),We.createPortal(t.jsxs("div",{ref:n,role:"dialog","aria-modal":"true","aria-label":"Scan QR code",className:"fixed inset-0 z-[1000] flex flex-col bg-transparent px-6 pb-[calc(var(--safe-area-inset-bottom,env(safe-area-inset-bottom,0px))+24px)] pt-[calc(var(--safe-area-inset-top,env(safe-area-inset-top,0px))+24px)] text-foreground",children:[t.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-6",children:[t.jsx("div",{className:"aspect-square w-full max-w-72 rounded-[28px] border-2 border-foreground/90 shadow-[0_0_0_9999px_color-mix(in_srgb,var(--surface-background)_18%,transparent)]","aria-hidden":!0}),t.jsx("p",{className:"max-w-sm rounded-[16px] border border-border/60 bg-background px-4 py-3 text-center typography-body text-foreground shadow-sm",children:"On your computer, open «Add a device» to show a QR code, then scan it here."})]}),t.jsxs(re,{type:"button",variant:"outline",size:"lg",className:"mx-auto min-h-12 w-full max-w-sm bg-background",onClick:e,children:[t.jsx(V,{name:"close",className:"size-[18px]"}),"Cancel"]})]}),document.body)},fs=()=>We.createPortal(t.jsxs("div",{role:"status",className:"fixed inset-0 z-[1000] flex flex-col items-center justify-center gap-5 bg-background px-6 text-foreground",children:[t.jsx(Ce,{width:96,height:96,isAnimated:!0}),t.jsxs("div",{className:"flex items-center gap-2 typography-ui-label text-muted-foreground",children:[t.jsx(V,{name:"loader-4",className:"size-[18px] animate-spin"}),t.jsx("span",{children:"Connecting..."})]})]}),document.body),so=({onConnected:e,notice:n=null})=>{const s=Ft(e),{connections:r,isBusy:o,isPasswordBusy:i,error:l,pendingConnection:c}=s,[u,d]=a.useState(""),[m,x]=a.useState(""),[k,N]=a.useState(""),[P,R]=a.useState(!1),[U,F]=a.useState(!1),h=a.useRef(null),v=a.useMemo(()=>Pt(),[]),[L,$]=a.useState(()=>!Pt()),[b,S]=a.useState(null),[y,B]=a.useState(""),g=a.useCallback(C=>{C.preventDefault(),s.connect({url:u,clientToken:k,label:m})},[k,s,m,u]),I=a.useCallback(C=>{if(/^pichamber:\/\//i.test(C.trim())){const O=ls(C);if(O){if("pairing"in O){s.redeemPairingConnection(O.pairing);return}d(O.url),O.label&&x(O.label),O.clientToken&&N(O.clientToken);return}}d(C)},[s]),w=a.useCallback(async()=>{if(h.current||o)return;s.setError(null),R(!0);const C=new AbortController;h.current=C;try{const O=await us({signal:C.signal});switch(h.current===C&&(h.current=null,R(!1)),O.status){case"ok":F(!0),d(O.url),O.label&&x(O.label),O.clientToken&&N(O.clientToken),await s.connect({url:O.url,clientToken:O.clientToken,label:O.label});break;case"pairing":F(!0),await s.redeemPairingConnection(O.pairing);break;case"permission-denied":s.setError("Camera access is off. Enable it in Settings to scan a QR code.");break;case"invalid":s.setError("That QR code is not an PiChamber connection code.");break;case"unsupported":s.setError("QR scanning is only available in the installed mobile app.");break;case"failed":s.setError("Could not scan that QR code. Try again or enter the URL manually.");break;default:break}}finally{F(!1),h.current===C&&(h.current=null,R(!1))}},[s,o]);a.useEffect(()=>()=>h.current?.abort(),[]);const E=a.useCallback(C=>{C.preventDefault(),s.submitPassword(y)},[s,y]),p=a.useCallback(()=>{B(""),s.cancelPassword()},[s]);return t.jsxs(t.Fragment,{children:[P?t.jsx(ds,{onCancel:()=>h.current?.abort()}):null,U?t.jsx(fs,{}):null,t.jsx("main",{className:"oc-keyboard-fill-screen flex min-h-dvh flex-col overflow-y-auto bg-background px-6 pb-[calc(var(--safe-area-inset-bottom,env(safe-area-inset-bottom,0px))+28px)] pt-[calc(var(--safe-area-inset-top,env(safe-area-inset-top,0px))+28px)] text-foreground",children:t.jsxs("div",{className:"m-auto flex w-full max-w-[360px] shrink-0 flex-col items-center gap-9 py-8",children:[t.jsxs("div",{className:"flex flex-col items-center gap-5 text-center",children:[t.jsx(Ce,{width:72,height:72,className:"size-[72px]"}),t.jsx("h1",{className:"typography-h2 text-foreground",children:"Connect to PiChamber"})]}),n?t.jsxs("div",{role:"status",className:"flex w-full items-center gap-3 rounded-[18px] border border-[color-mix(in_srgb,var(--status-warning)_35%,transparent)] bg-[color-mix(in_srgb,var(--status-warning)_10%,transparent)] px-3.5 py-3",children:[t.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-[color-mix(in_srgb,var(--status-warning)_16%,transparent)] text-[var(--status-warning)]",children:t.jsx(V,{name:n.kind==="auth-expired"?"lock":"cloud-off",className:"size-[18px]"})}),t.jsx("p",{className:"min-w-0 flex-1 typography-small text-foreground",children:n.kind==="auth-expired"?`Access to ${n.label} has expired or was revoked. Sign in again.`:`Couldn't reach ${n.label}. Check that the server is running.`})]}):null,c?t.jsxs("form",{className:"flex w-full flex-col gap-3",onSubmit:E,children:[t.jsxs("div",{className:"flex items-center gap-3 rounded-[18px] border border-border/70 bg-surface-elevated px-3.5 py-3",children:[t.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:t.jsx(V,{name:"lock",className:"size-[18px]"})}),t.jsxs("div",{className:"min-w-0 text-left",children:[t.jsx("p",{className:"truncate typography-ui-label text-foreground",children:c.label}),t.jsx("p",{className:"truncate typography-small text-muted-foreground",children:c.candidates.some(C=>C.kind==="direct")?xe(c):"via PiChamber Relay"})]})]}),t.jsx("input",{...He,value:y,onChange:C=>B(C.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:Ye}),l?t.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,t.jsx(re,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",disabled:i||!y.trim(),children:i?"Connecting...":"Unlock and connect"}),t.jsx(re,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:p,children:"Use another server"})]}):t.jsxs("div",{className:"flex w-full flex-col gap-6",children:[v?t.jsxs("div",{className:"flex w-full flex-col gap-2",children:[t.jsxs(re,{type:"button",size:"lg",className:"h-12 w-full",onClick:()=>{w()},disabled:P||o,children:[t.jsx(V,{name:"scan-2",className:K("size-[18px]",P&&"animate-pulse")}),o?"Connecting...":"Scan QR code"]}),t.jsx("p",{className:"px-2 text-center typography-small text-muted-foreground",children:"On your computer, open «Add a device» to show a QR code, then scan it here."})]}):null,l&&!L?t.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,r.length>0?t.jsxs("section",{className:"flex w-full flex-col gap-2.5",children:[t.jsx("h2",{className:"text-center typography-micro uppercase tracking-[0.14em] text-muted-foreground",children:"Saved connections"}),t.jsx("div",{className:"overflow-hidden rounded-[18px] border border-border/70 bg-surface-elevated",children:r.map(C=>{const O=b===C.id;return t.jsxs("button",{type:"button",disabled:o,className:"flex min-h-14 w-full items-center gap-3 border-b border-border/70 px-3.5 py-2.5 text-left last:border-b-0 hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary disabled:opacity-70",onClick:()=>{S(C.id),s.connect({id:C.id,candidates:C.candidates,clientToken:C.clientToken,label:C.label}).finally(()=>S(null))},children:[t.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:t.jsx(V,{name:"server",className:"size-[18px]"})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:C.label}),t.jsx("span",{className:K("block truncate typography-small",O?"text-foreground":"text-muted-foreground"),children:O?"Connecting...":C.candidates.some(q=>q.kind==="direct")?xe(C):"via PiChamber Relay"})]}),O?t.jsx(V,{name:"loader-4",className:"size-5 animate-spin text-muted-foreground"}):t.jsx(V,{name:"arrow-right-s",className:"size-5 text-muted-foreground"})]},C.id)})})]}):null,t.jsxs("div",{className:"flex w-full flex-col",children:[v?t.jsxs("button",{type:"button",onClick:()=>$(C=>!C),"aria-expanded":L,className:"mx-auto flex items-center gap-1 rounded-full px-2 py-1 typography-small text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:[t.jsx("span",{children:"Connect by address"}),t.jsx(V,{name:"arrow-down-s",className:K("size-4 transition-transform duration-200",L&&"rotate-180")})]}):null,t.jsx("div",{className:"grid transition-[grid-template-rows] duration-200 ease-out",style:{gridTemplateRows:L?"1fr":"0fr"},children:t.jsx("div",{className:"min-h-0 overflow-hidden",children:t.jsxs("form",{className:"flex w-full flex-col gap-3 pt-3",onSubmit:g,children:[t.jsx("input",{...He,value:u,onChange:C=>I(C.target.value),placeholder:"http://192.168.1.74:2606","aria-label":"Server URL",type:"url",inputMode:"url",autoCapitalize:"none",tabIndex:L?void 0:-1,className:K(Ye,"text-center")}),t.jsx("input",{value:m,onChange:C=>x(C.target.value),placeholder:"Optional display name","aria-label":"Name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,tabIndex:L?void 0:-1,className:K(Ye,"text-center")}),t.jsx("input",{...He,value:k,onChange:C=>N(C.target.value),placeholder:"Paste access token","aria-label":"Client token",tabIndex:L?void 0:-1,autoCapitalize:"none",className:K(Ye,"text-center")}),t.jsx("p",{className:"px-1 text-center typography-micro text-muted-foreground",children:"Only needed if your server requires a token instead of a password."}),l?t.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,t.jsx(re,{type:"submit",variant:v?"outline":"default",size:"lg",className:"h-12 w-full",disabled:o||P||!u.trim(),children:o?"Connecting...":"Connect"})]})})})]})]})]})})]})},ro=10,mn=380,ao=(e,n)=>e.title?.trim()||n,oo=({session:e,meta:n,active:s,onSelect:r})=>{const o=dr(e.id),i=fr(e.id),l=o?.type??"idle",c=l==="busy"||l==="retry",u=!c&&i>0&&!s,d=hr(e.id,c),m=c&&d,x=mr(e.time?.updated??e.time?.created??0);return t.jsxs("button",{type:"button",className:K("flex w-full items-center gap-3 rounded-xl px-2.5 py-2 text-left transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",s&&"bg-[color-mix(in_srgb,var(--primary)_10%,transparent)]"),onClick:r,style:{touchAction:"manipulation"},children:[t.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsx("span",{className:K("block truncate typography-ui-label",s?"text-primary":"text-foreground"),children:ao(e,"Untitled Session")}),n?t.jsx("span",{className:"block truncate typography-micro text-muted-foreground",children:n}):null]}),c?t.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-primary","aria-hidden":!0}):u?t.jsx(pr,{label:"Session complete"}):null,m?t.jsx(gr,{sessionId:e.id,running:c,className:"typography-micro"}):u?null:x?t.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground tabular-nums",children:x}):null]})},io=({open:e,onClose:n,anchorRef:s})=>{const r=a.useRef(null),[o,i]=a.useState(e),[l,c]=a.useState(!1),{enabled:u}=Bn(),d=a.useRef(null),[m,x]=a.useState(null);a.useLayoutEffect(()=>{if(!e||!u||!o)return;const h=()=>{const $=s.current?.getBoundingClientRect(),b=d.current?.getBoundingClientRect();if(!$||!b){x(null);return}const S=$.left-b.left;x(Math.min(Math.max(S,8),Math.max(8,b.width-mn-8)))};h();const v=d.current;if(typeof ResizeObserver>"u"||!v)return;const L=new ResizeObserver(h);return L.observe(v),()=>L.disconnect()},[s,u,e,o]);const k=u&&m!==null,N=ge(h=>h.currentSessionId),P=ge(h=>h.setCurrentSession),R=Un(h=>h.setActiveProjectIdOnly),U=ur(e||o,{maxParents:ro});a.useEffect(()=>{if(e){i(!0),c(!1);return}if(!o)return;c(!0);const h=window.setTimeout(()=>{i(!1),c(!1)},140);return()=>window.clearTimeout(h)},[e,o]),a.useEffect(()=>{if(!e)return;const h=v=>{v.key==="Escape"&&n()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[n,e]),a.useEffect(()=>{if(!e)return;const h=v=>{const L=v.target;if(!(L instanceof Node)){n();return}r.current?.contains(L)||s.current?.contains(L)||n()};return document.addEventListener("pointerdown",h,!0),()=>document.removeEventListener("pointerdown",h,!0)},[s,n,e]);const F=a.useCallback(h=>{P(h.id,At(h)),n()},[n,P]);return o?t.jsxs("div",{ref:d,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:r,role:"dialog","aria-label":"Open session switcher",className:K("flex flex-col overflow-hidden rounded-[20px] border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_12px_32px_rgb(0_0_0_/_0.2)] will-change-transform",k?"absolute origin-top-left":"mx-3 mt-2",l?"pointer-events-none":"pointer-events-auto"),style:{animation:`${l?"session-switcher-out":"session-switcher-in"} ${l?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))",...k?{top:8,left:m??8,width:`min(${mn}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"oc-hide-scrollbar min-h-0 flex-1 space-y-0.5 overflow-y-auto overscroll-contain",children:U.length===0?t.jsx("p",{className:"px-3 py-6 text-center typography-small text-muted-foreground",children:"No recent sessions"}):U.map(h=>{const v=h.node.session,L=[h.secondaryMeta?.projectLabel,h.secondaryMeta?.branchLabel].filter(Boolean).join(" · ");return t.jsx(oo,{session:v,meta:L,active:v.id===N,onSelect:()=>{h.projectId&&R(h.projectId),F(v)}},v.id)})})}),t.jsx("style",{children:`
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiffView-DGD9DMS7.js","assets/vendor-react-DYyjh7Q0.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-BAqpUCjs.js","assets/vendor-zustand-CnsBKjP5.js","assets/index-riABQmQ_.css","assets/SessionSwitcherDropdown-o1RjhCfF.js","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-CkHYYg0E.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-Dp_Z-0GD.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-clsx-B-dksMZM.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/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/PierreDiffViewer-COYd5Qr-.js","assets/web-components-Cct1r-wn.js","assets/computeVirtualFileMetrics-DdOCbMyK.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/VirtualizedFileDiff-UMgLcO4Q.js","assets/isDiffPlainText-CGIf0q8p.js","assets/vendor-diff-C3JhlQdm.js","assets/usePanelSlide-a4c67FIY.js","assets/permissionStore-BRcQ9Jgt.js","assets/usePanelSlide-BV3KOtdA.css","assets/useInlineCommentController-DD31jQNC.js","assets/collapsible-Kx4bmsQM.js","assets/appThemeRegistry-BK0dHKa6.js","assets/registerCustomTheme-BBXUCRnG.js","assets/contextFileOpenGuard-BRldMp0d.js","assets/FilesView-DB5VI7EN.js","assets/vendor-codemirror-search-8kyQdB3f.js","assets/vendor-replit-codemirror-vim-BJY5fGLS.js","assets/JsonTreeView-CoX1ZscV.js","assets/Virtualizer-BxW2CJGB.js","assets/isFilePlainText-D4hgTRxT.js","assets/DiagramEditor-D1yc4joK.js","assets/vendor-react-drawio-Boqanm0j.js","assets/vendor-capacitor-status-bar-B-N0EOVk.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/vendor-capacitor-app-BrDJj9I_.js","assets/vendor-capacitor-keyboard-CYccoJjr.js","assets/vendor-capacitor-push-notifications-KNe1zSBF.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as De,j as t,R as a,b as We,e as vs}from"./vendor-react-DYyjh7Q0.js";import"./vendor-katex-CHD9BdDO.js";import{u as de,a as rt,b as _n,d as Wt,i as le,e as Se,s as $e,f as tt,r as Mn,h as ws,j as ks,k as zn,p as js,l as Ss,m as On,n as Cs,o as Es,q as Et,t as Ns,v as Vt,w as Rs,x as $n,y as Ts}from"./index-BAqpUCjs.js";import{u as Ps,a as As,b as Is,s as Ds,c as Ls,d as _s}from"./useWindowTitle-DoHrUC5r.js";import{u as Ue,M as Ms,i as zs,D as Kt,a as Gt,b as Xt,g as Os,c as qt,d as $s,s as Us,S as Bs,e as Fs,T as Hs,P as Ws,r as Vs,f as Ks,h as Gs,F as Xs,j as qs,k as Ys,l as Js,m as Qs,n as Zs,H as er,A as tr,C as nr,o as sr}from"./usePanelSlide-a4c67FIY.js";import{u as rr,a as ar,b as Un,c as or,d as ir,r as At,e as lr,t as oe,o as cr,I as V,P as Ce,B as re,f as K,g as Bn,h as ge,i as ur,j as dr,k as fr,l as hr,m as mr,S as pr,n as gr,p as yr,F as Fn,T as br,q as xr,s as vr,v as It,O as wr,D as Yt,w as Jt,x as Qt,y as Zt,z as en,A as tn,C as Hn,E as Dt,G as kr,H as jr,J as Sr,K as ke,L as Cr,M as Er,N as Nr,Q as Rr,R as Tr,U as Pr,V as Ar,W as Ir,X as pe,Y as Dr,Z as Wn,_ as Nt,$ as Vn,a0 as Lr,a1 as nn,a2 as _r,a3 as Mr,a4 as zr,a5 as je,a6 as Or,a7 as $r,a8 as Ur,a9 as Br,aa as Fr,ab as Hr,ac as Wr,ad as Vr,ae as Kr,af as Gr,ag as Xr,ah as qr,ai as Yr,aj as Jr,ak as Qr,al as Zr,am as ea,an as ta,ao as na,ap as sa,aq as ra,ar as aa}from"./SessionSwitcherDropdown-o1RjhCfF.js";import{S as oa,A as ia}from"./SettingsView-BYqvfMTS.js";import{_ as be}from"./vendor-vite-runtime-DD1OZmLC.js";import{p as la}from"./vendor-aparajita-capacitor-secure-storage-5IShChL0.js";import{Capacitor as ca}from"./vendor-capacitor-core-B4EWRrHz.js";import{u as ua}from"./vendor-tanstack-react-virtual-IrbCBGJ4.js";import{C as da}from"./CommitSection-BAYzLtBf.js";import{P as fa}from"./PierreDiffViewer-COYd5Qr-.js";import{K as sn,P as ha,d as ma,p as pa,U as ga,Z as ya,Q as ba,r as xa}from"./vendor-remixicon-react-CzPq62YO.js";let Kn=null,rn=!1;const va=new Promise(e=>{Kn=e});function wa(){rn||(rn=!0,Kn?.())}const ka=6,ja=e=>e.parentID??null,an=e=>{const n=e.replace(/\/+$/,"");return n.slice(n.lastIndexOf("/")+1)||n},Sa=e=>e.replace(/\\/g,"/").replace(/\/+$/,""),Ca=(e,n)=>{if(!e)return"";let s=null,r=-1;for(const o of n){const i=Sa(o.path);(e===i||e.startsWith(`${i}/`))&&i.length>r&&(s=o,r=i.length)}return s?s.label?.trim()||an(s.path):an(e)},Ea=()=>{const e=rr.getState().activeSessions,n=ar.getState().index.session.unseenCount,s=de.getState().notifyOnSubtasks,r=Un.getState().projects,o=or.getState().ids,i=ir.getState().rankById;let l=0;const c=[];for(const d of e){const m=ja(d)!==null,k=(n[d.id]??0)>0&&(!m||s);k&&(l+=1),m||c.push({session:d,unread:k,project:Ca(At(d),r)})}c.sort((d,m)=>lr(d.session,m.session,o,i));const u=c.slice(0,ka).map(({session:d,unread:m,project:x})=>({id:d.id,title:d.title??"",unread:m,project:x}));return{runtimeKey:rt(),attentionCount:l,recentSessions:u}},Na="__PICHAMBER_WIDGET_SNAPSHOT__",Ra=()=>{typeof window>"u"||(window[Na]=()=>{try{return JSON.stringify(Ea())}catch{return null}})},vt="mobile-app-update-available",on="mobile-app-update-toast-dismissed-version",Ta=()=>{const e=Ue(i=>i.available),n=Ue(i=>i.runtimeType),s=Ue(i=>i.info?.version),r=Ue(i=>i.info?.downloadUrl),o=De.useRef(new Set);return De.useEffect(()=>{if(_n()!=="android"||n!=="mobile"||!e||!s||!r){oe.dismiss(vt);return}Wt().getItem(on)!==s&&(o.current.has(s)||(o.current.add(s),oe.info("PiChamber update available",{id:vt,description:`Version ${s} is ready for Android.`,duration:1/0,icon:t.jsx(V,{name:"download",className:"h-4 w-4 text-muted-foreground"}),action:{label:"Download",onClick:()=>{cr(r)}},cancel:{label:"Dismiss",onClick:()=>{Wt().setItem(on,s),oe.dismiss(vt)}}})))},[e,r,n,s]),null},Pa="Updating OpenCode configuration...",Gn=0,Xn=Pa,ln=new Set;function Aa(e){return ln.add(e),e({isUpdating:Gn>0,message:Xn}),()=>{ln.delete(e)}}function Ia(){return{isUpdating:Gn>0,message:Xn}}const Da=()=>{const[{isUpdating:e},n]=a.useState(()=>Ia());return a.useEffect(()=>Aa(n),[]),e?t.jsx("div",{className:"fixed inset-0 z-[9999] flex items-center justify-center bg-background/90",children:t.jsx(Ce,{width:80,height:80,isAnimated:!0})}):null},ft="pichamber.mobile.connections.v1",La="pichamber.mobile.",cn="pichamber.mobile.deviceId",_a=()=>{try{const e=window.localStorage.getItem(cn);if(e&&e.trim())return e.trim();const n=crypto.randomUUID();return window.localStorage.setItem(cn,n),n}catch{return crypto.randomUUID()}},un=()=>`mobile:${_a()}`,dn=()=>{try{const e=ca.getPlatform();return e==="ios"||e==="android"?e:void 0}catch{return}},qn=12,Ma=8e3,za=2500,Oa=3e3,ht=2500,Yn=()=>{let e=0;return{begin:()=>(e+=1,e),cancel:()=>{e+=1},isCurrent:n=>n===e}},ze=e=>{const n=e.trim();if(!n)return"";const s=/^https?:\/\//i.test(n)?n:`http://${n}`,r=new URL(s);return r.hash="",r.search="",r.pathname=r.pathname.replace(/\/+$/,""),r.toString().replace(/\/+$/,"")},Qe=e=>{try{return new URL(e).host}catch{return e}},Ve=e=>{try{return ze(e)}catch{return e.trim().replace(/\/+$/g,"")}},Lt=(e,n)=>Ve(e)===Ve(n),_t=e=>`relay:${e.serverId}@${e.relayUrl.trim()}`,$a=e=>`relay://${e.serverId}`,gt=e=>e.candidates.filter(n=>n.kind==="direct"),_e=e=>{const n=e.candidates.find(s=>s.kind==="relay");return n&&n.kind==="relay"?n.relay:null},xe=e=>{const n=gt(e)[0];if(n)return n.url;const s=_e(e);return s?$a(s):""},ie=e=>{const n=_e(e);if(n)return _t(n);const s=gt(e)[0];return s?Ve(s.url):""},mt=(e,n)=>{const s=e.find(i=>i.kind==="relay"),r=s&&s.kind==="relay"?s.relay.serverId:null,o=new Set(e.filter(i=>i.kind==="direct").map(i=>Ve(i.url)));return n.some(i=>i.kind==="relay"?r!==null&&i.relay.serverId===r:o.has(Ve(i.url)))},Mt=e=>{const n=(()=>{try{return ze(e)}catch{return""}})();return n?[{kind:"direct",url:n}]:[]},fn=e=>{if(e.candidates&&e.candidates.length>0)return e.candidates;const n=[];return typeof e.url=="string"&&e.url.trim()&&!/^relay:\/\//i.test(e.url.trim())&&n.push(...Mt(e.url)),e.relay&&n.push({kind:"relay",relay:e.relay}),n},zt=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const n=e;if(typeof n.relayUrl!="string"||!n.relayUrl.trim()||typeof n.serverId!="string"||!n.serverId.trim())return null;const s=n.hostEncPubJwk;if(!s||typeof s!="object"||Array.isArray(s))return null;const r=s;return r.kty!=="EC"||r.crv!=="P-256"||typeof r.x!="string"||!r.x||typeof r.y!="string"||!r.y?null:{relayUrl:n.relayUrl,serverId:n.serverId,hostEncPubJwk:{kty:"EC",crv:"P-256",x:r.x,y:r.y}}},yt=e=>{try{return JSON.stringify(e)}catch{return String(e)}},ce=(e,n={})=>{console.info("[mobile-connect]",e,yt(n)),ks("connect",{code:e,status:typeof n.status=="number"?n.status:void 0,detail:typeof n.reason=="string"?n.reason:typeof n.result=="string"?n.result:void 0})},Ke=(e,n={})=>{console.info("[mobile-storage]",e,yt(n))},Ua=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},Ba=e=>{if(typeof e!="string")return e??void 0;try{return JSON.parse(e)}catch{return e}},Fa=async(e,n)=>{if(!le())return null;try{const{CapacitorHttp:s}=await be(async()=>{const{CapacitorHttp:i}=await import("./vendor-capacitor-core-B4EWRrHz.js");return{CapacitorHttp:i}},[]),r=Object.fromEntries(new Headers(n?.headers).entries()),o=await s.request({url:e,method:n?.method||"GET",headers:r,data:Ba(n?.body)});return{ok:o.status>=200&&o.status<300,status:o.status,source:"native-http",json:async()=>Ua(o.data)}}catch(s){return console.warn("[mobile-connect]","native-http failed",yt({url:e,error:s instanceof Error?s.message:String(s)})),null}},Ha=async(e,n)=>{const s=await fetch(e,n).catch(r=>(console.warn("[mobile-connect]","browser-fetch failed",yt({url:e,error:r instanceof Error?r.message:String(r)})),null));return s?{ok:s.ok,status:s.status,source:"browser-fetch",json:()=>s.json()}:null},Ne=async(e,n,s)=>{let r;const o=new Promise(i=>{r=window.setTimeout(()=>{s?.(),i(null)},e)});try{return await Promise.race([n,o])}catch{return null}finally{r!==void 0&&window.clearTimeout(r)}},Me=async(e,n,s)=>{const r=s?.totalTimeoutMs??Ma,o=Date.now(),i=await Ne(Math.min(za,r),Fa(e,n));if(i)return i;const l=new AbortController,c=Math.max(500,r-(Date.now()-o));return Ne(c,Ha(e,{...n,signal:l.signal}),()=>l.abort())},bt=async e=>{if(!e)return null;const n=await e.json().catch(()=>null);if(!n||typeof n!="object")return null;const s=n;return{authenticated:typeof s.authenticated=="boolean"?s.authenticated:void 0,disabled:typeof s.disabled=="boolean"?s.disabled:void 0,scope:typeof s.scope=="string"?s.scope:void 0}},Ge=15e3,Wa=async(e,n,s,r=Ge,o)=>{const i=zn({relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk}),l=c=>c==="ok"&&o?.keepTunnel?{outcome:c,tunnel:i}:(i.close(),{outcome:c});try{const c=n?{Authorization:`Bearer ${n}`}:void 0,u=await Ne(r,i.fetch("/auth/session",{headers:c}).catch(()=>null));if(ce("relay:session",{ok:u?.ok===!0,status:u?.status??null,hasToken:!!n}),!u)return l("unreachable");if(u.status===401)return l(n?"auth-failed":"needs-login");if(!u.ok&&u.status!==404)return l("auth-failed");const d=await bt(u);return d&&d.disabled!==!0&&d.authenticated===!1?l(n?"auth-failed":"needs-login"):l("ok")}catch(c){throw i.close(),c}},Va=(e,n,s,r,o)=>{const i=typeof window<"u"?window.location.origin:"",l={relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk,...s?{grant:s}:{}};o&&ws(l,o),$e({apiBaseUrl:i,clientToken:n,runtimeKey:r??_t(e),relay:l})},Ka=e=>{if(!e||typeof e!="object")return null;const n=e;if(n.kind==="direct")return typeof n.url=="string"&&n.url.trim()?{kind:"direct",url:n.url}:null;if(n.kind==="relay"){const s=zt(n.relay);return s?{kind:"relay",relay:s}:null}return null},Ga=e=>{if(e.mode==="relay"){const n=zt(e.relay);return n?[{kind:"relay",relay:n}]:[]}return typeof e.url=="string"?Mt(e.url):[]},Oe=()=>{if(typeof window>"u")return[];let e;try{e=JSON.parse(window.localStorage.getItem(ft)||"[]")}catch{return[]}if(!Array.isArray(e))return[];const n=le();return e.flatMap(s=>{if(!s||typeof s!="object")return[];const r=s;if(typeof r.id!="string")return[];const o=Array.isArray(r.candidates)?r.candidates.map(Ka).filter(u=>!!u):Ga(r);if(o.length===0)return[];const i=typeof r.clientToken=="string"&&r.clientToken.trim()?r.clientToken:void 0,l=typeof r.label=="string"&&r.label.trim()?r.label:Qe(xe({candidates:o})),c={id:r.id,label:l,candidates:o,lastUsedAt:typeof r.lastUsedAt=="number"?r.lastUsedAt:0};return n?[{...c,hasToken:!!r.hasToken||!!i}]:[{...c,clientToken:i,hasToken:!!i}]}).sort((s,r)=>r.lastUsedAt-s.lastUsedAt)},Rt=e=>e.kind==="relay"?{kind:"relay",relay:{relayUrl:e.relay.relayUrl,serverId:e.relay.serverId,hostEncPubJwk:e.relay.hostEncPubJwk}}:{kind:"direct",url:e.url},Ot=e=>{if(typeof window>"u")return;const n=le(),s=e.slice(0,qn).map(r=>{const o={id:r.id,label:r.label,candidates:r.candidates.map(Rt),lastUsedAt:r.lastUsedAt};return n?{...o,hasToken:!!(r.hasToken||r.clientToken)}:{...o,clientToken:r.clientToken}});try{window.localStorage.setItem(ft,JSON.stringify(s))}catch(r){console.warn("[mobile-storage] failed to persist connection metadata",r)}},Jn=(e,n)=>{const s=e.find(i=>n.id&&i.id===n.id||mt(i.candidates,n.candidates)),r=le(),o={id:n.id||s?.id||crypto.randomUUID(),label:n.label,candidates:n.candidates,lastUsedAt:Date.now(),...r?{hasToken:n.hasToken??(!!n.clientToken||s?.hasToken||!1)}:{clientToken:n.clientToken??s?.clientToken,hasToken:!!(n.clientToken??s?.clientToken)}};return[o,...e.filter(i=>i.id!==o.id&&!mt(i.candidates,n.candidates))].slice(0,qn)},$t=la,Xa=0,Ut=e=>`${La}token.${encodeURIComponent(e)}`,qa=async(e,n)=>{let s;const r=new Promise(o=>{s=window.setTimeout(()=>o(n),Oa)});try{return await Promise.race([e.catch(()=>n),r])}finally{s!==void 0&&window.clearTimeout(s)}},Bt=async(e,n,s)=>le()?qa(n().catch(r=>(console.warn(`[mobile-storage] ${e} failed`,r),s)),s):s,nt=async e=>{Ke("secure:read-start",{key:e});const n=await Bt("secure:read",async()=>(await $t.internalGetItem({prefixedKey:Ut(e),sync:!1})).data,null),s=typeof n=="string"&&n.trim()?n:void 0;return Ke("secure:read",{key:e,hasToken:!!s}),s},Ie=async(e,n)=>{Ke("secure:write-start",{key:e});const s=await Bt("secure:write",async()=>(await $t.internalSetItem({prefixedKey:Ut(e),data:n,sync:!1,access:Xa}),!0),!1);return Ke("secure:write",{key:e,ok:s}),s},Ya=async e=>{await Bt("secure:delete",async()=>(await $t.internalRemoveItem({prefixedKey:Ut(e),sync:!1}),!0),!1)},Qn=async(e,n)=>{let s=0,r=0;return{records:await Promise.all(e.map(async i=>{if(!i||typeof i!="object")return i;const l=i,c=typeof l.url=="string"?l.url:null,u=typeof l.clientToken=="string"?l.clientToken.trim():"";if(!c||!u)return i;if(!await n(c,u))return r+=1,i;s+=1;const{clientToken:d,...m}=l;return{...m,hasToken:!0}})),migrated:s,failed:r}},Zn=async()=>{if(typeof window>"u"||!le())return;let e;try{e=JSON.parse(window.localStorage.getItem(ft)||"[]")}catch{return}if(!Array.isArray(e))return;const n=e.filter(r=>!!r&&typeof r=="object"&&typeof r.url=="string"&&typeof r.clientToken=="string"&&!!r.clientToken.trim());if(n.length===0)return;Ke("secure:migrate-start",{count:n.length});const s=await Qn(e,async(r,o)=>{const i=Ve(r);return await Ie(i,o)?await nt(i)===o:!1});if(s.migrated>0)try{window.localStorage.setItem(ft,JSON.stringify(s.records))}catch(r){console.warn("[mobile-storage] failed to finalize secure token migration",r);return}Ke("secure:migrate-done",{migrated:s.migrated,failed:s.failed})},es=async()=>(await Zn(),Oe()),st=async e=>{const n=Jn(Oe(),e);return Ot(n),le()&&e.clientToken&&await Ie(ie({candidates:e.candidates}),e.clientToken),n},ts=async e=>{const n=Oe(),s=n.find(o=>o.id===e)??null,r=n.filter(o=>o.id!==e);return Ot(r),s&&le()&&await Ya(ie(s)),r},Ja=1500,pt=async(e,n,s)=>{const r=s?.fast?{totalTimeoutMs:ht}:void 0,o=_e({candidates:e})?.serverId??null,i=e.find(d=>d.kind==="relay")??null,l=e.filter(d=>d.kind==="direct"),c=async()=>{for(const d of l){const m=ze(d.url)||d.url,x=n?{Authorization:`Bearer ${n}`}:void 0,k=await Me(`${m}/health`,{method:"GET"},r);if(!k?.ok)continue;if(o){const U=await k.json().catch(()=>null),F=U&&typeof U=="object"?U.serverId:null;if(typeof F=="string"&&F&&F!==o){ce("probe:server-id-mismatch",{url:m});continue}}const N=await Me(`${m}/auth/session`,{method:"GET",credentials:n?"omit":"include",headers:x},r);if(N?.status===401)return{status:"needs-login"};if(!N||!N.ok&&N.status!==404)continue;const P=await bt(N);if(P&&P.disabled!==!0&&P.authenticated===!1)return{status:"needs-login"};const R=P?.disabled===!0;return!n&&le()&&!R&&P?.scope!=="client"?{status:"needs-login"}:{status:"ok",transport:{kind:"direct",url:m}}}return{status:"unreachable"}},u=async()=>{if(!i)return{status:"unreachable"};const{outcome:d,tunnel:m}=await Wa(i.relay,n,void 0,s?.fast?ht:void 0,{keepTunnel:!0});return d==="ok"?{status:"ok",transport:{kind:"relay",relay:i.relay,tunnel:m}}:d==="needs-login"||d==="auth-failed"?{status:"needs-login"}:{status:"unreachable"}};return i?l.length===0?u():new Promise(d=>{let m=!1,x=!1,k,N=null,P=null;const R=h=>{h?.status==="ok"&&h.transport.kind==="relay"&&h.transport.tunnel?.close()},U=h=>{m||(m=!0,d(h))},F=()=>{x||m||(k!==void 0&&(window.clearTimeout(k),k=void 0),u().then(h=>{if(P=h,m||x){R(h);return}if(h.status==="ok"||h.status==="needs-login"){U(h);return}N&&U(N)}))};c().then(h=>{if(N=h,!m){if(h.status==="ok"||h.status==="needs-login"){x=!0,k!==void 0&&window.clearTimeout(k),R(P),U(h);return}if(P){U(P);return}F()}}),k=window.setTimeout(F,Ja)}):c()},Le=(e,n,s)=>{e.kind==="relay"?Va(e.relay,n,s?.grant,s?.runtimeKey,e.tunnel):$e({apiBaseUrl:e.url,clientToken:n,runtimeKey:s?.runtimeKey}),os()},Be=()=>{const e=Oe()[0];return e?.label?.trim()?e.label:null},dt=async()=>{await Zn();const e=Oe()[0];if(!e)return{status:"no-candidate"};let n;if(le()){if(!e.hasToken)return{status:"no-candidate"};if(n=await nt(ie(e)),!n)return{status:"no-candidate"}}else if(n=e.clientToken,!n)return{status:"no-candidate"};const s=await pt(e.candidates,n,{fast:!0});return s.status==="needs-login"?{status:"needs-login",label:e.label}:s.status!=="ok"?{status:"unreachable",label:e.label}:(await st({id:e.id,label:e.label,candidates:e.candidates}),Le(s.transport,n,{runtimeKey:ie(e)}),{status:"connected"})},ns=async(e,n)=>{let s="";try{s=ze(e.url)}catch{return!1}if(!s)return!1;const r=e.clientToken?.trim()||void 0,o=r?{Authorization:`Bearer ${r}`}:void 0,i=n?.fast?{totalTimeoutMs:ht}:void 0;if(!(await Me(`${s}/health`,{method:"GET",headers:o},i))?.ok)return!1;const c=await Me(`${s}/auth/session`,{method:"GET",credentials:r?"omit":"include",headers:o},i);if(!c||!c.ok&&c.status!==404)return!1;const u=await bt(c);return!(u&&u.disabled!==!0&&u.authenticated===!1)},Qa=e=>[...e].sort((n,s)=>{const r=(n.priority??100)-(s.priority??100);if(r!==0)return r;const o=i=>i.type==="relay"?2:i.url.startsWith("https://")?0:1;return o(n)-o(s)}).flatMap(n=>{if(n.type==="relay"){const s=zt({relayUrl:n.relayUrl,serverId:n.serverId,hostEncPubJwk:n.hostEncPubJwk});return s?[{kind:"relay",relay:s}]:[]}return Mt(n.url)}),hn=async e=>{const n=_e({candidates:e})?.serverId??null;for(const s of e){if(s.kind==="relay"){const i=zn(s.relay),l=await Ne(Ge,i.fetch("/health").catch(()=>null));if(ce("establish:relay:health",{ok:l?.ok===!0,status:l?.status??null}),l?.ok)return{kind:"relay",relay:s.relay,tunnel:i};i.close();continue}const r=ze(s.url)||s.url,o=await Me(`${r}/health`,{method:"GET"});if(ce("establish:direct:health",{ok:o?.ok===!0,status:o?.status??null}),!!o?.ok){if(n){const i=await o.json().catch(()=>null),l=i&&typeof i=="object"?i.serverId:null;if(typeof l=="string"&&l&&l!==n){ce("establish:server-id-mismatch",{url:r});continue}}return{kind:"direct",url:r}}}return null},ss=async(e,n)=>{if(!tt())return ns(e,n);const s=await Ne(n?.fast?ht:Ge,Mn("/auth/session").then(o=>o).catch(()=>null));if(!s)return!0;if(s.status===401)return!1;if(!s.ok&&s.status!==404)return!0;const r=await bt(s);return!(r&&r.disabled!==!0&&r.authenticated===!1)},Za=e=>e.kind==="relay"?tt():!tt()&&Lt(e.url,Se()),rs=()=>{const e=rt();return e?Oe().find(n=>ie(n)===e)??null:null},Tt=e=>{const n=rt();return!!n&&ie(e)===n},Ze=async()=>{const e=rs();if(!e)return"no-connection";let n;if(le()?n=e.hasToken?await nt(ie(e)):void 0:n=e.clientToken,!n)return"unreachable";const s=e.candidates.findIndex(c=>Za(c.kind==="relay"?{kind:"relay",relay:c.relay}:{kind:"direct",url:c.url})),r=s>=0?e.candidates.slice(0,s):e.candidates,o=await pt(r,n,{fast:!0});if(o.status==="ok")return await st({id:e.id,label:e.label,candidates:e.candidates}),Le(o.transport,n,{runtimeKey:ie(e)}),"switched";if(o.status==="needs-login")return"needs-login";if(s>=0&&await ss({url:Se(),clientToken:n},{fast:!0}))return os(),"unchanged";const i=s>=0?e.candidates.slice(s+1):[],l=await pt(i,n,{fast:!0});return l.status==="ok"?(await st({id:e.id,label:e.label,candidates:e.candidates}),Le(l.transport,n,{runtimeKey:ie(e)}),"switched"):l.status==="needs-login"?"needs-login":"unreachable"},eo=5e3;let wt=!1;const as=async()=>{if(wt)return"skipped";const e=rs();if(!e)return ce("candidates:refresh-skip",{reason:"no-active-connection"}),"skipped";const n=_e(e);if(!n)return ce("candidates:refresh-skip",{reason:"no-relay-candidate"}),"skipped";wt=!0;try{const s=await Ne(Ge,Mn("/api/client-auth/connection/candidates").then(d=>d).catch(()=>null));if(!s?.ok)return ce("candidates:refresh-skip",{reason:"fetch-failed",status:s?.status??null}),"skipped";const r=await s.json().catch(()=>null);if(!r||r.serverId!==n.serverId)return ce("candidates:refresh-skip",{reason:"server-id-mismatch"}),"skipped";const o=Array.isArray(r.candidates)?r.candidates:[],i=[];for(const d of o){if(!d||typeof d!="object")continue;const m=d;if(!(m.type!=="lan"||typeof m.url!="string"))try{const x=ze(m.url);x&&!i.includes(x)&&i.push(x)}catch{}}if(i.length===0)return ce("candidates:refresh-skip",{reason:"no-lan-reported"}),"skipped";const l=gt(e).filter(d=>d.url.startsWith("https://")),c=[...i.map(d=>({kind:"direct",url:d})),...l,{kind:"relay",relay:n}];return JSON.stringify(e.candidates.map(Rt))===JSON.stringify(c.map(Rt))?"unchanged":(ce("candidates:refreshed",{lanCount:i.length}),await st({id:e.id,label:e.label,candidates:c}),"updated")}finally{wt=!1}},os=()=>{typeof window>"u"||window.setTimeout(()=>{(async()=>{const e=await as().catch(()=>"skipped");ce("candidates:refresh-result",{result:e}),e==="updated"&&tt()&&await Ze().catch(()=>null)})()},eo)},Ft=e=>{const[n,s]=a.useState(()=>Oe()),[r,o]=a.useState(null),[i,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(n),m=a.useRef(null),x=a.useRef(Yn()),k=a.useCallback(b=>{d.current=b,s(b)},[]),N=a.useCallback(b=>{m.current=b,o(b)},[]),P=a.useCallback(b=>{m.current===b&&(m.current=null,o(null))},[]);a.useEffect(()=>{let b=!1;return es().then(S=>{b||k(S)}),()=>{b=!0}},[k]);const R=a.useCallback(b=>{const S=Jn(d.current,b);return k(S),Ot(S),S},[k]),U=a.useCallback(async b=>{l(null),N("connect");try{const S=fn(b);if(S.length===0){l("Enter a server URL.");return}const y=b.id?d.current.find(p=>p.id===b.id):d.current.find(p=>mt(p.candidates,S)),B=b.label?.trim()||y?.label||Qe(xe({candidates:S})),g=b.relayGrant;let I=b.clientToken?.trim()||void 0;const w=!!I;I||(le()?y?.hasToken&&(I=await nt(ie({candidates:S}))):I=y?.clientToken),ce("connect:start",{candidates:S.map(p=>p.kind),hasToken:!!I});const E=await pt(S,I);if(ce("connect:probe",{status:E.status}),E.status==="unreachable"){l("Could not reach that PiChamber server.");return}if(E.status==="needs-login"){R({id:y?.id,label:B,candidates:S}),u({id:y?.id??crypto.randomUUID(),label:B,candidates:S,relay:_e({candidates:S})??void 0,relayGrant:g});return}I&&w&&le()&&await Ie(ie({candidates:S}),I),R({id:y?.id,label:B,candidates:S,clientToken:I}),Le(E.transport,I??null,{runtimeKey:ie({candidates:S}),grant:g}),e()}catch(S){console.warn("[mobile-connect] connect threw",S),l("That server URL is not valid.")}finally{P("connect")}},[N,P,e,R]),F=a.useCallback(async b=>{if(m.current==="pairing")return;l(null),N("pairing");const S=Qa(b.candidates);let y=null,B=!1;try{if(y=await hn(S),!y){l("Could not reach that PiChamber server.");return}const g=JSON.stringify({pairingId:b.pairingId,secret:b.secret,clientLabel:"PiChamber Mobile",clientKind:"mobile",deviceName:"PiChamber Mobile",devicePlatform:dn(),dedupeKey:un()}),I={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:g},w=y.kind==="relay"?await Ne(Ge,y.tunnel.fetch("/api/client-auth/pairing/redeem",I).catch(()=>null)):await Me(`${y.url}/api/client-auth/pairing/redeem`,I);if(!w?.ok){l("This server needs a password or client token.");return}const E=await w.json().catch(()=>null),p=typeof E?.clientToken=="string"?E.clientToken.trim():"";if(!p){l("This server needs a password or client token.");return}const C=typeof E?.server?.label=="string"?E.server.label:"",O=b.label||C||Qe(xe({candidates:S}));if(le()&&!await Ie(ie({candidates:S}),p)){l("This server needs a password or client token.");return}R({label:O,candidates:S,clientToken:p}),Le(y.kind==="relay"?{kind:"relay",relay:y.relay,tunnel:y.tunnel}:{kind:"direct",url:y.url},p,{runtimeKey:ie({candidates:S})}),B=y.kind==="relay",e()}catch(g){console.warn("[mobile-connect] pairing threw",g),l("This server needs a password or client token.")}finally{!B&&y?.kind==="relay"&&y.tunnel.close(),P("pairing")}},[N,P,e,R]),h=a.useCallback(async b=>{if(!c||!b.trim()||m.current==="password")return;l(null),N("password");const S=x.current.begin(),y=()=>x.current.isCurrent(S),{id:B,label:g,candidates:I}=c;let w=null,E=!1;try{if(w=await hn(I),!y())return;if(!w){l("Could not reach that PiChamber server.");return}const p={method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:b,trustDevice:!0,issueClientToken:!0,clientLabel:"PiChamber Mobile",clientKind:"mobile",devicePlatform:dn(),dedupeKey:un()})};ce("password:start",{transport:w.kind});const C=w.kind==="relay"?await Ne(Ge,w.tunnel.fetch("/auth/session",p).catch(()=>null)):await Me(`${w.url}/auth/session`,p);if(!y())return;if(ce("password:done",{ok:C?.ok===!0,status:C?.status??null}),!C?.ok){l("Could not unlock that server. Check the password.");return}const O=await C.json().catch(()=>null);if(!y())return;const q=typeof O?.clientToken=="string"?O.clientToken.trim():"";if(ce("password:token",{issued:!!q}),!q){if(w.kind==="direct"&&!le()){R({id:B,label:g,candidates:I}),u(null),Le({kind:"direct",url:w.url},null,{runtimeKey:ie({candidates:I})}),e();return}l("This server needs a password or client token.");return}if(le()&&(!y()||(await Ie(ie({candidates:I}),q),!y()))||!y()||(R({id:B,label:g,candidates:I,clientToken:q}),u(null),Le(w.kind==="relay"?{kind:"relay",relay:w.relay,tunnel:w.tunnel}:{kind:"direct",url:w.url},q,{runtimeKey:ie({candidates:I})}),E=w.kind==="relay",!y()))return;e()}catch(p){if(!y())return;console.warn("[mobile-connect] password threw",p),l("Could not unlock that server. Check the password.")}finally{!E&&w?.kind==="relay"&&w.tunnel.close(),y()&&P("password")}},[N,P,e,c,R]),v=a.useCallback(()=>{x.current.cancel(),P("password"),u(null),l(null)},[P]),L=a.useCallback(async b=>{l(null);let S=fn(b);const y=b.id?d.current.find(w=>w.id===b.id)??null:null;if(y){const w=S.filter(C=>C.kind==="direct"),E=gt(y).filter(C=>C.url.startsWith("https://")&&!w.some(O=>Lt(O.url,C.url))),p=_e(y);S=[...w,...E,...p?[{kind:"relay",relay:p}]:[]]}if(S.length===0)return l("Enter a server URL."),null;const B=b.clientToken?.trim()||void 0,g=b.label?.trim()||Qe(xe({candidates:S}));if(le()){const w=ie({candidates:S});if(B)await Ie(w,B);else if(y?.hasToken){const E=ie(y);if(E&&w&&E!==w){const p=await nt(E);p&&await Ie(w,p)}}}return R({id:b.id,label:g,candidates:S,clientToken:B}).find(w=>mt(w.candidates,S))??null},[R]),$=a.useCallback(async b=>{const S=d.current.find(B=>B.id===b)??null,y=await ts(b);return k(y),S},[k]);return{connections:n,isBusy:r!==null,isPasswordBusy:r==="password",error:i,pendingConnection:c,connect:U,redeemPairingConnection:F,submitPassword:h,cancelPassword:v,saveConnection:L,removeConnection:$,setError:l}},vi=Object.freeze(Object.defineProperty({__proto__:null,autoConnectLastInstance:dt,connectionDisplayUrl:xe,createMobilePasswordOperationTracker:Yn,deleteMobileConnection:ts,getAutoConnectTargetLabel:Be,getConnectionLabel:Qe,isActiveRuntimeConnection:Tt,isSameConnectionUrl:Lt,loadMobileConnections:es,migrateLegacyInlineTokenRecords:Qn,normalizeConnectionUrl:ze,refreshActiveConnectionCandidates:as,relayConnectionRuntimeKey:_t,reprobeActiveConnection:Ze,upsertMobileConnection:st,useMobileConnection:Ft,validateActiveRuntimeSession:ss,validateMobileConnectionSession:ns},Symbol.toStringTag,{value:"Module"})),is=()=>{if(typeof window>"u")return null;const n=window.Capacitor?.Plugins?.BarcodeScanner;return n&&(typeof n.scan=="function"||typeof n.startScan=="function")?n:null},to=()=>window.Capacitor?.getPlatform?.()==="android",ls=e=>{const n=e.trim();if(!n)return null;if(/^pichamber:\/\//i.test(n)){const s=js(n);return s?{pairing:s}:null}return/^https?:\/\//i.test(n)?{url:n}:null},cs=(e,n)=>{const s=ls(e);if(!s&&n?.pairingStringFallback){const r=Ss(e);if(r)return{status:"pairing",pairing:r}}return s?"pairing"in s?{status:"pairing",...s}:{status:"ok",...s}:{status:"invalid"}},no=async(e,n)=>{if(!e.startScan||!e.stopScan||!e.addListener)return{status:"unsupported"};if(n?.aborted)return{status:"cancelled"};let s,r,o=!1,i=()=>{};const l=new Promise(d=>{i=d}),c=d=>{o||(o=!0,i(d))},u=()=>c({status:"cancelled"});n?.addEventListener("abort",u,{once:!0});try{return(await Promise.allSettled([Promise.resolve(e.addListener("barcodesScanned",({barcodes:m})=>{const x=m?.[0],k=(x?.rawValue??x?.displayValue??"").trim();k&&c(cs(k,{pairingStringFallback:!0}))})).then(m=>{s=m}),Promise.resolve(e.addListener("scanError",()=>c({status:"failed"}))).then(m=>{r=m})])).some(({status:m})=>m==="rejected")?c({status:"failed"}):o||e.startScan({formats:["QR_CODE"]}).catch(()=>c({status:"failed"})),await l}finally{n?.removeEventListener("abort",u),await Promise.allSettled([Promise.resolve(s?.remove()),Promise.resolve(r?.remove()),e.stopScan()])}},Pt=()=>is()!==null,us=async e=>{const n=is();if(!n)return{status:"unsupported"};try{if(n.requestPermissions){const l=(await n.requestPermissions())?.camera;if(l&&l!=="granted"&&l!=="limited")return{status:"permission-denied"}}if(e?.signal?.aborted)return{status:"cancelled"};if(to())return no(n,e?.signal);if(!n.scan)return{status:"unsupported"};const r=(await n.scan({formats:["QR_CODE"]}))?.barcodes?.[0],o=(r?.rawValue??r?.displayValue??"").trim();return o?cs(o):{status:"cancelled"}}catch{return{status:"failed"}}},He={autoComplete:"off",autoCorrect:"off",spellCheck:!1},Ye="h-12 w-full rounded-[16px] border border-border/70 bg-surface-elevated px-4 text-[16px] text-foreground outline-none transition-colors placeholder:text-muted-foreground focus:border-primary focus:ring-2 focus:ring-primary/20",ds=({onCancel:e})=>{const n=a.useRef(null);return a.useLayoutEffect(()=>{const s={value:document.documentElement.style.getPropertyValue("background-color"),priority:document.documentElement.style.getPropertyPriority("background-color")},r={value:document.body.style.getPropertyValue("background-color"),priority:document.body.style.getPropertyPriority("background-color")};document.documentElement.style.setProperty("background-color","rgba(0, 0, 0, 0)","important"),document.body.style.setProperty("background-color","rgba(0, 0, 0, 0)","important");const o=new Map,i=c=>{!(c instanceof HTMLElement)||c===n.current||o.has(c)||(o.set(c,{opacity:c.style.opacity,pointerEvents:c.style.pointerEvents}),c.style.setProperty("opacity","0"),c.style.setProperty("pointer-events","none"))};Array.from(document.body.children).forEach(i);const l=new MutationObserver(c=>{c.forEach(u=>u.addedNodes.forEach(i))});return l.observe(document.body,{childList:!0}),()=>{l.disconnect(),o.forEach((c,u)=>{u.style.opacity=c.opacity,u.style.pointerEvents=c.pointerEvents}),s.value?document.documentElement.style.setProperty("background-color",s.value,s.priority):document.documentElement.style.removeProperty("background-color"),r.value?document.body.style.setProperty("background-color",r.value,r.priority):document.body.style.removeProperty("background-color")}},[]),a.useEffect(()=>{const s=()=>{document.visibilityState==="hidden"&&e()};return document.addEventListener("visibilitychange",s),()=>document.removeEventListener("visibilitychange",s)},[e]),We.createPortal(t.jsxs("div",{ref:n,role:"dialog","aria-modal":"true","aria-label":"Scan QR code",className:"fixed inset-0 z-[1000] flex flex-col bg-transparent px-6 pb-[calc(var(--safe-area-inset-bottom,env(safe-area-inset-bottom,0px))+24px)] pt-[calc(var(--safe-area-inset-top,env(safe-area-inset-top,0px))+24px)] text-foreground",children:[t.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-6",children:[t.jsx("div",{className:"aspect-square w-full max-w-72 rounded-[28px] border-2 border-foreground/90 shadow-[0_0_0_9999px_color-mix(in_srgb,var(--surface-background)_18%,transparent)]","aria-hidden":!0}),t.jsx("p",{className:"max-w-sm rounded-[16px] border border-border/60 bg-background px-4 py-3 text-center typography-body text-foreground shadow-sm",children:"On your computer, open «Add a device» to show a QR code, then scan it here."})]}),t.jsxs(re,{type:"button",variant:"outline",size:"lg",className:"mx-auto min-h-12 w-full max-w-sm bg-background",onClick:e,children:[t.jsx(V,{name:"close",className:"size-[18px]"}),"Cancel"]})]}),document.body)},fs=()=>We.createPortal(t.jsxs("div",{role:"status",className:"fixed inset-0 z-[1000] flex flex-col items-center justify-center gap-5 bg-background px-6 text-foreground",children:[t.jsx(Ce,{width:96,height:96,isAnimated:!0}),t.jsxs("div",{className:"flex items-center gap-2 typography-ui-label text-muted-foreground",children:[t.jsx(V,{name:"loader-4",className:"size-[18px] animate-spin"}),t.jsx("span",{children:"Connecting..."})]})]}),document.body),so=({onConnected:e,notice:n=null})=>{const s=Ft(e),{connections:r,isBusy:o,isPasswordBusy:i,error:l,pendingConnection:c}=s,[u,d]=a.useState(""),[m,x]=a.useState(""),[k,N]=a.useState(""),[P,R]=a.useState(!1),[U,F]=a.useState(!1),h=a.useRef(null),v=a.useMemo(()=>Pt(),[]),[L,$]=a.useState(()=>!Pt()),[b,S]=a.useState(null),[y,B]=a.useState(""),g=a.useCallback(C=>{C.preventDefault(),s.connect({url:u,clientToken:k,label:m})},[k,s,m,u]),I=a.useCallback(C=>{if(/^pichamber:\/\//i.test(C.trim())){const O=ls(C);if(O){if("pairing"in O){s.redeemPairingConnection(O.pairing);return}d(O.url),O.label&&x(O.label),O.clientToken&&N(O.clientToken);return}}d(C)},[s]),w=a.useCallback(async()=>{if(h.current||o)return;s.setError(null),R(!0);const C=new AbortController;h.current=C;try{const O=await us({signal:C.signal});switch(h.current===C&&(h.current=null,R(!1)),O.status){case"ok":F(!0),d(O.url),O.label&&x(O.label),O.clientToken&&N(O.clientToken),await s.connect({url:O.url,clientToken:O.clientToken,label:O.label});break;case"pairing":F(!0),await s.redeemPairingConnection(O.pairing);break;case"permission-denied":s.setError("Camera access is off. Enable it in Settings to scan a QR code.");break;case"invalid":s.setError("That QR code is not an PiChamber connection code.");break;case"unsupported":s.setError("QR scanning is only available in the installed mobile app.");break;case"failed":s.setError("Could not scan that QR code. Try again or enter the URL manually.");break;default:break}}finally{F(!1),h.current===C&&(h.current=null,R(!1))}},[s,o]);a.useEffect(()=>()=>h.current?.abort(),[]);const E=a.useCallback(C=>{C.preventDefault(),s.submitPassword(y)},[s,y]),p=a.useCallback(()=>{B(""),s.cancelPassword()},[s]);return t.jsxs(t.Fragment,{children:[P?t.jsx(ds,{onCancel:()=>h.current?.abort()}):null,U?t.jsx(fs,{}):null,t.jsx("main",{className:"oc-keyboard-fill-screen flex min-h-dvh flex-col overflow-y-auto bg-background px-6 pb-[calc(var(--safe-area-inset-bottom,env(safe-area-inset-bottom,0px))+28px)] pt-[calc(var(--safe-area-inset-top,env(safe-area-inset-top,0px))+28px)] text-foreground",children:t.jsxs("div",{className:"m-auto flex w-full max-w-[360px] shrink-0 flex-col items-center gap-9 py-8",children:[t.jsxs("div",{className:"flex flex-col items-center gap-5 text-center",children:[t.jsx(Ce,{width:72,height:72,className:"size-[72px]"}),t.jsx("h1",{className:"typography-h2 text-foreground",children:"Connect to PiChamber"})]}),n?t.jsxs("div",{role:"status",className:"flex w-full items-center gap-3 rounded-[18px] border border-[color-mix(in_srgb,var(--status-warning)_35%,transparent)] bg-[color-mix(in_srgb,var(--status-warning)_10%,transparent)] px-3.5 py-3",children:[t.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-[color-mix(in_srgb,var(--status-warning)_16%,transparent)] text-[var(--status-warning)]",children:t.jsx(V,{name:n.kind==="auth-expired"?"lock":"cloud-off",className:"size-[18px]"})}),t.jsx("p",{className:"min-w-0 flex-1 typography-small text-foreground",children:n.kind==="auth-expired"?`Access to ${n.label} has expired or was revoked. Sign in again.`:`Couldn't reach ${n.label}. Check that the server is running.`})]}):null,c?t.jsxs("form",{className:"flex w-full flex-col gap-3",onSubmit:E,children:[t.jsxs("div",{className:"flex items-center gap-3 rounded-[18px] border border-border/70 bg-surface-elevated px-3.5 py-3",children:[t.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:t.jsx(V,{name:"lock",className:"size-[18px]"})}),t.jsxs("div",{className:"min-w-0 text-left",children:[t.jsx("p",{className:"truncate typography-ui-label text-foreground",children:c.label}),t.jsx("p",{className:"truncate typography-small text-muted-foreground",children:c.candidates.some(C=>C.kind==="direct")?xe(c):"via PiChamber Relay"})]})]}),t.jsx("input",{...He,value:y,onChange:C=>B(C.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:Ye}),l?t.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,t.jsx(re,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",disabled:i||!y.trim(),children:i?"Connecting...":"Unlock and connect"}),t.jsx(re,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:p,children:"Use another server"})]}):t.jsxs("div",{className:"flex w-full flex-col gap-6",children:[v?t.jsxs("div",{className:"flex w-full flex-col gap-2",children:[t.jsxs(re,{type:"button",size:"lg",className:"h-12 w-full",onClick:()=>{w()},disabled:P||o,children:[t.jsx(V,{name:"scan-2",className:K("size-[18px]",P&&"animate-pulse")}),o?"Connecting...":"Scan QR code"]}),t.jsx("p",{className:"px-2 text-center typography-small text-muted-foreground",children:"On your computer, open «Add a device» to show a QR code, then scan it here."})]}):null,l&&!L?t.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,r.length>0?t.jsxs("section",{className:"flex w-full flex-col gap-2.5",children:[t.jsx("h2",{className:"text-center typography-micro uppercase tracking-[0.14em] text-muted-foreground",children:"Saved connections"}),t.jsx("div",{className:"overflow-hidden rounded-[18px] border border-border/70 bg-surface-elevated",children:r.map(C=>{const O=b===C.id;return t.jsxs("button",{type:"button",disabled:o,className:"flex min-h-14 w-full items-center gap-3 border-b border-border/70 px-3.5 py-2.5 text-left last:border-b-0 hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary disabled:opacity-70",onClick:()=>{S(C.id),s.connect({id:C.id,candidates:C.candidates,clientToken:C.clientToken,label:C.label}).finally(()=>S(null))},children:[t.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:t.jsx(V,{name:"server",className:"size-[18px]"})}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:C.label}),t.jsx("span",{className:K("block truncate typography-small",O?"text-foreground":"text-muted-foreground"),children:O?"Connecting...":C.candidates.some(q=>q.kind==="direct")?xe(C):"via PiChamber Relay"})]}),O?t.jsx(V,{name:"loader-4",className:"size-5 animate-spin text-muted-foreground"}):t.jsx(V,{name:"arrow-right-s",className:"size-5 text-muted-foreground"})]},C.id)})})]}):null,t.jsxs("div",{className:"flex w-full flex-col",children:[v?t.jsxs("button",{type:"button",onClick:()=>$(C=>!C),"aria-expanded":L,className:"mx-auto flex items-center gap-1 rounded-full px-2 py-1 typography-small text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:[t.jsx("span",{children:"Connect by address"}),t.jsx(V,{name:"arrow-down-s",className:K("size-4 transition-transform duration-200",L&&"rotate-180")})]}):null,t.jsx("div",{className:"grid transition-[grid-template-rows] duration-200 ease-out",style:{gridTemplateRows:L?"1fr":"0fr"},children:t.jsx("div",{className:"min-h-0 overflow-hidden",children:t.jsxs("form",{className:"flex w-full flex-col gap-3 pt-3",onSubmit:g,children:[t.jsx("input",{...He,value:u,onChange:C=>I(C.target.value),placeholder:"http://192.168.1.74:2606","aria-label":"Server URL",type:"url",inputMode:"url",autoCapitalize:"none",tabIndex:L?void 0:-1,className:K(Ye,"text-center")}),t.jsx("input",{value:m,onChange:C=>x(C.target.value),placeholder:"Optional display name","aria-label":"Name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,tabIndex:L?void 0:-1,className:K(Ye,"text-center")}),t.jsx("input",{...He,value:k,onChange:C=>N(C.target.value),placeholder:"Paste access token","aria-label":"Client token",tabIndex:L?void 0:-1,autoCapitalize:"none",className:K(Ye,"text-center")}),t.jsx("p",{className:"px-1 text-center typography-micro text-muted-foreground",children:"Only needed if your server requires a token instead of a password."}),l?t.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,t.jsx(re,{type:"submit",variant:v?"outline":"default",size:"lg",className:"h-12 w-full",disabled:o||P||!u.trim(),children:o?"Connecting...":"Connect"})]})})})]})]})]})})]})},ro=10,mn=380,ao=(e,n)=>e.title?.trim()||n,oo=({session:e,meta:n,active:s,onSelect:r})=>{const o=dr(e.id),i=fr(e.id),l=o?.type??"idle",c=l==="busy"||l==="retry",u=!c&&i>0&&!s,d=hr(e.id,c),m=c&&d,x=mr(e.time?.updated??e.time?.created??0);return t.jsxs("button",{type:"button",className:K("flex w-full items-center gap-3 rounded-xl px-2.5 py-2 text-left transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary",s&&"bg-[color-mix(in_srgb,var(--primary)_10%,transparent)]"),onClick:r,style:{touchAction:"manipulation"},children:[t.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[t.jsx("span",{className:K("block truncate typography-ui-label",s?"text-primary":"text-foreground"),children:ao(e,"Untitled Session")}),n?t.jsx("span",{className:"block truncate typography-micro text-muted-foreground",children:n}):null]}),c?t.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-primary","aria-hidden":!0}):u?t.jsx(pr,{label:"Session complete"}):null,m?t.jsx(gr,{sessionId:e.id,running:c,className:"typography-micro"}):u?null:x?t.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground tabular-nums",children:x}):null]})},io=({open:e,onClose:n,anchorRef:s})=>{const r=a.useRef(null),[o,i]=a.useState(e),[l,c]=a.useState(!1),{enabled:u}=Bn(),d=a.useRef(null),[m,x]=a.useState(null);a.useLayoutEffect(()=>{if(!e||!u||!o)return;const h=()=>{const $=s.current?.getBoundingClientRect(),b=d.current?.getBoundingClientRect();if(!$||!b){x(null);return}const S=$.left-b.left;x(Math.min(Math.max(S,8),Math.max(8,b.width-mn-8)))};h();const v=d.current;if(typeof ResizeObserver>"u"||!v)return;const L=new ResizeObserver(h);return L.observe(v),()=>L.disconnect()},[s,u,e,o]);const k=u&&m!==null,N=ge(h=>h.currentSessionId),P=ge(h=>h.setCurrentSession),R=Un(h=>h.setActiveProjectIdOnly),U=ur(e||o,{maxParents:ro});a.useEffect(()=>{if(e){i(!0),c(!1);return}if(!o)return;c(!0);const h=window.setTimeout(()=>{i(!1),c(!1)},140);return()=>window.clearTimeout(h)},[e,o]),a.useEffect(()=>{if(!e)return;const h=v=>{v.key==="Escape"&&n()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[n,e]),a.useEffect(()=>{if(!e)return;const h=v=>{const L=v.target;if(!(L instanceof Node)){n();return}r.current?.contains(L)||s.current?.contains(L)||n()};return document.addEventListener("pointerdown",h,!0),()=>document.removeEventListener("pointerdown",h,!0)},[s,n,e]);const F=a.useCallback(h=>{P(h.id,At(h)),n()},[n,P]);return o?t.jsxs("div",{ref:d,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:r,role:"dialog","aria-label":"Open session switcher",className:K("flex flex-col overflow-hidden rounded-[20px] border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_12px_32px_rgb(0_0_0_/_0.2)] will-change-transform",k?"absolute origin-top-left":"mx-3 mt-2",l?"pointer-events-none":"pointer-events-auto"),style:{animation:`${l?"session-switcher-out":"session-switcher-in"} ${l?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))",...k?{top:8,left:m??8,width:`min(${mn}px, calc(100% - 16px))`}:null},children:t.jsx("div",{className:"oc-hide-scrollbar min-h-0 flex-1 space-y-0.5 overflow-y-auto overscroll-contain",children:U.length===0?t.jsx("p",{className:"px-3 py-6 text-center typography-small text-muted-foreground",children:"No recent sessions"}):U.map(h=>{const v=h.node.session,L=[h.secondaryMeta?.projectLabel,h.secondaryMeta?.branchLabel].filter(Boolean).join(" · ");return t.jsx(oo,{session:v,meta:L,active:v.id===N,onSelect:()=>{h.projectId&&R(h.projectId),F(v)}},v.id)})})}),t.jsx("style",{children:`
|
|
3
3
|
@keyframes session-switcher-in {
|
|
4
4
|
from { opacity: 0; transform: translateY(-8px) scale(0.985); }
|
|
5
5
|
to { opacity: 1; transform: translateY(0) scale(1); }
|
|
@@ -8,7 +8,7 @@ import{r as De,j as t,R as a,b as We,e as vs}from"./vendor-react-DYyjh7Q0.js";im
|
|
|
8
8
|
from { opacity: 1; transform: translateY(0) scale(1); }
|
|
9
9
|
to { opacity: 0; transform: translateY(-6px) scale(0.985); }
|
|
10
10
|
}
|
|
11
|
-
`})]}):null},lo=({onOpenSessions:e,onOpenWorkspace:n,compactTitle:s=!1})=>{const[r,o]=a.useState(!1),[i,l]=a.useState(!1),c=a.useRef(null),u=On(v=>v.currentDirectory),d=ge(v=>v.currentSessionId),x=ge(a.useCallback(v=>d?v.getDirectoryForSession(d):null,[d]))||u,k=yr(d),N=ge(v=>!!v.newSessionDraft?.open),R=k?.title?.trim()||(d?"Untitled session":"New session");a.useEffect(()=>{o(!1),l(!1)},[d,x]);const U=a.useCallback(()=>{o(!1),l(!1),e()},[e]),F=a.useCallback(v=>{o(L=>{const $=typeof v=="function"?v(L):v;return $&&l(!1),$})},[]),h=a.useCallback(()=>{l(v=>{const L=!v;return L&&o(!1),L})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("header",{className:"oc-mobile-header relative z-30 flex shrink-0 items-center gap-1 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:t.jsxs("div",{className:"flex h-[var(--oc-header-height,56px)] w-full items-center gap-1 px-2",children:[t.jsx("button",{type:"button",className:"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","aria-label":"Open sessions and projects",onClick:U,style:{touchAction:"manipulation"},children:t.jsx(V,{name:"list-unordered",className:"size-5"})}),t.jsx("button",{ref:c,type:"button",className:K("flex min-w-0 items-center rounded-lg px-2 py-1.5 text-left transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",s?"shrink":"flex-1"),"aria-label":"Open session switcher","aria-haspopup":"dialog","aria-expanded":i,onClick:h,style:{touchAction:"manipulation"},children:t.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[t.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",children:R}),t.jsx(V,{name:"arrow-down-s",className:K("size-4 shrink-0 text-muted-foreground transition-transform duration-150",i&&"rotate-180")})]})}),s?t.jsx("div",{className:"min-w-0 flex-1"}):null,t.jsx(Ms,{open:r,onOpenChange:F,currentSessionId:d,effectiveDirectory:x,isNewSessionDraftOpen:N}),t.jsx("button",{type:"button",className:"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","aria-label":"Open workspace panel",onClick:()=>{o(!1),l(!1),n()},style:{touchAction:"manipulation"},children:t.jsx(V,{name:"layout-right",className:"size-5"})})]})}),t.jsx(io,{open:i,onClose:()=>l(!1),anchorRef:c})]})},co=({onActiveConnectionDeleted:e,onConnect:n})=>{const s=Ft(n),{connections:r,isBusy:o,isPasswordBusy:i,error:l,pendingConnection:c,connect:u,submitPassword:d,cancelPassword:m,saveConnection:x,removeConnection:k,setError:N}=s,[P,R]=a.useState(null),U=P?r.find(z=>z.id===P)??null:null,[F,h]=a.useState(null),[v,L]=a.useState(""),[$,b]=a.useState(""),[S,y]=a.useState(""),[B,g]=a.useState(""),[I,w]=a.useState(!1),[E,p]=a.useState(!1),[C,O]=a.useState(!1),[q,Z]=a.useState(null),X=a.useRef(null),A=a.useMemo(()=>Pt(),[]),[G,Y]=a.useState(!1),[f,j]=a.useState(null),_=a.useCallback(()=>{R(null),L(""),b(""),y(""),N(null),Y(!1)},[N]),H=a.useCallback(z=>{z.preventDefault(),x({id:P??void 0,url:v,label:$,clientToken:S}).then(Q=>{Q&&_()})},[S,P,$,_,x,v]),te=a.useCallback(async()=>{if(X.current)return;N(null),w(!0);const z=new AbortController;X.current=z;try{const Q=await us({signal:z.signal});switch(X.current===z&&(X.current=null,w(!1)),Q.status){case"ok":L(Q.url),Q.label&&b(Q.label),Q.clientToken&&y(Q.clientToken),Y(!0);break;case"pairing":p(!0),await s.redeemPairingConnection(Q.pairing);break;case"permission-denied":N("Camera access is off. Enable it in Settings to scan a QR code.");break;case"invalid":N("That QR code is not an PiChamber connection code.");break;case"unsupported":N("QR scanning is only available in the installed mobile app.");break;case"failed":N("Could not scan that QR code. Try again or enter the URL manually.");break;default:break}}finally{p(!1),X.current===z&&(X.current=null,w(!1))}},[s,N]);a.useEffect(()=>()=>X.current?.abort(),[]);const J=a.useCallback(z=>{z.preventDefault(),d(B)},[B,d]),ae=a.useCallback(()=>{g(""),m()},[m]),Te=a.useCallback(async()=>{if(!C){Z(null),O(!0);try{const z=await Cs();Z(z==="copied"?"Diagnostics copied to the clipboard.":z==="downloaded"?"Diagnostics downloaded.":"Diagnostics ready to share.")}catch{Z("Diagnostics export was cancelled or unavailable.")}finally{O(!1)}}},[C]),ue=a.useCallback(z=>{h(Q=>Q===z?null:z)},[]),ye=a.useCallback(z=>{h(null),P===z&&_();const Q=r.length===1;k(z).then(ne=>{ne&&(Q||Tt(ne))&&e()})},[r.length,P,e,k,_]),se=Ye;return c?t.jsx("div",{className:"flex h-full flex-col overflow-hidden",children:t.jsx("form",{className:"flex-1 overflow-y-auto px-5 py-4",onSubmit:J,children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center gap-3 rounded-[18px] border border-border/70 bg-surface-elevated px-3.5 py-3",children:[t.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:t.jsx(V,{name:"lock",className:"size-[18px]"})}),t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"truncate typography-ui-label text-foreground",children:c.label}),t.jsx("p",{className:"truncate typography-small text-muted-foreground",children:c.candidates.some(z=>z.kind==="direct")?xe(c):"via PiChamber Relay"})]})]}),t.jsx("input",{...He,value:B,onChange:z=>g(z.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:se}),l?t.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:l}):null,t.jsx(re,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",disabled:i||!B.trim(),children:i?"Connecting...":"Unlock and connect"}),t.jsx(re,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:ae,children:"Use another server"})]})})}):t.jsxs(t.Fragment,{children:[I?t.jsx(ds,{onCancel:()=>X.current?.abort()}):null,E?t.jsx(fs,{}):null,t.jsx("div",{className:"flex h-full flex-col overflow-hidden",children:t.jsx("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:t.jsxs("div",{className:"space-y-6",children:[r.length>0?t.jsx("div",{className:"overflow-hidden rounded-[18px] border border-border/70 bg-surface-elevated",children:r.map(z=>{const Q=F===z.id,ne=Tt(z),we=f===z.id,ve=we?"Connecting...":ne?tt()?"Connected · Private relay":"Connected · Local network":z.candidates.some(Pe=>Pe.kind==="direct")?xe(z):"via PiChamber Relay";return t.jsxs("div",{className:K("flex items-center border-b border-border/70 transition-colors last:border-b-0",Q&&"bg-[color-mix(in_srgb,var(--destructive)_8%,transparent)]"),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-3 px-3.5 py-3 text-left transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary disabled:opacity-60",onClick:()=>{ne||(j(z.id),u({id:z.id,candidates:z.candidates,clientToken:z.clientToken,label:z.label}).finally(()=>j(null)))},disabled:o&&!we||Q,children:[t.jsxs("span",{className:"relative flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:[t.jsx(V,{name:"server",className:"size-[18px]"}),ne?t.jsx("span",{className:"absolute -right-0.5 -top-0.5 size-2.5 rounded-full border-2 border-[var(--surface-elevated)] bg-[var(--status-success)]","aria-hidden":!0}):null]}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:z.label}),t.jsx("span",{className:K("block truncate typography-small",ne&&!we?"text-[var(--status-success)]":"text-muted-foreground"),children:ve})]}),we?t.jsx(V,{name:"loader-4",className:"size-5 shrink-0 animate-spin text-muted-foreground"}):null]}),t.jsxs("div",{className:"flex items-center gap-0.5 pr-2",children:[Q?t.jsxs("button",{type:"button","aria-label":`Confirm deleting ${z.label}`,className:"flex h-9 shrink-0 items-center gap-1.5 rounded-full bg-destructive px-3 text-destructive-foreground transition-opacity active:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive",onClick:()=>ye(z.id),style:{touchAction:"manipulation"},children:[t.jsx(V,{name:"delete-bin",className:"size-[18px]"}),t.jsx("span",{className:"typography-ui-label",children:"Delete"})]}):z.candidates.some(Pe=>Pe.kind==="direct")?t.jsx("button",{type:"button","aria-label":"Edit",className:"flex size-9 items-center justify-center rounded-full text-muted-foreground transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>{R(z.id),L(xe(z)),b(z.label),y(z.clientToken||""),N(null)},style:{touchAction:"manipulation"},children:t.jsx(V,{name:"edit",className:"size-[18px]"})}):null,t.jsx("button",{type:"button","aria-label":Q?`Keep ${z.label}`:`Delete ${z.label}`,className:"flex size-9 items-center justify-center rounded-full text-muted-foreground transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>ue(z.id),style:{touchAction:"manipulation"},children:t.jsx(V,{name:Q?"close":"delete-bin",className:"size-[18px]"})})]})]},z.id)})}):t.jsx("p",{className:"rounded-[18px] border border-dashed border-border/70 px-4 py-6 text-center typography-small text-muted-foreground",children:"No saved connections yet."}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs(re,{type:"button",variant:"outline",size:"lg",className:"h-12 w-full",onClick:()=>{Te()},disabled:C,children:[t.jsx(V,{name:"download",className:"size-[18px]"}),C?"Preparing diagnostics…":"Export diagnostics"]}),q?t.jsx("p",{className:"px-1 text-center typography-small text-muted-foreground",children:q}):null]}),!G&&!U?t.jsxs("div",{className:"space-y-2",children:[A?t.jsxs(re,{type:"button",size:"lg",className:"h-12 w-full",onClick:()=>{te()},disabled:I,children:[t.jsx(V,{name:"scan-2",className:K("size-[18px]",I&&"animate-pulse")}),"Scan QR code"]}):null,t.jsxs(re,{type:"button",variant:A?"ghost":"outline",size:"lg",className:"h-12 w-full",onClick:()=>{N(null),Y(!0)},children:[t.jsx(V,{name:"add",className:"size-[18px]"}),"Add by address"]}),l?t.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null]}):t.jsxs("form",{className:"space-y-3",onSubmit:H,children:[t.jsxs("div",{className:"flex h-8 items-center justify-between gap-3 px-1",children:[t.jsx("h3",{className:"typography-ui-label text-foreground",children:U?"Edit instance":"Add instance"}),t.jsx(re,{type:"button",variant:"ghost",size:"xs",onClick:_,children:"Cancel"})]}),t.jsxs("label",{className:"block space-y-1.5",children:[t.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Server URL"}),t.jsx("input",{...He,value:v,onChange:z=>L(z.target.value),placeholder:"http://192.168.1.74:2606",type:"url",inputMode:"url",autoCapitalize:"none",className:se})]}),t.jsxs("label",{className:"block space-y-1.5",children:[t.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Name"}),t.jsx("input",{value:$,onChange:z=>b(z.target.value),placeholder:"Optional display name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,className:se})]}),t.jsxs("label",{className:"block space-y-1.5",children:[t.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Client token"}),t.jsx("input",{...He,value:S,onChange:z=>y(z.target.value),placeholder:"Paste access token",autoCapitalize:"none",className:se}),t.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:"Only needed if your server requires a token instead of a password."})]}),l?t.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:l}):null,t.jsx(re,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",children:U?"Save changes":"Save instance"})]})]})})})]})},Xe=320,Re="cubic-bezier(0.22, 1, 0.36, 1)",hs=({side:e,enabled:n,open:s,drawerRef:r,scrimRef:o,onClose:i,widthRatio:l,prefersReducedMotion:c})=>{a.useEffect(()=>{if(!n||!s)return;const u=r.current,d=o.current;if(!u||!d)return;let m=!1,x=!1,k=!1,N=0,P=0,R=0,U=0;const F=c?0:Xe,h=e==="left"?"translateX(-100%)":"translateX(100%)",v=()=>({drawer:F?`transform ${F}ms ${Re}`:"none",scrim:F?`opacity ${F}ms ${Re}`:"none"}),L=()=>{const w=v();u.style.transition=w.drawer,d.style.transition=w.scrim,u.style.transform="none",d.style.opacity="1",d.style.pointerEvents="auto"},$=()=>{m=!1,x=!1,k=!1},b=()=>{if(!(m||x)){$();return}L(),$()},S=w=>{if(w.touches.length!==1){(m||x)&&b();return}if(zs(w.target,u,{excludeInteractive:!1}))return;u.style.transition&&u.style.transition!=="none"&&(u.style.transition="none",d.style.transition="none");const E=w.touches[0];N=E.clientX,P=E.clientY,R=Date.now(),U=u.offsetWidth||window.innerWidth*l,U<10&&(U=window.innerWidth*l),m=!0,x=!1,k=!1},y=w=>{if(!m)return;if(w.touches.length!==1){b();return}const E=w.touches[0],p=E.clientX-N,C=E.clientY-P;if(!k){if(Math.abs(p)<Kt&&Math.abs(C)<Kt)return;if(Math.abs(C)>Math.abs(p)*Gt||!Xt(e,p)){m=!1;return}k=!0,x=!0,u.style.transition="none",d.style.transition="none"}if(!x)return;w.cancelable&&w.preventDefault();const O=qt(e,p,U);u.style.transform=Os(e,O),d.style.opacity=String(O)},B=(w,E,p)=>{if(!m)return;const C=w-N,O=E-P,q=Math.max(1,Date.now()-R),Z=qt(e,C,U),X=Us({side:e,dx:C,dy:O,dt:q,progress:Z,isDragging:x}),A=v();u.style.transition=A.drawer,d.style.transition=A.scrim,u.style.transform=X?h:"none",d.style.opacity=X?"0":"1",d.style.pointerEvents=X?"none":"auto",$(),X&&i()},g=w=>{const E=w.changedTouches[0];if(!E){b();return}const p=E.clientX-N,C=E.clientY-P,O=Math.abs(p)>=$s&&Math.abs(C)<=Math.abs(p)*Gt&&Xt(e,p);m&&(x||O)&&w.cancelable&&w.preventDefault(),B(E.clientX,E.clientY)},I=()=>{b()};return u.addEventListener("touchstart",S,{passive:!0}),u.addEventListener("touchmove",y,{passive:!1}),u.addEventListener("touchend",g,{passive:!1}),u.addEventListener("touchcancel",I,{passive:!0}),()=>{try{b()}catch{}u.removeEventListener("touchstart",S),u.removeEventListener("touchmove",y),u.removeEventListener("touchend",g),u.removeEventListener("touchcancel",I)}},[r,n,i,s,c,o,e,l])},uo=16,pn=a.memo(function({open:n,onOpenChange:s,variant:r="drawer",drawerRefExternal:o,scrimRefExternal:i,rootRefExternal:l}){const c=a.useRef(null),u=a.useCallback(()=>{const y=typeof document<"u"?document.activeElement:null;y instanceof HTMLElement&&c.current?.contains(y)&&y.blur(),s(!1)},[s]),d=ge(y=>y.openNewSessionDraft),m=de(y=>y.setActiveMainTab),x=de(y=>y.setSessionSwitcherOpen),[k,N]=a.useState(!1),P=a.useRef(null),R=a.useRef(null),U=o??P,F=i??R,h=a.useCallback(y=>{c.current=y,l&&(l.current=y)},[l]),v=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]);a.useEffect(()=>{const y=c.current;if(!y||n)return;const B=document.activeElement;B&&y.contains(B)&&B.blur()},[n]),a.useEffect(()=>{if(r!=="sidebar"){if(n){const y=window.setTimeout(()=>N(!0),v?0:uo);return()=>window.clearTimeout(y)}N(!1)}},[n,v,r]),a.useEffect(()=>{if(r==="sidebar"||!n)return;const y=document.body.style.overflow;document.body.style.overflow="hidden";const B=g=>{g.key==="Escape"&&u()};return document.addEventListener("keydown",B),()=>{document.body.style.overflow=y,document.removeEventListener("keydown",B)}},[u,n,r]);const L=a.useCallback(()=>{de.getState().closeMainSurfaces(),m("chat"),x(!1),d(),u()},[u,d,m,x]),$=r==="sidebar",b=t.jsx(Bs,{mobileVariant:!$,isVisible:n,allowReselect:!0,onSessionSelected:$?void 0:u,onNavigateAway:$?void 0:u});if(hs({side:"left",enabled:r==="drawer",open:n,drawerRef:U,scrimRef:F,onClose:u,widthRatio:.72,prefersReducedMotion:v}),r==="sidebar")return t.jsx("aside",{className:"relative flex h-full w-full flex-col bg-sidebar",children:b});if(typeof document>"u")return null;const S=v?0:Xe;return We.createPortal(t.jsxs("div",{ref:h,className:"fixed inset-0 z-50",inert:!n,style:{pointerEvents:n?"auto":"none"},"data-mobile-sessions-root":"true",children:[t.jsx("button",{ref:F,type:"button",className:"absolute inset-0 cursor-default bg-black/70","aria-label":"Close sessions",onClick:u,tabIndex:n?0:-1,style:{opacity:k?1:0,transition:`opacity ${S}ms ${Re}`},"data-mobile-sessions-scrim":"true"}),t.jsx("div",{ref:U,className:K("relative z-10 flex h-full w-[72%] max-w-[72%] flex-col bg-sidebar"),style:{paddingTop:"var(--oc-safe-area-top, 0px)",transform:k?"none":"translateX(-100%)",transition:S?`transform ${S}ms ${Re}`:"none",touchAction:"pan-x pan-y"},"data-mobile-sessions-drawer":"true",children:b}),t.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-0 z-20 flex w-[28%] items-end justify-center",style:{paddingBottom:"calc(1rem + var(--oc-safe-area-bottom, 0px))"},children:n?t.jsx(re,{type:"button",variant:"outline",size:"lg",className:"pointer-events-auto size-12 rounded-full p-0 [corner-shape:round] supports-[corner-shape:squircle]:rounded-full",onClick:L,"aria-label":"New session",children:t.jsx(V,{name:"chat-new",className:"size-5"})}):null})]}),document.body)}),gn="mobile-surface-root",kt=16,ct=200,fo=()=>{if(typeof document>"u")return null;let e=document.getElementById(gn);return e||(e=document.createElement("div"),e.id=gn,document.body.appendChild(e)),e},jt=({open:e,onClose:n,title:s,subtitle:r,trailing:o,disableEscapeDismiss:i=!1,headerless:l=!1,noHeaderBorder:c=!1,ariaLabel:u,variant:d="fullscreen",dialogAlign:m="chat",children:x})=>{const k=a.useRef(null),[N,P]=a.useState(!1),[R,U]=a.useState(!1),F=a.useRef(null),h=a.useRef(null),v=a.useRef(n);if(a.useEffect(()=>{v.current=n},[n]),typeof document<"u"&&!k.current&&(k.current=fo()),a.useEffect(()=>{if(!e){P(!1);return}const b=window.setTimeout(()=>P(!0),kt);return()=>window.clearTimeout(b)},[e]),a.useEffect(()=>{if(!e){U(!1);return}const b=window.setTimeout(()=>U(!0),kt+ct+80);return()=>window.clearTimeout(b)},[e]),a.useEffect(()=>{if(!e)return;const b=document.body.style.overflow;h.current=document.activeElement instanceof HTMLElement?document.activeElement:null,document.body.style.overflow="hidden";const S=()=>{const g=F.current;if(!g)return;(g.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??g).focus({preventScroll:!0})},y=window.setTimeout(S,kt),B=g=>{if(g.key==="Escape"&&!i){v.current();return}if(g.key!=="Tab")return;const I=F.current;if(!I)return;const w=Array.from(I.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')).filter(O=>!O.hasAttribute("disabled")&&O.getAttribute("aria-hidden")!=="true");if(w.length===0){g.preventDefault(),I.focus({preventScroll:!0});return}const E=w[0],p=w[w.length-1],C=document.activeElement;g.shiftKey&&C===E?(g.preventDefault(),p.focus({preventScroll:!0})):!g.shiftKey&&C===p&&(g.preventDefault(),E.focus({preventScroll:!0}))};return document.addEventListener("keydown",B),()=>{window.clearTimeout(y),document.body.style.overflow=b,document.removeEventListener("keydown",B),h.current?.focus?.({preventScroll:!0}),h.current=null}},[i,e]),!e||!k.current)return null;const L=d==="dialog",$=t.jsxs("section",{ref:F,role:"dialog","aria-modal":"true","aria-label":u,tabIndex:-1,className:K("flex flex-col bg-background text-foreground",L?"h-[min(88dvh,860px)] w-full max-w-[720px] overflow-hidden rounded-2xl border border-border/70 shadow-[0_24px_64px_rgb(0_0_0_/_0.32)]":"oc-keyboard-inset-surface fixed inset-0 z-50"),style:L?{opacity:N?1:0,transform:N?"none":"scale(0.97)",transition:`opacity ${ct}ms ease-out, transform ${ct}ms cubic-bezier(0.32, 0.72, 0, 1)`}:{paddingTop:"var(--oc-safe-area-top, 0px)",transform:N?"none":"translateX(100%)",transition:`transform ${ct}ms cubic-bezier(0.32, 0.72, 0, 1)`},onTransitionEnd:b=>{N&&b.target===b.currentTarget&&b.propertyName==="transform"&&U(!0)},children:[l?null:t.jsxs("header",{className:K("flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-2 px-3",!c&&"border-b border-border/70"),children:[t.jsx("button",{type:"button",className:"-ml-1 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","aria-label":"Close",onClick:n,style:{touchAction:"manipulation"},children:t.jsx(V,{name:"close",className:"size-5"})}),t.jsxs("div",{className:"min-w-0 flex-1 px-1",children:[s?typeof s=="string"?t.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:s}):s:null,r?typeof r=="string"?t.jsx("p",{className:"truncate typography-micro text-muted-foreground",children:r}):r:null]}),o?t.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:o}):null]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:R?t.jsx("div",{className:"h-full",style:{animation:"oc-surface-content-in 200ms ease-out"},children:x}):null}),t.jsx("style",{children:"@keyframes oc-surface-content-in { from { opacity: 0 } to { opacity: 1 } }"})]});return L?We.createPortal(t.jsx("div",{className:"oc-keyboard-inset-surface fixed inset-0 z-50 flex items-center justify-center p-4 transition-opacity duration-200 ease-out",style:{background:"rgb(0 0 0 / 0.45)",opacity:N?1:0,paddingLeft:m==="chat"?"max(1rem, var(--oc-chat-inset-left, 0px))":"1rem",paddingRight:m==="chat"?"max(1rem, var(--oc-chat-inset-right, 0px))":"1rem",paddingTop:"max(1rem, var(--oc-safe-area-top, 0px))"},onClick:n,children:t.jsx("div",{className:"flex w-full max-w-[720px] justify-center",onClick:b=>b.stopPropagation(),children:$})}),k.current):We.createPortal($,k.current)},ms={"?":{code:"?",color:"var(--status-info)",description:"Untracked file"},A:{code:"A",color:"var(--status-success)",description:"New file"},D:{code:"D",color:"var(--status-error)",description:"Deleted file"},R:{code:"R",color:"var(--status-info)",description:"Renamed file"},C:{code:"C",color:"var(--status-info)",description:"Copied file"},M:{code:"M",color:"var(--status-warning)",description:"Modified file"}},ho=ms.M;function mo(e){const n=e.index?.trim(),s=e.working_dir?.trim();return n&&n!=="?"?n.charAt(0):s?s.charAt(0):n?.charAt(0)||s?.charAt(0)||"M"}function po(e){const n=mo(e);return ms[n]??ho}const go=a.memo(function({file:n,actionLabel:s,actionSymbol:r,onAction:o,onViewDiff:i,onRevert:l,isReverting:c,stats:u,rowPaddingClassName:d,indentPx:m=0,actionAtStart:x=!1,showRevert:k=!0}){const N=De.useMemo(()=>po(n),[n]),P=N.description,R=u?.insertions??0,U=u?.deletions??0,F=De.useCallback($=>{$.key===" "?($.preventDefault(),o()):$.key==="Enter"&&($.preventDefault(),i())},[o,i]),h=De.useCallback($=>{$.preventDefault(),$.stopPropagation(),o()},[o]),v=De.useCallback($=>{$.preventDefault(),$.stopPropagation(),l()},[l]),L=t.jsx("button",{type:"button",onClick:h,className:"flex size-5 shrink-0 items-center justify-center rounded typography-micro font-semibold text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":s,title:s,children:r});return t.jsxs("div",{className:`group flex items-center gap-2 py-1.5 cursor-pointer ${d??"px-3"}`,role:"button",tabIndex:0,onClick:i,onKeyDown:F,style:m>0?{paddingLeft:`${m}px`}:void 0,children:[x?L:null,t.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:N.color},title:P,"aria-label":P,children:N.code}),t.jsx(Fn,{filePath:n.path,className:"h-3.5 w-3.5 shrink-0"}),(()=>{const $=n.path.lastIndexOf("/");if($===-1)return t.jsx("span",{className:"flex-1 min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:n.path,children:n.path});const b=n.path.slice(0,$),S=n.path.slice($);return t.jsxs("span",{className:"flex-1 min-w-0 flex items-baseline overflow-hidden",title:n.path,children:[t.jsx("span",{className:"min-w-0 truncate typography-ui-label text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:b}),t.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[t.jsx("span",{className:"text-muted-foreground",children:"/"}),t.jsx("span",{className:"text-foreground",children:S.slice(1)})]})]})})(),t.jsxs("span",{className:"shrink-0 typography-micro",children:[t.jsxs("span",{style:{color:"var(--status-success)"},children:["+",R]}),t.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),t.jsxs("span",{style:{color:"var(--status-error)"},children:["-",U]})]}),k?t.jsxs(br,{children:[t.jsx(xr,{asChild:!0,children:t.jsx("button",{type:"button",onClick:v,disabled:c,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes in ${n.path}`,children:c?t.jsx(V,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(V,{name:"arrow-go-back",className:"size-3.5"})})}),t.jsx(vr,{sideOffset:8,children:"Revert changes"})]}):null,x?null:L]})}),yn=14,ps=e=>e.replace(/\\/g,"/").replace(/^\/+/,"").trim(),bn=(e,n)=>({id:`dir:${e}`,path:e,name:n,children:new Map,directFiles:[],files:[]}),yo=e=>{const n=bn("","");for(const s of e){const r=ps(s.path);if(!r)continue;const i=r.split("/").filter(Boolean).slice(0,-1);let l=n;if(l.files.push(s),i.length>0){let c="";for(const u of i){c=c?`${c}/${u}`:u;const d=l.children.get(u);if(d){d.files.push(s),l=d;continue}const m=bn(c,u);m.files.push(s),l.children.set(u,m),l=m}}l.directFiles.push(s)}return n},bo=(e,n)=>{const s=[],r=(o,i)=>{const l=Array.from(o.children.values()).sort((u,d)=>u.path.localeCompare(d.path));for(const u of l)s.push({key:u.id,kind:"directory",depth:i,directory:u}),n.has(u.path)&&r(u,i+1);const c=[...o.directFiles].sort((u,d)=>u.path.localeCompare(d.path));for(const u of c)s.push({key:`file:${ps(u.path)}`,kind:"file",depth:i,file:u})};return r(e,0),s},xo=1e3,xn=34,St=30,ut="pl-0 pr-2",Ct=(e,n)=>`${e} ${n}`,vo=({groups:e,diffStats:n,revertingPaths:s,isRevertingAll:r=!1,headerBackgroundClassName:o="bg-sidebar",onVisiblePathsChange:i,onRevertAll:l,onRevertDirectory:c})=>{const u=a.useRef(null),m=de(f=>f.gitChangesViewMode)==="tree",x=a.useMemo(()=>e.filter(f=>f.entries.length>0),[e]),[k,N]=a.useState(new Set),[P,R]=a.useState(new Set),[U,F]=a.useState(!1),[h,v]=a.useState(null),L=a.useMemo(()=>x.map(f=>yo(f.entries)),[x]),$=a.useMemo(()=>{const f=[];return x.forEach((j,_)=>{Array.from(L[_]?.children.values()??[]).forEach(H=>{f.push(Ct(j.id,H.path))})}),f},[L,x]);a.useEffect(()=>{m&&R(f=>{const j=new Set,_=new Set($);return f.forEach(H=>{(H.slice(H.indexOf(" ")+1).includes("/")||_.has(H))&&j.add(H)}),$.forEach(H=>j.add(H)),j})},[m,$]);const b=a.useMemo(()=>{const f=[];return x.forEach((j,_)=>{if(f.push({type:"header",key:`header:${j.id}`,groupIndex:_}),!k.has(j.id)){if(m){const H=new Set;P.forEach(J=>{J.startsWith(`${j.id} `)&&H.add(J.slice(j.id.length+1))}),bo(L[_],H).forEach(J=>{J.kind==="file"?f.push({type:"file",key:`${j.id}:${J.key}`,groupIndex:_,file:J.file,depth:J.depth}):f.push({type:"directory",key:`${j.id}:${J.key}`,groupIndex:_,directory:J.directory,depth:J.depth})});return}j.entries.forEach(H=>{f.push({type:"file",key:`${j.id}:file:${H.path}`,groupIndex:_,file:H,depth:0})})}}),l&&x.length>0&&f.push({type:"revert-all",key:"revert-all"}),f},[k,P,m,l,L,x]),S=b.length,y=S>=xo,B=ua({count:S,enabled:y,getScrollElement:()=>u.current,estimateSize:()=>xn,overscan:12,getItemKey:f=>b[f]?.key??f}),g=B.getVirtualItems(),I=a.useMemo(()=>{if(!y)return 0;const f=u.current?.scrollTop??0;return g.find(_=>_.end>f)?.index??0},[y,g,u]);a.useEffect(()=>{if(!i)return;const f=j=>j&&j.type==="file"?j.file.path:null;if(S===0){i([]);return}if(!y){const j=[];for(const _ of b)if(_.type==="file"&&(j.push(_.file.path),j.length>=St))break;i(j);return}i(b.slice(I,I+Math.ceil((u.current?.clientHeight??0)/xn)+St).map(j=>f(j)).filter(j=>!!j).slice(0,St))},[i,S,b,y,I]);const w=a.useCallback(f=>{N(j=>{const _=new Set(j);return _.has(f)?_.delete(f):_.add(f),_})},[]),E=a.useCallback((f,j)=>{R(_=>{const H=new Set(_),te=Ct(f,j);return H.has(te)?H.delete(te):H.add(te),H})},[]),p=a.useMemo(()=>{const f=new Set;return x.forEach(j=>j.entries.forEach(_=>f.add(_.path))),Array.from(f)},[x]),C=p.length,O=h?r||h.paths.some(f=>s.has(f)):!1,q=a.useCallback(async()=>{!l||r||p.length===0||(await l(p),F(!1))},[p,r,l]),Z=a.useCallback(async()=>{!c||!h||O||(await c(h.paths),v(null))},[O,c,h]),X=a.useCallback((f,j)=>{const _=k.has(f.id),H=f.entries.length;return t.jsxs("div",{className:K("sticky top-0 z-10 flex items-center gap-2 py-2",o,ut,!j&&"mt-1 border-t border-border/40"),children:[t.jsx("button",{type:"button",onClick:()=>f.onActionAll(f.entries.map(te=>te.path)),className:"flex size-5 shrink-0 items-center justify-center rounded typography-micro font-semibold text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":f.actionAllLabel,title:f.actionAllLabel,children:f.actionSymbol}),t.jsxs("button",{type:"button",onClick:()=>w(f.id),className:"flex min-w-0 flex-1 items-center gap-2 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-expanded":!_,children:[t.jsx("h3",{className:"truncate typography-ui-header font-semibold text-foreground",children:f.title}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:H}),t.jsx(V,{name:"arrow-down-s",className:K("size-3.5 shrink-0 text-muted-foreground transition-transform",_&&"-rotate-90")})]})]})},[k,o,w]),A=a.useCallback((f,j,_)=>{const H=P.has(Ct(f.id,j.path)),te=j.files.map(ae=>ae.path),J=r||te.some(ae=>s.has(ae));return t.jsxs("div",{className:K("group flex items-center gap-2 py-1.5",ut),style:{paddingLeft:`${_*yn}px`},children:[t.jsxs("button",{type:"button",onClick:()=>E(f.id,j.path),className:"flex min-w-0 flex-1 items-center gap-2 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":H?`Collapse directory ${j.path}`:`Expand directory ${j.path}`,children:[H?t.jsx(V,{name:"folder-open-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):t.jsx(V,{name:"folder-3-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}),t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",title:j.path,children:j.name}),t.jsx("span",{className:"ml-auto shrink-0 typography-micro text-muted-foreground",children:j.files.length})]}),f.showRevertActions!==!1&&c?t.jsx("button",{type:"button",onClick:()=>v({path:j.path,paths:te,count:te.length}),disabled:J,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes in ${j.path}`,title:"Revert folder changes",children:J?t.jsx(V,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(V,{name:"arrow-go-back",className:"size-3.5"})}):null,t.jsx("button",{type:"button",onClick:()=>f.onActionAll(j.files.map(ae=>ae.path)),className:"flex size-5 shrink-0 items-center justify-center rounded typography-micro font-semibold text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":f.actionSymbol==="+"?`Stage all changes in ${j.path}`:`Unstage all changes in ${j.path}`,title:f.actionSymbol==="+"?`Stage all changes in ${j.path}`:`Unstage all changes in ${j.path}`,children:f.actionSymbol})]})},[P,r,c,s,E]),G=a.useCallback((f,j)=>{if(f.type==="revert-all")return t.jsx("div",{className:K("flex justify-end py-2",ut),children:t.jsxs(re,{variant:"ghost",size:"sm",onClick:()=>F(!0),disabled:r,className:"gap-1.5 text-[var(--status-error)] hover:bg-[var(--status-error)]/10 hover:text-[var(--status-error)]",children:[t.jsx(V,{name:"arrow-go-back",className:"size-3.5"}),"Revert all"]})});const _=x[f.groupIndex];if(!_)return null;if(f.type==="header")return X(_,j);if(f.type==="directory")return A(_,f.directory,f.depth);const H=f.file;return t.jsx(go,{file:H,actionLabel:_.getActionLabel(H.path),actionSymbol:_.actionSymbol,onAction:()=>_.onActionFile(H.path),stats:n?.[H.path],onViewDiff:()=>_.onViewDiff(H.path),onRevert:()=>_.onRevertFile(H.path),isReverting:s.has(H.path)||r,rowPaddingClassName:ut,indentPx:f.depth*yn,actionAtStart:!m,showRevert:_.showRevertActions!==!1})},[n,r,m,A,X,s,x]),Y=a.useCallback(f=>{const j=b[f],_=b[f-1];return!j||!_||j.type!=="file"&&j.type!=="directory"||_.type!=="file"&&_.type!=="directory"?!1:_.groupIndex===j.groupIndex},[b]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"relative flex h-full min-h-0 w-full flex-col overflow-hidden",children:[t.jsx(It,{ref:u,className:"overlay-scrollbar-target overlay-scrollbar-container min-h-0 w-full flex-1 overflow-x-hidden overflow-y-auto",children:y?t.jsx("div",{style:{height:B.getTotalSize(),position:"relative"},children:g.map(f=>{const j=b[f.index];return j?t.jsx("div",{"data-index":f.index,ref:B.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${f.start}px)`},className:K(Y(f.index)&&"before:pointer-events-none before:absolute before:left-0 before:right-2 before:top-0 before:border-t before:border-border/60"),children:G(j,f.index===0)},j.key):null})}):t.jsx("div",{role:"list","aria-label":"Changed files",children:b.map((f,j)=>t.jsx("div",{className:K("relative",Y(j)&&"before:pointer-events-none before:absolute before:left-0 before:right-2 before:top-0 before:border-t before:border-border/60"),children:G(f,j===0)},f.key))})}),t.jsx(wr,{containerRef:u,disableHorizontal:!0})]}),t.jsx(Yt,{open:U,onOpenChange:f=>{!r&&!f&&F(!1)},children:t.jsxs(Jt,{className:"max-w-md",children:[t.jsxs(Qt,{children:[t.jsx(Zt,{children:"Revert all changes?"}),t.jsx(en,{children:C===1?`Revert ${C} changed file? This cannot be undone.`:`Revert ${C} changed files? This cannot be undone.`})]}),t.jsxs(tn,{children:[t.jsx(re,{variant:"outline",size:"sm",onClick:()=>F(!1),disabled:r,children:"Cancel"}),t.jsx(re,{variant:"destructive",size:"sm",onClick:()=>{q()},disabled:r,children:r?"Reverting...":"Revert all"})]})]})}),t.jsx(Yt,{open:!!h,onOpenChange:f=>{!O&&!f&&v(null)},children:t.jsxs(Jt,{className:"max-w-md",children:[t.jsxs(Qt,{children:[t.jsx(Zt,{children:"Revert folder changes?"}),t.jsx(en,{children:h?h.count===1?`This will discard local changes in ${h.count} file under ${h.path}.`:`This will discard local changes in ${h.count} files under ${h.path}.`:null})]}),t.jsxs(tn,{children:[t.jsx(re,{variant:"outline",size:"sm",onClick:()=>v(null),disabled:O,children:"Cancel"}),t.jsx(re,{variant:"destructive",size:"sm",onClick:()=>{Z()},disabled:O||!h,children:O?"Reverting...":"Revert folder"})]})]})})]})},wo=Pr(()=>be(()=>import("./DiffView-vrxi5oWp.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,110,111,112,113,114,115,116,117,118])).then(e=>({default:e.DiffView}))),ko=e=>(e||"").replace(/\\/g,"/").replace(/\/+$/g,""),jo=e=>{const n=e.index?.trim();return!!(n&&n!=="?")},So=e=>{const n=e.working_dir?.trim(),s=e.index?.trim();return!!(n||s==="?")},vn=(e,n)=>n?`${e}\0staged`:e,Co=({onClose:e,initialDiffPath:n,initialDiffStaged:s=!1})=>{const{git:r}=Hn(),o=ko(Dt()??null),i=kr(o||null),l=jr(o||null),c=Sr(o||null),u=ke(T=>T.setActiveDirectory),d=ke(T=>T.ensureAll),m=ke(T=>T.fetchStatus),x=ke(T=>T.fetchBranches),k=ke(T=>T.prefetchDiffs),N=ke(T=>T.getDiff),P=ke(T=>T.setDiff),[R,U]=a.useState(()=>n?{type:"diff",path:n,staged:s}:{type:"list"});a.useEffect(()=>{n&&U(T=>T.type==="diff"&&T.path===n&&T.staged===s?T:{type:"diff",path:n,staged:s})},[n,s]);const[F,h]=a.useState(null),[v,L]=a.useState(null),[$,b]=a.useState(""),[S,y]=a.useState(new Set),[B,g]=a.useState(!1),[I,w]=a.useState(!1),[E,p]=a.useState([]),[C,O]=a.useState([]),[q,Z]=a.useState([]),[X,A]=a.useState(null),[G,Y]=a.useState(null),[f,j]=a.useState(0),_=a.useMemo(()=>{const T=i?.files??[],M=new Map;for(const W of T)M.set(W.path,W);return Array.from(M.values()).sort((W,ee)=>W.path.localeCompare(ee.path))},[i?.files]),H=a.useMemo(()=>_.filter(jo),[_]),te=a.useMemo(()=>_.filter(So),[_]),J=a.useMemo(()=>{if(q.length>0)return q;const T=i?.tracking?.includes("/")?i.tracking.split("/")[0]:null;return T||X?[{name:T||"origin",fetchUrl:X??"",pushUrl:X??""}]:[]},[X,q,i?.tracking]),ae=ke(a.useCallback(T=>!o||R.type!=="diff"?null:T.directories.get(o)?.diffCache.get(vn(R.path,R.staged))??null,[o,R])),Te=a.useMemo(()=>R.type!=="diff"?null:_.find(T=>T.path===R.path)??null,[_,R]),ue=a.useCallback(async(T=!0)=>{if(o)try{await Promise.all([m(o,r),x(o,r)])}catch(M){T&&oe.error(M instanceof Error?M.message:"Failed to refresh repository")}},[o,x,m,r]),ye=a.useCallback(async()=>{if(!o){Z([]),A(null);return}try{const[T,M]=await Promise.all([r.getRemotes(o).catch(()=>[]),r.getRemoteUrl?r.getRemoteUrl(o).catch(()=>null):Promise.resolve(null)]);Z(T),A(M)}catch{Z([]),A(null)}},[o,r]);a.useEffect(()=>{o&&(u(o),d(o,r))},[o,d,r,u]),a.useEffect(()=>{ye()},[ye]),a.useEffect(()=>{if(!o||_.length===0)return;const T=Array.from(new Set([...H.map(W=>W.path),...C,..._.slice(0,20).map(W=>W.path)])).filter(Boolean);if(T.length===0)return;const M=window.setTimeout(()=>{k(o,r,T,{maxFiles:40})},120);return()=>window.clearTimeout(M)},[_,o,r,k,H,C]),a.useEffect(()=>{if(R.type!=="diff"){Y(null);return}const T=vn(R.path,R.staged);if(!o||N(o,T)){Y(null);return}let M=!1;const W=rt();return Y(null),r.getGitFileDiff(o,{path:R.path,staged:R.staged||void 0}).then(ee=>{M||P(o,T,{original:ee.original??"",modified:ee.modified??"",isBinary:ee.isBinary},W)}).catch(ee=>{M||Y(ee instanceof Error?ee.message:String(ee))}),()=>{M=!0}},[o,f,N,r,R,P]);const se=async(T,M)=>{if(o){h(T);try{const W=ee=>{const D=`${ee.name}/`,he=i?.tracking?.startsWith(D)?i.tracking.slice(D.length):void 0;return{remote:ee.name,branch:he,rebase:!0}};if(T==="fetch"){if(!M)throw new Error("No remote available");await r.gitFetch(o,{remote:M.name}),oe.success(`Fetched from ${M.name}`)}else if(T==="sync"){if(!M)throw new Error("No remote available");await r.gitFetch(o,{remote:M.name});const ee=await r.getGitStatus(o);if((ee.behind??0)>0){if((ee.files?.length??0)>0){oe.error("Commit or stash your changes before syncing");return}await r.gitPull(o,W(M))}((await r.getGitStatus(o)).ahead??0)>0&&await r.gitPush(o),oe.success("Already up to date")}await ue(!1),await ye()}catch(W){oe.error(W instanceof Error?W.message:"Sync Changes failed")}finally{h(null)}}},z=a.useCallback(async(T,M)=>{if(!(!o||T.length===0))try{M==="stage"?T.length>1?await Cr(o,T):await Er(o,T[0]):T.length>1?await Nr(o,T):await Rr(o,T[0]),await ue(!1)}catch(W){oe.error(W instanceof Error?W.message:M==="stage"?"Failed to stage changes":"Failed to unstage changes")}},[o,ue]),Q=a.useCallback((T,M=!1)=>{U({type:"diff",path:T,staged:M})},[]),ne=a.useCallback(async T=>{if(o){y(M=>new Set(M).add(T));try{await r.revertGitFile(o,T),oe.success(`Reverted ${T}`),await ue(!1)}catch(M){oe.error(M instanceof Error?M.message:"Failed to revert changes")}finally{y(M=>{const W=new Set(M);return W.delete(T),W})}}},[o,r,ue]),we=a.useCallback(async T=>{if(!o||T.length===0||B)return;const M=Array.from(new Set(T));g(!0),y(new Set(M));try{await Promise.all(M.map(W=>r.revertGitFile(o,W))),await ue(!1),oe.success(M.length===1?`Reverted ${M.length} file`:`Reverted ${M.length} files`)}catch(W){oe.error(W instanceof Error?W.message:"Failed to revert changes")}finally{y(new Set),g(!1)}},[o,r,B,ue]),ve=a.useCallback(T=>{const M=T.map(W=>W.trim()).filter(Boolean);if(M.length===0){p([]);return}b(W=>`${W.trim()}${W.trim()?`
|
|
11
|
+
`})]}):null},lo=({onOpenSessions:e,onOpenWorkspace:n,compactTitle:s=!1})=>{const[r,o]=a.useState(!1),[i,l]=a.useState(!1),c=a.useRef(null),u=On(v=>v.currentDirectory),d=ge(v=>v.currentSessionId),x=ge(a.useCallback(v=>d?v.getDirectoryForSession(d):null,[d]))||u,k=yr(d),N=ge(v=>!!v.newSessionDraft?.open),R=k?.title?.trim()||(d?"Untitled session":"New session");a.useEffect(()=>{o(!1),l(!1)},[d,x]);const U=a.useCallback(()=>{o(!1),l(!1),e()},[e]),F=a.useCallback(v=>{o(L=>{const $=typeof v=="function"?v(L):v;return $&&l(!1),$})},[]),h=a.useCallback(()=>{l(v=>{const L=!v;return L&&o(!1),L})},[]);return t.jsxs(t.Fragment,{children:[t.jsx("header",{className:"oc-mobile-header relative z-30 flex shrink-0 items-center gap-1 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:t.jsxs("div",{className:"flex h-[var(--oc-header-height,56px)] w-full items-center gap-1 px-2",children:[t.jsx("button",{type:"button",className:"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","aria-label":"Open sessions and projects",onClick:U,style:{touchAction:"manipulation"},children:t.jsx(V,{name:"list-unordered",className:"size-5"})}),t.jsx("button",{ref:c,type:"button",className:K("flex min-w-0 items-center rounded-lg px-2 py-1.5 text-left transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",s?"shrink":"flex-1"),"aria-label":"Open session switcher","aria-haspopup":"dialog","aria-expanded":i,onClick:h,style:{touchAction:"manipulation"},children:t.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[t.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",children:R}),t.jsx(V,{name:"arrow-down-s",className:K("size-4 shrink-0 text-muted-foreground transition-transform duration-150",i&&"rotate-180")})]})}),s?t.jsx("div",{className:"min-w-0 flex-1"}):null,t.jsx(Ms,{open:r,onOpenChange:F,currentSessionId:d,effectiveDirectory:x,isNewSessionDraftOpen:N}),t.jsx("button",{type:"button",className:"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","aria-label":"Open workspace panel",onClick:()=>{o(!1),l(!1),n()},style:{touchAction:"manipulation"},children:t.jsx(V,{name:"layout-right",className:"size-5"})})]})}),t.jsx(io,{open:i,onClose:()=>l(!1),anchorRef:c})]})},co=({onActiveConnectionDeleted:e,onConnect:n})=>{const s=Ft(n),{connections:r,isBusy:o,isPasswordBusy:i,error:l,pendingConnection:c,connect:u,submitPassword:d,cancelPassword:m,saveConnection:x,removeConnection:k,setError:N}=s,[P,R]=a.useState(null),U=P?r.find(z=>z.id===P)??null:null,[F,h]=a.useState(null),[v,L]=a.useState(""),[$,b]=a.useState(""),[S,y]=a.useState(""),[B,g]=a.useState(""),[I,w]=a.useState(!1),[E,p]=a.useState(!1),[C,O]=a.useState(!1),[q,Z]=a.useState(null),X=a.useRef(null),A=a.useMemo(()=>Pt(),[]),[G,Y]=a.useState(!1),[f,j]=a.useState(null),_=a.useCallback(()=>{R(null),L(""),b(""),y(""),N(null),Y(!1)},[N]),H=a.useCallback(z=>{z.preventDefault(),x({id:P??void 0,url:v,label:$,clientToken:S}).then(Q=>{Q&&_()})},[S,P,$,_,x,v]),te=a.useCallback(async()=>{if(X.current)return;N(null),w(!0);const z=new AbortController;X.current=z;try{const Q=await us({signal:z.signal});switch(X.current===z&&(X.current=null,w(!1)),Q.status){case"ok":L(Q.url),Q.label&&b(Q.label),Q.clientToken&&y(Q.clientToken),Y(!0);break;case"pairing":p(!0),await s.redeemPairingConnection(Q.pairing);break;case"permission-denied":N("Camera access is off. Enable it in Settings to scan a QR code.");break;case"invalid":N("That QR code is not an PiChamber connection code.");break;case"unsupported":N("QR scanning is only available in the installed mobile app.");break;case"failed":N("Could not scan that QR code. Try again or enter the URL manually.");break;default:break}}finally{p(!1),X.current===z&&(X.current=null,w(!1))}},[s,N]);a.useEffect(()=>()=>X.current?.abort(),[]);const J=a.useCallback(z=>{z.preventDefault(),d(B)},[B,d]),ae=a.useCallback(()=>{g(""),m()},[m]),Te=a.useCallback(async()=>{if(!C){Z(null),O(!0);try{const z=await Cs();Z(z==="copied"?"Diagnostics copied to the clipboard.":z==="downloaded"?"Diagnostics downloaded.":"Diagnostics ready to share.")}catch{Z("Diagnostics export was cancelled or unavailable.")}finally{O(!1)}}},[C]),ue=a.useCallback(z=>{h(Q=>Q===z?null:z)},[]),ye=a.useCallback(z=>{h(null),P===z&&_();const Q=r.length===1;k(z).then(ne=>{ne&&(Q||Tt(ne))&&e()})},[r.length,P,e,k,_]),se=Ye;return c?t.jsx("div",{className:"flex h-full flex-col overflow-hidden",children:t.jsx("form",{className:"flex-1 overflow-y-auto px-5 py-4",onSubmit:J,children:t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsxs("div",{className:"flex items-center gap-3 rounded-[18px] border border-border/70 bg-surface-elevated px-3.5 py-3",children:[t.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:t.jsx(V,{name:"lock",className:"size-[18px]"})}),t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"truncate typography-ui-label text-foreground",children:c.label}),t.jsx("p",{className:"truncate typography-small text-muted-foreground",children:c.candidates.some(z=>z.kind==="direct")?xe(c):"via PiChamber Relay"})]})]}),t.jsx("input",{...He,value:B,onChange:z=>g(z.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:se}),l?t.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:l}):null,t.jsx(re,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",disabled:i||!B.trim(),children:i?"Connecting...":"Unlock and connect"}),t.jsx(re,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:ae,children:"Use another server"})]})})}):t.jsxs(t.Fragment,{children:[I?t.jsx(ds,{onCancel:()=>X.current?.abort()}):null,E?t.jsx(fs,{}):null,t.jsx("div",{className:"flex h-full flex-col overflow-hidden",children:t.jsx("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:t.jsxs("div",{className:"space-y-6",children:[r.length>0?t.jsx("div",{className:"overflow-hidden rounded-[18px] border border-border/70 bg-surface-elevated",children:r.map(z=>{const Q=F===z.id,ne=Tt(z),we=f===z.id,ve=we?"Connecting...":ne?tt()?"Connected · Private relay":"Connected · Local network":z.candidates.some(Pe=>Pe.kind==="direct")?xe(z):"via PiChamber Relay";return t.jsxs("div",{className:K("flex items-center border-b border-border/70 transition-colors last:border-b-0",Q&&"bg-[color-mix(in_srgb,var(--destructive)_8%,transparent)]"),children:[t.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-center gap-3 px-3.5 py-3 text-left transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary disabled:opacity-60",onClick:()=>{ne||(j(z.id),u({id:z.id,candidates:z.candidates,clientToken:z.clientToken,label:z.label}).finally(()=>j(null)))},disabled:o&&!we||Q,children:[t.jsxs("span",{className:"relative flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:[t.jsx(V,{name:"server",className:"size-[18px]"}),ne?t.jsx("span",{className:"absolute -right-0.5 -top-0.5 size-2.5 rounded-full border-2 border-[var(--surface-elevated)] bg-[var(--status-success)]","aria-hidden":!0}):null]}),t.jsxs("span",{className:"min-w-0 flex-1",children:[t.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:z.label}),t.jsx("span",{className:K("block truncate typography-small",ne&&!we?"text-[var(--status-success)]":"text-muted-foreground"),children:ve})]}),we?t.jsx(V,{name:"loader-4",className:"size-5 shrink-0 animate-spin text-muted-foreground"}):null]}),t.jsxs("div",{className:"flex items-center gap-0.5 pr-2",children:[Q?t.jsxs("button",{type:"button","aria-label":`Confirm deleting ${z.label}`,className:"flex h-9 shrink-0 items-center gap-1.5 rounded-full bg-destructive px-3 text-destructive-foreground transition-opacity active:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive",onClick:()=>ye(z.id),style:{touchAction:"manipulation"},children:[t.jsx(V,{name:"delete-bin",className:"size-[18px]"}),t.jsx("span",{className:"typography-ui-label",children:"Delete"})]}):z.candidates.some(Pe=>Pe.kind==="direct")?t.jsx("button",{type:"button","aria-label":"Edit",className:"flex size-9 items-center justify-center rounded-full text-muted-foreground transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>{R(z.id),L(xe(z)),b(z.label),y(z.clientToken||""),N(null)},style:{touchAction:"manipulation"},children:t.jsx(V,{name:"edit",className:"size-[18px]"})}):null,t.jsx("button",{type:"button","aria-label":Q?`Keep ${z.label}`:`Delete ${z.label}`,className:"flex size-9 items-center justify-center rounded-full text-muted-foreground transition-colors active:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",onClick:()=>ue(z.id),style:{touchAction:"manipulation"},children:t.jsx(V,{name:Q?"close":"delete-bin",className:"size-[18px]"})})]})]},z.id)})}):t.jsx("p",{className:"rounded-[18px] border border-dashed border-border/70 px-4 py-6 text-center typography-small text-muted-foreground",children:"No saved connections yet."}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs(re,{type:"button",variant:"outline",size:"lg",className:"h-12 w-full",onClick:()=>{Te()},disabled:C,children:[t.jsx(V,{name:"download",className:"size-[18px]"}),C?"Preparing diagnostics…":"Export diagnostics"]}),q?t.jsx("p",{className:"px-1 text-center typography-small text-muted-foreground",children:q}):null]}),!G&&!U?t.jsxs("div",{className:"space-y-2",children:[A?t.jsxs(re,{type:"button",size:"lg",className:"h-12 w-full",onClick:()=>{te()},disabled:I,children:[t.jsx(V,{name:"scan-2",className:K("size-[18px]",I&&"animate-pulse")}),"Scan QR code"]}):null,t.jsxs(re,{type:"button",variant:A?"ghost":"outline",size:"lg",className:"h-12 w-full",onClick:()=>{N(null),Y(!0)},children:[t.jsx(V,{name:"add",className:"size-[18px]"}),"Add by address"]}),l?t.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null]}):t.jsxs("form",{className:"space-y-3",onSubmit:H,children:[t.jsxs("div",{className:"flex h-8 items-center justify-between gap-3 px-1",children:[t.jsx("h3",{className:"typography-ui-label text-foreground",children:U?"Edit instance":"Add instance"}),t.jsx(re,{type:"button",variant:"ghost",size:"xs",onClick:_,children:"Cancel"})]}),t.jsxs("label",{className:"block space-y-1.5",children:[t.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Server URL"}),t.jsx("input",{...He,value:v,onChange:z=>L(z.target.value),placeholder:"http://192.168.1.74:2606",type:"url",inputMode:"url",autoCapitalize:"none",className:se})]}),t.jsxs("label",{className:"block space-y-1.5",children:[t.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Name"}),t.jsx("input",{value:$,onChange:z=>b(z.target.value),placeholder:"Optional display name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,className:se})]}),t.jsxs("label",{className:"block space-y-1.5",children:[t.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Client token"}),t.jsx("input",{...He,value:S,onChange:z=>y(z.target.value),placeholder:"Paste access token",autoCapitalize:"none",className:se}),t.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:"Only needed if your server requires a token instead of a password."})]}),l?t.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:l}):null,t.jsx(re,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",children:U?"Save changes":"Save instance"})]})]})})})]})},Xe=320,Re="cubic-bezier(0.22, 1, 0.36, 1)",hs=({side:e,enabled:n,open:s,drawerRef:r,scrimRef:o,onClose:i,widthRatio:l,prefersReducedMotion:c})=>{a.useEffect(()=>{if(!n||!s)return;const u=r.current,d=o.current;if(!u||!d)return;let m=!1,x=!1,k=!1,N=0,P=0,R=0,U=0;const F=c?0:Xe,h=e==="left"?"translateX(-100%)":"translateX(100%)",v=()=>({drawer:F?`transform ${F}ms ${Re}`:"none",scrim:F?`opacity ${F}ms ${Re}`:"none"}),L=()=>{const w=v();u.style.transition=w.drawer,d.style.transition=w.scrim,u.style.transform="none",d.style.opacity="1",d.style.pointerEvents="auto"},$=()=>{m=!1,x=!1,k=!1},b=()=>{if(!(m||x)){$();return}L(),$()},S=w=>{if(w.touches.length!==1){(m||x)&&b();return}if(zs(w.target,u,{excludeInteractive:!1}))return;u.style.transition&&u.style.transition!=="none"&&(u.style.transition="none",d.style.transition="none");const E=w.touches[0];N=E.clientX,P=E.clientY,R=Date.now(),U=u.offsetWidth||window.innerWidth*l,U<10&&(U=window.innerWidth*l),m=!0,x=!1,k=!1},y=w=>{if(!m)return;if(w.touches.length!==1){b();return}const E=w.touches[0],p=E.clientX-N,C=E.clientY-P;if(!k){if(Math.abs(p)<Kt&&Math.abs(C)<Kt)return;if(Math.abs(C)>Math.abs(p)*Gt||!Xt(e,p)){m=!1;return}k=!0,x=!0,u.style.transition="none",d.style.transition="none"}if(!x)return;w.cancelable&&w.preventDefault();const O=qt(e,p,U);u.style.transform=Os(e,O),d.style.opacity=String(O)},B=(w,E,p)=>{if(!m)return;const C=w-N,O=E-P,q=Math.max(1,Date.now()-R),Z=qt(e,C,U),X=Us({side:e,dx:C,dy:O,dt:q,progress:Z,isDragging:x}),A=v();u.style.transition=A.drawer,d.style.transition=A.scrim,u.style.transform=X?h:"none",d.style.opacity=X?"0":"1",d.style.pointerEvents=X?"none":"auto",$(),X&&i()},g=w=>{const E=w.changedTouches[0];if(!E){b();return}const p=E.clientX-N,C=E.clientY-P,O=Math.abs(p)>=$s&&Math.abs(C)<=Math.abs(p)*Gt&&Xt(e,p);m&&(x||O)&&w.cancelable&&w.preventDefault(),B(E.clientX,E.clientY)},I=()=>{b()};return u.addEventListener("touchstart",S,{passive:!0}),u.addEventListener("touchmove",y,{passive:!1}),u.addEventListener("touchend",g,{passive:!1}),u.addEventListener("touchcancel",I,{passive:!0}),()=>{try{b()}catch{}u.removeEventListener("touchstart",S),u.removeEventListener("touchmove",y),u.removeEventListener("touchend",g),u.removeEventListener("touchcancel",I)}},[r,n,i,s,c,o,e,l])},uo=16,pn=a.memo(function({open:n,onOpenChange:s,variant:r="drawer",drawerRefExternal:o,scrimRefExternal:i,rootRefExternal:l}){const c=a.useRef(null),u=a.useCallback(()=>{const y=typeof document<"u"?document.activeElement:null;y instanceof HTMLElement&&c.current?.contains(y)&&y.blur(),s(!1)},[s]),d=ge(y=>y.openNewSessionDraft),m=de(y=>y.setActiveMainTab),x=de(y=>y.setSessionSwitcherOpen),[k,N]=a.useState(!1),P=a.useRef(null),R=a.useRef(null),U=o??P,F=i??R,h=a.useCallback(y=>{c.current=y,l&&(l.current=y)},[l]),v=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]);a.useEffect(()=>{const y=c.current;if(!y||n)return;const B=document.activeElement;B&&y.contains(B)&&B.blur()},[n]),a.useEffect(()=>{if(r!=="sidebar"){if(n){const y=window.setTimeout(()=>N(!0),v?0:uo);return()=>window.clearTimeout(y)}N(!1)}},[n,v,r]),a.useEffect(()=>{if(r==="sidebar"||!n)return;const y=document.body.style.overflow;document.body.style.overflow="hidden";const B=g=>{g.key==="Escape"&&u()};return document.addEventListener("keydown",B),()=>{document.body.style.overflow=y,document.removeEventListener("keydown",B)}},[u,n,r]);const L=a.useCallback(()=>{de.getState().closeMainSurfaces(),m("chat"),x(!1),d(),u()},[u,d,m,x]),$=r==="sidebar",b=t.jsx(Bs,{mobileVariant:!$,isVisible:n,allowReselect:!0,onSessionSelected:$?void 0:u,onNavigateAway:$?void 0:u});if(hs({side:"left",enabled:r==="drawer",open:n,drawerRef:U,scrimRef:F,onClose:u,widthRatio:.72,prefersReducedMotion:v}),r==="sidebar")return t.jsx("aside",{className:"relative flex h-full w-full flex-col bg-sidebar",children:b});if(typeof document>"u")return null;const S=v?0:Xe;return We.createPortal(t.jsxs("div",{ref:h,className:"fixed inset-0 z-50",inert:!n,style:{pointerEvents:n?"auto":"none"},"data-mobile-sessions-root":"true",children:[t.jsx("button",{ref:F,type:"button",className:"absolute inset-0 cursor-default bg-black/70","aria-label":"Close sessions",onClick:u,tabIndex:n?0:-1,style:{opacity:k?1:0,transition:`opacity ${S}ms ${Re}`},"data-mobile-sessions-scrim":"true"}),t.jsx("div",{ref:U,className:K("relative z-10 flex h-full w-[72%] max-w-[72%] flex-col bg-sidebar"),style:{paddingTop:"var(--oc-safe-area-top, 0px)",transform:k?"none":"translateX(-100%)",transition:S?`transform ${S}ms ${Re}`:"none",touchAction:"pan-x pan-y"},"data-mobile-sessions-drawer":"true",children:b}),t.jsx("div",{className:"pointer-events-none absolute inset-y-0 right-0 z-20 flex w-[28%] items-end justify-center",style:{paddingBottom:"calc(1rem + var(--oc-safe-area-bottom, 0px))"},children:n?t.jsx(re,{type:"button",variant:"outline",size:"lg",className:"pointer-events-auto size-12 rounded-full p-0 [corner-shape:round] supports-[corner-shape:squircle]:rounded-full",onClick:L,"aria-label":"New session",children:t.jsx(V,{name:"chat-new",className:"size-5"})}):null})]}),document.body)}),gn="mobile-surface-root",kt=16,ct=200,fo=()=>{if(typeof document>"u")return null;let e=document.getElementById(gn);return e||(e=document.createElement("div"),e.id=gn,document.body.appendChild(e)),e},jt=({open:e,onClose:n,title:s,subtitle:r,trailing:o,disableEscapeDismiss:i=!1,headerless:l=!1,noHeaderBorder:c=!1,ariaLabel:u,variant:d="fullscreen",dialogAlign:m="chat",children:x})=>{const k=a.useRef(null),[N,P]=a.useState(!1),[R,U]=a.useState(!1),F=a.useRef(null),h=a.useRef(null),v=a.useRef(n);if(a.useEffect(()=>{v.current=n},[n]),typeof document<"u"&&!k.current&&(k.current=fo()),a.useEffect(()=>{if(!e){P(!1);return}const b=window.setTimeout(()=>P(!0),kt);return()=>window.clearTimeout(b)},[e]),a.useEffect(()=>{if(!e){U(!1);return}const b=window.setTimeout(()=>U(!0),kt+ct+80);return()=>window.clearTimeout(b)},[e]),a.useEffect(()=>{if(!e)return;const b=document.body.style.overflow;h.current=document.activeElement instanceof HTMLElement?document.activeElement:null,document.body.style.overflow="hidden";const S=()=>{const g=F.current;if(!g)return;(g.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??g).focus({preventScroll:!0})},y=window.setTimeout(S,kt),B=g=>{if(g.key==="Escape"&&!i){v.current();return}if(g.key!=="Tab")return;const I=F.current;if(!I)return;const w=Array.from(I.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')).filter(O=>!O.hasAttribute("disabled")&&O.getAttribute("aria-hidden")!=="true");if(w.length===0){g.preventDefault(),I.focus({preventScroll:!0});return}const E=w[0],p=w[w.length-1],C=document.activeElement;g.shiftKey&&C===E?(g.preventDefault(),p.focus({preventScroll:!0})):!g.shiftKey&&C===p&&(g.preventDefault(),E.focus({preventScroll:!0}))};return document.addEventListener("keydown",B),()=>{window.clearTimeout(y),document.body.style.overflow=b,document.removeEventListener("keydown",B),h.current?.focus?.({preventScroll:!0}),h.current=null}},[i,e]),!e||!k.current)return null;const L=d==="dialog",$=t.jsxs("section",{ref:F,role:"dialog","aria-modal":"true","aria-label":u,tabIndex:-1,className:K("flex flex-col bg-background text-foreground",L?"h-[min(88dvh,860px)] w-full max-w-[720px] overflow-hidden rounded-2xl border border-border/70 shadow-[0_24px_64px_rgb(0_0_0_/_0.32)]":"oc-keyboard-inset-surface fixed inset-0 z-50"),style:L?{opacity:N?1:0,transform:N?"none":"scale(0.97)",transition:`opacity ${ct}ms ease-out, transform ${ct}ms cubic-bezier(0.32, 0.72, 0, 1)`}:{paddingTop:"var(--oc-safe-area-top, 0px)",transform:N?"none":"translateX(100%)",transition:`transform ${ct}ms cubic-bezier(0.32, 0.72, 0, 1)`},onTransitionEnd:b=>{N&&b.target===b.currentTarget&&b.propertyName==="transform"&&U(!0)},children:[l?null:t.jsxs("header",{className:K("flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-2 px-3",!c&&"border-b border-border/70"),children:[t.jsx("button",{type:"button",className:"-ml-1 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","aria-label":"Close",onClick:n,style:{touchAction:"manipulation"},children:t.jsx(V,{name:"close",className:"size-5"})}),t.jsxs("div",{className:"min-w-0 flex-1 px-1",children:[s?typeof s=="string"?t.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:s}):s:null,r?typeof r=="string"?t.jsx("p",{className:"truncate typography-micro text-muted-foreground",children:r}):r:null]}),o?t.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:o}):null]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:R?t.jsx("div",{className:"h-full",style:{animation:"oc-surface-content-in 200ms ease-out"},children:x}):null}),t.jsx("style",{children:"@keyframes oc-surface-content-in { from { opacity: 0 } to { opacity: 1 } }"})]});return L?We.createPortal(t.jsx("div",{className:"oc-keyboard-inset-surface fixed inset-0 z-50 flex items-center justify-center p-4 transition-opacity duration-200 ease-out",style:{background:"rgb(0 0 0 / 0.45)",opacity:N?1:0,paddingLeft:m==="chat"?"max(1rem, var(--oc-chat-inset-left, 0px))":"1rem",paddingRight:m==="chat"?"max(1rem, var(--oc-chat-inset-right, 0px))":"1rem",paddingTop:"max(1rem, var(--oc-safe-area-top, 0px))"},onClick:n,children:t.jsx("div",{className:"flex w-full max-w-[720px] justify-center",onClick:b=>b.stopPropagation(),children:$})}),k.current):We.createPortal($,k.current)},ms={"?":{code:"?",color:"var(--status-info)",description:"Untracked file"},A:{code:"A",color:"var(--status-success)",description:"New file"},D:{code:"D",color:"var(--status-error)",description:"Deleted file"},R:{code:"R",color:"var(--status-info)",description:"Renamed file"},C:{code:"C",color:"var(--status-info)",description:"Copied file"},M:{code:"M",color:"var(--status-warning)",description:"Modified file"}},ho=ms.M;function mo(e){const n=e.index?.trim(),s=e.working_dir?.trim();return n&&n!=="?"?n.charAt(0):s?s.charAt(0):n?.charAt(0)||s?.charAt(0)||"M"}function po(e){const n=mo(e);return ms[n]??ho}const go=a.memo(function({file:n,actionLabel:s,actionSymbol:r,onAction:o,onViewDiff:i,onRevert:l,isReverting:c,stats:u,rowPaddingClassName:d,indentPx:m=0,actionAtStart:x=!1,showRevert:k=!0}){const N=De.useMemo(()=>po(n),[n]),P=N.description,R=u?.insertions??0,U=u?.deletions??0,F=De.useCallback($=>{$.key===" "?($.preventDefault(),o()):$.key==="Enter"&&($.preventDefault(),i())},[o,i]),h=De.useCallback($=>{$.preventDefault(),$.stopPropagation(),o()},[o]),v=De.useCallback($=>{$.preventDefault(),$.stopPropagation(),l()},[l]),L=t.jsx("button",{type:"button",onClick:h,className:"flex size-5 shrink-0 items-center justify-center rounded typography-micro font-semibold text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":s,title:s,children:r});return t.jsxs("div",{className:`group flex items-center gap-2 py-1.5 cursor-pointer ${d??"px-3"}`,role:"button",tabIndex:0,onClick:i,onKeyDown:F,style:m>0?{paddingLeft:`${m}px`}:void 0,children:[x?L:null,t.jsx("span",{className:"typography-micro font-semibold w-4 text-center uppercase",style:{color:N.color},title:P,"aria-label":P,children:N.code}),t.jsx(Fn,{filePath:n.path,className:"h-3.5 w-3.5 shrink-0"}),(()=>{const $=n.path.lastIndexOf("/");if($===-1)return t.jsx("span",{className:"flex-1 min-w-0 truncate typography-ui-label text-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},title:n.path,children:n.path});const b=n.path.slice(0,$),S=n.path.slice($);return t.jsxs("span",{className:"flex-1 min-w-0 flex items-baseline overflow-hidden",title:n.path,children:[t.jsx("span",{className:"min-w-0 truncate typography-ui-label text-muted-foreground",style:{direction:"rtl",textAlign:"left",unicodeBidi:"plaintext"},children:b}),t.jsxs("span",{className:"flex-shrink-0 typography-ui-label",children:[t.jsx("span",{className:"text-muted-foreground",children:"/"}),t.jsx("span",{className:"text-foreground",children:S.slice(1)})]})]})})(),t.jsxs("span",{className:"shrink-0 typography-micro",children:[t.jsxs("span",{style:{color:"var(--status-success)"},children:["+",R]}),t.jsx("span",{className:"text-muted-foreground mx-0.5",children:"/"}),t.jsxs("span",{style:{color:"var(--status-error)"},children:["-",U]})]}),k?t.jsxs(br,{children:[t.jsx(xr,{asChild:!0,children:t.jsx("button",{type:"button",onClick:v,disabled:c,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes in ${n.path}`,children:c?t.jsx(V,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(V,{name:"arrow-go-back",className:"size-3.5"})})}),t.jsx(vr,{sideOffset:8,children:"Revert changes"})]}):null,x?null:L]})}),yn=14,ps=e=>e.replace(/\\/g,"/").replace(/^\/+/,"").trim(),bn=(e,n)=>({id:`dir:${e}`,path:e,name:n,children:new Map,directFiles:[],files:[]}),yo=e=>{const n=bn("","");for(const s of e){const r=ps(s.path);if(!r)continue;const i=r.split("/").filter(Boolean).slice(0,-1);let l=n;if(l.files.push(s),i.length>0){let c="";for(const u of i){c=c?`${c}/${u}`:u;const d=l.children.get(u);if(d){d.files.push(s),l=d;continue}const m=bn(c,u);m.files.push(s),l.children.set(u,m),l=m}}l.directFiles.push(s)}return n},bo=(e,n)=>{const s=[],r=(o,i)=>{const l=Array.from(o.children.values()).sort((u,d)=>u.path.localeCompare(d.path));for(const u of l)s.push({key:u.id,kind:"directory",depth:i,directory:u}),n.has(u.path)&&r(u,i+1);const c=[...o.directFiles].sort((u,d)=>u.path.localeCompare(d.path));for(const u of c)s.push({key:`file:${ps(u.path)}`,kind:"file",depth:i,file:u})};return r(e,0),s},xo=1e3,xn=34,St=30,ut="pl-0 pr-2",Ct=(e,n)=>`${e} ${n}`,vo=({groups:e,diffStats:n,revertingPaths:s,isRevertingAll:r=!1,headerBackgroundClassName:o="bg-sidebar",onVisiblePathsChange:i,onRevertAll:l,onRevertDirectory:c})=>{const u=a.useRef(null),m=de(f=>f.gitChangesViewMode)==="tree",x=a.useMemo(()=>e.filter(f=>f.entries.length>0),[e]),[k,N]=a.useState(new Set),[P,R]=a.useState(new Set),[U,F]=a.useState(!1),[h,v]=a.useState(null),L=a.useMemo(()=>x.map(f=>yo(f.entries)),[x]),$=a.useMemo(()=>{const f=[];return x.forEach((j,_)=>{Array.from(L[_]?.children.values()??[]).forEach(H=>{f.push(Ct(j.id,H.path))})}),f},[L,x]);a.useEffect(()=>{m&&R(f=>{const j=new Set,_=new Set($);return f.forEach(H=>{(H.slice(H.indexOf(" ")+1).includes("/")||_.has(H))&&j.add(H)}),$.forEach(H=>j.add(H)),j})},[m,$]);const b=a.useMemo(()=>{const f=[];return x.forEach((j,_)=>{if(f.push({type:"header",key:`header:${j.id}`,groupIndex:_}),!k.has(j.id)){if(m){const H=new Set;P.forEach(J=>{J.startsWith(`${j.id} `)&&H.add(J.slice(j.id.length+1))}),bo(L[_],H).forEach(J=>{J.kind==="file"?f.push({type:"file",key:`${j.id}:${J.key}`,groupIndex:_,file:J.file,depth:J.depth}):f.push({type:"directory",key:`${j.id}:${J.key}`,groupIndex:_,directory:J.directory,depth:J.depth})});return}j.entries.forEach(H=>{f.push({type:"file",key:`${j.id}:file:${H.path}`,groupIndex:_,file:H,depth:0})})}}),l&&x.length>0&&f.push({type:"revert-all",key:"revert-all"}),f},[k,P,m,l,L,x]),S=b.length,y=S>=xo,B=ua({count:S,enabled:y,getScrollElement:()=>u.current,estimateSize:()=>xn,overscan:12,getItemKey:f=>b[f]?.key??f}),g=B.getVirtualItems(),I=a.useMemo(()=>{if(!y)return 0;const f=u.current?.scrollTop??0;return g.find(_=>_.end>f)?.index??0},[y,g,u]);a.useEffect(()=>{if(!i)return;const f=j=>j&&j.type==="file"?j.file.path:null;if(S===0){i([]);return}if(!y){const j=[];for(const _ of b)if(_.type==="file"&&(j.push(_.file.path),j.length>=St))break;i(j);return}i(b.slice(I,I+Math.ceil((u.current?.clientHeight??0)/xn)+St).map(j=>f(j)).filter(j=>!!j).slice(0,St))},[i,S,b,y,I]);const w=a.useCallback(f=>{N(j=>{const _=new Set(j);return _.has(f)?_.delete(f):_.add(f),_})},[]),E=a.useCallback((f,j)=>{R(_=>{const H=new Set(_),te=Ct(f,j);return H.has(te)?H.delete(te):H.add(te),H})},[]),p=a.useMemo(()=>{const f=new Set;return x.forEach(j=>j.entries.forEach(_=>f.add(_.path))),Array.from(f)},[x]),C=p.length,O=h?r||h.paths.some(f=>s.has(f)):!1,q=a.useCallback(async()=>{!l||r||p.length===0||(await l(p),F(!1))},[p,r,l]),Z=a.useCallback(async()=>{!c||!h||O||(await c(h.paths),v(null))},[O,c,h]),X=a.useCallback((f,j)=>{const _=k.has(f.id),H=f.entries.length;return t.jsxs("div",{className:K("sticky top-0 z-10 flex items-center gap-2 py-2",o,ut,!j&&"mt-1 border-t border-border/40"),children:[t.jsx("button",{type:"button",onClick:()=>f.onActionAll(f.entries.map(te=>te.path)),className:"flex size-5 shrink-0 items-center justify-center rounded typography-micro font-semibold text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":f.actionAllLabel,title:f.actionAllLabel,children:f.actionSymbol}),t.jsxs("button",{type:"button",onClick:()=>w(f.id),className:"flex min-w-0 flex-1 items-center gap-2 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-expanded":!_,children:[t.jsx("h3",{className:"truncate typography-ui-header font-semibold text-foreground",children:f.title}),t.jsx("span",{className:"typography-meta text-muted-foreground",children:H}),t.jsx(V,{name:"arrow-down-s",className:K("size-3.5 shrink-0 text-muted-foreground transition-transform",_&&"-rotate-90")})]})]})},[k,o,w]),A=a.useCallback((f,j,_)=>{const H=P.has(Ct(f.id,j.path)),te=j.files.map(ae=>ae.path),J=r||te.some(ae=>s.has(ae));return t.jsxs("div",{className:K("group flex items-center gap-2 py-1.5",ut),style:{paddingLeft:`${_*yn}px`},children:[t.jsxs("button",{type:"button",onClick:()=>E(f.id,j.path),className:"flex min-w-0 flex-1 items-center gap-2 rounded text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":H?`Collapse directory ${j.path}`:`Expand directory ${j.path}`,children:[H?t.jsx(V,{name:"folder-open-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}):t.jsx(V,{name:"folder-3-fill",className:"h-4 w-4 flex-shrink-0 text-primary/60"}),t.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",title:j.path,children:j.name}),t.jsx("span",{className:"ml-auto shrink-0 typography-micro text-muted-foreground",children:j.files.length})]}),f.showRevertActions!==!1&&c?t.jsx("button",{type:"button",onClick:()=>v({path:j.path,paths:te,count:te.length}),disabled:J,className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] disabled:cursor-not-allowed disabled:opacity-50","aria-label":`Revert changes in ${j.path}`,title:"Revert folder changes",children:J?t.jsx(V,{name:"loader-4",className:"size-3.5 animate-spin"}):t.jsx(V,{name:"arrow-go-back",className:"size-3.5"})}):null,t.jsx("button",{type:"button",onClick:()=>f.onActionAll(j.files.map(ae=>ae.path)),className:"flex size-5 shrink-0 items-center justify-center rounded typography-micro font-semibold text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)]","aria-label":f.actionSymbol==="+"?`Stage all changes in ${j.path}`:`Unstage all changes in ${j.path}`,title:f.actionSymbol==="+"?`Stage all changes in ${j.path}`:`Unstage all changes in ${j.path}`,children:f.actionSymbol})]})},[P,r,c,s,E]),G=a.useCallback((f,j)=>{if(f.type==="revert-all")return t.jsx("div",{className:K("flex justify-end py-2",ut),children:t.jsxs(re,{variant:"ghost",size:"sm",onClick:()=>F(!0),disabled:r,className:"gap-1.5 text-[var(--status-error)] hover:bg-[var(--status-error)]/10 hover:text-[var(--status-error)]",children:[t.jsx(V,{name:"arrow-go-back",className:"size-3.5"}),"Revert all"]})});const _=x[f.groupIndex];if(!_)return null;if(f.type==="header")return X(_,j);if(f.type==="directory")return A(_,f.directory,f.depth);const H=f.file;return t.jsx(go,{file:H,actionLabel:_.getActionLabel(H.path),actionSymbol:_.actionSymbol,onAction:()=>_.onActionFile(H.path),stats:n?.[H.path],onViewDiff:()=>_.onViewDiff(H.path),onRevert:()=>_.onRevertFile(H.path),isReverting:s.has(H.path)||r,rowPaddingClassName:ut,indentPx:f.depth*yn,actionAtStart:!m,showRevert:_.showRevertActions!==!1})},[n,r,m,A,X,s,x]),Y=a.useCallback(f=>{const j=b[f],_=b[f-1];return!j||!_||j.type!=="file"&&j.type!=="directory"||_.type!=="file"&&_.type!=="directory"?!1:_.groupIndex===j.groupIndex},[b]);return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"relative flex h-full min-h-0 w-full flex-col overflow-hidden",children:[t.jsx(It,{ref:u,className:"overlay-scrollbar-target overlay-scrollbar-container min-h-0 w-full flex-1 overflow-x-hidden overflow-y-auto",children:y?t.jsx("div",{style:{height:B.getTotalSize(),position:"relative"},children:g.map(f=>{const j=b[f.index];return j?t.jsx("div",{"data-index":f.index,ref:B.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${f.start}px)`},className:K(Y(f.index)&&"before:pointer-events-none before:absolute before:left-0 before:right-2 before:top-0 before:border-t before:border-border/60"),children:G(j,f.index===0)},j.key):null})}):t.jsx("div",{role:"list","aria-label":"Changed files",children:b.map((f,j)=>t.jsx("div",{className:K("relative",Y(j)&&"before:pointer-events-none before:absolute before:left-0 before:right-2 before:top-0 before:border-t before:border-border/60"),children:G(f,j===0)},f.key))})}),t.jsx(wr,{containerRef:u,disableHorizontal:!0})]}),t.jsx(Yt,{open:U,onOpenChange:f=>{!r&&!f&&F(!1)},children:t.jsxs(Jt,{className:"max-w-md",children:[t.jsxs(Qt,{children:[t.jsx(Zt,{children:"Revert all changes?"}),t.jsx(en,{children:C===1?`Revert ${C} changed file? This cannot be undone.`:`Revert ${C} changed files? This cannot be undone.`})]}),t.jsxs(tn,{children:[t.jsx(re,{variant:"outline",size:"sm",onClick:()=>F(!1),disabled:r,children:"Cancel"}),t.jsx(re,{variant:"destructive",size:"sm",onClick:()=>{q()},disabled:r,children:r?"Reverting...":"Revert all"})]})]})}),t.jsx(Yt,{open:!!h,onOpenChange:f=>{!O&&!f&&v(null)},children:t.jsxs(Jt,{className:"max-w-md",children:[t.jsxs(Qt,{children:[t.jsx(Zt,{children:"Revert folder changes?"}),t.jsx(en,{children:h?h.count===1?`This will discard local changes in ${h.count} file under ${h.path}.`:`This will discard local changes in ${h.count} files under ${h.path}.`:null})]}),t.jsxs(tn,{children:[t.jsx(re,{variant:"outline",size:"sm",onClick:()=>v(null),disabled:O,children:"Cancel"}),t.jsx(re,{variant:"destructive",size:"sm",onClick:()=>{Z()},disabled:O||!h,children:O?"Reverting...":"Revert folder"})]})]})})]})},wo=Pr(()=>be(()=>import("./DiffView-DGD9DMS7.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,110,111,112,113,114,115,116,117,118])).then(e=>({default:e.DiffView}))),ko=e=>(e||"").replace(/\\/g,"/").replace(/\/+$/g,""),jo=e=>{const n=e.index?.trim();return!!(n&&n!=="?")},So=e=>{const n=e.working_dir?.trim(),s=e.index?.trim();return!!(n||s==="?")},vn=(e,n)=>n?`${e}\0staged`:e,Co=({onClose:e,initialDiffPath:n,initialDiffStaged:s=!1})=>{const{git:r}=Hn(),o=ko(Dt()??null),i=kr(o||null),l=jr(o||null),c=Sr(o||null),u=ke(T=>T.setActiveDirectory),d=ke(T=>T.ensureAll),m=ke(T=>T.fetchStatus),x=ke(T=>T.fetchBranches),k=ke(T=>T.prefetchDiffs),N=ke(T=>T.getDiff),P=ke(T=>T.setDiff),[R,U]=a.useState(()=>n?{type:"diff",path:n,staged:s}:{type:"list"});a.useEffect(()=>{n&&U(T=>T.type==="diff"&&T.path===n&&T.staged===s?T:{type:"diff",path:n,staged:s})},[n,s]);const[F,h]=a.useState(null),[v,L]=a.useState(null),[$,b]=a.useState(""),[S,y]=a.useState(new Set),[B,g]=a.useState(!1),[I,w]=a.useState(!1),[E,p]=a.useState([]),[C,O]=a.useState([]),[q,Z]=a.useState([]),[X,A]=a.useState(null),[G,Y]=a.useState(null),[f,j]=a.useState(0),_=a.useMemo(()=>{const T=i?.files??[],M=new Map;for(const W of T)M.set(W.path,W);return Array.from(M.values()).sort((W,ee)=>W.path.localeCompare(ee.path))},[i?.files]),H=a.useMemo(()=>_.filter(jo),[_]),te=a.useMemo(()=>_.filter(So),[_]),J=a.useMemo(()=>{if(q.length>0)return q;const T=i?.tracking?.includes("/")?i.tracking.split("/")[0]:null;return T||X?[{name:T||"origin",fetchUrl:X??"",pushUrl:X??""}]:[]},[X,q,i?.tracking]),ae=ke(a.useCallback(T=>!o||R.type!=="diff"?null:T.directories.get(o)?.diffCache.get(vn(R.path,R.staged))??null,[o,R])),Te=a.useMemo(()=>R.type!=="diff"?null:_.find(T=>T.path===R.path)??null,[_,R]),ue=a.useCallback(async(T=!0)=>{if(o)try{await Promise.all([m(o,r),x(o,r)])}catch(M){T&&oe.error(M instanceof Error?M.message:"Failed to refresh repository")}},[o,x,m,r]),ye=a.useCallback(async()=>{if(!o){Z([]),A(null);return}try{const[T,M]=await Promise.all([r.getRemotes(o).catch(()=>[]),r.getRemoteUrl?r.getRemoteUrl(o).catch(()=>null):Promise.resolve(null)]);Z(T),A(M)}catch{Z([]),A(null)}},[o,r]);a.useEffect(()=>{o&&(u(o),d(o,r))},[o,d,r,u]),a.useEffect(()=>{ye()},[ye]),a.useEffect(()=>{if(!o||_.length===0)return;const T=Array.from(new Set([...H.map(W=>W.path),...C,..._.slice(0,20).map(W=>W.path)])).filter(Boolean);if(T.length===0)return;const M=window.setTimeout(()=>{k(o,r,T,{maxFiles:40})},120);return()=>window.clearTimeout(M)},[_,o,r,k,H,C]),a.useEffect(()=>{if(R.type!=="diff"){Y(null);return}const T=vn(R.path,R.staged);if(!o||N(o,T)){Y(null);return}let M=!1;const W=rt();return Y(null),r.getGitFileDiff(o,{path:R.path,staged:R.staged||void 0}).then(ee=>{M||P(o,T,{original:ee.original??"",modified:ee.modified??"",isBinary:ee.isBinary},W)}).catch(ee=>{M||Y(ee instanceof Error?ee.message:String(ee))}),()=>{M=!0}},[o,f,N,r,R,P]);const se=async(T,M)=>{if(o){h(T);try{const W=ee=>{const D=`${ee.name}/`,he=i?.tracking?.startsWith(D)?i.tracking.slice(D.length):void 0;return{remote:ee.name,branch:he,rebase:!0}};if(T==="fetch"){if(!M)throw new Error("No remote available");await r.gitFetch(o,{remote:M.name}),oe.success(`Fetched from ${M.name}`)}else if(T==="sync"){if(!M)throw new Error("No remote available");await r.gitFetch(o,{remote:M.name});const ee=await r.getGitStatus(o);if((ee.behind??0)>0){if((ee.files?.length??0)>0){oe.error("Commit or stash your changes before syncing");return}await r.gitPull(o,W(M))}((await r.getGitStatus(o)).ahead??0)>0&&await r.gitPush(o),oe.success("Already up to date")}await ue(!1),await ye()}catch(W){oe.error(W instanceof Error?W.message:"Sync Changes failed")}finally{h(null)}}},z=a.useCallback(async(T,M)=>{if(!(!o||T.length===0))try{M==="stage"?T.length>1?await Cr(o,T):await Er(o,T[0]):T.length>1?await Nr(o,T):await Rr(o,T[0]),await ue(!1)}catch(W){oe.error(W instanceof Error?W.message:M==="stage"?"Failed to stage changes":"Failed to unstage changes")}},[o,ue]),Q=a.useCallback((T,M=!1)=>{U({type:"diff",path:T,staged:M})},[]),ne=a.useCallback(async T=>{if(o){y(M=>new Set(M).add(T));try{await r.revertGitFile(o,T),oe.success(`Reverted ${T}`),await ue(!1)}catch(M){oe.error(M instanceof Error?M.message:"Failed to revert changes")}finally{y(M=>{const W=new Set(M);return W.delete(T),W})}}},[o,r,ue]),we=a.useCallback(async T=>{if(!o||T.length===0||B)return;const M=Array.from(new Set(T));g(!0),y(new Set(M));try{await Promise.all(M.map(W=>r.revertGitFile(o,W))),await ue(!1),oe.success(M.length===1?`Reverted ${M.length} file`:`Reverted ${M.length} files`)}catch(W){oe.error(W instanceof Error?W.message:"Failed to revert changes")}finally{y(new Set),g(!1)}},[o,r,B,ue]),ve=a.useCallback(T=>{const M=T.map(W=>W.trim()).filter(Boolean);if(M.length===0){p([]);return}b(W=>`${W.trim()}${W.trim()?`
|
|
12
12
|
|
|
13
13
|
`:""}${M.join(`
|
|
14
|
-
`)}`.trim()),p([])},[]),Pe=a.useCallback(async()=>{if(!o)return;const T=H.map(M=>M.path).sort();if(T.length===0){oe.error("Select at least one file to describe");return}w(!0);try{const{message:M}=await Tr(o,T);b(M.subject?.trim()??""),p(Array.isArray(M.highlights)?M.highlights:[])}catch(M){oe.error(M instanceof Error?M.message:"Failed to generate commit message")}finally{w(!1)}},[o,H]),ot=async(T={})=>{if(!o)return;if(!$.trim()){oe.error("Enter a commit message");return}const M=H.map(W=>W.path).sort();if(M.length===0){oe.error("Select at least one file to commit");return}L(T.pushAfter?"commitAndPush":"commit");try{if(await r.createGitCommit(o,$.trim(),{files:M}),oe.success("Commit created"),b(""),p([]),T.pushAfter){const W=i?.tracking?.split("/")[0],ee=J.find(lt=>lt.name===W)??J[0];if(!ee)throw new Error("No remote available");h("sync");const D=`${ee.name}/`,he=i?.tracking?.startsWith(D)?i.tracking.slice(D.length):void 0;await r.gitFetch(o,{remote:ee.name}),((await r.getGitStatus(o)).behind??0)>0&&await r.gitPull(o,{remote:ee.name,branch:he,rebase:!0}),((await r.getGitStatus(o)).ahead??0)>0&&await r.gitPush(o),await ue(!1),await ye()}else await ue(!1)}catch(W){oe.error(W instanceof Error?W.message:"Failed to create commit")}finally{L(null),T.pushAfter&&h(null)}},xt=a.useMemo(()=>{const T=[];return H.length>0&&T.push({id:"staged",title:"Staged",entries:H,actionSymbol:"-",actionAllLabel:"Unstage all changes",getActionLabel:M=>`Unstage ${M}`,onActionFile:M=>{z([M],"unstage")},onActionAll:M=>{z(M,"unstage")},onViewDiff:M=>Q(M,!0),onRevertFile:ne,showRevertActions:!1,accent:!0}),te.length>0&&T.push({id:"unstaged",title:"Changes",entries:te,actionSymbol:"+",actionAllLabel:"Stage all changes",getActionLabel:M=>`Stage ${M}`,onActionFile:M=>{z([M],"stage")},onActionAll:M=>{z(M,"stage")},onViewDiff:M=>Q(M,!1),onRevertFile:ne}),T},[ne,Q,z,H,te]),qe=T=>t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[t.jsx("div",{className:"flex shrink-0 items-center gap-2 px-3 py-2",children:t.jsx("p",{className:"min-w-0 flex-1 truncate typography-ui-label text-muted-foreground",children:i?.current||o||""})}),t.jsx("div",{className:"min-h-0 flex-1",children:T})]});return o?c&&l===null?qe(t.jsx(Ee,{loading:!0,message:"Checking repository..."})):l===!1?qe(t.jsx(a.Suspense,{fallback:t.jsx(Ee,{loading:!0,message:"Loading last turn changes..."}),children:t.jsx(wo,{diffScope:"turn",hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,flushContent:!0})})):R.type==="diff"?t.jsx(Eo,{path:R.path,diff:ae,fileExists:!!Te,error:G,onBack:()=>U({type:"list"}),onRetry:()=>j(T=>T+1)}):t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[t.jsxs("div",{className:"flex shrink-0 items-center gap-2 px-3 py-2",children:[e?t.jsx("button",{type:"button",className:"flex size-9 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","aria-label":"Close",onClick:e,style:{touchAction:"manipulation"},children:t.jsx(V,{name:"close",className:"size-4"})}):null,t.jsx("p",{className:"min-w-0 flex-1 truncate typography-ui-label text-muted-foreground",children:i?.current||o}),t.jsx(Fs,{syncAction:F,remotes:J,onFetch:T=>{se("fetch",T)},onSync:T=>{se("sync",T)},disabled:v!==null||c,aheadCount:i?.ahead??0,behindCount:i?.behind??0,trackingRemoteName:i?.tracking?.split("/")[0],hasUncommittedChanges:_.length>0})]}),_.length>0?t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[t.jsx("div",{className:"min-h-0 flex-1 overflow-hidden px-3 pt-2",children:t.jsx(vo,{groups:xt,diffStats:i?.diffStats,revertingPaths:S,onRevertAll:we,isRevertingAll:B,headerBackgroundClassName:"bg-transparent",onVisiblePathsChange:O})}),t.jsx("div",{className:"shrink-0 border-t border-border/40 px-3 pb-3 pt-3",children:t.jsx(da,{stagedCount:H.length,commitMessage:$,onCommitMessageChange:b,generatedHighlights:E,onInsertHighlights:ve,onGenerateMessage:Pe,isGeneratingMessage:I,onCommit:()=>{ot({pushAfter:!1})},onCommitAndPush:()=>{ot({pushAfter:!0})},commitAction:v,gitmojiEnabled:!1,onOpenGitmojiPicker:()=>{}})})]}):t.jsx("div",{className:"min-h-0 flex-1",children:t.jsx(Ee,{icon:!0,message:"Working tree clean",description:"There are no changed files in this workspace."})})]}):qe(t.jsx(Ee,{message:"Select a session or directory to view Git status"}))},Ee=({message:e,description:n,loading:s=!1,icon:r=!1})=>t.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center",children:t.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-2",children:[s?t.jsx(V,{name:"loader-4",className:"size-5 animate-spin text-muted-foreground"}):null,r?t.jsx(V,{name:"git-branch",className:"size-6 text-muted-foreground"}):null,t.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e}),n?t.jsx("p",{className:"typography-meta text-muted-foreground",children:n}):null]})}),Eo=({path:e,diff:n,fileExists:s,error:r,onBack:o,onRetry:i})=>{const l=a.useMemo(()=>Ar(e)||"text",[e]);return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[t.jsxs("header",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2 text-foreground",children:[t.jsx("button",{type:"button",className:"flex size-9 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back",onClick:o,children:t.jsx(V,{name:"arrow-left",className:"size-4"})}),t.jsx("div",{className:"min-w-0 flex-1 px-2",children:t.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:e})})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:s?r?t.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center",children:t.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-3",children:[t.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),t.jsx("p",{className:"typography-meta text-muted-foreground",children:r}),t.jsx(re,{type:"button",size:"sm",variant:"outline",onClick:i,children:"Retry"})]})}):n?n.isBinary?t.jsx(Ee,{icon:!0,message:"Content of this file cannot be viewed."}):Ir(e)?t.jsx(Ee,{icon:!0,message:"Image diffs are not available in mobile Changes yet."}):t.jsx(It,{className:"h-full overflow-y-auto overflow-x-hidden p-3","data-diff-virtual-root":!0,"data-diff-virtual-content":!0,children:t.jsx(fa,{original:n.original,modified:n.modified,language:l,fileName:e,renderSideBySide:!1,wrapLines:!0,layout:"inline"})}):t.jsx(Ee,{loading:!0,message:"Loading diff..."}):t.jsx(Ee,{icon:!0,message:"File is no longer changed",description:"Go back to Changes and refresh the list."})})]})},fe=e=>(e||"").replace(/\\/g,"/").replace(/\/+$/g,""),Fe=e=>{const n=fe(e);return!n||n==="/"?n||"/":n.split("/").filter(Boolean).at(-1)??n},gs=e=>{const n=fe(e);if(!n||n==="/")return null;const s=n.lastIndexOf("/");if(s<0)return null;if(s===0)return"/";const r=n.slice(0,s);return/^[A-Za-z]:$/.test(r)?`${r}/`:r},wn=(e,n)=>{const s=fe(e),r=fe(n);return!s||!r?!1:s===r||s.startsWith(`${r}/`)},kn=(e,n)=>{const s=fe(e);if(!s)return fe(n);if(s.startsWith("/")||/^[A-Za-z]:(\/|$)/.test(s))return s;const r=fe(n);return r?`${r}/${s}`:s},No=(e,n)=>{const s=fe(e),r=fe(n);if(!s||s===r)return!1;const o=gs(s);return o?r&&wn(s,r)?wn(o,r):!0:!1},Ro=a.lazy(()=>be(()=>import("./FilesView-BD_h3EVr.js"),__vite__mapDeps([119,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,111,112,113,120,121,122,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,123,124,116,117,125,126,114,115])).then(e=>({default:e.FilesView}))),To=(e,n)=>{const s=fe(e),r=fe(n);return!r||s===r?Fe(s):s.startsWith(`${r}/`)?s.slice(r.length+1):s},Po=e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;const n=["KB","MB","GB"];let s=e/1024;for(const r of n){if(s<1024||r===n[n.length-1])return`${s.toFixed(s>=10?0:1)} ${r}`;s/=1024}return""},Ao=({onClose:e})=>{const{files:n}=Hn(),s=Es(p=>p.setSelectedPath),r=fe(Dt()??null),[o,i]=a.useState(()=>({type:"browser",directory:r})),[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,x]=a.useState(null),[k,N]=a.useState(""),[P,R]=a.useState([]),[U,F]=a.useState(!1),h=a.useRef(0);a.useEffect(()=>{r&&i(p=>p.type==="browser"&&p.directory?p:{type:"browser",directory:r})},[r]);const v=o.type==="browser"?o.directory:o.returnDirectory,L=a.useCallback(async p=>{if(!p)return;const C=h.current+1;h.current=C,d(!0),x(null);try{const O=await n.listDirectory(p);if(h.current!==C)return;c(O.entries.slice().sort((Z,X)=>Z.isDirectory!==X.isDirectory?Z.isDirectory?-1:1:Z.name.localeCompare(X.name)));const q=fe(O.directory);q&&q!==fe(p)&&i(Z=>Z.type==="browser"&&Z.directory!==q?{type:"browser",directory:q}:Z)}catch(O){if(h.current!==C)return;c([]),x(O instanceof Error?O.message:"Failed to load files")}finally{h.current===C&&d(!1)}},[n]);a.useEffect(()=>{o.type==="browser"&&L(o.directory)},[L,o]),a.useEffect(()=>{if(o.type!=="browser")return;const p=k.trim();if(!p){R([]),F(!1);return}let C=!1;const O=window.setTimeout(()=>{F(!0),n.search({directory:o.directory,query:p,maxResults:40}).then(q=>{C||R(q)}).catch(()=>{C||R([])}).finally(()=>{C||F(!1)})},250);return()=>{C=!0,window.clearTimeout(O)}},[n,k,o]);const $=p=>{N(""),i({type:"browser",directory:p})},b=p=>{s(r,p),i({type:"file",path:p,returnDirectory:v||r})},S=de(p=>p.pendingFileFocusPath),y=de(p=>p.pendingFileNavigation);if(a.useEffect(()=>{const p=fe(y?.path??S??"");!p||!r||p!==r&&!p.startsWith(`${r}/`)||(s(r,p),i({type:"file",path:p,returnDirectory:r}),S&&de.getState().setPendingFileFocusPath(null))},[S,y,r,s]),!r)return t.jsx(et,{message:"Select a project to browse files."});if(o.type==="file")return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[t.jsxs("header",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2 text-foreground",children:[t.jsx("button",{type:"button",className:"flex size-9 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back",onClick:()=>i({type:"browser",directory:o.returnDirectory}),style:{touchAction:"manipulation"},children:t.jsx(sn,{className:"size-4"})}),t.jsx("div",{className:"min-w-0 flex-1",children:t.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:Fe(o.path)})})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:t.jsx(pe,{children:t.jsx(a.Suspense,{fallback:t.jsx(et,{loading:!0,message:"Loading..."}),children:t.jsx(Ro,{mode:"editor-only"})})})})]});const B=o.directory===r?"Project files":Fe(o.directory),g=k.trim()?P:[],I=No(o.directory,r)?gs(o.directory):null,w=!!I&&!k.trim(),E=I===r?"Project files":Fe(I??"");return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[t.jsxs("header",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2 text-foreground",children:[e?t.jsx("button",{type:"button",className:"flex size-9 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","aria-label":"Close",onClick:e,style:{touchAction:"manipulation"},children:t.jsx(ha,{className:"size-4"})}):null,w&&I?t.jsx("button",{type:"button",className:"flex size-9 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","aria-label":`Back to ${Fe(I)}`,onClick:()=>$(I),style:{touchAction:"manipulation"},children:t.jsx(sn,{className:"size-4"})}):null,t.jsx("div",{className:"min-w-0 flex-1 px-1",children:t.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:B})}),t.jsx("button",{type:"button",className:"flex size-9 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","aria-label":"Refresh files",onClick:()=>{L(o.directory)},style:{touchAction:"manipulation"},children:t.jsx(ma,{className:K("size-4",u&&"animate-spin")})})]}),t.jsx("div",{className:"shrink-0 px-3 pb-2 pt-1",children:t.jsxs("div",{className:"relative",children:[t.jsx(pa,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),t.jsx(Dr,{value:k,onChange:p=>N(p.target.value),placeholder:"Search files",className:"h-11 pl-9"})]})}),t.jsx(It,{className:"min-h-0 w-full flex-1 overflow-y-auto pb-3",children:m?t.jsx(et,{message:m}):k.trim()?t.jsx(Io,{results:g,isSearching:U,onOpenFile:b}):t.jsxs("div",{className:"flex w-full min-w-0 flex-col",children:[w&&I?t.jsxs("button",{type:"button",className:Wn,"aria-label":`Up one level to ${E}`,onClick:()=>$(I),style:{touchAction:"manipulation"},children:[t.jsx(V,{name:"arrow-left",className:K(Nt(!0),"text-muted-foreground")}),t.jsx("span",{className:K(Vn(!0),"flex-1 text-muted-foreground"),children:"Up one level"})]}):null,l.length===0&&!u?t.jsx("div",{className:"px-3 py-8 text-center typography-ui-label text-muted-foreground",children:"This directory is empty."}):null,l.map(p=>t.jsx(ys,{name:p.name,path:p.path,directory:p.isDirectory,meta:p.isDirectory?void 0:Po(p.size),onClick:()=>p.isDirectory?$(kn(p.path,o.directory||r)):b(kn(p.path,o.directory||r))},p.path))]})})]})},ys=({name:e,path:n,directory:s,meta:r,onClick:o})=>t.jsxs("button",{type:"button",className:Wn,onClick:o,style:{touchAction:"manipulation"},children:[s?t.jsx(ba,{className:K(Nt(!0),"text-primary/80")}):t.jsx(Fn,{filePath:n,className:Nt(!0)}),t.jsx("span",{className:K(Vn(!0),"flex-1 text-foreground"),children:e}),r?t.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:r}):null,s?t.jsx(xa,{className:"size-4 shrink-0 text-muted-foreground/60"}):null]}),Io=({results:e,isSearching:n,onOpenFile:s})=>{const r=fe(Dt()??null);return n?t.jsx(et,{loading:!0,message:"Loading..."}):e.length===0?t.jsx(et,{message:"No files found."}):t.jsx("div",{className:"flex w-full min-w-0 flex-col",children:e.map(o=>t.jsx(ys,{name:Fe(o.path),path:o.path,directory:!1,meta:To(o.path,r),onClick:()=>s(o.path)},o.path))})},et=({message:e,loading:n=!1})=>t.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center",children:t.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-2",children:[n?t.jsx(ga,{className:"size-5 animate-spin text-muted-foreground"}):t.jsx(ya,{className:"size-6 text-muted-foreground"}),t.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e})]})}),jn="mobile-surface-root",Do=16,Lo=[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal"},{id:"notes",label:"Notes",icon:"sticky-note"}],Sn=a.memo(function({open:n,onClose:s,tab:r,onTabChange:o,pendingChangesDiff:i,variant:l="drawer",drawerRefExternal:c,scrimRefExternal:u,rootRefExternal:d}){const m=a.useRef(null),x=a.useRef(null),k=a.useRef(null),N=a.useRef(null),P=c??x,R=u??k,U=d??N,F=a.useCallback(E=>{N.current=E,d&&(d.current=E)},[d]),h=a.useCallback(()=>{const E=typeof document<"u"?document.activeElement:null;E instanceof HTMLElement&&U.current?.contains(E)&&E.blur(),s()},[s]),[v,L]=a.useState(!1),[$,b]=a.useState(n),S=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[y,B]=a.useState(()=>new Set);if(a.useEffect(()=>{n&&B(E=>{if(E.has(r))return E;const p=new Set(E);return p.add(r),p})},[n,r]),typeof document<"u"&&!m.current){let E=document.getElementById(jn);E||(E=document.createElement("div"),E.id=jn,document.body.appendChild(E)),m.current=E}if(a.useEffect(()=>{if(n){b(!0);const p=window.setTimeout(()=>L(!0),S?0:Do);return()=>window.clearTimeout(p)}L(!1);const E=window.setTimeout(()=>b(!1),Xe+40);return()=>window.clearTimeout(E)},[n,S]),a.useEffect(()=>{if(!n)return;const E=document.body.style.overflow;l==="drawer"&&(document.body.style.overflow="hidden");const p=C=>{C.key==="Escape"&&r!=="terminal"&&h()};return document.addEventListener("keydown",p),()=>{l==="drawer"&&(document.body.style.overflow=E),document.removeEventListener("keydown",p)}},[h,n,r,l]),a.useEffect(()=>{const E=U.current;if(!E||n||l!=="drawer")return;const p=document.activeElement;p&&E.contains(p)&&p.blur()},[n,l]),hs({side:"right",enabled:l==="drawer",open:n,drawerRef:P,scrimRef:R,onClose:h,widthRatio:1,prefersReducedMotion:S}),l==="drawer"&&!m.current)return null;const g=S?0:Xe,I=t.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto",role:"tablist","aria-label":"Workspace","data-no-drawer-swipe":"true",children:Lo.map(E=>{const p=r===E.id;return t.jsxs("button",{type:"button",role:"tab","aria-selected":p,onClick:()=>o(E.id),className:K("flex min-w-0 flex-1 items-center justify-center gap-1 rounded-lg px-1.5 py-2 typography-ui-label transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",p?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[t.jsx(V,{name:E.icon,className:"size-4 shrink-0"}),t.jsx("span",{className:"truncate",children:E.label})]},E.id)})}),w=t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-2 px-2",children:[I,t.jsx("button",{type:"button",onClick:h,"aria-label":"Close workspace panel",className:"flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(V,{name:"close",className:"size-4"})})]}),t.jsxs("div",{className:"min-h-0 flex-1 overflow-hidden",children:[y.has("changes")?t.jsx("div",{className:K("h-full",r!=="changes"&&"hidden"),children:t.jsx(pe,{children:t.jsx(Co,{initialDiffPath:i?.path??null,initialDiffStaged:i?.staged===!0})})},i?`changes:${i.path}:${i.staged}`:"changes"):null,y.has("files")?t.jsx("div",{className:K("h-full",r!=="files"&&"hidden"),children:t.jsx(pe,{children:t.jsx(Ao,{})})}):null,y.has("terminal")?t.jsx("div",{className:K("h-full",r!=="terminal"&&"hidden"),children:t.jsx(pe,{children:t.jsx(Hs,{visible:n&&r==="terminal"})})}):null,y.has("notes")?t.jsx("div",{className:K("h-full",r!=="notes"&&"hidden"),children:t.jsx(pe,{children:t.jsx(Ws,{onActionComplete:h})})}):null]})]});return l==="panel"?t.jsx("div",{className:"flex h-full min-h-0 flex-col bg-sidebar",children:w}):We.createPortal(t.jsxs("div",{ref:F,className:"fixed inset-0 z-50",inert:!n,style:{pointerEvents:n?"auto":"none",visibility:$?"visible":"hidden"},"data-mobile-workspace-root":"true",children:[t.jsx("button",{ref:R,type:"button",className:"absolute inset-0 cursor-default bg-black/70","aria-label":"Close workspace panel",onClick:h,tabIndex:n?0:-1,style:{opacity:v?1:0,transition:g?`opacity ${g}ms ${Re}`:"none"},"data-mobile-workspace-scrim":"true"}),t.jsx("section",{ref:P,role:"dialog","aria-modal":"true","aria-label":"Open workspace panel",className:"oc-keyboard-inset-surface absolute inset-y-0 right-0 z-10 flex h-full w-full flex-col bg-sidebar",style:{paddingTop:"var(--oc-safe-area-top, 0px)",transform:v?"none":"translateX(100%)",transition:g?`transform ${g}ms ${Re}`:"none",touchAction:"pan-x pan-y"},"data-mobile-workspace-drawer":"true",children:w})]}),m.current)}),at=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0?!0:window.location.protocol==="capacitor:",_o=()=>{a.useEffect(()=>{if(!at())return;let e=!1;const n=[],s=document.documentElement;s.classList.add("oc-capacitor-app"),window.Capacitor?.getPlatform?.()==="android"&&s.classList.add("oc-platform-android"),n.push(Lr());const o=i=>{s.style.setProperty("--oc-keyboard-inset",`${Math.max(0,Math.round(i))}px`)};return be(()=>import("./vendor-capacitor-status-bar-B-N0EOVk.js"),__vite__mapDeps([127,128])).then(async({StatusBar:i,Style:l})=>{if(e)return;const c=window.Capacitor?.getPlatform?.(),u=async()=>{if(c==="android"){const k=document.documentElement.classList.contains("dark"),N=(k?localStorage.getItem("splashBgDark"):localStorage.getItem("splashBgLight"))||(k?"#171515":"#fffdf4");await i.setOverlaysWebView({overlay:!1}).catch(()=>{}),await i.setBackgroundColor({color:N}).catch(()=>{}),await i.setStyle({style:k?l.Dark:l.Light}).catch(()=>{}),await i.show().catch(()=>{});return}await i.setStyle({style:l.Default}).catch(()=>{}),await i.setOverlaysWebView({overlay:!0}).catch(()=>{}),await i.show().catch(()=>{})};await u();const d=window.setTimeout(()=>{u()},400);n.push(()=>window.clearTimeout(d));const{App:m}=await be(async()=>{const{App:k}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:k}},__vite__mapDeps([129,8,128])),x=await m.addListener("appStateChange",({isActive:k})=>{k&&u()});if(e){x.remove();return}n.push(()=>{x.remove()})}).catch(()=>{}),be(()=>import("./vendor-capacitor-keyboard-CYccoJjr.js"),__vite__mapDeps([130,128])).then(async({Keyboard:i})=>{if(e)return;if(window.Capacitor?.getPlatform?.()==="android"){const g=await i.addListener("keyboardWillShow",C=>{nn(C.keyboardHeight),s.classList.add("oc-keyboard-open"),window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!0}}))}),I=await i.addListener("keyboardDidShow",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!0}}))}),w=await i.addListener("keyboardWillHide",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-intent",{detail:{open:!1}})),s.classList.remove("oc-keyboard-open")}),E=await i.addListener("keyboardDidHide",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!1}}))}),p=()=>{g.remove(),I.remove(),w.remove(),E.remove()};if(e){p();return}n.push(p);return}await i.setAccessoryBarVisible({isVisible:!1}).catch(()=>{});const c=250,u=200,d="cubic-bezier(0.38, 0.7, 0.125, 1)";let m=null,x=null,k=0,N=!1,P=0,R=!1;const U=(g,I)=>{s.style.setProperty(g,`${Math.max(0,Math.round(I))}px`)},F=()=>{m!==null&&(window.clearTimeout(m),m=null)},h=(g,I)=>{window.dispatchEvent(new CustomEvent(g,{detail:I}))},v=()=>{const g=[],I=document.querySelector(".oc-mobile-composer");I&&g.push({el:I,factor:1});const w=document.querySelector(".oc-draft-center");return w&&g.push({el:w,factor:.5}),g},L=()=>{for(const{el:g}of v())g.style.transition="",g.style.transform=""},$=await i.addListener("keyboardWillShow",g=>{if(F(),nn(g.keyboardHeight),R=!0,k=g.keyboardHeight,!N){const w=document.querySelector(".oc-mobile-app-shell");P=w&&parseFloat(getComputedStyle(w).paddingBottom)||0}const I=Math.max(0,k-P);s.classList.remove("oc-kb-hide"),x!==null&&(window.clearTimeout(x),x=null),s.classList.add("oc-keyboard-open","oc-kb-animating","oc-kb-caret-hold"),o(k);for(const{el:w,factor:E}of v())w.style.transition=`transform ${c}ms ${d}`,w.style.transform=`translateY(${-I*E}px)`;U("--oc-kb-scroll-inset",I),h("oc:keyboard-settled",{open:!0}),h("oc:keyboard-anim",{phase:"show",slide:I,durationMs:c,easing:d}),m=window.setTimeout(()=>{m=null,s.classList.remove("oc-kb-animating"),U("--oc-kb-layout",k),N=!0,L(),h("oc:keyboard-settled",{open:!0}),x=window.setTimeout(()=>{x=null,s.classList.remove("oc-kb-caret-hold")},250)},c+20)}),b=()=>{if(!R)return;R=!1,F(),h("oc:keyboard-intent",{open:!1}),x!==null&&(window.clearTimeout(x),x=null),s.classList.remove("oc-kb-caret-hold");const g=Math.max(0,k-P);if(s.classList.remove("oc-keyboard-open"),o(0),U("--oc-kb-scroll-inset",0),N){s.classList.remove("oc-kb-animating"),U("--oc-kb-layout",0),N=!1;for(const{el:I,factor:w}of v())I.style.transition="none",I.style.transform=`translateY(${-g*w}px)`;document.querySelector(".oc-mobile-app-shell")?.offsetHeight}h("oc:keyboard-anim",{phase:"hide",slide:g,durationMs:u,easing:d}),s.classList.add("oc-kb-animating","oc-kb-hide");for(const{el:I}of v())I.style.transition=`transform ${u}ms ${d}`,I.style.transform="translateY(0px)";m=window.setTimeout(()=>{m=null,s.classList.remove("oc-kb-animating","oc-kb-hide"),L(),h("oc:keyboard-settled",{open:!1})},u+20)},S=await i.addListener("keyboardWillHide",b),y=g=>g instanceof HTMLElement&&(g.tagName==="TEXTAREA"||g.tagName==="INPUT"||g.isContentEditable),B=g=>{R&&y(g.target)&&(y(g.relatedTarget)||window.setTimeout(()=>{R&&(y(document.activeElement)||b())},0))};if(document.addEventListener("focusout",B,!0),e){F(),document.removeEventListener("focusout",B,!0),$.remove(),S.remove();return}n.push(F,()=>{x!==null&&(window.clearTimeout(x),x=null)},()=>document.removeEventListener("focusout",B,!0),()=>{$.remove()},()=>{S.remove()})}).catch(()=>{}),()=>{e=!0,n.forEach(i=>i()),_r(),s.classList.remove("oc-capacitor-app","oc-keyboard-open","oc-kb-animating","oc-kb-hide","oc-kb-caret-hold","oc-platform-android"),s.style.removeProperty("--oc-keyboard-inset"),s.style.removeProperty("--oc-kb-shift"),s.style.removeProperty("--oc-kb-layout"),s.style.removeProperty("--oc-kb-scroll-inset")}},[])},Mo=e=>{const n=a.useRef(!1);a.useEffect(()=>{if(!at())return;let s=!1;const r=[],o=()=>{n.current&&(n.current=!1,e())},i=()=>{if(document.visibilityState==="hidden"){n.current=!0;return}o()};return document.addEventListener("visibilitychange",i),r.push(()=>document.removeEventListener("visibilitychange",i)),be(()=>import("./vendor-capacitor-app-BrDJj9I_.js"),__vite__mapDeps([129,8,128])).then(async({App:l})=>{if(s)return;const c=await l.addListener("appStateChange",({isActive:d})=>{if(document.documentElement.classList.toggle("oc-native-app-active",d),!d){n.current=!0;return}o()}),u=await l.addListener("resume",o);if(s){c.remove(),u.remove();return}r.push(()=>{c.remove()},()=>{u.remove()})}).catch(()=>{}),()=>{s=!0,r.forEach(l=>l())}},[e])},zo=e=>{a.useEffect(()=>{if(!at())return;let n=!1,s=null;return be(()=>import("./vendor-capacitor-app-BrDJj9I_.js"),__vite__mapDeps([129,8,128])).then(async({App:r})=>{if(n)return;const o=await r.addListener("backButton",()=>{e()||r.minimizeApp().catch(()=>{})});if(n){o.remove();return}s=()=>{o.remove()}}).catch(()=>{}),()=>{n=!0,s?.()}},[e])};function Oo(e=2500){const{uiFont:n}=Mr(),[s,r]=a.useState(!1);return a.useEffect(()=>{let o=!1;const i=()=>{o||r(!0)},l=()=>{requestAnimationFrame(()=>requestAnimationFrame(i))},c=Promise.all([zr(n).catch(()=>{}),document.fonts?.ready?.then(()=>{}).catch(()=>{})??Promise.resolve(),va.catch(()=>{})]).then(()=>{}),u=new Promise(d=>{window.setTimeout(d,e)});return Promise.race([c,u]).then(l),()=>{o=!0}},[n,e]),s}const $o="pichamber",Uo=e=>e.replace(/^\/+|\/+$/g,""),Bo=e=>{const n=Uo(e.pathname).split("/").filter(Boolean);return e.host?[e.host,...n]:n};function Fo(e){if(typeof e!="string"||e.length===0)return null;let n;try{n=new URL(e)}catch{return null}if(n.protocol!==`${$o}:`)return null;const s=Bo(n),r=(s[0]??"").toLowerCase(),o=s.slice(1),i=n.searchParams;switch(r){case"session":{const l=o[0]||i.get("id")||"";return l?{type:"session",sessionId:l,directory:i.get("dir")??void 0}:null}case"new":case"new-session":return{type:"new-session",directory:i.get("dir")??void 0,projectId:i.get("project")??void 0,agent:i.get("agent")??void 0,model:i.get("model")??void 0};case"sessions":{const l=i.get("filter");return{type:"sessions",filter:l==="attention"||l==="recent"||l==="all"?l:void 0}}case"status":return{type:"status"};case"settings":return{type:"settings",section:o[0]||i.get("section")||void 0};case"changes":return{type:"changes",path:o.join("/")||i.get("path")||void 0,staged:i.get("staged")==="true"};case"view":{const l=(o[0]||"").toLowerCase();return l==="changes"?{type:"changes"}:l==="files"||l==="mcp"||l==="instances"||l==="update"?{type:"view",target:l}:null}default:return null}}let me={},bs=!1,Je=null;const Ho=e=>{switch(e.type){case"session":return ge.getState().setCurrentSession(e.sessionId,e.directory??null),!0;case"new-session":{const n=ge.getState();return n.openNewSessionDraft(),(e.directory||e.projectId)&&n.setNewSessionDraftTarget({directoryOverride:e.directory??null,projectId:e.projectId??null,selectedProjectId:e.projectId??null}),!0}case"sessions":return me.openSessions?(me.openSessions(e.filter),!0):!1;case"status":return me.openSessions?(me.openSessions(),!0):!1;case"view":return me.openView?(me.openView(e.target),!0):!1;case"changes":return me.openChanges?(me.openChanges({path:e.path,staged:e.staged}),!0):!1;case"settings":return me.openSettings?(me.openSettings(e.section),!0):!1}},Ht=()=>{if(!bs||!Je)return;const e=Je;Je=null,Ho(e)||(Je=e)},xs=e=>{Je=e,Ht()},Cn=e=>{const n=Fo(e);n&&xs(n)},Wo=e=>{bs=e,Ht()},Vo=e=>{a.useEffect(()=>(me=e,Ht(),()=>{me===e&&(me={})}),[e])},Ko=e=>{const{ready:n}=e;a.useEffect(()=>{Wo(n)},[n]),a.useEffect(()=>{if(!le())return;let s=!1;const r=[];return be(()=>import("./vendor-capacitor-app-BrDJj9I_.js"),__vite__mapDeps([129,8,128])).then(async({App:o})=>{if(s)return;const i=await o.addListener("appUrlOpen",l=>{Cn(l?.url)});if(s){i.remove();return}r.push(()=>{i.remove()})}).catch(()=>{}),be(()=>import("./vendor-capacitor-push-notifications-KNe1zSBF.js"),__vite__mapDeps([131,128])).then(async({PushNotifications:o})=>{if(s)return;const i=await o.addListener("pushNotificationActionPerformed",l=>{const c=l?.notification?.data,u=typeof c?.url=="string"?c.url:typeof c?.deeplink=="string"?c.deeplink:void 0;if(u){Cn(u);return}const d=typeof c?.sessionId=="string"?c.sessionId:void 0;d&&xs({type:"session",sessionId:d})});if(s){i.remove();return}r.push(()=>{i.remove()})}).catch(()=>{}),()=>{s=!0,r.forEach(o=>o())}},[])},En=e=>{const n=e.drawer.current,s=e.scrim.current,r=e.root.current;r&&(r.style.pointerEvents="auto",r.style.visibility="visible"),n&&(n.style.transition="none"),s&&(s.style.transition="none")},Nn=(e,n,s)=>{const r=e.drawer.current,o=e.scrim.current;if(r&&(r.style.transform=s>=.999?"none":`translateX(${(n==="left"?s-1:1-s)*100}%)`),o){o.style.opacity=String(s);const i=s>.01?"auto":"none";o.style.pointerEvents!==i&&(o.style.pointerEvents=i)}},Rn=(e,n,s)=>{const r=s.drawer.current,o=s.scrim.current,i=s.root.current;r&&(r.style.transition=`transform ${Xe}ms ${Re}`,r.style.transform=n?"none":e==="left"?"translateX(-100%)":"translateX(100%)"),o&&(o.style.transition=`opacity ${Xe}ms ${Re}`,o.style.opacity=n?"1":"0",o.style.pointerEvents=n?"auto":"none"),i&&(i.style.pointerEvents=n?"auto":"none",i.style.visibility=n?"visible":"")},Tn=e=>{const n=e.shell.current,s=e.inner.current;n&&(n.style.overflow="visible"),s&&(s.style.transition="none")},Pn=(e,n,s,r)=>{const o=e.inner.current;if(!o)return;const i=r==="left"?(n-1)*s:(1-n)*s;o.style.transform=n>=.999?"translateX(0)":`translateX(${i}px)`},An=(e,n,s,r,o)=>{const i=e.shell.current,l=e.inner.current;return!i||!l?void 0:(l.style.transition="transform 200ms cubic-bezier(0.22, 1, 0.36, 1)",l.style.transform=n?"translateX(0)":`translateX(${r==="left"?-s:s}px)`,window.setTimeout(()=>{l.style.transition="",l.style.transform="",i.style.overflow=""},220))},Go=()=>{if(typeof window>"u")return;const e=window.__PICHAMBER_APNS_ENV__;if(e==="development")return"sandbox";if(e==="production")return"production"},Xo=()=>{if(typeof window>"u")return!1;const n=window.Capacitor?.getPlatform?.();return n==="ios"||n==="android"},qo=e=>{const{enabled:n}=e,s=de(o=>o.nativeNotificationsEnabled),r=a.useRef(null);a.useEffect(()=>{if(!n||!s||!Xo())return;let o=!1;const i=[];return be(()=>import("./vendor-capacitor-push-notifications-KNe1zSBF.js"),__vite__mapDeps([131,128])).then(async({PushNotifications:l})=>{if(o)return;let c=await l.checkPermissions().catch(()=>null);if(c?.receive!=="granted"&&(c=await l.requestPermissions().catch(()=>null)),c?.receive!=="granted")return;const u=await l.addListener("registration",m=>{r.current=m.value,Et()?.push?.registerApnsToken?.({token:m.value,platform:_n(),environment:Go()})}),d=await l.addListener("registrationError",m=>{console.warn("[Push] APNs registration error:",m)});if(await l.register().catch(()=>{}),o){u.remove(),d.remove();return}i.push(()=>{u.remove()},()=>{d.remove()})}).catch(()=>{}),()=>{o=!0,i.forEach(l=>l())}},[n,s]),a.useEffect(()=>{if(s)return;const o=r.current;if(!o)return;r.current=null,Et()?.push?.unregisterApnsToken?.({token:o})},[s])},In=({side:e,isResizing:n,ariaLabel:s,handleProps:r})=>t.jsx("div",{className:K("absolute inset-y-0 z-50 w-6 cursor-col-resize touch-none",e==="left"?"right-0":"left-0"),role:"separator","aria-orientation":"vertical","aria-label":s,...r,children:t.jsx("div",{className:K("absolute inset-y-0 w-[3px] transition-colors",e==="left"?"right-0":"left-0",n&&"bg-[var(--interactive-border)]")})}),Yo=320,Jo=380,Dn=280,Qo=560,Zo=900;function Ln(e,n,s,r=Qo){const o=a.useRef(null),[i,l]=a.useState(()=>{if(typeof window>"u")return s;const v=Number.parseInt(window.localStorage.getItem(n)??"",10);return Number.isFinite(v)?Math.min(r,Math.max(Dn,v)):s}),[c,u]=a.useState(!1),d=a.useRef(0),m=a.useRef(i),x=a.useRef(null),k=a.useRef(null),N=a.useCallback(v=>Math.min(r,Math.max(Dn,Math.round(v))),[r]),P=a.useCallback(v=>{const L=o.current;L&&(L.style.width=`${v}px`,L.style.minWidth=`${v}px`,L.style.maxWidth=`${v}px`,L.style.setProperty("--oc-ipad-sidebar-width",`${v}px`))},[]),R=a.useCallback(v=>{try{v.currentTarget.setPointerCapture(v.pointerId)}catch{}k.current=v.pointerId,d.current=v.clientX,m.current=i,x.current=i,u(!0),v.preventDefault()},[i]),U=a.useCallback(v=>{if(k.current!==v.pointerId)return;const L=v.clientX-d.current,$=N(m.current+(e==="left"?L:-L));x.current!==$&&(x.current=$,P($))},[P,N,e]),F=a.useCallback(v=>{if(k.current!==v.pointerId)return;try{v.currentTarget.releasePointerCapture(v.pointerId)}catch{}const L=N(x.current??m.current);k.current=null,x.current=null,u(!1),l(L);try{window.localStorage.setItem(n,String(L))}catch{}},[N,n]),h=a.useMemo(()=>({onPointerDown:R,onPointerMove:U,onPointerUp:F,onPointerCancel:F}),[R,F,U]);return{asideRef:o,width:i,isResizing:c,handleProps:h}}const ei=1e3,ti=a.memo(nr),ni=({onActiveConnectionDeleted:e})=>{const[n,s]=a.useState(!1),[r,o]=a.useState(null),[i,l]=a.useState(!1),[c,u]=a.useState("changes"),[d,m]=a.useState("nav"),[x,k]=a.useState(null),N=a.useRef([]),P=a.useCallback(()=>{N.current.forEach(D=>window.clearTimeout(D)),N.current=[]},[]);a.useEffect(()=>()=>P(),[P]);const R=a.useRef(null),U=a.useRef(null),F=a.useRef(null),h=a.useRef(null),v=a.useRef(null),L=a.useRef(null),$=a.useRef(null),b=a.useRef(null),S=a.useRef(0),y=a.useRef(0),B=a.useCallback(D=>{P(),s(D)},[P]),g=a.useCallback(D=>{P(),l(D)},[P]),I=de(D=>D.setSettingsPage),w=de(D=>D.isArchivePageOpen),E=de(D=>D.setArchivePageOpen),p=de(D=>D.wideChatLayoutEnabled),C=Ue(D=>D.available),O=Ue(D=>D.runtimeType),q=a.useMemo(()=>at(),[]),Z=!q&&C&&(O==="desktop"||O==="web"),X=a.useCallback(()=>{o(null)},[]),A=a.useCallback(D=>{o(D)},[]),G=a.useCallback(()=>{g(!1)},[g]),Y=a.useCallback(D=>{m(D),A("settings")},[A]),{enabled:f,roomyForPanels:j}=Bn(),H=Jr()==="portrait",te=Qr(),J=de(D=>D.setSidebarOpen),ae=de(D=>D.isSidebarOpen),Te=a.useRef(!1);a.useLayoutEffect(()=>{f&&!Te.current&&J(Zr().roomyForPanels),!f&&Te.current&&J(!1),Te.current=f},[f,J]);const ue=a.useCallback(()=>{k(null),u("files"),g(!0)},[g]),ye=a.useCallback((D=null)=>{k(D),u("changes"),g(!0)},[g]),se=Ln("left","pichamber.ipad.leftSidebarWidth",Yo),z=Ln("right","pichamber.ipad.rightSidebarWidth",Jo,Zo),Q=j,ne=Q&&i?z.width:0,we=Js(f&&ae),ve=f&&ae?se.width:0,Pe=a.useCallback(D=>{i&&c===D?g(!1):(u(D),g(!0))},[i,c,g]),ot=a.useCallback(()=>{g(!i)},[i,g]),xt=a.useCallback(D=>{!D&&!j&&J(!1)},[j,J]);a.useEffect(()=>{if(typeof document>"u")return;const D=document.documentElement;return D.style.setProperty("--oc-chat-inset-left",`${ve}px`),D.style.setProperty("--oc-chat-inset-right",`${ne}px`),()=>{D.style.removeProperty("--oc-chat-inset-left"),D.style.removeProperty("--oc-chat-inset-right")}},[ve,ne]),a.useEffect(()=>{if(typeof document>"u")return;const D=document.documentElement;return D.classList.toggle("wide-chat-layout",p),()=>D.classList.remove("wide-chat-layout")},[p]),a.useEffect(()=>{if(typeof document>"u")return;const D=f&&(H||te),he=document.documentElement;return he.classList.toggle("oc-keep-draft-starters",D),()=>he.classList.remove("oc-keep-draft-starters")},[te,f,H]);const qe=a.useMemo(()=>({openChanges:({diffPath:D,staged:he}={})=>{ye(D?{path:D,staged:he===!0}:null)},openFiles:()=>ue(),openSettings:()=>Y("nav"),openInstances:q?()=>A("instances"):void 0,instanceLabel:q?Be():null,openUpdate:Z?()=>A("update"):void 0}),[ye,ue,Y,A,q,Z]),T=a.useMemo(()=>({openSessions:()=>{f?J(!0):B(!0)},openView:D=>{if(D==="files"){ue();return}(D==="instances"||D==="update"||D==="mcp")&&A(D)},openChanges:({path:D,staged:he}={})=>{ye(D?{path:D,staged:he===!0}:null)},openSettings:D=>{D&&I(D),Y(D?"page-content":"nav")}}),[f,ye,ue,Y,A,I,B,J]);Vo(T);const M=a.useRef(null);Qs(M,{leftOpen:f?ae:n,rightOpen:i,leftWidth:()=>f?se.width:R.current?.offsetWidth||window.innerWidth*.72,rightWidth:()=>f?z.width:h.current?.offsetWidth||window.innerWidth,onLeftProgress:D=>{if(S.current=D,f){Pn({inner:$},D,se.width,"left");return}Nn({drawer:R,scrim:U},"left",D)},onRightProgress:D=>{if(y.current=D,f&&j){Pn({inner:b},D,z.width,"right");return}Nn({drawer:h,scrim:v},"right",D)},onLeftOpen:()=>{f?J(!0):B(!0)},onLeftClose:()=>{f?J(!1):B(!1)},onRightOpen:()=>g(!0),onRightClose:()=>g(!1),onDragStart:D=>{if(P(),D==="left"){S.current=f?ae?1:0:n?1:0,f?Tn({shell:se.asideRef,inner:$}):En({drawer:R,scrim:U,root:F});return}y.current=i?1:0,f&&j?Tn({shell:z.asideRef,inner:b}):En({drawer:h,scrim:v,root:L})},onDragEnd:(D,he)=>{if(D==="left"){const Ae=typeof he=="boolean"?he:S.current>.5;if(S.current=Ae?1:0,f){const lt=An({shell:se.asideRef,inner:$},Ae,se.width,"left");lt!==void 0&&N.current.push(lt)}else Rn("left",Ae,{drawer:R,scrim:U,root:F});return}const it=typeof he=="boolean"?he:y.current>.5;if(y.current=it?1:0,f&&j){const Ae=An({shell:z.asideRef,inner:b},it,z.width,"right");Ae!==void 0&&N.current.push(Ae)}else Rn("right",it,{drawer:h,scrim:v,root:L})}});const W=a.useCallback(()=>w?(E(!1),!0):r?(X(),!0):i?(G(),!0):n?(B(!1),!0):!1,[r,X,G,w,n,E,B,i]);zo(W);const ee=f?"dialog":"fullscreen";return t.jsx(ea,{actions:qe,children:t.jsxs("div",{className:"oc-mobile-app-shell main-content-safe-area relative flex h-[100dvh] flex-row bg-background text-foreground","data-page-scroll-lock":"true",children:[f?t.jsxs("aside",{ref:se.asideRef,className:K("relative flex h-full shrink-0 flex-col overflow-hidden border-r border-border/70 bg-sidebar motion-reduce:transition-none",!ae&&"border-r-0"),style:{width:ve,minWidth:ve,maxWidth:ve,"--oc-ipad-sidebar-width":`${se.width}px`,overflowX:"clip",paddingTop:"var(--oc-safe-area-top, 0px)"},inert:!ae,"data-page-scroll-lock":"true",children:[t.jsx("div",{ref:$,className:K("flex h-full shrink-0 flex-col",se.isResizing&&"pointer-events-none",!ae&&"pointer-events-none select-none"),style:{width:"var(--oc-ipad-sidebar-width)",overflowX:"hidden",transform:se.isResizing||we.slidIn?"translateX(0)":"translateX(-100%)",transition:se.isResizing?"none":"transform 200ms cubic-bezier(0.22, 1, 0.36, 1)"},children:t.jsx(pe,{children:t.jsx(pn,{open:ae,variant:"sidebar",onOpenChange:xt})})}),ae?t.jsx(In,{side:"left",isResizing:se.isResizing,ariaLabel:"Resize left panel",handleProps:se.handleProps}):null]}):null,t.jsxs("div",{className:"relative flex h-full min-w-0 flex-1 flex-col","data-page-scroll-lock":"true",children:[f?t.jsxs(t.Fragment,{children:[t.jsx(Zs,{}),t.jsx(er,{onToggleRightDrawer:ot,rightDrawerOpen:i,tabletWorkspaceTab:c,onSelectTabletWorkspaceTab:Pe})]}):t.jsx(lo,{onOpenSessions:()=>B(!0),onOpenWorkspace:()=>g(!0)}),t.jsx("main",{ref:M,className:"relative min-h-0 flex-1 overflow-hidden","data-page-scroll-lock":"true",style:{touchAction:"pan-x pan-y"},children:t.jsx("div",{className:"h-full w-full",children:t.jsx(pe,{children:t.jsx(ti,{})})})})]}),f?null:t.jsx(pn,{open:n,onOpenChange:B,drawerRefExternal:R,scrimRefExternal:U,rootRefExternal:F}),f?t.jsxs("aside",{ref:z.asideRef,className:K("relative flex h-full shrink-0 flex-col overflow-hidden border-l border-border/70 bg-background motion-reduce:transition-none",!ne&&"border-l-0"),style:{width:ne,minWidth:ne,maxWidth:ne,"--oc-ipad-sidebar-width":`${z.width}px`,overflowX:"clip",paddingTop:"var(--oc-safe-area-top, 0px)"},inert:!ne,"data-page-scroll-lock":"true",children:[t.jsx("div",{ref:b,className:K("flex h-full min-h-0 shrink-0 flex-col transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",z.isResizing&&"pointer-events-none",!ne&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-ipad-sidebar-width)",overflowX:"hidden",transform:ne?"translateX(0)":"translateX(100%)",transition:z.isResizing?"none":"transform 200ms cubic-bezier(0.22, 1, 0.36, 1), opacity 200ms cubic-bezier(0.22, 1, 0.36, 1)"},children:t.jsx(pe,{children:t.jsx(Sn,{open:i,onClose:G,tab:c,onTabChange:u,pendingChangesDiff:x,variant:Q?"panel":"drawer",drawerRefExternal:h,scrimRefExternal:v,rootRefExternal:L})})}),ne?t.jsx(In,{side:"right",isResizing:z.isResizing,ariaLabel:"Resize right panel",handleProps:z.handleProps}):null]}):t.jsx(Sn,{open:i,onClose:G,tab:c,onTabChange:u,pendingChangesDiff:x,drawerRefExternal:h,scrimRefExternal:v,rootRefExternal:L}),r==="instances"&&q?t.jsx(jt,{open:!0,variant:ee,dialogAlign:"app",onClose:X,ariaLabel:"Instances",title:"Instances",children:t.jsx(co,{onConnect:X,onActiveConnectionDeleted:e})}):null,r==="settings"?t.jsx(jt,{open:!0,variant:ee,dialogAlign:"app",onClose:X,ariaLabel:"Settings",headerless:!0,children:t.jsx(pe,{children:t.jsx(oa,{forceMobile:!f,isWindowed:!0,initialMobileStage:d,onClose:X})})}):null,r==="update"?t.jsx(jt,{open:!0,variant:ee,dialogAlign:"app",onClose:X,ariaLabel:"Update",title:"Update",children:t.jsx(pe,{children:t.jsx("div",{className:"h-full overflow-auto px-5 py-4",children:t.jsx(ia,{initialUpdateDialogOpen:!0})})})}):null,t.jsx(pe,{children:t.jsx(tr,{})})]})})};function si({apis:e}){const n=je(A=>A.initializeApp),s=je(A=>A.isInitialized),r=je(A=>A.isConnected),o=je(A=>A.connectionPhase),i=je(A=>A.providers.length),l=je(A=>A.agents.length),c=je(A=>A.loadProviders),u=je(A=>A.loadAgents),d=On(A=>A.currentDirectory),m=ge(A=>A.error),x=ge(A=>A.clearError),k=de(A=>A.setIsMobile),N=Or(A=>A.refreshStatus),[P,R]=a.useState(0),[U,F]=a.useState(0),[h,v]=a.useState(!1),[L,$]=a.useState("pending"),[b,S]=a.useState(null),y=a.useMemo(()=>Be(),[]),[,B]=a.useReducer(A=>A+1,0),g=a.useMemo(()=>at(),[]),I=a.useRef(0),w=a.useRef(0),E=a.useCallback(()=>{const A=Se(),G=w.current+1;if(w.current=G,!A){dt();return}const Y=()=>{n(),N(e.github,{force:!0}),i===0&&c({source:"mobileApp:nativeResume"}),l===0&&u({source:"mobileApp:nativeResume"})},f=()=>{$e({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),R(_=>_+1)};Ze().then(_=>{if(w.current===G){if(_==="no-connection"){f();return}if(_==="needs-login"){S({kind:"auth-expired",label:Be()??""}),f();return}if(_==="unreachable"){window.setTimeout(()=>{w.current===G&&Ze().then(H=>{if(w.current===G&&H!=="switched"){if(H==="unchanged"){Y();return}H==="needs-login"&&S({kind:"auth-expired",label:Be()??""}),f()}})},4e3);return}_!=="switched"&&Y()}});const j=Date.now();j-I.current>=ei&&(I.current=j,window.dispatchEvent(new Event("pichamber:system-resume")))},[l,e.github,n,u,c,i,N]);_o(),Mo(E),a.useEffect(()=>Ns(),[]),a.useEffect(()=>{if(!g)return;let A;const G=()=>{window.clearTimeout(A),A=window.setTimeout(()=>E(),1500)};return window.addEventListener("online",G),()=>{window.removeEventListener("online",G),window.clearTimeout(A)}},[g,E]),a.useEffect(()=>(Vt(e),()=>Vt(null)),[e]),a.useEffect(()=>Rs(A=>{if(!!A.runtimeKey&&A.runtimeKey===A.previousRuntimeKey){Vs(),B();return}Ks(A),F(Y=>Y+1),R(Y=>Y+1)}),[]),a.useEffect(()=>{$n()},[U]),a.useEffect(()=>{if(!g||r||Se()){$("done");return}let A=!1;return $("attempting"),dt().catch(()=>({status:"no-candidate"})).then(G=>{A||(G.status==="unreachable"?S({kind:"unreachable",label:G.label}):G.status==="needs-login"&&S({kind:"auth-expired",label:G.label}),$("done"))}),()=>{A=!0}},[]),a.useEffect(()=>{if(!g||!Se())return;let A=!1;const G=Y=>{Y&&S(Y),$e({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),R(f=>f+1)};return Ze().then(async Y=>{if(A||Y==="switched"||Y==="unchanged")return;const f=Be();if(Y==="needs-login"){G({kind:"auth-expired",label:f??""});return}if(Y==="unreachable"){G(f?{kind:"unreachable",label:f}:null);return}const j=await dt().catch(()=>({status:"no-candidate"}));A||j.status==="connected"||(j.status==="needs-login"?G({kind:"auth-expired",label:j.label}):j.status==="unreachable"?G({kind:"unreachable",label:j.label}):G(null))}),()=>{A=!0}},[]),a.useEffect(()=>{k(!0)},[k]),a.useEffect(()=>{g&&!Se()||n()},[P,n,g]),a.useEffect(()=>{r&&(i===0&&c({source:"mobileApp:recovery"}),l===0&&u({source:"mobileApp:recovery"}))},[l,r,u,c,i]);const p=a.useRef(!1),[C,O]=a.useState(g);a.useEffect(()=>{if(!g||!r||p.current)return;if(ge.getState().currentSessionId){p.current=!0,O(!1);return}const A=rt(),G=$r(A);if(!G){p.current=!0,O(!1);return}let Y=!1;const f=window.setTimeout(()=>O(!1),6e3);return(async()=>{const j=await Ur().catch(()=>null);if(Y)return;if(!j){O(!1);return}p.current=!0;const _=j.activeSessions.find(te=>te.id===G.sessionId);if(!_){Br(A),O(!1);return}const H=ge.getState();H.currentSessionId||H.setCurrentSession(_.id,At(_)??G.directory??void 0),O(!1)})(),()=>{Y=!0,window.clearTimeout(f)}},[P,r,g]),a.useEffect(()=>{r&&Fr.setDirectory(d)},[d,r]),a.useEffect(()=>{r&&N(e.github,{force:!0})},[e.github,r,N]),a.useEffect(()=>{if(!m)return;const A=window.setTimeout(()=>x(),5e3);return()=>window.clearTimeout(A)},[x,m]),a.useEffect(()=>{if(!(!r&&(g?!!Se():!0))){v(!1);return}const G=window.setTimeout(()=>{v(!0)},g?4e3:8e3);return()=>window.clearTimeout(G)},[r,g,P,U]),Hr(),Ps({enabled:!0}),As(),Gs(),qo({enabled:g&&r}),Ko({ready:g&&r&&s});const q=Oo(),Z=!r&&o==="reconnecting";if(!q)return t.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background text-foreground",children:t.jsx(Ce,{width:120,height:120,isAnimated:!0})});const X=!!Se();return g&&(!X||!r&&!Z)?X?t.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background px-6 text-center text-foreground",children:t.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-4",children:[t.jsx(Ce,{width:120,height:120,isAnimated:!h}),h?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx("h1",{className:"typography-h3 text-foreground",children:"Unable to reach server"}),t.jsx("p",{className:"typography-body text-muted-foreground",children:"Could not connect to the saved server. Check that it is running, or pick another instance."})]}),t.jsx(re,{type:"button",variant:"outline",onClick:()=>{$e({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),R(A=>A+1)},children:"Use another server"})]}):null]})}):L!=="done"?t.jsxs("main",{className:"relative flex min-h-dvh items-center justify-center bg-background text-foreground",children:[t.jsx(Ce,{width:120,height:120,isAnimated:!0}),y?t.jsxs("div",{className:"absolute inset-x-0 top-[calc(50%+84px)] flex flex-col items-center gap-0.5 px-6 text-center",children:[t.jsx("p",{className:"typography-small text-muted-foreground",children:"Connecting to device:"}),t.jsxs("p",{className:"typography-small text-foreground",children:[y,t.jsx(Wr,{})]})]}):null]}):t.jsx(t.Fragment,{children:t.jsx(so,{onConnected:()=>R(A=>A+1),notice:b})}):!r&&!Z?h?t.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background px-6 text-center text-foreground",children:t.jsxs("div",{className:"max-w-sm space-y-3",children:[t.jsx("h1",{className:"typography-h3 text-foreground",children:"Unable to reach server"}),t.jsx("p",{className:"typography-body text-muted-foreground",children:"We could not verify the UI session. If you're opening PiChamber from another device on your local network, make sure Desktop Network Access is enabled on the desktop app and use the LAN address shown in Settings."})]})}):t.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background text-foreground",children:t.jsx(Ce,{width:120,height:120,isAnimated:!0})}):t.jsx(pe,{children:t.jsx(Vr,{children:t.jsx(Kr,{apis:e,children:t.jsx(Gr,{delayDuration:300,skipDelayDuration:150,children:t.jsxs(Xs,{children:[t.jsx(qs,{}),t.jsxs("div",{className:"h-full bg-background text-foreground",children:[g&&C?t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background",children:t.jsx(Ce,{width:120,height:120,isAnimated:!0})}):null,t.jsx(Xr,{embeddedBackgroundWorkEnabled:s}),t.jsx(Ta,{}),t.jsx(ni,{onActiveConnectionDeleted:()=>{$e({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),R(A=>A+1)}}),t.jsx(Ys,{}),t.jsx(qr,{position:"top-center",offset:"calc(var(--oc-safe-area-top, 0px) + 16px)"}),t.jsx(Yr,{}),s?t.jsx(Da,{}):null]})]})})})},U)})}const ri=()=>{Ts().then(()=>{Promise.all([$n(),Is()]).catch(e=>{console.error("[mobile-main] settings init failed:",e)}),Ds(),Ls(),_s()}).catch(e=>{console.error("[mobile-main] appearance init failed:",e)}).finally(()=>{wa()})};function ai(e){window.__PICHAMBER_SURFACE__="mobile",ta(),ri(),Ra(),na();const n=document.getElementById("root");if(!n)throw new Error("Root element not found");const r=window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",o=e??Et();if(!o)throw new Error("Runtime APIs not registered");const i=r?{...o,notifications:{notifyAgentCompletion:async()=>!1,canNotify:()=>!1}}:o,l=t.jsx(si,{apis:i});vs.createRoot(n).render(t.jsx(De.StrictMode,{children:t.jsx(sa,{children:t.jsx(ra,{children:t.jsx(sr,{children:r?l:t.jsx(aa,{children:l})})})})}))}const wi=Object.freeze(Object.defineProperty({__proto__:null,renderMobileApp:ai},Symbol.toStringTag,{value:"Module"}));export{vi as m,wi as r};
|
|
14
|
+
`)}`.trim()),p([])},[]),Pe=a.useCallback(async()=>{if(!o)return;const T=H.map(M=>M.path).sort();if(T.length===0){oe.error("Select at least one file to describe");return}w(!0);try{const{message:M}=await Tr(o,T);b(M.subject?.trim()??""),p(Array.isArray(M.highlights)?M.highlights:[])}catch(M){oe.error(M instanceof Error?M.message:"Failed to generate commit message")}finally{w(!1)}},[o,H]),ot=async(T={})=>{if(!o)return;if(!$.trim()){oe.error("Enter a commit message");return}const M=H.map(W=>W.path).sort();if(M.length===0){oe.error("Select at least one file to commit");return}L(T.pushAfter?"commitAndPush":"commit");try{if(await r.createGitCommit(o,$.trim(),{files:M}),oe.success("Commit created"),b(""),p([]),T.pushAfter){const W=i?.tracking?.split("/")[0],ee=J.find(lt=>lt.name===W)??J[0];if(!ee)throw new Error("No remote available");h("sync");const D=`${ee.name}/`,he=i?.tracking?.startsWith(D)?i.tracking.slice(D.length):void 0;await r.gitFetch(o,{remote:ee.name}),((await r.getGitStatus(o)).behind??0)>0&&await r.gitPull(o,{remote:ee.name,branch:he,rebase:!0}),((await r.getGitStatus(o)).ahead??0)>0&&await r.gitPush(o),await ue(!1),await ye()}else await ue(!1)}catch(W){oe.error(W instanceof Error?W.message:"Failed to create commit")}finally{L(null),T.pushAfter&&h(null)}},xt=a.useMemo(()=>{const T=[];return H.length>0&&T.push({id:"staged",title:"Staged",entries:H,actionSymbol:"-",actionAllLabel:"Unstage all changes",getActionLabel:M=>`Unstage ${M}`,onActionFile:M=>{z([M],"unstage")},onActionAll:M=>{z(M,"unstage")},onViewDiff:M=>Q(M,!0),onRevertFile:ne,showRevertActions:!1,accent:!0}),te.length>0&&T.push({id:"unstaged",title:"Changes",entries:te,actionSymbol:"+",actionAllLabel:"Stage all changes",getActionLabel:M=>`Stage ${M}`,onActionFile:M=>{z([M],"stage")},onActionAll:M=>{z(M,"stage")},onViewDiff:M=>Q(M,!1),onRevertFile:ne}),T},[ne,Q,z,H,te]),qe=T=>t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[t.jsx("div",{className:"flex shrink-0 items-center gap-2 px-3 py-2",children:t.jsx("p",{className:"min-w-0 flex-1 truncate typography-ui-label text-muted-foreground",children:i?.current||o||""})}),t.jsx("div",{className:"min-h-0 flex-1",children:T})]});return o?c&&l===null?qe(t.jsx(Ee,{loading:!0,message:"Checking repository..."})):l===!1?qe(t.jsx(a.Suspense,{fallback:t.jsx(Ee,{loading:!0,message:"Loading last turn changes..."}),children:t.jsx(wo,{diffScope:"turn",hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,flushContent:!0})})):R.type==="diff"?t.jsx(Eo,{path:R.path,diff:ae,fileExists:!!Te,error:G,onBack:()=>U({type:"list"}),onRetry:()=>j(T=>T+1)}):t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[t.jsxs("div",{className:"flex shrink-0 items-center gap-2 px-3 py-2",children:[e?t.jsx("button",{type:"button",className:"flex size-9 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","aria-label":"Close",onClick:e,style:{touchAction:"manipulation"},children:t.jsx(V,{name:"close",className:"size-4"})}):null,t.jsx("p",{className:"min-w-0 flex-1 truncate typography-ui-label text-muted-foreground",children:i?.current||o}),t.jsx(Fs,{syncAction:F,remotes:J,onFetch:T=>{se("fetch",T)},onSync:T=>{se("sync",T)},disabled:v!==null||c,aheadCount:i?.ahead??0,behindCount:i?.behind??0,trackingRemoteName:i?.tracking?.split("/")[0],hasUncommittedChanges:_.length>0})]}),_.length>0?t.jsxs("div",{className:"flex min-h-0 flex-1 flex-col",children:[t.jsx("div",{className:"min-h-0 flex-1 overflow-hidden px-3 pt-2",children:t.jsx(vo,{groups:xt,diffStats:i?.diffStats,revertingPaths:S,onRevertAll:we,isRevertingAll:B,headerBackgroundClassName:"bg-transparent",onVisiblePathsChange:O})}),t.jsx("div",{className:"shrink-0 border-t border-border/40 px-3 pb-3 pt-3",children:t.jsx(da,{stagedCount:H.length,commitMessage:$,onCommitMessageChange:b,generatedHighlights:E,onInsertHighlights:ve,onGenerateMessage:Pe,isGeneratingMessage:I,onCommit:()=>{ot({pushAfter:!1})},onCommitAndPush:()=>{ot({pushAfter:!0})},commitAction:v,gitmojiEnabled:!1,onOpenGitmojiPicker:()=>{}})})]}):t.jsx("div",{className:"min-h-0 flex-1",children:t.jsx(Ee,{icon:!0,message:"Working tree clean",description:"There are no changed files in this workspace."})})]}):qe(t.jsx(Ee,{message:"Select a session or directory to view Git status"}))},Ee=({message:e,description:n,loading:s=!1,icon:r=!1})=>t.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center",children:t.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-2",children:[s?t.jsx(V,{name:"loader-4",className:"size-5 animate-spin text-muted-foreground"}):null,r?t.jsx(V,{name:"git-branch",className:"size-6 text-muted-foreground"}):null,t.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e}),n?t.jsx("p",{className:"typography-meta text-muted-foreground",children:n}):null]})}),Eo=({path:e,diff:n,fileExists:s,error:r,onBack:o,onRetry:i})=>{const l=a.useMemo(()=>Ar(e)||"text",[e]);return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[t.jsxs("header",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2 text-foreground",children:[t.jsx("button",{type:"button",className:"flex size-9 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back",onClick:o,children:t.jsx(V,{name:"arrow-left",className:"size-4"})}),t.jsx("div",{className:"min-w-0 flex-1 px-2",children:t.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:e})})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:s?r?t.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center",children:t.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-3",children:[t.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:"Failed to load diff"}),t.jsx("p",{className:"typography-meta text-muted-foreground",children:r}),t.jsx(re,{type:"button",size:"sm",variant:"outline",onClick:i,children:"Retry"})]})}):n?n.isBinary?t.jsx(Ee,{icon:!0,message:"Content of this file cannot be viewed."}):Ir(e)?t.jsx(Ee,{icon:!0,message:"Image diffs are not available in mobile Changes yet."}):t.jsx(It,{className:"h-full overflow-y-auto overflow-x-hidden p-3","data-diff-virtual-root":!0,"data-diff-virtual-content":!0,children:t.jsx(fa,{original:n.original,modified:n.modified,language:l,fileName:e,renderSideBySide:!1,wrapLines:!0,layout:"inline"})}):t.jsx(Ee,{loading:!0,message:"Loading diff..."}):t.jsx(Ee,{icon:!0,message:"File is no longer changed",description:"Go back to Changes and refresh the list."})})]})},fe=e=>(e||"").replace(/\\/g,"/").replace(/\/+$/g,""),Fe=e=>{const n=fe(e);return!n||n==="/"?n||"/":n.split("/").filter(Boolean).at(-1)??n},gs=e=>{const n=fe(e);if(!n||n==="/")return null;const s=n.lastIndexOf("/");if(s<0)return null;if(s===0)return"/";const r=n.slice(0,s);return/^[A-Za-z]:$/.test(r)?`${r}/`:r},wn=(e,n)=>{const s=fe(e),r=fe(n);return!s||!r?!1:s===r||s.startsWith(`${r}/`)},kn=(e,n)=>{const s=fe(e);if(!s)return fe(n);if(s.startsWith("/")||/^[A-Za-z]:(\/|$)/.test(s))return s;const r=fe(n);return r?`${r}/${s}`:s},No=(e,n)=>{const s=fe(e),r=fe(n);if(!s||s===r)return!1;const o=gs(s);return o?r&&wn(s,r)?wn(o,r):!0:!1},Ro=a.lazy(()=>be(()=>import("./FilesView-DB5VI7EN.js"),__vite__mapDeps([119,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,111,112,113,120,121,122,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,123,124,116,117,125,126,114,115])).then(e=>({default:e.FilesView}))),To=(e,n)=>{const s=fe(e),r=fe(n);return!r||s===r?Fe(s):s.startsWith(`${r}/`)?s.slice(r.length+1):s},Po=e=>{if(typeof e!="number"||!Number.isFinite(e)||e<0)return"";if(e<1024)return`${e} B`;const n=["KB","MB","GB"];let s=e/1024;for(const r of n){if(s<1024||r===n[n.length-1])return`${s.toFixed(s>=10?0:1)} ${r}`;s/=1024}return""},Ao=({onClose:e})=>{const{files:n}=Hn(),s=Es(p=>p.setSelectedPath),r=fe(Dt()??null),[o,i]=a.useState(()=>({type:"browser",directory:r})),[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,x]=a.useState(null),[k,N]=a.useState(""),[P,R]=a.useState([]),[U,F]=a.useState(!1),h=a.useRef(0);a.useEffect(()=>{r&&i(p=>p.type==="browser"&&p.directory?p:{type:"browser",directory:r})},[r]);const v=o.type==="browser"?o.directory:o.returnDirectory,L=a.useCallback(async p=>{if(!p)return;const C=h.current+1;h.current=C,d(!0),x(null);try{const O=await n.listDirectory(p);if(h.current!==C)return;c(O.entries.slice().sort((Z,X)=>Z.isDirectory!==X.isDirectory?Z.isDirectory?-1:1:Z.name.localeCompare(X.name)));const q=fe(O.directory);q&&q!==fe(p)&&i(Z=>Z.type==="browser"&&Z.directory!==q?{type:"browser",directory:q}:Z)}catch(O){if(h.current!==C)return;c([]),x(O instanceof Error?O.message:"Failed to load files")}finally{h.current===C&&d(!1)}},[n]);a.useEffect(()=>{o.type==="browser"&&L(o.directory)},[L,o]),a.useEffect(()=>{if(o.type!=="browser")return;const p=k.trim();if(!p){R([]),F(!1);return}let C=!1;const O=window.setTimeout(()=>{F(!0),n.search({directory:o.directory,query:p,maxResults:40}).then(q=>{C||R(q)}).catch(()=>{C||R([])}).finally(()=>{C||F(!1)})},250);return()=>{C=!0,window.clearTimeout(O)}},[n,k,o]);const $=p=>{N(""),i({type:"browser",directory:p})},b=p=>{s(r,p),i({type:"file",path:p,returnDirectory:v||r})},S=de(p=>p.pendingFileFocusPath),y=de(p=>p.pendingFileNavigation);if(a.useEffect(()=>{const p=fe(y?.path??S??"");!p||!r||p!==r&&!p.startsWith(`${r}/`)||(s(r,p),i({type:"file",path:p,returnDirectory:r}),S&&de.getState().setPendingFileFocusPath(null))},[S,y,r,s]),!r)return t.jsx(et,{message:"Select a project to browse files."});if(o.type==="file")return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[t.jsxs("header",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2 text-foreground",children:[t.jsx("button",{type:"button",className:"flex size-9 shrink-0 items-center justify-center rounded-full text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Back",onClick:()=>i({type:"browser",directory:o.returnDirectory}),style:{touchAction:"manipulation"},children:t.jsx(sn,{className:"size-4"})}),t.jsx("div",{className:"min-w-0 flex-1",children:t.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:Fe(o.path)})})]}),t.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:t.jsx(pe,{children:t.jsx(a.Suspense,{fallback:t.jsx(et,{loading:!0,message:"Loading..."}),children:t.jsx(Ro,{mode:"editor-only"})})})})]});const B=o.directory===r?"Project files":Fe(o.directory),g=k.trim()?P:[],I=No(o.directory,r)?gs(o.directory):null,w=!!I&&!k.trim(),E=I===r?"Project files":Fe(I??"");return t.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-transparent text-foreground",children:[t.jsxs("header",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2 text-foreground",children:[e?t.jsx("button",{type:"button",className:"flex size-9 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","aria-label":"Close",onClick:e,style:{touchAction:"manipulation"},children:t.jsx(ha,{className:"size-4"})}):null,w&&I?t.jsx("button",{type:"button",className:"flex size-9 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","aria-label":`Back to ${Fe(I)}`,onClick:()=>$(I),style:{touchAction:"manipulation"},children:t.jsx(sn,{className:"size-4"})}):null,t.jsx("div",{className:"min-w-0 flex-1 px-1",children:t.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:B})}),t.jsx("button",{type:"button",className:"flex size-9 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","aria-label":"Refresh files",onClick:()=>{L(o.directory)},style:{touchAction:"manipulation"},children:t.jsx(ma,{className:K("size-4",u&&"animate-spin")})})]}),t.jsx("div",{className:"shrink-0 px-3 pb-2 pt-1",children:t.jsxs("div",{className:"relative",children:[t.jsx(pa,{className:"pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"}),t.jsx(Dr,{value:k,onChange:p=>N(p.target.value),placeholder:"Search files",className:"h-11 pl-9"})]})}),t.jsx(It,{className:"min-h-0 w-full flex-1 overflow-y-auto pb-3",children:m?t.jsx(et,{message:m}):k.trim()?t.jsx(Io,{results:g,isSearching:U,onOpenFile:b}):t.jsxs("div",{className:"flex w-full min-w-0 flex-col",children:[w&&I?t.jsxs("button",{type:"button",className:Wn,"aria-label":`Up one level to ${E}`,onClick:()=>$(I),style:{touchAction:"manipulation"},children:[t.jsx(V,{name:"arrow-left",className:K(Nt(!0),"text-muted-foreground")}),t.jsx("span",{className:K(Vn(!0),"flex-1 text-muted-foreground"),children:"Up one level"})]}):null,l.length===0&&!u?t.jsx("div",{className:"px-3 py-8 text-center typography-ui-label text-muted-foreground",children:"This directory is empty."}):null,l.map(p=>t.jsx(ys,{name:p.name,path:p.path,directory:p.isDirectory,meta:p.isDirectory?void 0:Po(p.size),onClick:()=>p.isDirectory?$(kn(p.path,o.directory||r)):b(kn(p.path,o.directory||r))},p.path))]})})]})},ys=({name:e,path:n,directory:s,meta:r,onClick:o})=>t.jsxs("button",{type:"button",className:Wn,onClick:o,style:{touchAction:"manipulation"},children:[s?t.jsx(ba,{className:K(Nt(!0),"text-primary/80")}):t.jsx(Fn,{filePath:n,className:Nt(!0)}),t.jsx("span",{className:K(Vn(!0),"flex-1 text-foreground"),children:e}),r?t.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:r}):null,s?t.jsx(xa,{className:"size-4 shrink-0 text-muted-foreground/60"}):null]}),Io=({results:e,isSearching:n,onOpenFile:s})=>{const r=fe(Dt()??null);return n?t.jsx(et,{loading:!0,message:"Loading..."}):e.length===0?t.jsx(et,{message:"No files found."}):t.jsx("div",{className:"flex w-full min-w-0 flex-col",children:e.map(o=>t.jsx(ys,{name:Fe(o.path),path:o.path,directory:!1,meta:To(o.path,r),onClick:()=>s(o.path)},o.path))})},et=({message:e,loading:n=!1})=>t.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center",children:t.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-2",children:[n?t.jsx(ga,{className:"size-5 animate-spin text-muted-foreground"}):t.jsx(ya,{className:"size-6 text-muted-foreground"}),t.jsx("p",{className:"typography-ui-label font-semibold text-foreground",children:e})]})}),jn="mobile-surface-root",Do=16,Lo=[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal"},{id:"notes",label:"Notes",icon:"sticky-note"}],Sn=a.memo(function({open:n,onClose:s,tab:r,onTabChange:o,pendingChangesDiff:i,variant:l="drawer",drawerRefExternal:c,scrimRefExternal:u,rootRefExternal:d}){const m=a.useRef(null),x=a.useRef(null),k=a.useRef(null),N=a.useRef(null),P=c??x,R=u??k,U=d??N,F=a.useCallback(E=>{N.current=E,d&&(d.current=E)},[d]),h=a.useCallback(()=>{const E=typeof document<"u"?document.activeElement:null;E instanceof HTMLElement&&U.current?.contains(E)&&E.blur(),s()},[s]),[v,L]=a.useState(!1),[$,b]=a.useState(n),S=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[y,B]=a.useState(()=>new Set);if(a.useEffect(()=>{n&&B(E=>{if(E.has(r))return E;const p=new Set(E);return p.add(r),p})},[n,r]),typeof document<"u"&&!m.current){let E=document.getElementById(jn);E||(E=document.createElement("div"),E.id=jn,document.body.appendChild(E)),m.current=E}if(a.useEffect(()=>{if(n){b(!0);const p=window.setTimeout(()=>L(!0),S?0:Do);return()=>window.clearTimeout(p)}L(!1);const E=window.setTimeout(()=>b(!1),Xe+40);return()=>window.clearTimeout(E)},[n,S]),a.useEffect(()=>{if(!n)return;const E=document.body.style.overflow;l==="drawer"&&(document.body.style.overflow="hidden");const p=C=>{C.key==="Escape"&&r!=="terminal"&&h()};return document.addEventListener("keydown",p),()=>{l==="drawer"&&(document.body.style.overflow=E),document.removeEventListener("keydown",p)}},[h,n,r,l]),a.useEffect(()=>{const E=U.current;if(!E||n||l!=="drawer")return;const p=document.activeElement;p&&E.contains(p)&&p.blur()},[n,l]),hs({side:"right",enabled:l==="drawer",open:n,drawerRef:P,scrimRef:R,onClose:h,widthRatio:1,prefersReducedMotion:S}),l==="drawer"&&!m.current)return null;const g=S?0:Xe,I=t.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-0.5 overflow-x-auto",role:"tablist","aria-label":"Workspace","data-no-drawer-swipe":"true",children:Lo.map(E=>{const p=r===E.id;return t.jsxs("button",{type:"button",role:"tab","aria-selected":p,onClick:()=>o(E.id),className:K("flex min-w-0 flex-1 items-center justify-center gap-1 rounded-lg px-1.5 py-2 typography-ui-label transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",p?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[t.jsx(V,{name:E.icon,className:"size-4 shrink-0"}),t.jsx("span",{className:"truncate",children:E.label})]},E.id)})}),w=t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-2 px-2",children:[I,t.jsx("button",{type:"button",onClick:h,"aria-label":"Close workspace panel",className:"flex size-8 shrink-0 items-center justify-center rounded-lg text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:t.jsx(V,{name:"close",className:"size-4"})})]}),t.jsxs("div",{className:"min-h-0 flex-1 overflow-hidden",children:[y.has("changes")?t.jsx("div",{className:K("h-full",r!=="changes"&&"hidden"),children:t.jsx(pe,{children:t.jsx(Co,{initialDiffPath:i?.path??null,initialDiffStaged:i?.staged===!0})})},i?`changes:${i.path}:${i.staged}`:"changes"):null,y.has("files")?t.jsx("div",{className:K("h-full",r!=="files"&&"hidden"),children:t.jsx(pe,{children:t.jsx(Ao,{})})}):null,y.has("terminal")?t.jsx("div",{className:K("h-full",r!=="terminal"&&"hidden"),children:t.jsx(pe,{children:t.jsx(Hs,{visible:n&&r==="terminal"})})}):null,y.has("notes")?t.jsx("div",{className:K("h-full",r!=="notes"&&"hidden"),children:t.jsx(pe,{children:t.jsx(Ws,{onActionComplete:h})})}):null]})]});return l==="panel"?t.jsx("div",{className:"flex h-full min-h-0 flex-col bg-sidebar",children:w}):We.createPortal(t.jsxs("div",{ref:F,className:"fixed inset-0 z-50",inert:!n,style:{pointerEvents:n?"auto":"none",visibility:$?"visible":"hidden"},"data-mobile-workspace-root":"true",children:[t.jsx("button",{ref:R,type:"button",className:"absolute inset-0 cursor-default bg-black/70","aria-label":"Close workspace panel",onClick:h,tabIndex:n?0:-1,style:{opacity:v?1:0,transition:g?`opacity ${g}ms ${Re}`:"none"},"data-mobile-workspace-scrim":"true"}),t.jsx("section",{ref:P,role:"dialog","aria-modal":"true","aria-label":"Open workspace panel",className:"oc-keyboard-inset-surface absolute inset-y-0 right-0 z-10 flex h-full w-full flex-col bg-sidebar",style:{paddingTop:"var(--oc-safe-area-top, 0px)",transform:v?"none":"translateX(100%)",transition:g?`transform ${g}ms ${Re}`:"none",touchAction:"pan-x pan-y"},"data-mobile-workspace-drawer":"true",children:w})]}),m.current)}),at=()=>typeof window>"u"?!1:window.Capacitor?.isNativePlatform?.()===!0?!0:window.location.protocol==="capacitor:",_o=()=>{a.useEffect(()=>{if(!at())return;let e=!1;const n=[],s=document.documentElement;s.classList.add("oc-capacitor-app"),window.Capacitor?.getPlatform?.()==="android"&&s.classList.add("oc-platform-android"),n.push(Lr());const o=i=>{s.style.setProperty("--oc-keyboard-inset",`${Math.max(0,Math.round(i))}px`)};return be(()=>import("./vendor-capacitor-status-bar-B-N0EOVk.js"),__vite__mapDeps([127,128])).then(async({StatusBar:i,Style:l})=>{if(e)return;const c=window.Capacitor?.getPlatform?.(),u=async()=>{if(c==="android"){const k=document.documentElement.classList.contains("dark"),N=(k?localStorage.getItem("splashBgDark"):localStorage.getItem("splashBgLight"))||(k?"#171515":"#fffdf4");await i.setOverlaysWebView({overlay:!1}).catch(()=>{}),await i.setBackgroundColor({color:N}).catch(()=>{}),await i.setStyle({style:k?l.Dark:l.Light}).catch(()=>{}),await i.show().catch(()=>{});return}await i.setStyle({style:l.Default}).catch(()=>{}),await i.setOverlaysWebView({overlay:!0}).catch(()=>{}),await i.show().catch(()=>{})};await u();const d=window.setTimeout(()=>{u()},400);n.push(()=>window.clearTimeout(d));const{App:m}=await be(async()=>{const{App:k}=await import("./vendor-capacitor-app-BrDJj9I_.js");return{App:k}},__vite__mapDeps([129,8,128])),x=await m.addListener("appStateChange",({isActive:k})=>{k&&u()});if(e){x.remove();return}n.push(()=>{x.remove()})}).catch(()=>{}),be(()=>import("./vendor-capacitor-keyboard-CYccoJjr.js"),__vite__mapDeps([130,128])).then(async({Keyboard:i})=>{if(e)return;if(window.Capacitor?.getPlatform?.()==="android"){const g=await i.addListener("keyboardWillShow",C=>{nn(C.keyboardHeight),s.classList.add("oc-keyboard-open"),window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!0}}))}),I=await i.addListener("keyboardDidShow",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!0}}))}),w=await i.addListener("keyboardWillHide",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-intent",{detail:{open:!1}})),s.classList.remove("oc-keyboard-open")}),E=await i.addListener("keyboardDidHide",()=>{window.dispatchEvent(new CustomEvent("oc:keyboard-settled",{detail:{open:!1}}))}),p=()=>{g.remove(),I.remove(),w.remove(),E.remove()};if(e){p();return}n.push(p);return}await i.setAccessoryBarVisible({isVisible:!1}).catch(()=>{});const c=250,u=200,d="cubic-bezier(0.38, 0.7, 0.125, 1)";let m=null,x=null,k=0,N=!1,P=0,R=!1;const U=(g,I)=>{s.style.setProperty(g,`${Math.max(0,Math.round(I))}px`)},F=()=>{m!==null&&(window.clearTimeout(m),m=null)},h=(g,I)=>{window.dispatchEvent(new CustomEvent(g,{detail:I}))},v=()=>{const g=[],I=document.querySelector(".oc-mobile-composer");I&&g.push({el:I,factor:1});const w=document.querySelector(".oc-draft-center");return w&&g.push({el:w,factor:.5}),g},L=()=>{for(const{el:g}of v())g.style.transition="",g.style.transform=""},$=await i.addListener("keyboardWillShow",g=>{if(F(),nn(g.keyboardHeight),R=!0,k=g.keyboardHeight,!N){const w=document.querySelector(".oc-mobile-app-shell");P=w&&parseFloat(getComputedStyle(w).paddingBottom)||0}const I=Math.max(0,k-P);s.classList.remove("oc-kb-hide"),x!==null&&(window.clearTimeout(x),x=null),s.classList.add("oc-keyboard-open","oc-kb-animating","oc-kb-caret-hold"),o(k);for(const{el:w,factor:E}of v())w.style.transition=`transform ${c}ms ${d}`,w.style.transform=`translateY(${-I*E}px)`;U("--oc-kb-scroll-inset",I),h("oc:keyboard-settled",{open:!0}),h("oc:keyboard-anim",{phase:"show",slide:I,durationMs:c,easing:d}),m=window.setTimeout(()=>{m=null,s.classList.remove("oc-kb-animating"),U("--oc-kb-layout",k),N=!0,L(),h("oc:keyboard-settled",{open:!0}),x=window.setTimeout(()=>{x=null,s.classList.remove("oc-kb-caret-hold")},250)},c+20)}),b=()=>{if(!R)return;R=!1,F(),h("oc:keyboard-intent",{open:!1}),x!==null&&(window.clearTimeout(x),x=null),s.classList.remove("oc-kb-caret-hold");const g=Math.max(0,k-P);if(s.classList.remove("oc-keyboard-open"),o(0),U("--oc-kb-scroll-inset",0),N){s.classList.remove("oc-kb-animating"),U("--oc-kb-layout",0),N=!1;for(const{el:I,factor:w}of v())I.style.transition="none",I.style.transform=`translateY(${-g*w}px)`;document.querySelector(".oc-mobile-app-shell")?.offsetHeight}h("oc:keyboard-anim",{phase:"hide",slide:g,durationMs:u,easing:d}),s.classList.add("oc-kb-animating","oc-kb-hide");for(const{el:I}of v())I.style.transition=`transform ${u}ms ${d}`,I.style.transform="translateY(0px)";m=window.setTimeout(()=>{m=null,s.classList.remove("oc-kb-animating","oc-kb-hide"),L(),h("oc:keyboard-settled",{open:!1})},u+20)},S=await i.addListener("keyboardWillHide",b),y=g=>g instanceof HTMLElement&&(g.tagName==="TEXTAREA"||g.tagName==="INPUT"||g.isContentEditable),B=g=>{R&&y(g.target)&&(y(g.relatedTarget)||window.setTimeout(()=>{R&&(y(document.activeElement)||b())},0))};if(document.addEventListener("focusout",B,!0),e){F(),document.removeEventListener("focusout",B,!0),$.remove(),S.remove();return}n.push(F,()=>{x!==null&&(window.clearTimeout(x),x=null)},()=>document.removeEventListener("focusout",B,!0),()=>{$.remove()},()=>{S.remove()})}).catch(()=>{}),()=>{e=!0,n.forEach(i=>i()),_r(),s.classList.remove("oc-capacitor-app","oc-keyboard-open","oc-kb-animating","oc-kb-hide","oc-kb-caret-hold","oc-platform-android"),s.style.removeProperty("--oc-keyboard-inset"),s.style.removeProperty("--oc-kb-shift"),s.style.removeProperty("--oc-kb-layout"),s.style.removeProperty("--oc-kb-scroll-inset")}},[])},Mo=e=>{const n=a.useRef(!1);a.useEffect(()=>{if(!at())return;let s=!1;const r=[],o=()=>{n.current&&(n.current=!1,e())},i=()=>{if(document.visibilityState==="hidden"){n.current=!0;return}o()};return document.addEventListener("visibilitychange",i),r.push(()=>document.removeEventListener("visibilitychange",i)),be(()=>import("./vendor-capacitor-app-BrDJj9I_.js"),__vite__mapDeps([129,8,128])).then(async({App:l})=>{if(s)return;const c=await l.addListener("appStateChange",({isActive:d})=>{if(document.documentElement.classList.toggle("oc-native-app-active",d),!d){n.current=!0;return}o()}),u=await l.addListener("resume",o);if(s){c.remove(),u.remove();return}r.push(()=>{c.remove()},()=>{u.remove()})}).catch(()=>{}),()=>{s=!0,r.forEach(l=>l())}},[e])},zo=e=>{a.useEffect(()=>{if(!at())return;let n=!1,s=null;return be(()=>import("./vendor-capacitor-app-BrDJj9I_.js"),__vite__mapDeps([129,8,128])).then(async({App:r})=>{if(n)return;const o=await r.addListener("backButton",()=>{e()||r.minimizeApp().catch(()=>{})});if(n){o.remove();return}s=()=>{o.remove()}}).catch(()=>{}),()=>{n=!0,s?.()}},[e])};function Oo(e=2500){const{uiFont:n}=Mr(),[s,r]=a.useState(!1);return a.useEffect(()=>{let o=!1;const i=()=>{o||r(!0)},l=()=>{requestAnimationFrame(()=>requestAnimationFrame(i))},c=Promise.all([zr(n).catch(()=>{}),document.fonts?.ready?.then(()=>{}).catch(()=>{})??Promise.resolve(),va.catch(()=>{})]).then(()=>{}),u=new Promise(d=>{window.setTimeout(d,e)});return Promise.race([c,u]).then(l),()=>{o=!0}},[n,e]),s}const $o="pichamber",Uo=e=>e.replace(/^\/+|\/+$/g,""),Bo=e=>{const n=Uo(e.pathname).split("/").filter(Boolean);return e.host?[e.host,...n]:n};function Fo(e){if(typeof e!="string"||e.length===0)return null;let n;try{n=new URL(e)}catch{return null}if(n.protocol!==`${$o}:`)return null;const s=Bo(n),r=(s[0]??"").toLowerCase(),o=s.slice(1),i=n.searchParams;switch(r){case"session":{const l=o[0]||i.get("id")||"";return l?{type:"session",sessionId:l,directory:i.get("dir")??void 0}:null}case"new":case"new-session":return{type:"new-session",directory:i.get("dir")??void 0,projectId:i.get("project")??void 0,agent:i.get("agent")??void 0,model:i.get("model")??void 0};case"sessions":{const l=i.get("filter");return{type:"sessions",filter:l==="attention"||l==="recent"||l==="all"?l:void 0}}case"status":return{type:"status"};case"settings":return{type:"settings",section:o[0]||i.get("section")||void 0};case"changes":return{type:"changes",path:o.join("/")||i.get("path")||void 0,staged:i.get("staged")==="true"};case"view":{const l=(o[0]||"").toLowerCase();return l==="changes"?{type:"changes"}:l==="files"||l==="mcp"||l==="instances"||l==="update"?{type:"view",target:l}:null}default:return null}}let me={},bs=!1,Je=null;const Ho=e=>{switch(e.type){case"session":return ge.getState().setCurrentSession(e.sessionId,e.directory??null),!0;case"new-session":{const n=ge.getState();return n.openNewSessionDraft(),(e.directory||e.projectId)&&n.setNewSessionDraftTarget({directoryOverride:e.directory??null,projectId:e.projectId??null,selectedProjectId:e.projectId??null}),!0}case"sessions":return me.openSessions?(me.openSessions(e.filter),!0):!1;case"status":return me.openSessions?(me.openSessions(),!0):!1;case"view":return me.openView?(me.openView(e.target),!0):!1;case"changes":return me.openChanges?(me.openChanges({path:e.path,staged:e.staged}),!0):!1;case"settings":return me.openSettings?(me.openSettings(e.section),!0):!1}},Ht=()=>{if(!bs||!Je)return;const e=Je;Je=null,Ho(e)||(Je=e)},xs=e=>{Je=e,Ht()},Cn=e=>{const n=Fo(e);n&&xs(n)},Wo=e=>{bs=e,Ht()},Vo=e=>{a.useEffect(()=>(me=e,Ht(),()=>{me===e&&(me={})}),[e])},Ko=e=>{const{ready:n}=e;a.useEffect(()=>{Wo(n)},[n]),a.useEffect(()=>{if(!le())return;let s=!1;const r=[];return be(()=>import("./vendor-capacitor-app-BrDJj9I_.js"),__vite__mapDeps([129,8,128])).then(async({App:o})=>{if(s)return;const i=await o.addListener("appUrlOpen",l=>{Cn(l?.url)});if(s){i.remove();return}r.push(()=>{i.remove()})}).catch(()=>{}),be(()=>import("./vendor-capacitor-push-notifications-KNe1zSBF.js"),__vite__mapDeps([131,128])).then(async({PushNotifications:o})=>{if(s)return;const i=await o.addListener("pushNotificationActionPerformed",l=>{const c=l?.notification?.data,u=typeof c?.url=="string"?c.url:typeof c?.deeplink=="string"?c.deeplink:void 0;if(u){Cn(u);return}const d=typeof c?.sessionId=="string"?c.sessionId:void 0;d&&xs({type:"session",sessionId:d})});if(s){i.remove();return}r.push(()=>{i.remove()})}).catch(()=>{}),()=>{s=!0,r.forEach(o=>o())}},[])},En=e=>{const n=e.drawer.current,s=e.scrim.current,r=e.root.current;r&&(r.style.pointerEvents="auto",r.style.visibility="visible"),n&&(n.style.transition="none"),s&&(s.style.transition="none")},Nn=(e,n,s)=>{const r=e.drawer.current,o=e.scrim.current;if(r&&(r.style.transform=s>=.999?"none":`translateX(${(n==="left"?s-1:1-s)*100}%)`),o){o.style.opacity=String(s);const i=s>.01?"auto":"none";o.style.pointerEvents!==i&&(o.style.pointerEvents=i)}},Rn=(e,n,s)=>{const r=s.drawer.current,o=s.scrim.current,i=s.root.current;r&&(r.style.transition=`transform ${Xe}ms ${Re}`,r.style.transform=n?"none":e==="left"?"translateX(-100%)":"translateX(100%)"),o&&(o.style.transition=`opacity ${Xe}ms ${Re}`,o.style.opacity=n?"1":"0",o.style.pointerEvents=n?"auto":"none"),i&&(i.style.pointerEvents=n?"auto":"none",i.style.visibility=n?"visible":"")},Tn=e=>{const n=e.shell.current,s=e.inner.current;n&&(n.style.overflow="visible"),s&&(s.style.transition="none")},Pn=(e,n,s,r)=>{const o=e.inner.current;if(!o)return;const i=r==="left"?(n-1)*s:(1-n)*s;o.style.transform=n>=.999?"translateX(0)":`translateX(${i}px)`},An=(e,n,s,r,o)=>{const i=e.shell.current,l=e.inner.current;return!i||!l?void 0:(l.style.transition="transform 200ms cubic-bezier(0.22, 1, 0.36, 1)",l.style.transform=n?"translateX(0)":`translateX(${r==="left"?-s:s}px)`,window.setTimeout(()=>{l.style.transition="",l.style.transform="",i.style.overflow=""},220))},Go=()=>{if(typeof window>"u")return;const e=window.__PICHAMBER_APNS_ENV__;if(e==="development")return"sandbox";if(e==="production")return"production"},Xo=()=>{if(typeof window>"u")return!1;const n=window.Capacitor?.getPlatform?.();return n==="ios"||n==="android"},qo=e=>{const{enabled:n}=e,s=de(o=>o.nativeNotificationsEnabled),r=a.useRef(null);a.useEffect(()=>{if(!n||!s||!Xo())return;let o=!1;const i=[];return be(()=>import("./vendor-capacitor-push-notifications-KNe1zSBF.js"),__vite__mapDeps([131,128])).then(async({PushNotifications:l})=>{if(o)return;let c=await l.checkPermissions().catch(()=>null);if(c?.receive!=="granted"&&(c=await l.requestPermissions().catch(()=>null)),c?.receive!=="granted")return;const u=await l.addListener("registration",m=>{r.current=m.value,Et()?.push?.registerApnsToken?.({token:m.value,platform:_n(),environment:Go()})}),d=await l.addListener("registrationError",m=>{console.warn("[Push] APNs registration error:",m)});if(await l.register().catch(()=>{}),o){u.remove(),d.remove();return}i.push(()=>{u.remove()},()=>{d.remove()})}).catch(()=>{}),()=>{o=!0,i.forEach(l=>l())}},[n,s]),a.useEffect(()=>{if(s)return;const o=r.current;if(!o)return;r.current=null,Et()?.push?.unregisterApnsToken?.({token:o})},[s])},In=({side:e,isResizing:n,ariaLabel:s,handleProps:r})=>t.jsx("div",{className:K("absolute inset-y-0 z-50 w-6 cursor-col-resize touch-none",e==="left"?"right-0":"left-0"),role:"separator","aria-orientation":"vertical","aria-label":s,...r,children:t.jsx("div",{className:K("absolute inset-y-0 w-[3px] transition-colors",e==="left"?"right-0":"left-0",n&&"bg-[var(--interactive-border)]")})}),Yo=320,Jo=380,Dn=280,Qo=560,Zo=900;function Ln(e,n,s,r=Qo){const o=a.useRef(null),[i,l]=a.useState(()=>{if(typeof window>"u")return s;const v=Number.parseInt(window.localStorage.getItem(n)??"",10);return Number.isFinite(v)?Math.min(r,Math.max(Dn,v)):s}),[c,u]=a.useState(!1),d=a.useRef(0),m=a.useRef(i),x=a.useRef(null),k=a.useRef(null),N=a.useCallback(v=>Math.min(r,Math.max(Dn,Math.round(v))),[r]),P=a.useCallback(v=>{const L=o.current;L&&(L.style.width=`${v}px`,L.style.minWidth=`${v}px`,L.style.maxWidth=`${v}px`,L.style.setProperty("--oc-ipad-sidebar-width",`${v}px`))},[]),R=a.useCallback(v=>{try{v.currentTarget.setPointerCapture(v.pointerId)}catch{}k.current=v.pointerId,d.current=v.clientX,m.current=i,x.current=i,u(!0),v.preventDefault()},[i]),U=a.useCallback(v=>{if(k.current!==v.pointerId)return;const L=v.clientX-d.current,$=N(m.current+(e==="left"?L:-L));x.current!==$&&(x.current=$,P($))},[P,N,e]),F=a.useCallback(v=>{if(k.current!==v.pointerId)return;try{v.currentTarget.releasePointerCapture(v.pointerId)}catch{}const L=N(x.current??m.current);k.current=null,x.current=null,u(!1),l(L);try{window.localStorage.setItem(n,String(L))}catch{}},[N,n]),h=a.useMemo(()=>({onPointerDown:R,onPointerMove:U,onPointerUp:F,onPointerCancel:F}),[R,F,U]);return{asideRef:o,width:i,isResizing:c,handleProps:h}}const ei=1e3,ti=a.memo(nr),ni=({onActiveConnectionDeleted:e})=>{const[n,s]=a.useState(!1),[r,o]=a.useState(null),[i,l]=a.useState(!1),[c,u]=a.useState("changes"),[d,m]=a.useState("nav"),[x,k]=a.useState(null),N=a.useRef([]),P=a.useCallback(()=>{N.current.forEach(D=>window.clearTimeout(D)),N.current=[]},[]);a.useEffect(()=>()=>P(),[P]);const R=a.useRef(null),U=a.useRef(null),F=a.useRef(null),h=a.useRef(null),v=a.useRef(null),L=a.useRef(null),$=a.useRef(null),b=a.useRef(null),S=a.useRef(0),y=a.useRef(0),B=a.useCallback(D=>{P(),s(D)},[P]),g=a.useCallback(D=>{P(),l(D)},[P]),I=de(D=>D.setSettingsPage),w=de(D=>D.isArchivePageOpen),E=de(D=>D.setArchivePageOpen),p=de(D=>D.wideChatLayoutEnabled),C=Ue(D=>D.available),O=Ue(D=>D.runtimeType),q=a.useMemo(()=>at(),[]),Z=!q&&C&&(O==="desktop"||O==="web"),X=a.useCallback(()=>{o(null)},[]),A=a.useCallback(D=>{o(D)},[]),G=a.useCallback(()=>{g(!1)},[g]),Y=a.useCallback(D=>{m(D),A("settings")},[A]),{enabled:f,roomyForPanels:j}=Bn(),H=Jr()==="portrait",te=Qr(),J=de(D=>D.setSidebarOpen),ae=de(D=>D.isSidebarOpen),Te=a.useRef(!1);a.useLayoutEffect(()=>{f&&!Te.current&&J(Zr().roomyForPanels),!f&&Te.current&&J(!1),Te.current=f},[f,J]);const ue=a.useCallback(()=>{k(null),u("files"),g(!0)},[g]),ye=a.useCallback((D=null)=>{k(D),u("changes"),g(!0)},[g]),se=Ln("left","pichamber.ipad.leftSidebarWidth",Yo),z=Ln("right","pichamber.ipad.rightSidebarWidth",Jo,Zo),Q=j,ne=Q&&i?z.width:0,we=Js(f&&ae),ve=f&&ae?se.width:0,Pe=a.useCallback(D=>{i&&c===D?g(!1):(u(D),g(!0))},[i,c,g]),ot=a.useCallback(()=>{g(!i)},[i,g]),xt=a.useCallback(D=>{!D&&!j&&J(!1)},[j,J]);a.useEffect(()=>{if(typeof document>"u")return;const D=document.documentElement;return D.style.setProperty("--oc-chat-inset-left",`${ve}px`),D.style.setProperty("--oc-chat-inset-right",`${ne}px`),()=>{D.style.removeProperty("--oc-chat-inset-left"),D.style.removeProperty("--oc-chat-inset-right")}},[ve,ne]),a.useEffect(()=>{if(typeof document>"u")return;const D=document.documentElement;return D.classList.toggle("wide-chat-layout",p),()=>D.classList.remove("wide-chat-layout")},[p]),a.useEffect(()=>{if(typeof document>"u")return;const D=f&&(H||te),he=document.documentElement;return he.classList.toggle("oc-keep-draft-starters",D),()=>he.classList.remove("oc-keep-draft-starters")},[te,f,H]);const qe=a.useMemo(()=>({openChanges:({diffPath:D,staged:he}={})=>{ye(D?{path:D,staged:he===!0}:null)},openFiles:()=>ue(),openSettings:()=>Y("nav"),openInstances:q?()=>A("instances"):void 0,instanceLabel:q?Be():null,openUpdate:Z?()=>A("update"):void 0}),[ye,ue,Y,A,q,Z]),T=a.useMemo(()=>({openSessions:()=>{f?J(!0):B(!0)},openView:D=>{if(D==="files"){ue();return}(D==="instances"||D==="update"||D==="mcp")&&A(D)},openChanges:({path:D,staged:he}={})=>{ye(D?{path:D,staged:he===!0}:null)},openSettings:D=>{D&&I(D),Y(D?"page-content":"nav")}}),[f,ye,ue,Y,A,I,B,J]);Vo(T);const M=a.useRef(null);Qs(M,{leftOpen:f?ae:n,rightOpen:i,leftWidth:()=>f?se.width:R.current?.offsetWidth||window.innerWidth*.72,rightWidth:()=>f?z.width:h.current?.offsetWidth||window.innerWidth,onLeftProgress:D=>{if(S.current=D,f){Pn({inner:$},D,se.width,"left");return}Nn({drawer:R,scrim:U},"left",D)},onRightProgress:D=>{if(y.current=D,f&&j){Pn({inner:b},D,z.width,"right");return}Nn({drawer:h,scrim:v},"right",D)},onLeftOpen:()=>{f?J(!0):B(!0)},onLeftClose:()=>{f?J(!1):B(!1)},onRightOpen:()=>g(!0),onRightClose:()=>g(!1),onDragStart:D=>{if(P(),D==="left"){S.current=f?ae?1:0:n?1:0,f?Tn({shell:se.asideRef,inner:$}):En({drawer:R,scrim:U,root:F});return}y.current=i?1:0,f&&j?Tn({shell:z.asideRef,inner:b}):En({drawer:h,scrim:v,root:L})},onDragEnd:(D,he)=>{if(D==="left"){const Ae=typeof he=="boolean"?he:S.current>.5;if(S.current=Ae?1:0,f){const lt=An({shell:se.asideRef,inner:$},Ae,se.width,"left");lt!==void 0&&N.current.push(lt)}else Rn("left",Ae,{drawer:R,scrim:U,root:F});return}const it=typeof he=="boolean"?he:y.current>.5;if(y.current=it?1:0,f&&j){const Ae=An({shell:z.asideRef,inner:b},it,z.width,"right");Ae!==void 0&&N.current.push(Ae)}else Rn("right",it,{drawer:h,scrim:v,root:L})}});const W=a.useCallback(()=>w?(E(!1),!0):r?(X(),!0):i?(G(),!0):n?(B(!1),!0):!1,[r,X,G,w,n,E,B,i]);zo(W);const ee=f?"dialog":"fullscreen";return t.jsx(ea,{actions:qe,children:t.jsxs("div",{className:"oc-mobile-app-shell main-content-safe-area relative flex h-[100dvh] flex-row bg-background text-foreground","data-page-scroll-lock":"true",children:[f?t.jsxs("aside",{ref:se.asideRef,className:K("relative flex h-full shrink-0 flex-col overflow-hidden border-r border-border/70 bg-sidebar motion-reduce:transition-none",!ae&&"border-r-0"),style:{width:ve,minWidth:ve,maxWidth:ve,"--oc-ipad-sidebar-width":`${se.width}px`,overflowX:"clip",paddingTop:"var(--oc-safe-area-top, 0px)"},inert:!ae,"data-page-scroll-lock":"true",children:[t.jsx("div",{ref:$,className:K("flex h-full shrink-0 flex-col",se.isResizing&&"pointer-events-none",!ae&&"pointer-events-none select-none"),style:{width:"var(--oc-ipad-sidebar-width)",overflowX:"hidden",transform:se.isResizing||we.slidIn?"translateX(0)":"translateX(-100%)",transition:se.isResizing?"none":"transform 200ms cubic-bezier(0.22, 1, 0.36, 1)"},children:t.jsx(pe,{children:t.jsx(pn,{open:ae,variant:"sidebar",onOpenChange:xt})})}),ae?t.jsx(In,{side:"left",isResizing:se.isResizing,ariaLabel:"Resize left panel",handleProps:se.handleProps}):null]}):null,t.jsxs("div",{className:"relative flex h-full min-w-0 flex-1 flex-col","data-page-scroll-lock":"true",children:[f?t.jsxs(t.Fragment,{children:[t.jsx(Zs,{}),t.jsx(er,{onToggleRightDrawer:ot,rightDrawerOpen:i,tabletWorkspaceTab:c,onSelectTabletWorkspaceTab:Pe})]}):t.jsx(lo,{onOpenSessions:()=>B(!0),onOpenWorkspace:()=>g(!0)}),t.jsx("main",{ref:M,className:"relative min-h-0 flex-1 overflow-hidden","data-page-scroll-lock":"true",style:{touchAction:"pan-x pan-y"},children:t.jsx("div",{className:"h-full w-full",children:t.jsx(pe,{children:t.jsx(ti,{})})})})]}),f?null:t.jsx(pn,{open:n,onOpenChange:B,drawerRefExternal:R,scrimRefExternal:U,rootRefExternal:F}),f?t.jsxs("aside",{ref:z.asideRef,className:K("relative flex h-full shrink-0 flex-col overflow-hidden border-l border-border/70 bg-background motion-reduce:transition-none",!ne&&"border-l-0"),style:{width:ne,minWidth:ne,maxWidth:ne,"--oc-ipad-sidebar-width":`${z.width}px`,overflowX:"clip",paddingTop:"var(--oc-safe-area-top, 0px)"},inert:!ne,"data-page-scroll-lock":"true",children:[t.jsx("div",{ref:b,className:K("flex h-full min-h-0 shrink-0 flex-col transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",z.isResizing&&"pointer-events-none",!ne&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-ipad-sidebar-width)",overflowX:"hidden",transform:ne?"translateX(0)":"translateX(100%)",transition:z.isResizing?"none":"transform 200ms cubic-bezier(0.22, 1, 0.36, 1), opacity 200ms cubic-bezier(0.22, 1, 0.36, 1)"},children:t.jsx(pe,{children:t.jsx(Sn,{open:i,onClose:G,tab:c,onTabChange:u,pendingChangesDiff:x,variant:Q?"panel":"drawer",drawerRefExternal:h,scrimRefExternal:v,rootRefExternal:L})})}),ne?t.jsx(In,{side:"right",isResizing:z.isResizing,ariaLabel:"Resize right panel",handleProps:z.handleProps}):null]}):t.jsx(Sn,{open:i,onClose:G,tab:c,onTabChange:u,pendingChangesDiff:x,drawerRefExternal:h,scrimRefExternal:v,rootRefExternal:L}),r==="instances"&&q?t.jsx(jt,{open:!0,variant:ee,dialogAlign:"app",onClose:X,ariaLabel:"Instances",title:"Instances",children:t.jsx(co,{onConnect:X,onActiveConnectionDeleted:e})}):null,r==="settings"?t.jsx(jt,{open:!0,variant:ee,dialogAlign:"app",onClose:X,ariaLabel:"Settings",headerless:!0,children:t.jsx(pe,{children:t.jsx(oa,{forceMobile:!f,isWindowed:!0,initialMobileStage:d,onClose:X})})}):null,r==="update"?t.jsx(jt,{open:!0,variant:ee,dialogAlign:"app",onClose:X,ariaLabel:"Update",title:"Update",children:t.jsx(pe,{children:t.jsx("div",{className:"h-full overflow-auto px-5 py-4",children:t.jsx(ia,{initialUpdateDialogOpen:!0})})})}):null,t.jsx(pe,{children:t.jsx(tr,{})})]})})};function si({apis:e}){const n=je(A=>A.initializeApp),s=je(A=>A.isInitialized),r=je(A=>A.isConnected),o=je(A=>A.connectionPhase),i=je(A=>A.providers.length),l=je(A=>A.agents.length),c=je(A=>A.loadProviders),u=je(A=>A.loadAgents),d=On(A=>A.currentDirectory),m=ge(A=>A.error),x=ge(A=>A.clearError),k=de(A=>A.setIsMobile),N=Or(A=>A.refreshStatus),[P,R]=a.useState(0),[U,F]=a.useState(0),[h,v]=a.useState(!1),[L,$]=a.useState("pending"),[b,S]=a.useState(null),y=a.useMemo(()=>Be(),[]),[,B]=a.useReducer(A=>A+1,0),g=a.useMemo(()=>at(),[]),I=a.useRef(0),w=a.useRef(0),E=a.useCallback(()=>{const A=Se(),G=w.current+1;if(w.current=G,!A){dt();return}const Y=()=>{n(),N(e.github,{force:!0}),i===0&&c({source:"mobileApp:nativeResume"}),l===0&&u({source:"mobileApp:nativeResume"})},f=()=>{$e({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),R(_=>_+1)};Ze().then(_=>{if(w.current===G){if(_==="no-connection"){f();return}if(_==="needs-login"){S({kind:"auth-expired",label:Be()??""}),f();return}if(_==="unreachable"){window.setTimeout(()=>{w.current===G&&Ze().then(H=>{if(w.current===G&&H!=="switched"){if(H==="unchanged"){Y();return}H==="needs-login"&&S({kind:"auth-expired",label:Be()??""}),f()}})},4e3);return}_!=="switched"&&Y()}});const j=Date.now();j-I.current>=ei&&(I.current=j,window.dispatchEvent(new Event("pichamber:system-resume")))},[l,e.github,n,u,c,i,N]);_o(),Mo(E),a.useEffect(()=>Ns(),[]),a.useEffect(()=>{if(!g)return;let A;const G=()=>{window.clearTimeout(A),A=window.setTimeout(()=>E(),1500)};return window.addEventListener("online",G),()=>{window.removeEventListener("online",G),window.clearTimeout(A)}},[g,E]),a.useEffect(()=>(Vt(e),()=>Vt(null)),[e]),a.useEffect(()=>Rs(A=>{if(!!A.runtimeKey&&A.runtimeKey===A.previousRuntimeKey){Vs(),B();return}Ks(A),F(Y=>Y+1),R(Y=>Y+1)}),[]),a.useEffect(()=>{$n()},[U]),a.useEffect(()=>{if(!g||r||Se()){$("done");return}let A=!1;return $("attempting"),dt().catch(()=>({status:"no-candidate"})).then(G=>{A||(G.status==="unreachable"?S({kind:"unreachable",label:G.label}):G.status==="needs-login"&&S({kind:"auth-expired",label:G.label}),$("done"))}),()=>{A=!0}},[]),a.useEffect(()=>{if(!g||!Se())return;let A=!1;const G=Y=>{Y&&S(Y),$e({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),R(f=>f+1)};return Ze().then(async Y=>{if(A||Y==="switched"||Y==="unchanged")return;const f=Be();if(Y==="needs-login"){G({kind:"auth-expired",label:f??""});return}if(Y==="unreachable"){G(f?{kind:"unreachable",label:f}:null);return}const j=await dt().catch(()=>({status:"no-candidate"}));A||j.status==="connected"||(j.status==="needs-login"?G({kind:"auth-expired",label:j.label}):j.status==="unreachable"?G({kind:"unreachable",label:j.label}):G(null))}),()=>{A=!0}},[]),a.useEffect(()=>{k(!0)},[k]),a.useEffect(()=>{g&&!Se()||n()},[P,n,g]),a.useEffect(()=>{r&&(i===0&&c({source:"mobileApp:recovery"}),l===0&&u({source:"mobileApp:recovery"}))},[l,r,u,c,i]);const p=a.useRef(!1),[C,O]=a.useState(g);a.useEffect(()=>{if(!g||!r||p.current)return;if(ge.getState().currentSessionId){p.current=!0,O(!1);return}const A=rt(),G=$r(A);if(!G){p.current=!0,O(!1);return}let Y=!1;const f=window.setTimeout(()=>O(!1),6e3);return(async()=>{const j=await Ur().catch(()=>null);if(Y)return;if(!j){O(!1);return}p.current=!0;const _=j.activeSessions.find(te=>te.id===G.sessionId);if(!_){Br(A),O(!1);return}const H=ge.getState();H.currentSessionId||H.setCurrentSession(_.id,At(_)??G.directory??void 0),O(!1)})(),()=>{Y=!0,window.clearTimeout(f)}},[P,r,g]),a.useEffect(()=>{r&&Fr.setDirectory(d)},[d,r]),a.useEffect(()=>{r&&N(e.github,{force:!0})},[e.github,r,N]),a.useEffect(()=>{if(!m)return;const A=window.setTimeout(()=>x(),5e3);return()=>window.clearTimeout(A)},[x,m]),a.useEffect(()=>{if(!(!r&&(g?!!Se():!0))){v(!1);return}const G=window.setTimeout(()=>{v(!0)},g?4e3:8e3);return()=>window.clearTimeout(G)},[r,g,P,U]),Hr(),Ps({enabled:!0}),As(),Gs(),qo({enabled:g&&r}),Ko({ready:g&&r&&s});const q=Oo(),Z=!r&&o==="reconnecting";if(!q)return t.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background text-foreground",children:t.jsx(Ce,{width:120,height:120,isAnimated:!0})});const X=!!Se();return g&&(!X||!r&&!Z)?X?t.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background px-6 text-center text-foreground",children:t.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-4",children:[t.jsx(Ce,{width:120,height:120,isAnimated:!h}),h?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"space-y-2",children:[t.jsx("h1",{className:"typography-h3 text-foreground",children:"Unable to reach server"}),t.jsx("p",{className:"typography-body text-muted-foreground",children:"Could not connect to the saved server. Check that it is running, or pick another instance."})]}),t.jsx(re,{type:"button",variant:"outline",onClick:()=>{$e({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),R(A=>A+1)},children:"Use another server"})]}):null]})}):L!=="done"?t.jsxs("main",{className:"relative flex min-h-dvh items-center justify-center bg-background text-foreground",children:[t.jsx(Ce,{width:120,height:120,isAnimated:!0}),y?t.jsxs("div",{className:"absolute inset-x-0 top-[calc(50%+84px)] flex flex-col items-center gap-0.5 px-6 text-center",children:[t.jsx("p",{className:"typography-small text-muted-foreground",children:"Connecting to device:"}),t.jsxs("p",{className:"typography-small text-foreground",children:[y,t.jsx(Wr,{})]})]}):null]}):t.jsx(t.Fragment,{children:t.jsx(so,{onConnected:()=>R(A=>A+1),notice:b})}):!r&&!Z?h?t.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background px-6 text-center text-foreground",children:t.jsxs("div",{className:"max-w-sm space-y-3",children:[t.jsx("h1",{className:"typography-h3 text-foreground",children:"Unable to reach server"}),t.jsx("p",{className:"typography-body text-muted-foreground",children:"We could not verify the UI session. If you're opening PiChamber from another device on your local network, make sure Desktop Network Access is enabled on the desktop app and use the LAN address shown in Settings."})]})}):t.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background text-foreground",children:t.jsx(Ce,{width:120,height:120,isAnimated:!0})}):t.jsx(pe,{children:t.jsx(Vr,{children:t.jsx(Kr,{apis:e,children:t.jsx(Gr,{delayDuration:300,skipDelayDuration:150,children:t.jsxs(Xs,{children:[t.jsx(qs,{}),t.jsxs("div",{className:"h-full bg-background text-foreground",children:[g&&C?t.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background",children:t.jsx(Ce,{width:120,height:120,isAnimated:!0})}):null,t.jsx(Xr,{embeddedBackgroundWorkEnabled:s}),t.jsx(Ta,{}),t.jsx(ni,{onActiveConnectionDeleted:()=>{$e({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),R(A=>A+1)}}),t.jsx(Ys,{}),t.jsx(qr,{position:"top-center",offset:"calc(var(--oc-safe-area-top, 0px) + 16px)"}),t.jsx(Yr,{}),s?t.jsx(Da,{}):null]})]})})})},U)})}const ri=()=>{Ts().then(()=>{Promise.all([$n(),Is()]).catch(e=>{console.error("[mobile-main] settings init failed:",e)}),Ds(),Ls(),_s()}).catch(e=>{console.error("[mobile-main] appearance init failed:",e)}).finally(()=>{wa()})};function ai(e){window.__PICHAMBER_SURFACE__="mobile",ta(),ri(),Ra(),na();const n=document.getElementById("root");if(!n)throw new Error("Root element not found");const r=window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",o=e??Et();if(!o)throw new Error("Runtime APIs not registered");const i=r?{...o,notifications:{notifyAgentCompletion:async()=>!1,canNotify:()=>!1}}:o,l=t.jsx(si,{apis:i});vs.createRoot(n).render(t.jsx(De.StrictMode,{children:t.jsx(sa,{children:t.jsx(ra,{children:t.jsx(sr,{children:r?l:t.jsx(aa,{children:l})})})})}))}const wi=Object.freeze(Object.defineProperty({__proto__:null,renderMobileApp:ai},Symbol.toStringTag,{value:"Module"}));export{vi as m,wi as r};
|