@pi-chamber/web 0.9.9 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -67
- package/bin/cli.js +7 -32
- package/bin/dev-server.js +185 -0
- package/bin/dev-server.test.js +252 -0
- package/bin/lib/DOCUMENTATION.md +19 -0
- package/bin/lib/cli-startup.js +9 -1
- package/bin/lib/cli-startup.test.js +30 -0
- package/bin/lib/commands-serve.js +9 -5
- package/bin/lib/server-runtime.js +6 -0
- package/bin/lib/server-runtime.test.js +313 -0
- package/dist/assets/{DiagramView-YPcSEyVl.js → DiagramView-COHSzZ9Z.js} +1 -1
- package/dist/assets/{DiffView-IrM_w65M.js → DiffView-BA4LWExp.js} +1 -1
- package/dist/assets/{FileSaveConflictDialog-CtDwDmHo.js → FileSaveConflictDialog-hRumcJ2e.js} +1 -1
- package/dist/assets/{FilesView-EUL5SZDG.js → FilesView-CIx6Bq8l.js} +1 -1
- package/dist/assets/{GitView-7K4eJ1V3.js → GitView-3Hgk_pVS.js} +3 -3
- package/dist/assets/{JsonTreeView-Qz0QeRmI.js → JsonTreeView-CVLGj7jk.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-CsJfFWDC.js → MarkdownRendererImpl-CWeQW9_O.js} +2 -2
- package/dist/assets/{PatchDiff-DNhojsLA.js → PatchDiff-367QPDDL.js} +1 -1
- package/dist/assets/{SessionSwitcherContent-l1fTUann.js → SessionSwitcherContent-CbgywSHr.js} +1 -1
- package/dist/assets/{SessionSwitcherDropdown-CUyTFUnd.js → SessionSwitcherDropdown-BAHhqkBZ.js} +2 -2
- package/dist/assets/{SessionUnreadDot-CY3rTilj.js → SessionUnreadDot-CvIWGgIi.js} +1 -1
- package/dist/assets/SettingsView-BpGtnBKt.js +2 -0
- package/dist/assets/{SettingsWindow-9FD4QY3p.js → SettingsWindow-CN0wm-Fv.js} +1 -1
- package/dist/assets/{ToolOutputDialog-0uj3Kf5J.js → ToolOutputDialog-Bkh0DWJn.js} +3 -3
- package/dist/assets/{ToolPartDiffPreview-B29vAjqI.js → ToolPartDiffPreview-C_V9k2ob.js} +1 -1
- package/dist/assets/{VirtualizedFileDiff-B1Jii7gu.js → VirtualizedFileDiff-CFToyUp4.js} +4 -4
- package/dist/assets/{collapsible-B6bVtxgp.js → collapsible-BXBoS1M4.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-B6RnDAuP.js → computeVirtualFileMetrics-BpbB2xiE.js} +2 -2
- package/dist/assets/{contextFileOpenGuard-DIpJPFxL.js → contextFileOpenGuard-DsdrIBIY.js} +1 -1
- package/dist/assets/{gitStatusPredicates-lhIrHyDw.js → gitStatusPredicates-KYx0Vs9h.js} +1 -1
- package/dist/assets/{index-BUxQG4Eq.js → index-CVZfC79h.js} +1 -1
- package/dist/assets/{index-BXgR2dKM.css → index-Ci9OMaKW.css} +1 -1
- package/dist/assets/{index-BOtRfXre.js → index-DyeT2dc_.js} +7 -7
- package/dist/assets/{isDiffPlainText-r5sF6_KV.js → isDiffPlainText-dBQiDlRy.js} +1 -1
- package/dist/assets/{isFilePlainText-B4e2b2Bv.js → isFilePlainText-DWMzO-Ms.js} +1 -1
- package/dist/assets/{main-DSfSGm2f.js → main-DkXvFwTR.js} +3 -3
- package/dist/assets/{main-DMYsDuaV.js → main-DukaBOy3.js} +2 -2
- package/dist/assets/{markdownCore-0ygaCYcc.js → markdownCore-BH61OrJ2.js} +1 -1
- package/dist/assets/{miniChat-DUMRG1q5.js → miniChat-B1uBoxSn.js} +2 -2
- package/dist/assets/{mobile-DUcoCNyj.js → mobile-DV_RYy3x.js} +2 -2
- package/dist/assets/{renderElectronMiniChatApp-BNmJJQdl.js → renderElectronMiniChatApp-CA6co_Lh.js} +2 -2
- package/dist/assets/renderMobileApp-CyhFZ_4g.js +11 -0
- package/dist/assets/runtimeEndpointReset-CVoKFaRw.js +53 -0
- package/dist/assets/{runtimeSurface-CPm7KWaN.js → runtimeSurface-CxbVCK7k.js} +1 -1
- package/dist/assets/{useAppFontEffects-CDmJGQlK.js → useAppFontEffects-HCEusnq7.js} +86 -86
- package/dist/assets/{useFilesViewSearch-DDMI---4.js → useFilesViewSearch-Cq7IOB7l.js} +1 -1
- package/dist/assets/{usePushVisibilityBeacon-i8sRCEtS.js → usePushVisibilityBeacon-Tvi9uL7v.js} +1 -1
- package/dist/assets/{useSwitcherItems-BT_toOh9.js → useSwitcherItems-DLA7kskG.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-D09wcguI.js → vendor-codemirror-language-data-zF3O85ti.js} +2 -2
- package/dist/assets/{web-components-Cb0vnR_a.js → web-components-C7g3Hi85.js} +3 -3
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +8 -3
- package/server/index.js +40 -6
- package/server/lib/notifications/DOCUMENTATION.md +39 -0
- package/server/lib/notifications/delivery-runtime.js +314 -0
- package/server/lib/notifications/delivery-runtime.test.js +85 -0
- package/server/lib/notifications/pi-notification-watcher.js +154 -0
- package/server/lib/notifications/pi-notification-watcher.test.js +84 -0
- package/server/lib/notifications/routes.js +74 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -0
- package/server/lib/pi/session-daemon/pi-runtime-smoke.test.js +466 -0
- package/server/lib/pi/ui-settings-store.js +3 -2
- package/server/lib/server/runtime-requirements.js +193 -0
- package/server/lib/server/runtime-requirements.test.js +295 -0
- package/dist/assets/SettingsView-Cm4cKNof.js +0 -2
- package/dist/assets/renderMobileApp-DnhfWGEW.js +0 -11
- package/dist/assets/runtimeEndpointReset-B0SWG9Uo.js +0 -53
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/FilesView-EUL5SZDG.js","assets/vendor-react-B5Z1Mdn3.js","assets/vendor-scheduler-7OC5HNn7.js","assets/index-BOtRfXre.js","assets/vendor-zustand-GVb4H8HE.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-BXgR2dKM.css","assets/useAppFontEffects-CDmJGQlK.js","assets/vendor-base-ui-DXSHfszQ.js","assets/vendor-floating-ui-utils-BzXdqYpP.js","assets/vendor-floating-ui-dom-WyXykhNi.js","assets/vendor-floating-ui-core-CXmKXOXc.js","assets/vendor-floating-ui-react-dom-BZOGXAGe.js","assets/vendor-use-sync-external-store-D0AXkdQC.js","assets/vendor-simplewebauthn-browser-VDA66rT_.js","assets/vendor-sonner-BDtm25td.js","assets/vendor-codemirror-view-Ct4T37Ue.js","assets/vendor-codemirror-state-CNWM3Q8V.js","assets/vendor-marijn-find-cluster-break-DXwl3gUT.js","assets/vendor-style-mod-NZ5MEPvj.js","assets/vendor-w3c-keyname-Vcq4gwWv.js","assets/vendor-crelt-C8TCjufn.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-class-variance-authority-5VPnzWs2.js","assets/runtimeSurface-CPm7KWaN.js","assets/vendor-dnd-kit-core-C9qcAm_1.js","assets/vendor-dnd-kit-utilities-DTY1C6ST.js","assets/vendor-dnd-kit-accessibility-DZKKhs9S.js","assets/vendor-dnd-kit-sortable-D8ozj8M-.js","assets/vendor-cmdk-zXx6sGnS.js","assets/vendor-radix-ui-react-dialog-D2yhEu2p.js","assets/vendor-radix-ui-primitive-Dc_FVRD7.js","assets/vendor-radix-ui-react-compose-refs-8xy6TJML.js","assets/vendor-radix-ui-react-context-CFsX-AUC.js","assets/vendor-radix-ui-react-id-D2kS9K1j.js","assets/vendor-radix-ui-react-use-layout-effect-C8Yrsaph.js","assets/vendor-radix-ui-react-use-controllable-state-LiqmKSXO.js","assets/vendor-radix-ui-react-dismissable-layer-DrorBNg9.js","assets/vendor-radix-ui-react-primitive-DkH8dMOR.js","assets/vendor-radix-ui-react-slot-BIDFZX0-.js","assets/vendor-radix-ui-react-use-callback-ref-BwDcSoGV.js","assets/vendor-radix-ui-react-use-escape-keydown-DTkqjenV.js","assets/vendor-radix-ui-react-focus-scope-D2BkImwt.js","assets/vendor-radix-ui-react-portal-YgCRIyi7.js","assets/vendor-radix-ui-react-presence-D432pCMB.js","assets/vendor-radix-ui-react-focus-guards-BfdFmL7c.js","assets/vendor-react-remove-scroll-vR1dy1aP.js","assets/vendor-tslib-De9GV7Vy.js","assets/vendor-react-remove-scroll-bar-CSAHp1YF.js","assets/vendor-react-style-singleton-Ctw6HnYx.js","assets/vendor-get-nonce-C-Z93AgS.js","assets/vendor-use-sidecar-Vv4V8Nd1.js","assets/vendor-use-callback-ref-CVVuCyLj.js","assets/vendor-aria-hidden-DvXkyWUv.js","assets/vendor-codemirror-language-BByA_dGF.js","assets/vendor-lezer-common-B3-cUCR_.js","assets/vendor-lezer-highlight-CDMHUZ74.js","assets/vendor-codemirror-lang-javascript-DuOEwJ3f.js","assets/vendor-lezer-javascript-D7Tj24ot.js","assets/vendor-lezer-lr-bhwg1HMg.js","assets/vendor-codemirror-autocomplete-wd6iRebq.js","assets/vendor-codemirror-lang-json-CZ07HmNC.js","assets/vendor-lezer-json-Iaex0UN-.js","assets/vendor-codemirror-lang-css-djiuoTi8.js","assets/vendor-lezer-css-C5xB6jxd.js","assets/vendor-codemirror-lang-html-CKHqhW5R.js","assets/vendor-lezer-html-C0I1p52t.js","assets/vendor-codemirror-lang-markdown-DtcZDGqe.js","assets/vendor-lezer-markdown-C6g-d6P3.js","assets/vendor-codemirror-language-data-D09wcguI.js","assets/vendor-codemirror-lang-python-DzzokVau.js","assets/vendor-lezer-python-CvuFxeZl.js","assets/vendor-codemirror-commands-CNlncqrr.js","assets/vendor-tanstack-react-virtual-2skouoFw.js","assets/vendor-tanstack-virtual-core-Dubg10g5.js","assets/vendor-framer-motion-CfplGuM0.js","assets/vendor-motion-dom-DhJ-sYS5.js","assets/vendor-motion-utils-CKEGc_YG.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/themeResolver-yJ9XpNMI.js","assets/vendor-pierre-theming-Dgp7B_O4.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/FileSaveConflictDialog-CtDwDmHo.js","assets/vendor-react-drawio-BYDptOsj.js","assets/runtimeEndpointReset-B0SWG9Uo.js","assets/SessionUnreadDot-CY3rTilj.js","assets/vendor-xterm-xterm-CrXqRur4.js","assets/vendor-xterm-xterm-DDGTF8rc.css","assets/permissionStore-iKN1K2_x.js","assets/runtimeEndpointReset-BV3KOtdA.css","assets/useFilesViewSearch-DDMI---4.js","assets/JsonTreeView-Qz0QeRmI.js","assets/web-components-Cb0vnR_a.js","assets/computeVirtualFileMetrics-B6RnDAuP.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.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/Virtualizer-BSHVMKgK.js","assets/isFilePlainText-B4e2b2Bv.js","assets/vendor-codemirror-search-BV44140v.js","assets/vendor-replit-codemirror-vim-DaSwPsXt.js","assets/GitView-7K4eJ1V3.js","assets/gitStatusPredicates-lhIrHyDw.js","assets/VirtualizedFileDiff-B1Jii7gu.js","assets/isDiffPlainText-r5sF6_KV.js","assets/vendor-diff-C3JhlQdm.js","assets/collapsible-B6bVtxgp.js","assets/vendor-capacitor-app-BrDJj9I_.js","assets/vendor-capacitor-core-B4EWRrHz.js","assets/vendor-capacitor-push-notifications-KNe1zSBF.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as wt,j as n,R as a,b as ze,e as qn}from"./vendor-react-B5Z1Mdn3.js";import"./vendor-katex-CNckGUMB.js";import{u as we,a as ie,b as gn,d as Kt,e as rt,i as q,f as Je,h as ne,s as Ee,j as Qn,k as Ye,r as Zn,l as xn,m as vn,p as er,n as tr,o as K,q as wn,t as nr,v as kt,w as rr,x as sr,y as Wt,z as ar,A as kn,B as ir}from"./index-BOtRfXre.js";import{u as or,a as lr,s as cr}from"./usePushVisibilityBeacon-i8sRCEtS.js";import{u as Oe,a as ur,M as dr,b as fr,i as pr,D as Ft,c as Ht,d as Vt,g as hr,e as Gt,f as mr,s as yr,S as br,T as gr,h as xr,j as vr,k as wr,H as kr,A as Sr,C as Cr,r as jr,l as Er,m as Rr,F as Tr,n as Nr,o as Ir,W as Pr,p as Ar}from"./runtimeEndpointReset-B0SWG9Uo.js";import{g as He,l as _r,u as Dr,a as Sn,b as Mr,c as Or,r as Cn,d as Lr,t as ht,o as zr,I as F,B as Q,P as Re,e as ce,f as Ur,h as Br,i as $r,j as Kr,E as de,k as jn,m as Wr,n as Fr,p as Hr,q as Vr,s as Gr,D as Xr,v as Jr,w as Yr,x as ge,y as qr,z as pe,A as Qr,C as Zr,F as es,G as ts,H as ns,J as rs,K as ss,L as as,R as is,W as os,T as ls,S as cs,M as us,N as ds,O as fs,Q as ps,U as hs,V as ms,X as ys,Y as bs}from"./useAppFontEffects-CDmJGQlK.js";import{Capacitor as gs}from"./vendor-capacitor-core-B4EWRrHz.js";import{p as xs}from"./vendor-aparajita-capacitor-secure-storage-5IShChL0.js";import{_ as Ue}from"./vendor-vite-runtime-DD1OZmLC.js";import{S as vs,A as ws}from"./SettingsView-Cm4cKNof.js";import{f as ks,S as Ss,a as Cs,g as En}from"./SessionUnreadDot-CY3rTilj.js";import{u as js}from"./useSwitcherItems-BT_toOh9.js";let Rn=null,Xt=!1;const Es=new Promise(e=>{Rn=e});function Rs(){Xt||(Xt=!0,Rn?.())}const Ts=6,Ns=e=>e.parentID??null,Jt=e=>{const t=e.replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||t},Is=e=>e.replace(/\\/g,"/").replace(/\/+$/,""),Ps=(e,t)=>{if(!e)return"";let r=null,s=-1;for(const o of t){const i=Is(o.path);(e===i||e.startsWith(`${i}/`))&&i.length>s&&(r=o,s=i.length)}return r?r.label?.trim()||Jt(r.path):Jt(e)},As=()=>{const e=He().getState().catalog,t=[];for(const d of e.byId.values())d.archived||t.push(_r(d));const r=Dr.getState().index.session.unseenCount,s=we.getState().notifyOnSubtasks,o=Sn.getState().projects,i=Mr.getState().ids,l=Or.getState().rankById;let c=0;const u=[];for(const d of t){const m=Ns(d)!==null,v=(r[d.id]??0)>0&&(!m||s);v&&(c+=1),m||u.push({session:d,unread:v,project:Ps(Cn(d),o)})}u.sort((d,m)=>Lr(d.session,m.session,i,l));const p=u.slice(0,Ts).map(({session:d,unread:m,project:j})=>({id:d.id,title:d.title??"",unread:m,project:j}));return{runtimeKey:ie(),attentionCount:c,recentSessions:p}},_s="__PICHAMBER_WIDGET_SNAPSHOT__",Ds=()=>{typeof window>"u"||(window[_s]=()=>{try{return JSON.stringify(As())}catch{return null}})},mt="mobile-app-update-available",Yt="mobile-app-update-toast-dismissed-version",Ms=()=>{const e=Oe(i=>i.available),t=Oe(i=>i.runtimeType),r=Oe(i=>i.info?.version),s=Oe(i=>i.info?.downloadUrl),o=wt.useRef(new Set);return wt.useEffect(()=>{if(gn()!=="android"||t!=="mobile"||!e||!r||!s){ht.dismiss(mt);return}Kt().getItem(Yt)!==r&&(o.current.has(r)||(o.current.add(r),ht.info("PiChamber update available",{id:mt,description:`Version ${r} is ready for Android.`,duration:1/0,icon:n.jsx(F,{name:"download",className:"h-4 w-4 text-muted-foreground"}),action:{label:"Download",onClick:()=>{zr(s)}},cancel:{label:"Dismiss",onClick:()=>{Kt().setItem(Yt,r),ht.dismiss(mt)}}})))},[e,s,t,r]),null},Os=e=>{const{persisted:t,persistedDirectory:r,stale:s,ready:o,catalog:i,runtimeKey:l,capturedRuntimeKey:c,storeIdentityMatches:u,generationMatches:p}=e;if(!t||!r)return{action:"wait"};if(s||l!==c||!u||!p)return{action:"wait"};if(!o||!i)return{action:"wait"};const d=i.byId.get(t.sessionId);return!d||d.archived?{action:"clear"}:{action:"select",sessionId:d.id,directory:d.directory??r}},st="pichamber.mobile.connections.v1",Ls="pichamber.mobile.",qt="pichamber.mobile.deviceId",Tn=12,zs=8e3,Us=2500,Bs=3e3,at=2500,Be=15e3,$s=1500,Ks=5e3,Ws=()=>{try{const e=window.localStorage.getItem(qt);if(e&&e.trim())return e.trim();const t=rt();return window.localStorage.setItem(qt,t),t}catch{return rt()}},Qt=()=>`mobile:${Ws()}`,Zt=()=>{try{const e=gs.getPlatform();return e==="ios"||e==="android"?e:void 0}catch{return}},Nn=()=>{let e=0;return{begin:()=>(e+=1,e),cancel:()=>{e+=1},isCurrent:t=>t===e}},_e=e=>{const t=e.trim();if(!t)return"";const r=/^https?:\/\//i.test(t)?t:`http://${t}`,s=new URL(r);return s.hash="",s.search="",s.pathname=s.pathname.replace(/\/+$/,""),s.toString().replace(/\/+$/,"")},Xe=e=>{try{return new URL(e).host}catch{return e}},$e=e=>{try{return _e(e)}catch{return e.trim().replace(/\/+$/g,"")}},Rt=(e,t)=>$e(e)===$e(t),Tt=e=>`relay:${e.serverId}@${e.relayUrl.trim()}`,Fs=e=>`relay://${e.serverId}`,ct=e=>e.candidates.filter(t=>t.kind==="direct"),Pe=e=>{const t=e.candidates.find(r=>r.kind==="relay");return t&&t.kind==="relay"?t.relay:null},fe=e=>{const t=ct(e)[0];if(t)return t.url;const r=Pe(e);return r?Fs(r):""},V=e=>{const t=Pe(e);if(t)return Tt(t);const r=ct(e)[0];return r?$e(r.url):""},it=(e,t)=>{const r=e.find(i=>i.kind==="relay"),s=r&&r.kind==="relay"?r.relay.serverId:null,o=new Set(e.filter(i=>i.kind==="direct").map(i=>$e(i.url)));return t.some(i=>i.kind==="relay"?s!==null&&i.relay.serverId===s:o.has($e(i.url)))},Nt=e=>{const t=(()=>{try{return _e(e)}catch{return""}})();return t?[{kind:"direct",url:t}]:[]},en=e=>{if(e.candidates&&e.candidates.length>0)return e.candidates;const t=[];return typeof e.url=="string"&&e.url.trim()&&!/^relay:\/\//i.test(e.url.trim())&&t.push(...Nt(e.url)),e.relay&&t.push({kind:"relay",relay:e.relay}),t},It=e=>{if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e;if(typeof t.relayUrl!="string"||!t.relayUrl.trim()||typeof t.serverId!="string"||!t.serverId.trim())return null;const r=t.hostEncPubJwk;if(!r||typeof r!="object"||Array.isArray(r))return null;const s=r;return s.kty!=="EC"||s.crv!=="P-256"||typeof s.x!="string"||!s.x||typeof s.y!="string"||!s.y?null:{relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:{kty:"EC",crv:"P-256",x:s.x,y:s.y}}},Hs=e=>{if(!e||typeof e!="object")return null;const t=e;if(t.kind==="direct")return typeof t.url=="string"&&t.url.trim()?{kind:"direct",url:t.url}:null;if(t.kind==="relay"){const r=It(t.relay);return r?{kind:"relay",relay:r}:null}return null},Vs=e=>{if(e.mode==="relay"){const t=It(e.relay);return t?[{kind:"relay",relay:t}]:[]}return typeof e.url=="string"?Nt(e.url):[]},qe=e=>e.kind==="relay"?{kind:"relay",relay:{relayUrl:e.relay.relayUrl,serverId:e.relay.serverId,hostEncPubJwk:e.relay.hostEncPubJwk}}:{kind:"direct",url:e.url},De=()=>{if(typeof window>"u")return[];let e;try{e=JSON.parse(window.localStorage.getItem(st)||"[]")}catch{return[]}if(!Array.isArray(e))return[];const t=q();return e.flatMap(r=>{if(!r||typeof r!="object")return[];const s=r;if(typeof s.id!="string")return[];const o=Array.isArray(s.candidates)?s.candidates.map(Hs).filter(u=>!!u):Vs(s);if(o.length===0)return[];const i=typeof s.clientToken=="string"&&s.clientToken.trim()?s.clientToken:void 0,l=typeof s.label=="string"&&s.label.trim()?s.label:Xe(fe({candidates:o})),c={id:s.id,label:l,candidates:o,lastUsedAt:typeof s.lastUsedAt=="number"?s.lastUsedAt:0};return t?[{...c,hasToken:!!s.hasToken||!!i}]:[{...c,clientToken:i,hasToken:!!i}]}).sort((r,s)=>s.lastUsedAt-r.lastUsedAt)},Pt=e=>{if(typeof window>"u")return;const t=q(),r=e.slice(0,Tn).map(s=>{const o={id:s.id,label:s.label,candidates:s.candidates.map(qe),lastUsedAt:s.lastUsedAt};return t?{...o,hasToken:!!(s.hasToken||s.clientToken)}:{...o,clientToken:s.clientToken}});try{window.localStorage.setItem(st,JSON.stringify(r))}catch(s){console.warn("[mobile-storage] failed to persist connection metadata",s)}},In=(e,t)=>{const r=e.find(i=>t.id&&i.id===t.id||it(i.candidates,t.candidates)),s=q(),o={id:t.id||r?.id||rt(),label:t.label,candidates:t.candidates,lastUsedAt:Date.now(),...s?{hasToken:t.hasToken??(!!t.clientToken||r?.hasToken||!1)}:{clientToken:t.clientToken??r?.clientToken,hasToken:!!(t.clientToken??r?.clientToken)}};return[o,...e.filter(i=>i.id!==o.id&&!it(i.candidates,t.candidates))].slice(0,Tn)},At=xs,Gs=0,_t=e=>`${Ls}token.${encodeURIComponent(e)}`,Xs=async(e,t)=>{let r;const s=new Promise(o=>{r=window.setTimeout(()=>o(t),Bs)});try{return await Promise.race([e.catch(()=>t),s])}finally{r!==void 0&&window.clearTimeout(r)}},Dt=async(e,t,r)=>q()?Xs(t().catch(s=>(console.warn(`[mobile-storage] ${e} failed`,s),r)),r):r,Qe=async e=>{const t=await Dt("secure:read",async()=>(await At.internalGetItem({prefixedKey:_t(e),sync:!1})).data,null);return typeof t=="string"&&t.trim()?t:void 0},Te=async(e,t)=>Dt("secure:write",async()=>(await At.internalSetItem({prefixedKey:_t(e),data:t,sync:!1,access:Gs}),!0),!1),Js=async e=>{await Dt("secure:delete",async()=>(await At.internalRemoveItem({prefixedKey:_t(e),sync:!1}),!0),!1)},Pn=async(e,t)=>{let r=0,s=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 t(c,u))return s+=1,i;r+=1;const{clientToken:p,...d}=l;return{...d,hasToken:!0}})),migrated:r,failed:s}},An=async()=>{if(typeof window>"u"||!q())return;let e;try{e=JSON.parse(window.localStorage.getItem(st)||"[]")}catch{return}if(!Array.isArray(e)||e.filter(s=>!!s&&typeof s=="object"&&typeof s.url=="string"&&typeof s.clientToken=="string"&&!!s.clientToken.trim()).length===0)return;const r=await Pn(e,async(s,o)=>{const i=$e(s);return await Te(i,o)?await Qe(i)===o:!1});if(r.migrated>0)try{window.localStorage.setItem(st,JSON.stringify(r.records))}catch(s){console.warn("[mobile-storage] failed to finalize secure token migration",s)}},_n=async()=>(await An(),De()),Ze=async e=>{const t=In(De(),e);return Pt(t),q()&&e.clientToken&&await Te(V({candidates:e.candidates}),e.clientToken),t},Dn=async e=>{const t=De(),r=t.find(o=>o.id===e)??null,s=t.filter(o=>o.id!==e);return Pt(s),r&&q()&&await Js(V(r)),s},Mt=e=>{try{return JSON.stringify(e)}catch{return String(e)}},G=(e,t={})=>{console.info("[mobile-connect]",e,Mt(t)),Zn("connect",{code:e,status:typeof t.status=="number"?t.status:void 0,detail:typeof t.reason=="string"?t.reason:typeof t.result=="string"?t.result:void 0})},Ys=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},qs=e=>{if(typeof e!="string")return e??void 0;try{return JSON.parse(e)}catch{return e}},Qs=async(e,t)=>{if(!q())return null;try{const{CapacitorHttp:r}=await Ue(async()=>{const{CapacitorHttp:i}=await import("./vendor-capacitor-core-B4EWRrHz.js");return{CapacitorHttp:i}},[]),s=Object.fromEntries(new Headers(t?.headers).entries()),o=await r.request({url:e,method:t?.method||"GET",headers:s,data:qs(t?.body)});return{ok:o.status>=200&&o.status<300,status:o.status,source:"native-http",json:async()=>Ys(o.data)}}catch(r){return console.warn("[mobile-connect]","native-http failed",Mt({url:e,error:r instanceof Error?r.message:String(r)})),null}},Zs=async(e,t)=>{const r=await fetch(e,t).catch(s=>(console.warn("[mobile-connect]","browser-fetch failed",Mt({url:e,error:s instanceof Error?s.message:String(s)})),null));return r?{ok:r.ok,status:r.status,source:"browser-fetch",json:()=>r.json()}:null},ke=async(e,t,r)=>{let s;const o=new Promise(i=>{s=window.setTimeout(()=>{r?.(),i(null)},e)});try{return await Promise.race([t,o])}catch{return null}finally{s!==void 0&&window.clearTimeout(s)}},Ae=async(e,t,r)=>{const s=r?.totalTimeoutMs??zs,o=Date.now(),i=await ke(Math.min(Us,s),Qs(e,t));if(i)return i;const l=new AbortController,c=Math.max(500,s-(Date.now()-o));return ke(c,Zs(e,{...t,signal:l.signal}),()=>l.abort())},ut=async e=>{if(!e)return null;const t=await e.json().catch(()=>null);if(!t||typeof t!="object")return null;const r=t;return{authenticated:typeof r.authenticated=="boolean"?r.authenticated:void 0,disabled:typeof r.disabled=="boolean"?r.disabled:void 0,scope:typeof r.scope=="string"?r.scope:void 0}},ea=async(e,t,r,s=Be,o)=>{if(o?.shouldAbort?.())return{outcome:"unreachable"};const i=xn({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=t?{Authorization:`Bearer ${t}`}:void 0,u=await ke(s,i.fetch("/auth/session",{headers:c}).catch(()=>null));if(G("relay:session",{ok:u?.ok===!0,status:u?.status??null,hasToken:!!t}),!u)return l("unreachable");if(u.status===401)return l(t?"auth-failed":"needs-login");if(!u.ok&&u.status!==404)return l("auth-failed");const p=await ut(u);return p&&p.disabled!==!0&&p.authenticated===!1?l(t?"auth-failed":"needs-login"):l("ok")}catch(c){throw i.close(),c}},ta=(e,t,r,s,o)=>{const i=typeof window<"u"?window.location.origin:"",l={relayUrl:e.relayUrl,serverId:e.serverId,hostEncPubJwk:e.hostEncPubJwk,...r?{grant:r}:{}};o&&Qn(l,o),Ee({apiBaseUrl:i,clientToken:t,runtimeKey:s??Tt(e),relay:l})},ot=async(e,t,r)=>{const s=r?.shouldAbort,o=r?.fast?{totalTimeoutMs:at}:void 0,i=Pe({candidates:e})?.serverId??null,l=e.find(d=>d.kind==="relay")??null,c=e.filter(d=>d.kind==="direct"),u=async()=>{for(const d of c){if(s?.())return{status:"unreachable"};const m=_e(d.url)||d.url,j=t?{Authorization:`Bearer ${t}`}:void 0,v=await Ae(`${m}/health`,{method:"GET"},o);if(s?.())return{status:"unreachable"};if(!v?.ok)continue;if(i){const _=await v.json().catch(()=>null),I=_&&typeof _=="object"?_.serverId:null;if(typeof I=="string"&&I&&I!==i){G("probe:server-id-mismatch",{url:m});continue}}const w=await Ae(`${m}/auth/session`,{method:"GET",credentials:t?"omit":"include",headers:j},o);if(s?.())return{status:"unreachable"};if(w?.status===401)return{status:"needs-login"};if(!w||!w.ok&&w.status!==404)continue;const N=await ut(w);if(N&&N.disabled!==!0&&N.authenticated===!1)return{status:"needs-login"};const L=N?.disabled===!0;return!t&&q()&&!L&&N?.scope!=="client"?{status:"needs-login"}:{status:"ok",transport:{kind:"direct",url:m}}}return{status:"unreachable"}},p=async()=>{if(!l)return{status:"unreachable"};if(s?.())return{status:"unreachable"};const{outcome:d,tunnel:m}=await ea(l.relay,t,void 0,r?.fast?at:void 0,{keepTunnel:!0,...s?{shouldAbort:s}:{}});return s?.()?(m?.close(),{status:"unreachable"}):d==="ok"?{status:"ok",transport:{kind:"relay",relay:l.relay,tunnel:m}}:d==="needs-login"||d==="auth-failed"?{status:"needs-login"}:{status:"unreachable"}};return l?c.length===0?p():new Promise(d=>{let m=!1,j=!1,v,w=null,N=null;const L=h=>{h?.status==="ok"&&h.transport.kind==="relay"&&h.transport.tunnel?.close()},_=h=>{m||(m=!0,d(h))},I=()=>{j||m||s?.()||(v!==void 0&&(window.clearTimeout(v),v=void 0),p().then(h=>{if(N=h,m||j){L(h);return}if(h.status==="ok"||h.status==="needs-login"){_(h);return}w&&_(w)}))};u().then(h=>{if(w=h,!m){if(h.status==="ok"||h.status==="needs-login"){j=!0,v!==void 0&&window.clearTimeout(v),L(N),_(h);return}if(N){_(N);return}I()}}),v=window.setTimeout(I,$s)}):u()},Ne=(e,t,r)=>{e.kind==="relay"?ta(e.relay,t,r?.grant,r?.runtimeKey,e.tunnel):Ee({apiBaseUrl:e.url,clientToken:t,runtimeKey:r?.runtimeKey}),Un()},xe=()=>{const e=De()[0];return e?.label?.trim()?e.label:null},nt=async()=>{const e=Je(),t=`${ie()}|${ne()}`,r=()=>Je()!==e||`${ie()}|${ne()}`!==t;if(await An(),r())return{status:"no-candidate"};const s=De()[0];if(!s)return{status:"no-candidate"};let o;if(q()){if(!s.hasToken)return{status:"no-candidate"};if(o=await Qe(V(s)),!o)return{status:"no-candidate"}}else if(o=s.clientToken,!o)return{status:"no-candidate"};const i=await ot(s.candidates,o,{fast:!0});return r()?(Ct(i),{status:"no-candidate"}):i.status==="needs-login"?{status:"needs-login",label:s.label}:i.status!=="ok"?{status:"unreachable",label:s.label}:(await Ze({id:s.id,label:s.label,candidates:s.candidates}),r()?(lt(i.transport),{status:"no-candidate"}):(Ne(i.transport,o,{runtimeKey:V(s)}),{status:"connected"}))},Mn=async(e,t)=>{let r="";try{r=_e(e.url)}catch{return!1}if(!r)return!1;const s=e.clientToken?.trim()||void 0,o=s?{Authorization:`Bearer ${s}`}:void 0,i=t?.fast?{totalTimeoutMs:at}:void 0;if(!(await Ae(`${r}/health`,{method:"GET",headers:o},i))?.ok)return!1;const c=await Ae(`${r}/auth/session`,{method:"GET",credentials:s?"omit":"include",headers:o},i);if(!c||!c.ok&&c.status!==404)return!1;const u=await ut(c);return!(u&&u.disabled!==!0&&u.authenticated===!1)},tn=async e=>{const t=Pe({candidates:e})?.serverId??null;for(const r of e){if(r.kind==="relay"){const i=xn(r.relay),l=await ke(Be,i.fetch("/health").catch(()=>null));if(G("establish:relay:health",{ok:l?.ok===!0,status:l?.status??null}),l?.ok)return{kind:"relay",relay:r.relay,tunnel:i};i.close();continue}const s=_e(r.url)||r.url,o=await Ae(`${s}/health`,{method:"GET"});if(G("establish:direct:health",{ok:o?.ok===!0,status:o?.status??null}),!!o?.ok){if(t){const i=await o.json().catch(()=>null),l=i&&typeof i=="object"?i.serverId:null;if(typeof l=="string"&&l&&l!==t){G("establish:server-id-mismatch",{url:s});continue}}return{kind:"direct",url:s}}}return null},na=e=>[...e].sort((t,r)=>{const s=(t.priority??100)-(r.priority??100);if(s!==0)return s;const o=i=>i.type==="relay"?2:i.url.startsWith("https://")?0:1;return o(t)-o(r)}).flatMap(t=>{if(t.type==="relay"){const r=It({relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:t.hostEncPubJwk});return r?[{kind:"relay",relay:r}]:[]}return Nt(t.url)}),On=async(e,t)=>{if(!Ye())return Mn(e,t);const r=await ke(t?.fast?at:Be,vn("/auth/session").then(o=>o).catch(()=>null));if(!r)return!0;if(r.status===401)return!1;if(!r.ok&&r.status!==404)return!0;const s=await ut(r);return!(s&&s.disabled!==!0&&s.authenticated===!1)},ra=e=>e.kind==="relay"?Ye():!Ye()&&Rt(e.url,ne()),dt=()=>{const e=ie();return e?De().find(t=>V(t)===e)??null:null},St=e=>{const t=ie();return!!t&&V(e)===t},Ot=e=>({generation:Je(),runtimeKey:ie(),apiBaseUrl:ne(),connectionId:e.id,secureKey:V(e),candidatesJson:JSON.stringify(e.candidates.map(qe))}),Ln=e=>{if(Je()!==e.generation||ie()!==e.runtimeKey||ne()!==e.apiBaseUrl)return!0;const t=dt();if(!t||t.id!==e.connectionId||V(t)!==e.secureKey)return!0;try{if(JSON.stringify(t.candidates.map(qe))!==e.candidatesJson)return!0}catch{return!0}return!1},lt=e=>{try{e?.kind==="relay"&&e.tunnel?.close()}catch{}},Ct=e=>{e.status==="ok"&<(e.transport)},sa=e=>e?`${e.generation}|${e.runtimeKey}|${e.apiBaseUrl}|${e.connectionId}|${e.secureKey}|${e.candidatesJson}`:`noselection|${Je()}|${ie()}`;let Ie=null,jt="";const nn=(e,t)=>{const r=t.finally(()=>{Ie===r&&(Ie=null,jt="")});return Ie=r,jt=e,r},Lt=()=>{const e=dt(),t=e?Ot(e):null,r=sa(t);if(Ie&&jt===r)return Ie;if(Ie){const o=Ie.then(()=>yt(),()=>yt());return nn(r,o)}return nn(r,yt())},yt=async()=>{const e=dt();if(!e)return"no-connection";const t=Ot(e),r=()=>Ln(t);let s;if(q()){if(s=e.hasToken?await Qe(V(e)):void 0,r())return"no-connection"}else s=e.clientToken;if(!s)return"unreachable";if(r())return"no-connection";const o=e.candidates.findIndex(p=>ra(p.kind==="relay"?{kind:"relay",relay:p.relay}:{kind:"direct",url:p.url})),i=o>=0?e.candidates.slice(0,o):e.candidates,l=await ot(i,s,{fast:!0,shouldAbort:r});if(r())return Ct(l),"no-connection";if(l.status==="ok")return await Ze({id:e.id,label:e.label,candidates:e.candidates}),r()?(lt(l.transport),"no-connection"):(Ne(l.transport,s,{runtimeKey:V(e)}),"switched");if(l.status==="needs-login")return"needs-login";if(o>=0){if(r())return"no-connection";const p=await On({url:t.apiBaseUrl,clientToken:s},{fast:!0});if(r())return"no-connection";if(p)return Un(),"unchanged"}const c=o>=0?e.candidates.slice(o+1):[];if(c.length===0)return"unreachable";const u=await ot(c,s,{fast:!0,shouldAbort:r});return r()?(Ct(u),"no-connection"):u.status==="ok"?(await Ze({id:e.id,label:e.label,candidates:e.candidates}),r()?(lt(u.transport),"no-connection"):(Ne(u.transport,s,{runtimeKey:V(e)}),"switched")):u.status==="needs-login"?"needs-login":"unreachable"};let bt=!1;const zn=async()=>{if(bt)return"skipped";const e=dt();if(!e)return G("candidates:refresh-skip",{reason:"no-active-connection"}),"skipped";const t=Pe(e);if(!t)return G("candidates:refresh-skip",{reason:"no-relay-candidate"}),"skipped";const r=Ot(e),s=()=>Ln(r);bt=!0;try{const o=await ke(Be,vn("/api/client-auth/connection/candidates").then(m=>m).catch(()=>null));if(!o?.ok)return G("candidates:refresh-skip",{reason:"fetch-failed",status:o?.status??null}),"skipped";if(s())return G("candidates:refresh-skip",{reason:"selection-changed"}),"skipped";const i=await o.json().catch(()=>null);if(!i||i.serverId!==t.serverId)return G("candidates:refresh-skip",{reason:"server-id-mismatch"}),"skipped";const l=Array.isArray(i.candidates)?i.candidates:[],c=[];for(const m of l){if(!m||typeof m!="object")continue;const j=m;if(!(j.type!=="lan"||typeof j.url!="string"))try{const v=_e(j.url);v&&!c.includes(v)&&c.push(v)}catch{}}if(c.length===0)return G("candidates:refresh-skip",{reason:"no-lan-reported"}),"skipped";const u=ct(e).filter(m=>m.url.startsWith("https://")),p=[...c.map(m=>({kind:"direct",url:m})),...u,{kind:"relay",relay:t}];return JSON.stringify(e.candidates.map(qe))===JSON.stringify(p.map(qe))?"unchanged":s()?(G("candidates:refresh-skip",{reason:"selection-changed"}),"skipped"):(G("candidates:refreshed",{lanCount:c.length}),await Ze({id:e.id,label:e.label,candidates:p}),"updated")}finally{bt=!1}},Un=()=>{typeof window>"u"||window.setTimeout(()=>{(async()=>{const e=await zn().catch(()=>"skipped");G("candidates:refresh-result",{result:e}),e==="updated"&&Ye()&&await Lt().catch(()=>null)})()},Ks)},zt=e=>{const[t,r]=a.useState(()=>De()),[s,o]=a.useState(null),[i,l]=a.useState(null),[c,u]=a.useState(null),p=a.useRef(t),d=a.useRef(null),m=a.useRef(Nn()),j=a.useCallback(x=>{p.current=x,r(x)},[]),v=a.useCallback(x=>{d.current=x,o(x)},[]),w=a.useCallback(x=>{d.current===x&&(d.current=null,o(null))},[]);a.useEffect(()=>{let x=!1;return _n().then(E=>{x||j(E)}),()=>{x=!0}},[j]);const N=a.useCallback(x=>{const E=In(p.current,x);return j(E),Pt(E),E},[j]),L=a.useCallback(async x=>{l(null),v("connect");try{const E=en(x);if(E.length===0){l("Enter a server URL.");return}const R=x.id?p.current.find(T=>T.id===x.id):p.current.find(T=>it(T.candidates,E)),M=x.label?.trim()||R?.label||Xe(fe({candidates:E})),P=x.relayGrant;let z=x.clientToken?.trim()||void 0;const f=!!z;z||(q()?R?.hasToken&&(z=await Qe(V({candidates:E}))):z=R?.clientToken),G("connect:start",{candidates:E.map(T=>T.kind),hasToken:!!z});const g=await ot(E,z);if(G("connect:probe",{status:g.status}),g.status==="unreachable"){l("Could not reach that PiChamber server.");return}if(g.status==="needs-login"){N({id:R?.id,label:M,candidates:E}),u({id:R?.id??rt(),label:M,candidates:E,relay:Pe({candidates:E})??void 0,relayGrant:P});return}z&&f&&q()&&await Te(V({candidates:E}),z),N({id:R?.id,label:M,candidates:E,clientToken:z}),Ne(g.transport,z??null,{runtimeKey:V({candidates:E}),grant:P}),e()}catch(E){console.warn("[mobile-connect] connect threw",E),l("That server URL is not valid.")}finally{w("connect")}},[v,w,e,N]),_=a.useCallback(async x=>{if(d.current==="pairing")return;l(null),v("pairing");const E=na(x.candidates);let R=null,M=!1;try{if(R=await tn(E),!R){l("Could not reach that PiChamber server.");return}const P=JSON.stringify({pairingId:x.pairingId,secret:x.secret,clientLabel:"PiChamber Mobile",clientKind:"mobile",deviceName:"PiChamber Mobile",devicePlatform:Zt(),dedupeKey:Qt()}),z={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:P},f=R.kind==="relay"?await ke(Be,R.tunnel.fetch("/api/client-auth/pairing/redeem",z).catch(()=>null)):await Ae(`${R.url}/api/client-auth/pairing/redeem`,z);if(!f?.ok){l("This server needs a password or client token.");return}const g=await f.json().catch(()=>null),T=typeof g?.clientToken=="string"?g.clientToken.trim():"";if(!T){l("This server needs a password or client token.");return}const k=typeof g?.server?.label=="string"?g.server.label:"",A=x.label||k||Xe(fe({candidates:E}));if(q()&&!await Te(V({candidates:E}),T)){l("This server needs a password or client token.");return}N({label:A,candidates:E,clientToken:T}),Ne(R.kind==="relay"?{kind:"relay",relay:R.relay,tunnel:R.tunnel}:{kind:"direct",url:R.url},T,{runtimeKey:V({candidates:E})}),M=R.kind==="relay",e()}catch(P){console.warn("[mobile-connect] pairing threw",P),l("This server needs a password or client token.")}finally{!M&&R?.kind==="relay"&&R.tunnel.close(),w("pairing")}},[v,w,e,N]),I=a.useCallback(async x=>{if(!c||!x.trim()||d.current==="password")return;l(null),v("password");const E=m.current.begin(),R=()=>m.current.isCurrent(E),{id:M,label:P,candidates:z}=c;let f=null,g=!1;try{if(f=await tn(z),!R())return;if(!f){l("Could not reach that PiChamber server.");return}const T={method:"POST",credentials:"include",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify({password:x,trustDevice:!0,issueClientToken:!0,clientLabel:"PiChamber Mobile",clientKind:"mobile",devicePlatform:Zt(),dedupeKey:Qt()})};G("password:start",{transport:f.kind});const k=f.kind==="relay"?await ke(Be,f.tunnel.fetch("/auth/session",T).catch(()=>null)):await Ae(`${f.url}/auth/session`,T);if(!R())return;if(G("password:done",{ok:k?.ok===!0,status:k?.status??null}),!k?.ok){l("Could not unlock that server. Check the password.");return}const A=await k.json().catch(()=>null);if(!R())return;const X=typeof A?.clientToken=="string"?A.clientToken.trim():"";if(G("password:token",{issued:!!X}),!X){if(f.kind==="direct"&&!q()){N({id:M,label:P,candidates:z}),u(null),Ne({kind:"direct",url:f.url},null,{runtimeKey:V({candidates:z})}),e();return}l("This server needs a password or client token.");return}if(q()&&(!R()||(await Te(V({candidates:z}),X),!R()))||!R()||(N({id:M,label:P,candidates:z,clientToken:X}),u(null),Ne(f.kind==="relay"?{kind:"relay",relay:f.relay,tunnel:f.tunnel}:{kind:"direct",url:f.url},X,{runtimeKey:V({candidates:z})}),g=f.kind==="relay",!R()))return;e()}catch(T){if(!R())return;console.warn("[mobile-connect] password threw",T),l("Could not unlock that server. Check the password.")}finally{!g&&f?.kind==="relay"&&f.tunnel.close(),R()&&w("password")}},[v,w,e,c,N]),h=a.useCallback(()=>{m.current.cancel(),w("password"),u(null),l(null)},[w]),b=a.useCallback(async x=>{l(null);let E=en(x);const R=x.id?p.current.find(f=>f.id===x.id)??null:null;if(R){const f=E.filter(k=>k.kind==="direct"),g=ct(R).filter(k=>k.url.startsWith("https://")&&!f.some(A=>Rt(A.url,k.url))),T=Pe(R);E=[...f,...g,...T?[{kind:"relay",relay:T}]:[]]}if(E.length===0)return l("Enter a server URL."),null;const M=x.clientToken?.trim()||void 0,P=x.label?.trim()||Xe(fe({candidates:E}));if(q()){const f=V({candidates:E});if(M)await Te(f,M);else if(R?.hasToken){const g=V(R);if(g&&f&&g!==f){const T=await Qe(g);T&&await Te(f,T)}}}return N({id:x.id,label:P,candidates:E,clientToken:M}).find(f=>it(f.candidates,E))??null},[N]),U=a.useCallback(async x=>{const E=p.current.find(M=>M.id===x)??null,R=await Dn(x);return j(R),E},[j]);return{connections:t,isBusy:s!==null,isPasswordBusy:s==="password",error:i,pendingConnection:c,connect:L,redeemPairingConnection:_,submitPassword:I,cancelPassword:h,saveConnection:b,removeConnection:U,setError:l}},si=Object.freeze(Object.defineProperty({__proto__:null,autoConnectLastInstance:nt,connectionDisplayUrl:fe,createMobilePasswordOperationTracker:Nn,deleteMobileConnection:Dn,getAutoConnectTargetLabel:xe,getConnectionLabel:Xe,isActiveRuntimeConnection:St,isSameConnectionUrl:Rt,loadMobileConnections:_n,migrateLegacyInlineTokenRecords:Pn,normalizeConnectionUrl:_e,refreshActiveConnectionCandidates:zn,relayConnectionRuntimeKey:Tt,reprobeActiveConnection:Lt,upsertMobileConnection:Ze,useMobileConnection:zt,validateActiveRuntimeSession:On,validateMobileConnectionSession:Mn},Symbol.toStringTag,{value:"Module"})),Bn=()=>{if(typeof window>"u")return null;const t=window.Capacitor?.Plugins?.BarcodeScanner;return t&&(typeof t.scan=="function"||typeof t.startScan=="function")?t:null},aa=()=>window.Capacitor?.getPlatform?.()==="android",$n=e=>{const t=e.trim();if(!t)return null;if(/^pichamber:\/\//i.test(t)){const r=er(t);return r?{pairing:r}:null}return/^https?:\/\//i.test(t)?{url:t}:null},Kn=(e,t)=>{const r=$n(e);if(!r&&t?.pairingStringFallback){const s=tr(e);if(s)return{status:"pairing",pairing:s}}return r?"pairing"in r?{status:"pairing",...r}:{status:"ok",...r}:{status:"invalid"}},ia=async(e,t)=>{if(!e.startScan||!e.stopScan||!e.addListener)return{status:"unsupported"};if(t?.aborted)return{status:"cancelled"};let r,s,o=!1,i=()=>{};const l=new Promise(p=>{i=p}),c=p=>{o||(o=!0,i(p))},u=()=>c({status:"cancelled"});t?.addEventListener("abort",u,{once:!0});try{return(await Promise.allSettled([Promise.resolve(e.addListener("barcodesScanned",({barcodes:d})=>{const m=d?.[0],j=(m?.rawValue??m?.displayValue??"").trim();j&&c(Kn(j,{pairingStringFallback:!0}))})).then(d=>{r=d}),Promise.resolve(e.addListener("scanError",()=>c({status:"failed"}))).then(d=>{s=d})])).some(({status:d})=>d==="rejected")?c({status:"failed"}):o||e.startScan({formats:["QR_CODE"]}).catch(()=>c({status:"failed"})),await l}finally{t?.removeEventListener("abort",u),await Promise.allSettled([Promise.resolve(r?.remove()),Promise.resolve(s?.remove()),e.stopScan()])}},Et=()=>Bn()!==null,Wn=async e=>{const t=Bn();if(!t)return{status:"unsupported"};try{if(t.requestPermissions){const l=(await t.requestPermissions())?.camera;if(l&&l!=="granted"&&l!=="limited")return{status:"permission-denied"}}if(e?.signal?.aborted)return{status:"cancelled"};if(aa())return ia(t,e?.signal);if(!t.scan)return{status:"unsupported"};const s=(await t.scan({formats:["QR_CODE"]}))?.barcodes?.[0],o=(s?.rawValue??s?.displayValue??"").trim();return o?Kn(o):{status:"cancelled"}}catch{return{status:"failed"}}},Le={autoComplete:"off",autoCorrect:"off",spellCheck:!1},Ve="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",Fn=({onCancel:e})=>{const t=a.useRef(null);return a.useLayoutEffect(()=>{const r={value:document.documentElement.style.getPropertyValue("background-color"),priority:document.documentElement.style.getPropertyPriority("background-color")},s={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===t.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}),r.value?document.documentElement.style.setProperty("background-color",r.value,r.priority):document.documentElement.style.removeProperty("background-color"),s.value?document.body.style.setProperty("background-color",s.value,s.priority):document.body.style.removeProperty("background-color")}},[]),a.useEffect(()=>{const r=()=>{document.visibilityState==="hidden"&&e()};return document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[e]),ze.createPortal(n.jsxs("div",{ref:t,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:[n.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center gap-6",children:[n.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}),n.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."})]}),n.jsxs(Q,{type:"button",variant:"outline",size:"lg",className:"mx-auto min-h-12 w-full max-w-sm bg-background",onClick:e,children:[n.jsx(F,{name:"close",className:"size-[18px]"}),"Cancel"]})]}),document.body)},Hn=()=>ze.createPortal(n.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:[n.jsx(Re,{width:96,height:96,isAnimated:!0}),n.jsxs("div",{className:"flex items-center gap-2 typography-ui-label text-muted-foreground",children:[n.jsx(F,{name:"loader-4",className:"size-[18px] animate-spin"}),n.jsx("span",{children:"Connecting..."})]})]}),document.body),oa=({onConnected:e,notice:t=null})=>{const r=zt(e),{connections:s,isBusy:o,isPasswordBusy:i,error:l,pendingConnection:c}=r,[u,p]=a.useState(""),[d,m]=a.useState(""),[j,v]=a.useState(""),[w,N]=a.useState(!1),[L,_]=a.useState(!1),I=a.useRef(null),h=a.useMemo(()=>Et(),[]),[b,U]=a.useState(()=>!Et()),[x,E]=a.useState(null),[R,M]=a.useState(""),P=a.useCallback(k=>{k.preventDefault(),r.connect({url:u,clientToken:j,label:d})},[j,r,d,u]),z=a.useCallback(k=>{if(/^pichamber:\/\//i.test(k.trim())){const A=$n(k);if(A){if("pairing"in A){r.redeemPairingConnection(A.pairing);return}p(A.url),A.label&&m(A.label),A.clientToken&&v(A.clientToken);return}}p(k)},[r]),f=a.useCallback(async()=>{if(I.current||o)return;r.setError(null),N(!0);const k=new AbortController;I.current=k;try{const A=await Wn({signal:k.signal});switch(I.current===k&&(I.current=null,N(!1)),A.status){case"ok":_(!0),p(A.url),A.label&&m(A.label),A.clientToken&&v(A.clientToken),await r.connect({url:A.url,clientToken:A.clientToken,label:A.label});break;case"pairing":_(!0),await r.redeemPairingConnection(A.pairing);break;case"permission-denied":r.setError("Camera access is off. Enable it in Settings to scan a QR code.");break;case"invalid":r.setError("That QR code is not an PiChamber connection code.");break;case"unsupported":r.setError("QR scanning is only available in the installed mobile app.");break;case"failed":r.setError("Could not scan that QR code. Try again or enter the URL manually.");break;default:break}}finally{_(!1),I.current===k&&(I.current=null,N(!1))}},[r,o]);a.useEffect(()=>()=>I.current?.abort(),[]);const g=a.useCallback(k=>{k.preventDefault(),r.submitPassword(R)},[r,R]),T=a.useCallback(()=>{M(""),r.cancelPassword()},[r]);return n.jsxs(n.Fragment,{children:[w?n.jsx(Fn,{onCancel:()=>I.current?.abort()}):null,L?n.jsx(Hn,{}):null,n.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:n.jsxs("div",{className:"m-auto flex w-full max-w-[360px] shrink-0 flex-col items-center gap-9 py-8",children:[n.jsxs("div",{className:"flex flex-col items-center gap-5 text-center",children:[n.jsx(Re,{width:72,height:72,className:"size-[72px]"}),n.jsx("h1",{className:"typography-h2 text-foreground",children:"Connect to PiChamber"})]}),t?n.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:[n.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:n.jsx(F,{name:t.kind==="auth-expired"?"lock":"cloud-off",className:"size-[18px]"})}),n.jsx("p",{className:"min-w-0 flex-1 typography-small text-foreground",children:t.kind==="auth-expired"?`Access to ${t.label} has expired or was revoked. Sign in again.`:`Couldn't reach ${t.label}. Check that the server is running.`})]}):null,c?n.jsxs("form",{className:"flex w-full flex-col gap-3",onSubmit:g,children:[n.jsxs("div",{className:"flex items-center gap-3 rounded-[18px] border border-border/70 bg-surface-elevated px-3.5 py-3",children:[n.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:n.jsx(F,{name:"lock",className:"size-[18px]"})}),n.jsxs("div",{className:"min-w-0 text-left",children:[n.jsx("p",{className:"truncate typography-ui-label text-foreground",children:c.label}),n.jsx("p",{className:"truncate typography-small text-muted-foreground",children:c.candidates.some(k=>k.kind==="direct")?fe(c):"via PiChamber Relay"})]})]}),n.jsx("input",{...Le,value:R,onChange:k=>M(k.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:Ve}),l?n.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,n.jsx(Q,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",disabled:i||!R.trim(),children:i?"Connecting...":"Unlock and connect"}),n.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:T,children:"Use another server"})]}):n.jsxs("div",{className:"flex w-full flex-col gap-6",children:[h?n.jsxs("div",{className:"flex w-full flex-col gap-2",children:[n.jsxs(Q,{type:"button",size:"lg",className:"h-12 w-full",onClick:()=>{f()},disabled:w||o,children:[n.jsx(F,{name:"scan-2",className:K("size-[18px]",w&&"animate-pulse")}),o?"Connecting...":"Scan QR code"]}),n.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&&!b?n.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,s.length>0?n.jsxs("section",{className:"flex w-full flex-col gap-2.5",children:[n.jsx("h2",{className:"text-center typography-micro uppercase tracking-[0.14em] text-muted-foreground",children:"Saved connections"}),n.jsx("div",{className:"overflow-hidden rounded-[18px] border border-border/70 bg-surface-elevated",children:s.map(k=>{const A=x===k.id;return n.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:()=>{E(k.id),r.connect({id:k.id,candidates:k.candidates,clientToken:k.clientToken,label:k.label}).finally(()=>E(null))},children:[n.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:n.jsx(F,{name:"server",className:"size-[18px]"})}),n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:k.label}),n.jsx("span",{className:K("block truncate typography-small",A?"text-foreground":"text-muted-foreground"),children:A?"Connecting...":k.candidates.some(X=>X.kind==="direct")?fe(k):"via PiChamber Relay"})]}),A?n.jsx(F,{name:"loader-4",className:"size-5 animate-spin text-muted-foreground"}):n.jsx(F,{name:"arrow-right-s",className:"size-5 text-muted-foreground"})]},k.id)})})]}):null,n.jsxs("div",{className:"flex w-full flex-col",children:[h?n.jsxs("button",{type:"button",onClick:()=>U(k=>!k),"aria-expanded":b,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:[n.jsx("span",{children:"Connect by address"}),n.jsx(F,{name:"arrow-down-s",className:K("size-4 transition-transform duration-200",b&&"rotate-180")})]}):null,n.jsx("div",{className:"grid transition-[grid-template-rows] duration-200 ease-out",style:{gridTemplateRows:b?"1fr":"0fr"},children:n.jsx("div",{className:"min-h-0 overflow-hidden",children:n.jsxs("form",{className:"flex w-full flex-col gap-3 pt-3",onSubmit:P,children:[n.jsx("input",{...Le,value:u,onChange:k=>z(k.target.value),placeholder:"http://192.168.1.74:2606","aria-label":"Server URL",type:"url",inputMode:"url",autoCapitalize:"none",tabIndex:b?void 0:-1,className:K(Ve,"text-center")}),n.jsx("input",{value:d,onChange:k=>m(k.target.value),placeholder:"Optional display name","aria-label":"Name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,tabIndex:b?void 0:-1,className:K(Ve,"text-center")}),n.jsx("input",{...Le,value:j,onChange:k=>v(k.target.value),placeholder:"Paste access token","aria-label":"Client token",tabIndex:b?void 0:-1,autoCapitalize:"none",className:K(Ve,"text-center")}),n.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?n.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,n.jsx(Q,{type:"submit",variant:h?"outline":"default",size:"lg",className:"h-12 w-full",disabled:o||w||!u.trim(),children:o?"Connecting...":"Connect"})]})})})]})]})]})})]})},la=10,ca=(e,t)=>En(e,t),ua=({session:e,meta:t,active:r,onSelect:s})=>{const o=Ur(e.id),i=Br(e.id),l=o?.type??"idle",c=l==="busy"||l==="retry",u=!c&&i>0&&!r,p=$r(e.id,c),d=c&&p,m=ks(e.time?.updated??e.time?.created??0);return n.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",r&&"bg-[color-mix(in_srgb,var(--primary)_10%,transparent)]"),onClick:s,style:{touchAction:"manipulation"},children:[n.jsxs("span",{className:"flex min-w-0 flex-1 flex-col",children:[n.jsx("span",{className:K("block truncate typography-ui-label",r?"text-primary":"text-foreground"),children:ca(e,"Untitled Session")}),t?n.jsx("span",{className:"block truncate typography-micro text-muted-foreground",children:t}):null]}),c?n.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-primary","aria-hidden":!0}):u?n.jsx(Ss,{label:"Session complete"}):null,d?n.jsx(Cs,{sessionId:e.id,running:c,className:"typography-micro"}):u?null:m?n.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground tabular-nums",children:m}):null]})},da=({open:e,onClose:t,anchorRef:r})=>{const{panelRef:s,wrapperRef:o,shouldRender:i,isExiting:l,anchorLeft:c,isPopover:u}=ur({open:e,onClose:t,anchorRef:r}),p=ce(w=>w.currentSessionId),d=ce(w=>w.setCurrentSession),m=Sn(w=>w.setActiveProjectIdOnly),j=js(e||i,{maxParents:la}),v=a.useCallback(w=>{d(w.id,Cn(w)),t()},[t,d]);return i?n.jsxs("div",{ref:o,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:[n.jsx("div",{ref:s,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",u?"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))",...u?{top:8,left:c??8,width:`min(${dr}px, calc(100% - 16px))`}:null},children:n.jsx("div",{className:"oc-hide-scrollbar min-h-0 flex-1 space-y-0.5 overflow-y-auto overscroll-contain",children:j.length===0?n.jsx("p",{className:"px-3 py-6 text-center typography-small text-muted-foreground",children:"No recent sessions"}):j.map(w=>{const N=w.node.session,L=[w.secondaryMeta?.projectLabel,w.secondaryMeta?.branchLabel].filter(Boolean).join(" · ");return n.jsx(ua,{session:N,meta:L,active:N.id===p,onSelect:()=>{w.projectId&&m(w.projectId),v(N)}},N.id)})})}),n.jsx("style",{children:`
|
|
3
|
-
@keyframes session-switcher-in {
|
|
4
|
-
from { opacity: 0; transform: translateY(-8px) scale(0.985); }
|
|
5
|
-
to { opacity: 1; transform: translateY(0) scale(1); }
|
|
6
|
-
}
|
|
7
|
-
@keyframes session-switcher-out {
|
|
8
|
-
from { opacity: 1; transform: translateY(0) scale(1); }
|
|
9
|
-
to { opacity: 0; transform: translateY(-6px) scale(0.985); }
|
|
10
|
-
}
|
|
11
|
-
`})]}):null},fa=({onOpenSessions:e,onOpenWorkspace:t,compactTitle:r=!1})=>{const[s,o]=a.useState(!1),[i,l]=a.useState(!1),c=a.useRef(null),u=wn(h=>h.currentDirectory),p=ce(h=>h.currentSessionId),m=ce(a.useCallback(h=>p?h.getDirectoryForSession(p):null,[p]))||u,j=Kr(p),v=ce(h=>!!h.newSessionDraft?.open),N=j?.title?.trim()||(p?En(j,"Untitled session"):"New session");a.useEffect(()=>{o(!1),l(!1)},[p,m]);const L=a.useCallback(()=>{o(!1),l(!1),e()},[e]),_=a.useCallback(h=>{o(b=>{const U=typeof h=="function"?h(b):h;return U&&l(!1),U})},[]),I=a.useCallback(()=>{l(h=>{const b=!h;return b&&o(!1),b})},[]);return n.jsxs(n.Fragment,{children:[n.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:n.jsxs("div",{className:"flex h-[var(--oc-header-height,56px)] w-full items-center gap-1 px-2",children:[n.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:L,style:{touchAction:"manipulation"},children:n.jsx(F,{name:"list-unordered",className:"size-5"})}),n.jsx("button",{ref:c,type:"button",className:K("flex h-10 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",r?"shrink":"flex-1"),"aria-label":"Open session switcher","aria-haspopup":"dialog","aria-expanded":i,onClick:I,style:{touchAction:"manipulation"},children:n.jsxs("span",{className:"flex min-w-0 items-center gap-1",children:[n.jsx("span",{className:"block min-w-0 truncate typography-ui-label text-foreground",children:N}),n.jsx(F,{name:"arrow-down-s",className:K("size-4 shrink-0 text-muted-foreground transition-transform duration-150",i&&"rotate-180")})]})}),r?n.jsx("div",{className:"min-w-0 flex-1"}):null,n.jsx(fr,{open:s,onOpenChange:_,currentSessionId:p,effectiveDirectory:m,isNewSessionDraftOpen:v}),n.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),t()},style:{touchAction:"manipulation"},children:n.jsx(F,{name:"layout-right",className:"size-5"})})]})}),n.jsx(da,{open:i,onClose:()=>l(!1),anchorRef:c})]})},pa=({onActiveConnectionDeleted:e,onConnect:t})=>{const r=zt(t),{connections:s,isBusy:o,isPasswordBusy:i,error:l,pendingConnection:c,connect:u,submitPassword:p,cancelPassword:d,saveConnection:m,removeConnection:j,setError:v}=r,[w,N]=a.useState(null),L=w?s.find(S=>S.id===w)??null:null,[_,I]=a.useState(null),[h,b]=a.useState(""),[U,x]=a.useState(""),[E,R]=a.useState(""),[M,P]=a.useState(""),[z,f]=a.useState(!1),[g,T]=a.useState(!1),[k,A]=a.useState(!1),[X,H]=a.useState(null),W=a.useRef(null),Z=a.useMemo(()=>Et(),[]),[se,B]=a.useState(!1),[J,We]=a.useState(null),oe=a.useCallback(()=>{N(null),b(""),x(""),R(""),v(null),B(!1)},[v]),me=a.useCallback(S=>{S.preventDefault(),m({id:w??void 0,url:h,label:U,clientToken:E}).then(D=>{D&&oe()})},[E,w,U,oe,m,h]),ee=a.useCallback(async()=>{if(W.current)return;v(null),f(!0);const S=new AbortController;W.current=S;try{const D=await Wn({signal:S.signal});switch(W.current===S&&(W.current=null,f(!1)),D.status){case"ok":b(D.url),D.label&&x(D.label),D.clientToken&&R(D.clientToken),B(!0);break;case"pairing":T(!0),await r.redeemPairingConnection(D.pairing);break;case"permission-denied":v("Camera access is off. Enable it in Settings to scan a QR code.");break;case"invalid":v("That QR code is not an PiChamber connection code.");break;case"unsupported":v("QR scanning is only available in the installed mobile app.");break;case"failed":v("Could not scan that QR code. Try again or enter the URL manually.");break;default:break}}finally{T(!1),W.current===S&&(W.current=null,f(!1))}},[r,v]);a.useEffect(()=>()=>W.current?.abort(),[]);const te=a.useCallback(S=>{S.preventDefault(),p(M)},[M,p]),Ce=a.useCallback(()=>{P(""),d()},[d]),ye=a.useCallback(async()=>{if(!k){H(null),A(!0);try{const S=await nr();H(S==="copied"?"Diagnostics copied to the clipboard.":S==="downloaded"?"Diagnostics downloaded.":"Diagnostics ready to share.")}catch{H("Diagnostics export was cancelled or unavailable.")}finally{A(!1)}}},[k]),y=a.useCallback(S=>{I(D=>D===S?null:S)},[]),O=a.useCallback(S=>{I(null),w===S&&oe();const D=s.length===1;j(S).then(Y=>{Y&&(D||St(Y))&&e()})},[s.length,w,e,j,oe]),$=Ve;return c?n.jsx("div",{className:"flex h-full flex-col overflow-hidden",children:n.jsx("form",{className:"flex-1 overflow-y-auto px-5 py-4",onSubmit:te,children:n.jsxs("div",{className:"flex flex-col gap-3",children:[n.jsxs("div",{className:"flex items-center gap-3 rounded-[18px] border border-border/70 bg-surface-elevated px-3.5 py-3",children:[n.jsx("span",{className:"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:n.jsx(F,{name:"lock",className:"size-[18px]"})}),n.jsxs("div",{className:"min-w-0",children:[n.jsx("p",{className:"truncate typography-ui-label text-foreground",children:c.label}),n.jsx("p",{className:"truncate typography-small text-muted-foreground",children:c.candidates.some(S=>S.kind==="direct")?fe(c):"via PiChamber Relay"})]})]}),n.jsx("input",{...Le,value:M,onChange:S=>P(S.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:$}),l?n.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:l}):null,n.jsx(Q,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",disabled:i||!M.trim(),children:i?"Connecting...":"Unlock and connect"}),n.jsx(Q,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:Ce,children:"Use another server"})]})})}):n.jsxs(n.Fragment,{children:[z?n.jsx(Fn,{onCancel:()=>W.current?.abort()}):null,g?n.jsx(Hn,{}):null,n.jsx("div",{className:"flex h-full flex-col overflow-hidden",children:n.jsx("div",{className:"flex-1 overflow-y-auto px-5 py-4",children:n.jsxs("div",{className:"space-y-6",children:[s.length>0?n.jsx("div",{className:"overflow-hidden rounded-[18px] border border-border/70 bg-surface-elevated",children:s.map(S=>{const D=_===S.id,Y=St(S),ae=J===S.id,ue=ae?"Connecting...":Y?Ye()?"Connected · Private relay":"Connected · Local network":S.candidates.some(be=>be.kind==="direct")?fe(S):"via PiChamber Relay";return n.jsxs("div",{className:K("flex items-center border-b border-border/70 transition-colors last:border-b-0",D&&"bg-[color-mix(in_srgb,var(--destructive)_8%,transparent)]"),children:[n.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:()=>{Y||(We(S.id),u({id:S.id,candidates:S.candidates,clientToken:S.clientToken,label:S.label}).finally(()=>We(null)))},disabled:o&&!ae||D,children:[n.jsxs("span",{className:"relative flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-interactive-hover text-foreground",children:[n.jsx(F,{name:"server",className:"size-[18px]"}),Y?n.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]}),n.jsxs("span",{className:"min-w-0 flex-1",children:[n.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:S.label}),n.jsx("span",{className:K("block truncate typography-small",Y&&!ae?"text-[var(--status-success)]":"text-muted-foreground"),children:ue})]}),ae?n.jsx(F,{name:"loader-4",className:"size-5 shrink-0 animate-spin text-muted-foreground"}):null]}),n.jsxs("div",{className:"flex items-center gap-0.5 pr-2",children:[D?n.jsxs("button",{type:"button","aria-label":`Confirm deleting ${S.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:()=>O(S.id),style:{touchAction:"manipulation"},children:[n.jsx(F,{name:"delete-bin",className:"size-[18px]"}),n.jsx("span",{className:"typography-ui-label",children:"Delete"})]}):S.candidates.some(be=>be.kind==="direct")?n.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:()=>{N(S.id),b(fe(S)),x(S.label),R(S.clientToken||""),v(null)},style:{touchAction:"manipulation"},children:n.jsx(F,{name:"edit",className:"size-[18px]"})}):null,n.jsx("button",{type:"button","aria-label":D?`Keep ${S.label}`:`Delete ${S.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:()=>y(S.id),style:{touchAction:"manipulation"},children:n.jsx(F,{name:D?"close":"delete-bin",className:"size-[18px]"})})]})]},S.id)})}):n.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."}),n.jsxs("div",{className:"space-y-2",children:[n.jsxs(Q,{type:"button",variant:"outline",size:"lg",className:"h-12 w-full",onClick:()=>{ye()},disabled:k,children:[n.jsx(F,{name:"download",className:"size-[18px]"}),k?"Preparing diagnostics…":"Export diagnostics"]}),X?n.jsx("p",{className:"px-1 text-center typography-small text-muted-foreground",children:X}):null]}),!se&&!L?n.jsxs("div",{className:"space-y-2",children:[Z?n.jsxs(Q,{type:"button",size:"lg",className:"h-12 w-full",onClick:()=>{ee()},disabled:z,children:[n.jsx(F,{name:"scan-2",className:K("size-[18px]",z&&"animate-pulse")}),"Scan QR code"]}):null,n.jsxs(Q,{type:"button",variant:Z?"ghost":"outline",size:"lg",className:"h-12 w-full",onClick:()=>{v(null),B(!0)},children:[n.jsx(F,{name:"add",className:"size-[18px]"}),"Add by address"]}),l?n.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null]}):n.jsxs("form",{className:"space-y-3",onSubmit:me,children:[n.jsxs("div",{className:"flex h-8 items-center justify-between gap-3 px-1",children:[n.jsx("h3",{className:"typography-ui-label text-foreground",children:L?"Edit instance":"Add instance"}),n.jsx(Q,{type:"button",variant:"ghost",size:"xs",onClick:oe,children:"Cancel"})]}),n.jsxs("label",{className:"block space-y-1.5",children:[n.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Server URL"}),n.jsx("input",{...Le,value:h,onChange:S=>b(S.target.value),placeholder:"http://192.168.1.74:2606",type:"url",inputMode:"url",autoCapitalize:"none",className:$})]}),n.jsxs("label",{className:"block space-y-1.5",children:[n.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Name"}),n.jsx("input",{value:U,onChange:S=>x(S.target.value),placeholder:"Optional display name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,className:$})]}),n.jsxs("label",{className:"block space-y-1.5",children:[n.jsx("span",{className:"block px-1 typography-ui-label text-foreground",children:"Client token"}),n.jsx("input",{...Le,value:E,onChange:S=>R(S.target.value),placeholder:"Paste access token",autoCapitalize:"none",className:$}),n.jsx("p",{className:"px-1 typography-micro text-muted-foreground",children:"Only needed if your server requires a token instead of a password."})]}),l?n.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:l}):null,n.jsx(Q,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",children:L?"Save changes":"Save instance"})]})]})})})]})},Ke=320,Se="cubic-bezier(0.22, 1, 0.36, 1)",Vn=({side:e,enabled:t,open:r,drawerRef:s,scrimRef:o,onClose:i,widthRatio:l,prefersReducedMotion:c})=>{a.useEffect(()=>{if(!t||!r)return;const u=s.current,p=o.current;if(!u||!p)return;let d=!1,m=!1,j=!1,v=0,w=0,N=0,L=0;const _=c?0:Ke,I=e==="left"?"translateX(-100%)":"translateX(100%)",h=()=>({drawer:_?`transform ${_}ms ${Se}`:"none",scrim:_?`opacity ${_}ms ${Se}`:"none"}),b=()=>{const f=h();u.style.transition=f.drawer,p.style.transition=f.scrim,u.style.transform="none",p.style.opacity="1",p.style.pointerEvents="auto"},U=()=>{d=!1,m=!1,j=!1},x=()=>{if(!(d||m)){U();return}b(),U()},E=f=>{if(f.touches.length!==1){(d||m)&&x();return}if(pr(f.target,u,{excludeInteractive:!1}))return;u.style.transition&&u.style.transition!=="none"&&(u.style.transition="none",p.style.transition="none");const g=f.touches[0];v=g.clientX,w=g.clientY,N=Date.now(),L=u.offsetWidth||window.innerWidth*l,L<10&&(L=window.innerWidth*l),d=!0,m=!1,j=!1},R=f=>{if(!d)return;if(f.touches.length!==1){x();return}const g=f.touches[0],T=g.clientX-v,k=g.clientY-w;if(!j){if(Math.abs(T)<Ft&&Math.abs(k)<Ft)return;if(Math.abs(k)>Math.abs(T)*Ht||!Vt(e,T)){d=!1;return}j=!0,m=!0,u.style.transition="none",p.style.transition="none"}if(!m)return;f.cancelable&&f.preventDefault();const A=Gt(e,T,L);u.style.transform=hr(e,A),p.style.opacity=String(A)},M=(f,g,T)=>{if(!d)return;const k=f-v,A=g-w,X=Math.max(1,Date.now()-N),H=Gt(e,k,L),W=yr({side:e,dx:k,dy:A,dt:X,progress:H,isDragging:m}),Z=h();u.style.transition=Z.drawer,p.style.transition=Z.scrim,u.style.transform=W?I:"none",p.style.opacity=W?"0":"1",p.style.pointerEvents=W?"none":"auto",U(),W&&i()},P=f=>{const g=f.changedTouches[0];if(!g){x();return}const T=g.clientX-v,k=g.clientY-w,A=Math.abs(T)>=mr&&Math.abs(k)<=Math.abs(T)*Ht&&Vt(e,T);d&&(m||A)&&f.cancelable&&f.preventDefault(),M(g.clientX,g.clientY)},z=()=>{x()};return u.addEventListener("touchstart",E,{passive:!0}),u.addEventListener("touchmove",R,{passive:!1}),u.addEventListener("touchend",P,{passive:!1}),u.addEventListener("touchcancel",z,{passive:!0}),()=>{try{x()}catch{}u.removeEventListener("touchstart",E),u.removeEventListener("touchmove",R),u.removeEventListener("touchend",P),u.removeEventListener("touchcancel",z)}},[s,t,i,r,c,o,e,l])},ha=16,rn=a.memo(function({open:t,onOpenChange:r,variant:s="drawer",drawerRefExternal:o,scrimRefExternal:i,rootRefExternal:l}){const c=a.useRef(null),u=a.useCallback(()=>{const b=typeof document<"u"?document.activeElement:null;b instanceof HTMLElement&&c.current?.contains(b)&&b.blur(),r(!1)},[r]),[p,d]=a.useState(!1),m=a.useRef(null),j=a.useRef(null),v=o??m,w=i??j,N=a.useCallback(b=>{c.current=b,l&&(l.current=b)},[l]),L=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]);a.useEffect(()=>{const b=c.current;if(!b||t)return;const U=document.activeElement;U&&b.contains(U)&&U.blur()},[t]),a.useEffect(()=>{if(s!=="sidebar"){if(t){const b=window.setTimeout(()=>d(!0),L?0:ha);return()=>window.clearTimeout(b)}d(!1)}},[t,L,s]),a.useEffect(()=>{if(s==="sidebar"||!t)return;const b=document.body.style.overflow;document.body.style.overflow="hidden";const U=x=>{x.key==="Escape"&&u()};return document.addEventListener("keydown",U),()=>{document.body.style.overflow=b,document.removeEventListener("keydown",U)}},[u,t,s]);const _=s==="sidebar",I=n.jsx(br,{mobileVariant:!_,isVisible:t,allowReselect:!0,onSessionSelected:_?void 0:u,onNavigateAway:_?void 0:u});if(Vn({side:"left",enabled:s==="drawer",open:t,drawerRef:v,scrimRef:w,onClose:u,widthRatio:.72,prefersReducedMotion:L}),s==="sidebar")return n.jsx("aside",{className:"relative flex h-full w-full flex-col bg-sidebar",children:I});if(typeof document>"u")return null;const h=L?0:Ke;return ze.createPortal(n.jsxs("div",{ref:N,className:"fixed inset-0 z-50",inert:!t,style:{pointerEvents:t?"auto":"none"},"data-mobile-sessions-root":"true",children:[n.jsx("button",{ref:w,type:"button",className:"absolute inset-0 cursor-default bg-black/70","aria-label":"Close sessions",onClick:u,tabIndex:t?0:-1,style:{opacity:p?1:0,transition:`opacity ${h}ms ${Se}`},"data-mobile-sessions-scrim":"true"}),n.jsx("div",{ref:v,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:p?"none":"translateX(-100%)",transition:h?`transform ${h}ms ${Se}`:"none",touchAction:"pan-x pan-y"},"data-mobile-sessions-drawer":"true",children:I})]}),document.body)}),sn="mobile-surface-root",gt=16,tt=200,ma=()=>{if(typeof document>"u")return null;let e=document.getElementById(sn);return e||(e=document.createElement("div"),e.id=sn,document.body.appendChild(e)),e},xt=({open:e,onClose:t,title:r,subtitle:s,trailing:o,disableEscapeDismiss:i=!1,headerless:l=!1,noHeaderBorder:c=!1,ariaLabel:u,variant:p="fullscreen",dialogAlign:d="chat",children:m})=>{const j=a.useRef(null),[v,w]=a.useState(!1),[N,L]=a.useState(!1),_=a.useRef(null),I=a.useRef(null),h=a.useRef(t);if(a.useEffect(()=>{h.current=t},[t]),typeof document<"u"&&!j.current&&(j.current=ma()),a.useEffect(()=>{if(!e){w(!1);return}const x=window.setTimeout(()=>w(!0),gt);return()=>window.clearTimeout(x)},[e]),a.useEffect(()=>{if(!e){L(!1);return}const x=window.setTimeout(()=>L(!0),gt+tt+80);return()=>window.clearTimeout(x)},[e]),a.useEffect(()=>{if(!e)return;const x=document.body.style.overflow;I.current=document.activeElement instanceof HTMLElement?document.activeElement:null,document.body.style.overflow="hidden";const E=()=>{const P=_.current;if(!P)return;(P.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??P).focus({preventScroll:!0})},R=window.setTimeout(E,gt),M=P=>{if(P.key==="Escape"&&!i){h.current();return}if(P.key!=="Tab")return;const z=_.current;if(!z)return;const f=Array.from(z.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')).filter(A=>!A.hasAttribute("disabled")&&A.getAttribute("aria-hidden")!=="true");if(f.length===0){P.preventDefault(),z.focus({preventScroll:!0});return}const g=f[0],T=f[f.length-1],k=document.activeElement;P.shiftKey&&k===g?(P.preventDefault(),T.focus({preventScroll:!0})):!P.shiftKey&&k===T&&(P.preventDefault(),g.focus({preventScroll:!0}))};return document.addEventListener("keydown",M),()=>{window.clearTimeout(R),document.body.style.overflow=x,document.removeEventListener("keydown",M),I.current?.focus?.({preventScroll:!0}),I.current=null}},[i,e]),!e||!j.current)return null;const b=p==="dialog",U=n.jsxs("section",{ref:_,role:"dialog","aria-modal":"true","aria-label":u,tabIndex:-1,className:K("flex flex-col bg-background text-foreground",b?"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:b?{opacity:v?1:0,transform:v?"none":"scale(0.97)",transition:`opacity ${tt}ms ease-out, transform ${tt}ms cubic-bezier(0.32, 0.72, 0, 1)`}:{paddingTop:"var(--oc-safe-area-top, 0px)",transform:v?"none":"translateX(100%)",transition:`transform ${tt}ms cubic-bezier(0.32, 0.72, 0, 1)`},onTransitionEnd:x=>{v&&x.target===x.currentTarget&&x.propertyName==="transform"&&L(!0)},children:[l?null:n.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:[n.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:t,style:{touchAction:"manipulation"},children:n.jsx(F,{name:"close",className:"size-5"})}),n.jsxs("div",{className:"min-w-0 flex-1 px-1",children:[r?typeof r=="string"?n.jsx("h2",{className:"truncate typography-ui-label text-foreground",children:r}):r:null,s?typeof s=="string"?n.jsx("p",{className:"truncate typography-micro text-muted-foreground",children:s}):s:null]}),o?n.jsx("div",{className:"flex shrink-0 items-center gap-1.5",children:o}):null]}),n.jsx("div",{className:"min-h-0 flex-1 overflow-hidden",children:N?n.jsx("div",{className:"h-full",style:{animation:"oc-surface-content-in 200ms ease-out"},children:m}):null}),n.jsx("style",{children:"@keyframes oc-surface-content-in { from { opacity: 0 } to { opacity: 1 } }"})]});return b?ze.createPortal(n.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:v?1:0,paddingLeft:d==="chat"?"max(1rem, var(--oc-chat-inset-left, 0px))":"1rem",paddingRight:d==="chat"?"max(1rem, var(--oc-chat-inset-right, 0px))":"1rem",paddingTop:"max(1rem, var(--oc-safe-area-top, 0px))"},onClick:t,children:n.jsx("div",{className:"flex w-full max-w-[720px] justify-center",onClick:x=>x.stopPropagation(),children:U})}),j.current):ze.createPortal(U,j.current)},ya=a.lazy(()=>Ue(()=>import("./FilesView-EUL5SZDG.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,119,120,121,122])).then(e=>({default:e.FilesView}))),ba=a.lazy(()=>Ue(()=>import("./GitView-7K4eJ1V3.js"),__vite__mapDeps([123,24,1,2,9,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,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,100,101,102,103,104,105,124,108,109,110,84,85,86,87,88,89,90,91,92,93,94,95,96,97,111,82,83,112,113,114,115,116,117,118,125,126,127,80,81,128])).then(e=>({default:e.GitView}))),an="mobile-surface-root",ga=16,xa=[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal"}],on=a.memo(function({open:t,onClose:r,tab:s,onTabChange:o,pendingChangesDiff:i,variant:l="drawer",drawerRefExternal:c,scrimRefExternal:u,rootRefExternal:p}){const d=a.useRef(null),m=a.useRef(null),j=a.useRef(null),v=a.useRef(null),w=c??m,N=u??j,L=p??v,_=a.useCallback(g=>{v.current=g,p&&(p.current=g)},[p]),I=a.useCallback(()=>{const g=typeof document<"u"?document.activeElement:null;g instanceof HTMLElement&&L.current?.contains(g)&&g.blur(),r()},[r]),[h,b]=a.useState(!1),[U,x]=a.useState(t),E=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[R,M]=a.useState(()=>new Set);if(a.useEffect(()=>{t&&M(g=>{if(g.has(s))return g;const T=new Set(g);return T.add(s),T})},[t,s]),typeof document<"u"&&!d.current){let g=document.getElementById(an);g||(g=document.createElement("div"),g.id=an,document.body.appendChild(g)),d.current=g}if(a.useEffect(()=>{if(t){x(!0);const T=window.setTimeout(()=>b(!0),E?0:ga);return()=>window.clearTimeout(T)}b(!1);const g=window.setTimeout(()=>x(!1),Ke+40);return()=>window.clearTimeout(g)},[t,E]),a.useEffect(()=>{if(!t)return;const g=document.body.style.overflow;l==="drawer"&&(document.body.style.overflow="hidden");const T=k=>{k.key==="Escape"&&s!=="terminal"&&I()};return document.addEventListener("keydown",T),()=>{l==="drawer"&&(document.body.style.overflow=g),document.removeEventListener("keydown",T)}},[I,t,s,l]),a.useEffect(()=>{const g=L.current;if(!g||t||l!=="drawer")return;const T=document.activeElement;T&&g.contains(T)&&T.blur()},[t,l]),Vn({side:"right",enabled:l==="drawer",open:t,drawerRef:w,scrimRef:N,onClose:I,widthRatio:1,prefersReducedMotion:E}),l==="drawer"&&!d.current)return null;const P=E?0:Ke,z=n.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:xa.map(g=>{const T=s===g.id;return n.jsxs("button",{type:"button",role:"tab","aria-selected":T,onClick:()=>o(g.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",T?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[n.jsx(F,{name:g.icon,className:"size-5 shrink-0"}),n.jsx("span",{className:"truncate",children:g.label})]},g.id)})}),f=n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2",children:[z,n.jsx("button",{type:"button",onClick:I,"aria-label":"Close workspace panel",className:"flex size-10 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/50",children:n.jsx(F,{name:"close",className:"size-5"})})]}),n.jsxs("div",{className:"min-h-0 flex-1 overflow-hidden",children:[R.has("changes")?n.jsx("div",{className:K("h-full",s!=="changes"&&"hidden"),children:n.jsx(de,{children:n.jsx(a.Suspense,{fallback:null,children:n.jsx(ba,{isActive:t&&s==="changes",chrome:"mobile",initialDiffPath:i?.path??null,initialDiffStaged:i?.staged===!0})})})},i?`changes:${i.path}:${i.staged}`:"changes"):null,R.has("files")?n.jsx("div",{className:K("h-full",s!=="files"&&"hidden"),children:n.jsx(de,{children:n.jsx(a.Suspense,{fallback:null,children:n.jsx(ya,{chrome:"mobile",mode:"editor-only",isVisible:t&&s==="files"})})})}):null,R.has("terminal")?n.jsx("div",{className:K("h-full",s!=="terminal"&&"hidden"),children:n.jsx(de,{children:n.jsx(gr,{visible:t&&s==="terminal"})})}):null]})]});return l==="panel"?n.jsx("div",{className:"flex h-full min-h-0 flex-col bg-sidebar",children:f}):ze.createPortal(n.jsxs("div",{ref:_,className:"fixed inset-0 z-50",inert:!t,style:{pointerEvents:t?"auto":"none",visibility:U?"visible":"hidden"},"data-mobile-workspace-root":"true",children:[n.jsx("button",{ref:N,type:"button",className:"absolute inset-0 cursor-default bg-black/70","aria-label":"Close workspace panel",onClick:I,tabIndex:t?0:-1,style:{opacity:h?1:0,transition:P?`opacity ${P}ms ${Se}`:"none"},"data-mobile-workspace-scrim":"true"}),n.jsx("section",{ref:w,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:h?"none":"translateX(100%)",transition:P?`transform ${P}ms ${Se}`:"none",touchAction:"pan-x pan-y"},"data-mobile-workspace-drawer":"true",children:f})]}),d.current)}),va="pichamber",wa=e=>e.replace(/^\/+|\/+$/g,""),ka=e=>{const t=wa(e.pathname).split("/").filter(Boolean);return e.host?[e.host,...t]:t};function Sa(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}if(t.protocol!==`${va}:`)return null;const r=ka(t),s=(r[0]??"").toLowerCase(),o=r.slice(1),i=t.searchParams;switch(s){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 re={},Gn=!1,Ge=null;const Ca=e=>{switch(e.type){case"session":return ce.getState().setCurrentSession(e.sessionId,e.directory??null),!0;case"new-session":{const t=ce.getState();return t.openNewSessionDraft(),(e.directory||e.projectId)&&t.setNewSessionDraftTarget({directoryOverride:e.directory??null,projectId:e.projectId??null,selectedProjectId:e.projectId??null}),!0}case"sessions":return re.openSessions?(re.openSessions(e.filter),!0):!1;case"status":return re.openSessions?(re.openSessions(),!0):!1;case"view":return re.openView?(re.openView(e.target),!0):!1;case"changes":return re.openChanges?(re.openChanges({path:e.path,staged:e.staged}),!0):!1;case"settings":return re.openSettings?(re.openSettings(e.section),!0):!1}},Ut=()=>{if(!Gn||!Ge)return;const e=Ge;Ge=null,Ca(e)||(Ge=e)},Xn=e=>{Ge=e,Ut()},ln=e=>{const t=Sa(e);t&&Xn(t)},ja=e=>{Gn=e,Ut()},Ea=e=>{a.useEffect(()=>(re=e,Ut(),()=>{re===e&&(re={})}),[e])},Ra=e=>{const{ready:t}=e;a.useEffect(()=>{ja(t)},[t]),a.useEffect(()=>{if(!q())return;let r=!1;const s=[];return Ue(()=>import("./vendor-capacitor-app-BrDJj9I_.js"),__vite__mapDeps([129,24,130])).then(async({App:o})=>{if(r)return;const i=await o.addListener("appUrlOpen",l=>{ln(l?.url)});if(r){i.remove();return}s.push(()=>{i.remove()})}).catch(()=>{}),Ue(()=>import("./vendor-capacitor-push-notifications-KNe1zSBF.js"),__vite__mapDeps([131,130])).then(async({PushNotifications:o})=>{if(r)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){ln(u);return}const p=typeof c?.sessionId=="string"?c.sessionId:void 0;p&&Xn({type:"session",sessionId:p})});if(r){i.remove();return}s.push(()=>{i.remove()})}).catch(()=>{}),()=>{r=!0,s.forEach(o=>o())}},[])},cn=e=>{const t=e.drawer.current,r=e.scrim.current,s=e.root.current;s&&(s.style.pointerEvents="auto",s.style.visibility="visible"),t&&(t.style.transition="none"),r&&(r.style.transition="none")},un=(e,t,r)=>{const s=e.drawer.current,o=e.scrim.current;if(s&&(s.style.transform=r>=.999?"none":`translateX(${(t==="left"?r-1:1-r)*100}%)`),o){o.style.opacity=String(r);const i=r>.01?"auto":"none";o.style.pointerEvents!==i&&(o.style.pointerEvents=i)}},dn=(e,t,r)=>{const s=r.drawer.current,o=r.scrim.current,i=r.root.current;s&&(s.style.transition=`transform ${Ke}ms ${Se}`,s.style.transform=t?"none":e==="left"?"translateX(-100%)":"translateX(100%)"),o&&(o.style.transition=`opacity ${Ke}ms ${Se}`,o.style.opacity=t?"1":"0",o.style.pointerEvents=t?"auto":"none"),i&&(i.style.pointerEvents=t?"auto":"none",i.style.visibility=t?"visible":"")},fn=e=>{const t=e.shell.current,r=e.inner.current;t&&(t.style.overflow="visible"),r&&(r.style.transition="none")},pn=(e,t,r,s)=>{const o=e.inner.current;if(!o)return;const i=s==="left"?(t-1)*r:(1-t)*r;o.style.transform=t>=.999?"translateX(0)":`translateX(${i}px)`},hn=(e,t,r,s,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=t?"translateX(0)":`translateX(${s==="left"?-r:r}px)`,window.setTimeout(()=>{l.style.transition="",l.style.transform="",i.style.overflow=""},220))},mn=({side:e,isResizing:t,ariaLabel:r,handleProps:s})=>n.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":r,...s,children:n.jsx("div",{className:K("absolute inset-y-0 w-[3px] transition-colors",e==="left"?"right-0":"left-0",t&&"bg-[var(--interactive-border)]")})}),Ta=320,Na=380,yn=280,Ia=560,Pa=900;function bn(e,t,r,s=Ia){const o=a.useRef(null),[i,l]=a.useState(()=>{if(typeof window>"u")return r;const h=Number.parseInt(window.localStorage.getItem(t)??"",10);return Number.isFinite(h)?Math.min(s,Math.max(yn,h)):r}),[c,u]=a.useState(!1),p=a.useRef(0),d=a.useRef(i),m=a.useRef(null),j=a.useRef(null),v=a.useCallback(h=>Math.min(s,Math.max(yn,Math.round(h))),[s]),w=a.useCallback(h=>{const b=o.current;b&&(b.style.width=`${h}px`,b.style.minWidth=`${h}px`,b.style.maxWidth=`${h}px`,b.style.setProperty("--oc-ipad-sidebar-width",`${h}px`))},[]),N=a.useCallback(h=>{try{h.currentTarget.setPointerCapture(h.pointerId)}catch{}j.current=h.pointerId,p.current=h.clientX,d.current=i,m.current=i,u(!0),h.preventDefault()},[i]),L=a.useCallback(h=>{if(j.current!==h.pointerId)return;const b=h.clientX-p.current,U=v(d.current+(e==="left"?b:-b));m.current!==U&&(m.current=U,w(U))},[w,v,e]),_=a.useCallback(h=>{if(j.current!==h.pointerId)return;try{h.currentTarget.releasePointerCapture(h.pointerId)}catch{}const b=v(m.current??d.current);j.current=null,m.current=null,u(!1),l(b);try{window.localStorage.setItem(t,String(b))}catch{}},[v,t]),I=a.useMemo(()=>({onPointerDown:N,onPointerMove:L,onPointerUp:_,onPointerCancel:_}),[N,_,L]);return{asideRef:o,width:i,isResizing:c,handleProps:I}}const Aa=a.memo(Cr),_a=({onActiveConnectionDeleted:e})=>{const[t,r]=a.useState(!1),[s,o]=a.useState(null),[i,l]=a.useState(!1),[c,u]=a.useState("changes"),[p,d]=a.useState("nav"),[m,j]=a.useState(null),v=a.useRef([]),w=a.useCallback(()=>{v.current.forEach(C=>window.clearTimeout(C)),v.current=[]},[]);a.useEffect(()=>()=>w(),[w]);const N=a.useRef(null),L=a.useRef(null),_=a.useRef(null),I=a.useRef(null),h=a.useRef(null),b=a.useRef(null),U=a.useRef(null),x=a.useRef(null),E=a.useRef(0),R=a.useRef(0),M=a.useCallback(C=>{w(),r(C)},[w]),P=a.useCallback(C=>{w(),l(C)},[w]),z=we(C=>C.setSettingsPage),f=we(C=>C.isArchivePageOpen),g=we(C=>C.setArchivePageOpen),T=Oe(C=>C.available),k=Oe(C=>C.runtimeType),A=a.useMemo(()=>jn(),[]),X=!A&&T&&(k==="desktop"||k==="web"),H=a.useCallback(()=>{o(null)},[]),W=a.useCallback(C=>{o(C)},[]),Z=a.useCallback(()=>{P(!1)},[P]),se=a.useCallback(C=>{d(C),W("settings")},[W]),{enabled:B,roomyForPanels:J}=Wr(),oe=Fr()==="portrait",me=Hr(),ee=we(C=>C.setSidebarOpen),te=we(C=>C.isSidebarOpen),Ce=a.useRef(!1);a.useLayoutEffect(()=>{B&&!Ce.current&&ee(Vr().roomyForPanels),!B&&Ce.current&&ee(!1),Ce.current=B},[B,ee]);const ye=a.useCallback(()=>{j(null),u("files"),P(!0)},[P]),y=a.useCallback((C=null)=>{j(C),u("changes"),P(!0)},[P]),O=bn("left","pichamber.ipad.leftSidebarWidth",Ta),$=bn("right","pichamber.ipad.rightSidebarWidth",Na,Pa),S=J,D=S&&i?$.width:0,Y=xr(B&&te),ae=B&&te?O.width:0,ue=a.useCallback(C=>{i&&c===C?P(!1):(u(C),P(!0))},[i,c,P]),be=a.useCallback(()=>{P(!i)},[i,P]),Fe=a.useCallback(C=>{!C&&!J&&ee(!1)},[J,ee]);a.useEffect(()=>{if(typeof document>"u")return;const C=document.documentElement;return C.style.setProperty("--oc-chat-inset-left",`${ae}px`),C.style.setProperty("--oc-chat-inset-right",`${D}px`),()=>{C.style.removeProperty("--oc-chat-inset-left"),C.style.removeProperty("--oc-chat-inset-right")}},[ae,D]),a.useEffect(()=>{if(typeof document>"u")return;const C=B&&(oe||me),le=document.documentElement;return le.classList.toggle("oc-keep-draft-starters",C),()=>le.classList.remove("oc-keep-draft-starters")},[me,B,oe]);const je=a.useCallback(()=>{M(!1),P(!1)},[M,P]),et=a.useMemo(()=>({openChanges:({diffPath:C,staged:le}={})=>{y(C?{path:C,staged:le===!0}:null)},openFiles:()=>ye(),openSettings:C=>{C&&z(C),se(C?"page-content":"nav")},openInstances:A?()=>W("instances"):void 0,instanceLabel:A?xe():null,openUpdate:X?()=>W("update"):void 0,closeDrawers:je}),[je,y,ye,se,W,z,A,X]),Jn=a.useMemo(()=>({openSessions:()=>{B?ee(!0):M(!0)},openView:C=>{if(C==="files"){ye();return}(C==="instances"||C==="update"||C==="mcp")&&W(C)},openChanges:({path:C,staged:le}={})=>{y(C?{path:C,staged:le===!0}:null)},openSettings:C=>{C&&z(C),se(C?"page-content":"nav")}}),[B,y,ye,se,W,z,M,ee]);Ea(Jn);const Bt=a.useRef(null);vr(Bt,{leftOpen:B?te:t,rightOpen:i,leftWidth:()=>B?O.width:N.current?.offsetWidth||window.innerWidth*.72,rightWidth:()=>B?$.width:I.current?.offsetWidth||window.innerWidth,onLeftProgress:C=>{if(E.current=C,B){pn({inner:U},C,O.width,"left");return}un({drawer:N,scrim:L},"left",C)},onRightProgress:C=>{if(R.current=C,B&&J){pn({inner:x},C,$.width,"right");return}un({drawer:I,scrim:h},"right",C)},onLeftOpen:()=>{B?ee(!0):M(!0)},onLeftClose:()=>{B?ee(!1):M(!1)},onRightOpen:()=>P(!0),onRightClose:()=>P(!1),onDragStart:C=>{if(w(),C==="left"){E.current=B?te?1:0:t?1:0,B?fn({shell:O.asideRef,inner:U}):cn({drawer:N,scrim:L,root:_});return}R.current=i?1:0,B&&J?fn({shell:$.asideRef,inner:x}):cn({drawer:I,scrim:h,root:b})},onDragEnd:(C,le)=>{if(C==="left"){const Me=typeof le=="boolean"?le:E.current>.5;if(E.current=Me?1:0,B){const $t=hn({shell:O.asideRef,inner:U},Me,O.width,"left");$t!==void 0&&v.current.push($t)}else dn("left",Me,{drawer:N,scrim:L,root:_});return}const pt=typeof le=="boolean"?le:R.current>.5;if(R.current=pt?1:0,B&&J){const Me=hn({shell:$.asideRef,inner:x},pt,$.width,"right");Me!==void 0&&v.current.push(Me)}else dn("right",pt,{drawer:I,scrim:h,root:b})}});const Yn=a.useCallback(()=>f?(g(!1),!0):s?(H(),!0):i?(Z(),!0):t?(M(!1),!0):!1,[s,H,Z,f,t,g,M,i]);Gr(Yn);const ft=B?"dialog":"fullscreen";return n.jsx(Xr,{actions:et,children:n.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:[B?n.jsxs("aside",{ref:O.asideRef,className:K("relative flex h-full shrink-0 flex-col overflow-hidden border-r border-border/70 bg-sidebar motion-reduce:transition-none",!te&&"border-r-0"),style:{width:ae,minWidth:ae,maxWidth:ae,"--oc-ipad-sidebar-width":`${O.width}px`,overflowX:"clip",paddingTop:"var(--oc-safe-area-top, 0px)"},inert:!te,"data-page-scroll-lock":"true",children:[n.jsx("div",{ref:U,className:K("flex h-full shrink-0 flex-col",O.isResizing&&"pointer-events-none",!te&&"pointer-events-none select-none"),style:{width:"var(--oc-ipad-sidebar-width)",overflowX:"hidden",transform:O.isResizing||Y.slidIn?"translateX(0)":"translateX(-100%)",transition:O.isResizing?"none":"transform 200ms cubic-bezier(0.22, 1, 0.36, 1)"},children:n.jsx(de,{children:n.jsx(rn,{open:te,variant:"sidebar",onOpenChange:Fe})})}),te?n.jsx(mn,{side:"left",isResizing:O.isResizing,ariaLabel:"Resize left panel",handleProps:O.handleProps}):null]}):null,n.jsxs("div",{className:"relative flex h-full min-w-0 flex-1 flex-col","data-page-scroll-lock":"true",children:[B?n.jsxs(n.Fragment,{children:[n.jsx(wr,{}),n.jsx(kr,{onToggleRightDrawer:be,rightDrawerOpen:i,tabletWorkspaceTab:c,onSelectTabletWorkspaceTab:ue})]}):n.jsx(fa,{onOpenSessions:()=>M(!0),onOpenWorkspace:()=>P(!0)}),n.jsx("main",{ref:Bt,className:"relative min-h-0 flex-1 overflow-hidden","data-page-scroll-lock":"true",style:{touchAction:"pan-x pan-y"},children:n.jsx("div",{className:"h-full w-full",children:n.jsx(de,{children:n.jsx(Aa,{})})})})]}),B?null:n.jsx(rn,{open:t,onOpenChange:M,drawerRefExternal:N,scrimRefExternal:L,rootRefExternal:_}),B?n.jsxs("aside",{ref:$.asideRef,className:K("relative flex h-full shrink-0 flex-col overflow-hidden border-l border-border/70 bg-background motion-reduce:transition-none",!D&&"border-l-0"),style:{width:D,minWidth:D,maxWidth:D,"--oc-ipad-sidebar-width":`${$.width}px`,overflowX:"clip",paddingTop:"var(--oc-safe-area-top, 0px)"},inert:!D,"data-page-scroll-lock":"true",children:[n.jsx("div",{ref:x,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",$.isResizing&&"pointer-events-none",!D&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-ipad-sidebar-width)",overflowX:"hidden",transform:D?"translateX(0)":"translateX(100%)",transition:$.isResizing?"none":"transform 200ms cubic-bezier(0.22, 1, 0.36, 1), opacity 200ms cubic-bezier(0.22, 1, 0.36, 1)"},children:n.jsx(de,{children:n.jsx(on,{open:i,onClose:Z,tab:c,onTabChange:u,pendingChangesDiff:m,variant:S?"panel":"drawer",drawerRefExternal:I,scrimRefExternal:h,rootRefExternal:b})})}),D?n.jsx(mn,{side:"right",isResizing:$.isResizing,ariaLabel:"Resize right panel",handleProps:$.handleProps}):null]}):n.jsx(on,{open:i,onClose:Z,tab:c,onTabChange:u,pendingChangesDiff:m,drawerRefExternal:I,scrimRefExternal:h,rootRefExternal:b}),s==="instances"&&A?n.jsx(xt,{open:!0,variant:ft,dialogAlign:"app",onClose:H,ariaLabel:"Instances",title:"Instances",children:n.jsx(pa,{onConnect:H,onActiveConnectionDeleted:e})}):null,s==="settings"?n.jsx(xt,{open:!0,variant:ft,dialogAlign:"app",onClose:H,ariaLabel:"Settings",headerless:!0,children:n.jsx(de,{children:n.jsx(vs,{forceMobile:!B,isWindowed:!0,initialMobileStage:p,onClose:H})})}):null,s==="update"?n.jsx(xt,{open:!0,variant:ft,dialogAlign:"app",onClose:H,ariaLabel:"Update",title:"Update",children:n.jsx(de,{children:n.jsx("div",{className:"h-full overflow-auto px-5 py-4",children:n.jsx(ws,{initialUpdateDialogOpen:!0})})})}):null,n.jsx(de,{children:n.jsx(Sr,{})})]})})},Da=8,Ma=6e4,vt=[1e3,2e3,4e3,8e3,15e3,3e4,3e4,3e4],Oa=(e,t)=>{if(t?.offline||t?.hidden)return Ma;if(e<=0)return vt[0];const r=Math.min(e-1,vt.length-1);return vt[r]??3e4},ve=()=>typeof navigator<"u"&&typeof navigator.onLine=="boolean"?!navigator.onLine:!1,he=()=>typeof document<"u"&&typeof document.visibilityState=="string"?document.visibilityState==="hidden":!1;class La{constructor(t,r,s=()=>""){this.probe=t,this.callbacks=r,this.getRuntimeIdentity=s}generation=0;attempt=0;timer=null;wakeCleanup=null;running=!1;exhausted=!1;probingGeneration=null;get currentGeneration(){return this.generation}get currentAttempt(){return this.attempt}get isRunning(){return this.running&&!this.exhausted}start(){this.startCycle(!1)}startCycle(t){this.clearTimer(),this.generation+=1,this.attempt=0,this.exhausted=!1,this.running=!0,t?this.runAttempt(this.generation):this.scheduleNext(this.generation)}retryNow(){if(this.exhausted){if(ve()||he())return;this.startCycle(!0);return}this.running&&(this.clearTimer(),this.runAttempt(this.generation))}cancel(){this.generation+=1,this.running=!1,this.exhausted=!1,this.attempt=0,this.probingGeneration=null,this.clearTimer()}async probeOnce(){if(this.running||this.exhausted||this.probingGeneration!==null||ve()||he())return null;const t=this.generation;this.probingGeneration=t;const r=this.getRuntimeIdentity();let s;try{s=await this.probe()}catch{s="unreachable"}finally{this.probingGeneration===t&&(this.probingGeneration=null)}return t!==this.generation||this.getRuntimeIdentity()!==r?null:s}clearTimer(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.wakeCleanup&&(this.wakeCleanup(),this.wakeCleanup=null)}scheduleNext(t){if(t!==this.generation||!this.running||this.exhausted)return;if(this.attempt>=Da){this.exhausted=!0,this.running=!1,this.callbacks.onExhausted();return}const r=this.attempt+1,s=Oa(r,{offline:ve(),hidden:he()});this.callbacks.onAttempt?.(r,s);const o=()=>{ve()||he()||t===this.generation&&(this.clearTimer(),this.runAttempt(t))},i=()=>o(),l=()=>{typeof document<"u"&&document.visibilityState==="visible"&&o()};typeof window<"u"&&window.addEventListener("online",i),typeof document<"u"&&document.addEventListener("visibilitychange",l),this.wakeCleanup=()=>{typeof window<"u"&&window.removeEventListener("online",i),typeof document<"u"&&document.removeEventListener("visibilitychange",l)},this.timer=setTimeout(()=>{if(this.timer=null,this.wakeCleanup?.(),this.wakeCleanup=null,!(t!==this.generation||!this.running||this.exhausted)){if(ve()||he()){this.scheduleNext(t);return}this.runAttempt(t)}},s)}async runAttempt(t){if(t!==this.generation||!this.running||this.exhausted||this.probingGeneration===t)return;if(ve()||he()){this.scheduleNext(t);return}this.probingGeneration=t;const r=this.getRuntimeIdentity();let s;try{s=await this.probe()}catch{s="unreachable"}finally{this.probingGeneration===t&&(this.probingGeneration=null)}if(t===this.generation&&this.getRuntimeIdentity()===r){if(s==="switched"||s==="unchanged"){this.running=!1,this.clearTimer(),this.callbacks.onHealthy(s);return}if(s==="needs-login"){this.running=!1,this.clearTimer(),this.callbacks.onAuthExpired();return}if(s==="no-connection"){this.running=!1,this.clearTimer(),this.callbacks.onNoConnection();return}this.attempt+=1,this.scheduleNext(t)}}}function za(e=2500){const{uiFont:t}=Jr(),[r,s]=a.useState(!1);return a.useEffect(()=>{let o=!1;const i=()=>{o||s(!0)},l=()=>{requestAnimationFrame(()=>requestAnimationFrame(i))},c=Promise.all([Yr(t).catch(()=>{}),document.fonts?.ready?.then(()=>{}).catch(()=>{})??Promise.resolve(),Es.catch(()=>{})]).then(()=>{}),u=new Promise(p=>{window.setTimeout(p,e)});return Promise.race([c,u]).then(l),()=>{o=!0}},[t,e]),r}const Ua=()=>{if(typeof window>"u")return;const e=window.__PICHAMBER_APNS_ENV__;if(e==="development")return"sandbox";if(e==="production")return"production"},Ba=()=>{if(typeof window>"u")return!1;const t=window.Capacitor?.getPlatform?.();return t==="ios"||t==="android"},$a=e=>{const{enabled:t}=e,r=we(o=>o.nativeNotificationsEnabled),s=a.useRef(null);a.useEffect(()=>{if(!t||!r||!Ba())return;let o=!1;const i=[];return Ue(()=>import("./vendor-capacitor-push-notifications-KNe1zSBF.js"),__vite__mapDeps([131,130])).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",d=>{s.current=d.value,kt()?.push?.registerApnsToken?.({token:d.value,platform:gn(),environment:Ua()})}),p=await l.addListener("registrationError",d=>{console.warn("[Push] APNs registration error:",d)});if(await l.register().catch(()=>{}),o){u.remove(),p.remove();return}i.push(()=>{u.remove()},()=>{p.remove()})}).catch(()=>{}),()=>{o=!0,i.forEach(l=>l())}},[t,r]),a.useEffect(()=>{if(r)return;const o=s.current;if(!o)return;s.current=null,kt()?.push?.unregisterApnsToken?.({token:o})},[r])},Ka=1e3;function Wa({apis:e}){const t=ge(y=>y.initializeApp),r=ge(y=>y.isInitialized),s=ge(y=>y.isConnected),o=ge(y=>y.connectionPhase),i=ge(y=>y.providers.length),l=ge(y=>y.loadProviders),c=wn(y=>y.currentDirectory),u=ce(y=>y.error),p=ce(y=>y.clearError),d=we(y=>y.setIsMobile),[m,j]=a.useState(0),[v,w]=a.useState(0),[N,L]=a.useState(!1),[_,I]=a.useState("idle"),h=qr(),b=a.useRef(null),U=a.useRef(_);U.current=_;const[x,E]=a.useState("pending"),[R,M]=a.useState(null),P=a.useMemo(()=>xe(),[]),[,z]=a.useReducer(y=>y+1,0),f=a.useMemo(()=>jn(),[]),g=a.useRef(0),T=a.useRef(0),k=a.useRef(!1);a.useEffect(()=>{const y=new La(()=>Lt(),{onHealthy:O=>{if(I("idle"),pe(!1),O==="unchanged"){ge.getState().initializeApp();const $=ge.getState();$.providers.length===0&&$.loadProviders({source:"mobileApp:recovery"})}},onAuthExpired:()=>{I("idle"),pe(!1),M({kind:"auth-expired",label:xe()??""}),Ee({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),j(O=>O+1)},onNoConnection:()=>{I("idle"),pe(!1),Ee({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),j(O=>O+1)},onExhausted:()=>{I("exhausted")}},()=>`${ie()}|${ne()}`);return b.current=y,()=>{y.cancel(),b.current=null}},[]);const A=a.useCallback(()=>{if(!f||!ne())return;const y=b.current;if(y){if(y.isRunning){y.retryNow();return}I("recovering"),pe(!0),y.start()}},[f]),X=a.useCallback(()=>{b.current?.cancel(),I("idle"),pe(!1)},[]),H=a.useCallback(y=>{b.current?.cancel(),I("idle"),pe(!1),y&&M(y),Ee({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),j(O=>O+1)},[]),W=a.useCallback(()=>{const y=Date.now();y-g.current>=Ka&&(g.current=y,window.dispatchEvent(new Event("pichamber:system-resume")))},[]),Z=a.useCallback(()=>{const y=ne(),O=T.current+1;if(T.current=O,!y){if(k.current)return;k.current=!0,nt().catch(()=>{}).finally(()=>{k.current=!1});return}if(b.current?.isRunning){b.current.retryNow(),W();return}if(U.current==="exhausted"){if(ve()||he())return;I("recovering"),pe(!0),b.current?.start(),W();return}if(ve()||he()){A();return}const $=()=>{t(),i===0&&l({source:"mobileApp:nativeResume"})},S=b.current;S&&(S.probeOnce().then(D=>{if(D!==null&&T.current===O){if(D==="no-connection"){H(null);return}if(D==="needs-login"){H({kind:"auth-expired",label:xe()??""});return}if(D==="unreachable"){A();return}D!=="switched"&&$()}}),W())},[H,W,t,l,i,A]);Qr(),Zr(Z),a.useEffect(()=>rr(),[]),a.useEffect(()=>{if(!f)return;let y;const O=()=>{if(b.current?.isRunning){b.current.retryNow();return}if(U.current==="exhausted"){if(he())return;I("recovering"),pe(!0),b.current?.start();return}window.clearTimeout(y),y=window.setTimeout(()=>Z(),1500)};return window.addEventListener("online",O),()=>{window.removeEventListener("online",O),window.clearTimeout(y)}},[f,Z]),a.useEffect(()=>{if(f)return sr(()=>{ne()&&H({kind:"auth-expired",label:xe()??""})})},[H,f]),a.useEffect(()=>(Wt(e),()=>Wt(null)),[e]),a.useEffect(()=>ar(y=>{if(!!y.runtimeKey&&y.runtimeKey===y.previousRuntimeKey){jr(),z();return}b.current?.cancel(),I("idle"),pe(!1),Er(y),w($=>$+1),j($=>$+1)}),[]),a.useEffect(()=>{kn()},[v]),a.useEffect(()=>{if(!f||s||ne()){E("done");return}let y=!1;return E("attempting"),nt().catch(()=>({status:"no-candidate"})).then(O=>{y||(O.status==="unreachable"?M({kind:"unreachable",label:O.label}):O.status==="needs-login"&&M({kind:"auth-expired",label:O.label}),E("done"))}),()=>{y=!0}},[]),a.useEffect(()=>{if(!f||!ne())return;let y=!1;const O=S=>{S&&M(S),Ee({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),j(D=>D+1)},$=b.current;if($)return $.probeOnce().then(async S=>{if(y||S===null||S==="switched"||S==="unchanged")return;const D=xe();if(S==="needs-login"){O({kind:"auth-expired",label:D??""});return}if(S==="unreachable"){O(D?{kind:"unreachable",label:D}:null);return}const Y=await nt().catch(()=>({status:"no-candidate"}));y||Y.status==="connected"||(Y.status==="needs-login"?O({kind:"auth-expired",label:Y.label}):Y.status==="unreachable"?O({kind:"unreachable",label:Y.label}):O(null))}),()=>{y=!0}},[]),a.useEffect(()=>{d(!0)},[d]),a.useEffect(()=>{f&&!ne()||t()},[m,t,f]),a.useEffect(()=>{s&&i===0&&l({source:"mobileApp:recovery"})},[s,l,i]);const se=a.useRef(!1),[B,J]=a.useState(f);a.useEffect(()=>{if(!f||!s||se.current)return;if(ce.getState().currentSessionId){se.current=!0,J(!1);return}const y=ie(),O=es(y);if(!O){se.current=!0,J(!1);return}const $=ir(O.directory??null);if(!$){se.current=!0,J(!1);return}const S=He();let D=0;try{D=S.getRuntimeGeneration()}catch{D=0}let Y=!1;const ae=window.setTimeout(()=>J(!1),6e3);return(async()=>{let ue=null;try{ue=await ts([$])}catch{ue=null}if(Y)return;if(!ue){J(!1);return}const be=He();let Fe=D;try{Fe=be.getRuntimeGeneration()}catch{Fe=D}const je=Os({persisted:O,persistedDirectory:$,stale:ue.stale,ready:ue.readyDirectories.has($),catalog:ue.catalog,runtimeKey:ie(),capturedRuntimeKey:y,storeIdentityMatches:be===S,generationMatches:Fe===D});if(je.action==="wait"){J(!1);return}if(se.current=!0,je.action==="clear"){ns(y),J(!1);return}const et=ce.getState();if(ie()!==y||He()!==S){J(!1);return}et.currentSessionId||et.setCurrentSession(je.sessionId,je.directory),J(!1)})(),()=>{Y=!0,window.clearTimeout(ae)}},[m,s,f]),a.useEffect(()=>{s&&He().focusProject(c,null)},[c,s]),a.useEffect(()=>{if(!u)return;const y=window.setTimeout(()=>p(),5e3);return()=>window.clearTimeout(y)},[p,u]),a.useEffect(()=>{if(f&&_!=="idle"){L(!1);return}if(!(!s&&(f?!!ne():!0))){L(!1);return}const O=window.setTimeout(()=>{L(!0)},f?4e3:8e3);return()=>window.clearTimeout(O)},[s,f,m,_,v]),rs(),or({enabled:!0}),Rr(),$a({enabled:f&&s}),Ra({ready:f&&s&&r});const We=za(),oe=!s&&o==="reconnecting",me=!!ne(),ee=f&&me&&_!=="idle",te=xe()??"",Ce=a.useCallback(()=>{const y=b.current;if(y){if(U.current==="exhausted"){y.retryNow(),y.isRunning&&I("recovering");return}A()}},[A]),ye=a.useCallback(()=>{H(null)},[H]);return We?f&&!ee&&(!me||!s&&!oe)?me?n.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background px-6 text-center text-foreground",children:n.jsxs("div",{className:"flex max-w-sm flex-col items-center gap-4",children:[n.jsx(Re,{width:120,height:120,isAnimated:!N}),N?n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"space-y-2",children:[n.jsx("h1",{className:"typography-h3 text-foreground",children:"Unable to reach server"}),n.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."})]}),n.jsx(Q,{type:"button",variant:"outline",onClick:()=>{H(null)},children:"Use another server"})]}):null]})}):x!=="done"?n.jsxs("main",{className:"relative flex min-h-dvh items-center justify-center bg-background text-foreground",children:[n.jsx(Re,{width:120,height:120,isAnimated:!0}),P?n.jsxs("div",{className:"absolute inset-x-0 top-[calc(50%+84px)] flex flex-col items-center gap-0.5 px-6 text-center",children:[n.jsx("p",{className:"typography-small text-muted-foreground",children:"Connecting to device:"}),n.jsx("div",{className:"flex justify-center",children:n.jsx(ss,{text:P,showElapsed:!1})})]}):null]}):n.jsx(n.Fragment,{children:n.jsx(oa,{onConnected:()=>j(y=>y+1),notice:R})}):!s&&!oe?N?n.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background px-6 text-center text-foreground",children:n.jsxs("div",{className:"max-w-sm space-y-3",children:[n.jsx("h1",{className:"typography-h3 text-foreground",children:"Unable to reach server"}),n.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."})]})}):n.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background text-foreground",children:n.jsx(Re,{width:120,height:120,isAnimated:!0})}):n.jsx(de,{children:n.jsx(as,{children:n.jsxs(is,{apis:e,children:[n.jsx(os,{}),n.jsx(ls,{delayDuration:300,skipDelayDuration:150,children:n.jsxs(Tr,{children:[n.jsx(Nr,{}),n.jsxs("div",{className:"h-full bg-background text-foreground",children:[f&&B?n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background",children:n.jsx(Re,{width:120,height:120,isAnimated:!0})}):null,n.jsx(cs,{embeddedBackgroundWorkEnabled:r&&!h}),ee?n.jsxs("div",{role:"status","aria-live":"polite",className:_==="exhausted"?"flex items-center gap-3 border-b border-[color-mix(in_srgb,var(--status-error)_35%,transparent)] bg-[color-mix(in_srgb,var(--status-error)_10%,transparent)] px-4 py-2.5":"flex items-center gap-3 border-b border-[color-mix(in_srgb,var(--status-warning)_35%,transparent)] bg-[color-mix(in_srgb,var(--status-warning)_10%,transparent)] px-4 py-2.5",children:[n.jsx("span",{className:_==="exhausted"?"flex size-9 shrink-0 items-center justify-center rounded-[12px] bg-[color-mix(in_srgb,var(--status-error)_16%,transparent)] text-[var(--status-error)]":"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:n.jsx(F,{name:_==="exhausted"?"cloud-off":"loader-4",className:_==="exhausted"?"size-[18px]":"size-[18px] animate-spin"})}),n.jsxs("span",{className:"min-w-0 flex-1 text-left",children:[n.jsx("span",{className:"block truncate typography-ui-label text-foreground",children:_==="exhausted"?te?`Couldn't reach ${te}`:"Server unreachable":"Reconnecting…"}),n.jsx("span",{className:"block truncate typography-small text-muted-foreground",children:_==="exhausted"?"Chats and drafts are kept. Check the server, then try again.":"Keeping chats and drafts. Retrying automatically."})]}),n.jsx(Q,{type:"button",size:"sm",onClick:Ce,children:_==="exhausted"?"Try again":"Retry now"}),n.jsx(Q,{type:"button",variant:"ghost",size:"sm",onClick:ye,children:"Use another server"})]}):null,n.jsx(Ms,{}),n.jsx(_a,{onActiveConnectionDeleted:()=>{X(),Ee({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),j(y=>y+1)}}),n.jsx(Ir,{}),n.jsx(Pr,{}),n.jsx(us,{position:"top-center",offset:"calc(var(--oc-safe-area-top, 0px) + 16px)"}),n.jsx(ds,{})]})]})})]})},v)}):n.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background text-foreground",children:n.jsx(Re,{width:120,height:120,isAnimated:!0})})}const Fa=()=>{(async()=>{try{await Promise.all([kn(),lr()])}catch(e){console.error("[mobile-main] settings init failed:",e)}ys(),bs(),cr()})().finally(()=>{Rs()})};function Ha(e){window.__PICHAMBER_SURFACE__="mobile",fs(),Fa(),Ds(),ps();const t=document.getElementById("root");if(!t)throw new Error("Root element not found");const s=window.Capacitor?.isNativePlatform?.()===!0||window.location.protocol==="capacitor:",o=e??kt();if(!o)throw new Error("Runtime APIs not registered");const i=s?{...o,notifications:{notifyAgentCompletion:async()=>!1,canNotify:()=>!1}}:o,l=n.jsx(Wa,{apis:i});qn.createRoot(t).render(n.jsx(wt.StrictMode,{children:n.jsx(hs,{children:n.jsx(Ar,{children:s?l:n.jsx(ms,{children:l})})})}))}const ai=Object.freeze(Object.defineProperty({__proto__:null,renderMobileApp:Ha},Symbol.toStringTag,{value:"Module"}));export{si as m,ai as r};
|