@pi-chamber/web 1.0.4-rc.2 → 1.0.4

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.
Files changed (149) hide show
  1. package/dist/assets/DiagramView-BpG1c3Hi.js +1 -0
  2. package/dist/assets/{DiffView-Cay8VAqL.js → DiffView-BxwoRCYx.js} +5 -5
  3. package/dist/assets/FileSaveConflictDialog-DP7k9a-i.js +3 -0
  4. package/dist/assets/{FilesView-CEeQzjc6.js → FilesView-D_2QcdUt.js} +4 -4
  5. package/dist/assets/{GitHubDetailScaffold-q4YP8iyJ.js → GitHubDetailScaffold-UxLAMAOl.js} +2 -2
  6. package/dist/assets/GitHubLinkPicker-Bh9RO1yK.js +1 -0
  7. package/dist/assets/{GitHubListPrimitives-XkALat1v.js → GitHubListPrimitives-DQyhT5wG.js} +1 -1
  8. package/dist/assets/{GitView-DV3d0oSJ.js → GitView-XBBheKRM.js} +4 -4
  9. package/dist/assets/{IssuesSurface-OTyt9f3A.js → IssuesSurface-BA1kpvAJ.js} +3 -3
  10. package/dist/assets/{JsonTreeView-X2Auiy_q.js → JsonTreeView-BAaEPL4O.js} +1 -1
  11. package/dist/assets/MarkdownRendererImpl-DzgDmUsL.js +12 -0
  12. package/dist/assets/{PatchDiff-GMQAv4en.js → PatchDiff-BMEUsgXH.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-0X__nypk.js → PierreDiffViewer-BW8MO-O6.js} +2 -2
  14. package/dist/assets/PullRequestsSurface-B3ictm4I.js +2 -0
  15. package/dist/assets/SessionSwitcherContent-rLoyVqgs.js +1 -0
  16. package/dist/assets/SessionSwitcherDropdown-CfySKnUu.js +2 -0
  17. package/dist/assets/{SessionUnreadDot-CJFawQpo.js → SessionUnreadDot-CmEF9sxM.js} +1 -1
  18. package/dist/assets/SettingsView-BiwlwnTK.js +6 -0
  19. package/dist/assets/SettingsWindow-j0e99YI0.js +1 -0
  20. package/dist/assets/ToolOutputDialog-VlS12Xyq.js +8 -0
  21. package/dist/assets/ToolPartDiffPreview-DdSneZws.js +1 -0
  22. package/dist/assets/{VirtualizedFileDiff-CUWx7JVZ.js → VirtualizedFileDiff-BqiXjvP6.js} +1 -1
  23. package/dist/assets/{Virtualizer-wpC51ZBQ.js → Virtualizer-Cp_cJWbI.js} +1 -1
  24. package/dist/assets/{collapsible-Ce85nuXX.js → collapsible-C7oyikVm.js} +1 -1
  25. package/dist/assets/{computeVirtualFileMetrics-3PpRLd5B.js → computeVirtualFileMetrics-BJjC-tXV.js} +1 -1
  26. package/dist/assets/{contextFileOpenGuard-PoBklHMz.js → contextFileOpenGuard-BBzqKGei.js} +1 -1
  27. package/dist/assets/{gitStatusPredicates-BvzxqidP.js → gitStatusPredicates-Dq-E5DaH.js} +1 -1
  28. package/dist/assets/{githubLink-iQ51wqRa.js → githubLink-Cryd7GkG.js} +5 -5
  29. package/dist/assets/index-BbhXFTId.js +1 -0
  30. package/dist/assets/index-BnZVqcki.js +11 -0
  31. package/dist/assets/index-BnieExes.css +1 -0
  32. package/dist/assets/{main-PSCt716b.js → main-9O5IAtT_.js} +4 -4
  33. package/dist/assets/{main-FasHq7Ck.js → main-DWGwALIw.js} +2 -2
  34. package/dist/assets/{markdownCore-BH56o6Wu.js → markdownCore-B9AuEyYi.js} +1 -1
  35. package/dist/assets/miniChat-CgOaJfD8.js +2 -0
  36. package/dist/assets/mobile-BbJcYVym.js +2 -0
  37. package/dist/assets/nativeFileSave-BzhtrDoD.js +1 -0
  38. package/dist/assets/{pi-session-focus-preference-D2-1HWmY.js → pi-session-focus-preference-Bmk1iOvn.js} +4 -4
  39. package/dist/assets/{renderDiffWithHighlighter-l8hZWWBO.js → renderDiffWithHighlighter-CVLsdtQ5.js} +1 -1
  40. package/dist/assets/renderElectronMiniChatApp-R5o9NwFC.js +2 -0
  41. package/dist/assets/{renderFileWithHighlighter-BvDoP7ob.js → renderFileWithHighlighter-DJ9mk2bZ.js} +1 -1
  42. package/dist/assets/renderMobileApp-CQ9tWYIj.js +11 -0
  43. package/dist/assets/runtimeEndpointReset-CtK4C_5h.js +62 -0
  44. package/dist/assets/{runtimeSurface-B1GRkkKC.js → runtimeSurface-DBiUWYK2.js} +1 -1
  45. package/dist/assets/useAppFontEffects-DviRbaCJ.js +212 -0
  46. package/dist/assets/{useFilesViewSearch-D1jsGQrN.js → useFilesViewSearch-D2Au5Xgt.js} +1 -1
  47. package/dist/assets/{useGitHubRemoteSearch-zNgy2bSt.js → useGitHubRemoteSearch-D-K7aolk.js} +1 -1
  48. package/dist/assets/{useSwitcherItems-OCRYcHeu.js → useSwitcherItems-Dej8BzXI.js} +1 -1
  49. package/dist/assets/vendor-aparajita-capacitor-secure-storage-BYohCVY0.js +1 -0
  50. package/dist/assets/{vendor-base-ui-DIkTOIJS.js → vendor-base-ui-BscvGUFt.js} +1 -1
  51. package/dist/assets/vendor-boot-Dgb9NVFe.js +69 -0
  52. package/dist/assets/vendor-capacitor-app-BjdQVib9.js +1 -0
  53. package/dist/assets/vendor-capacitor-keyboard-eTtI5go3.js +1 -0
  54. package/dist/assets/vendor-capacitor-push-notifications-CBKq2Arn.js +1 -0
  55. package/dist/assets/vendor-capacitor-status-bar-9rNIGxlO.js +1 -0
  56. package/dist/assets/{vendor-codemirror-autocomplete-DsFn4GLp.js → vendor-codemirror-autocomplete-DxS3jwvE.js} +1 -1
  57. package/dist/assets/{vendor-codemirror-lang-angular-B_NMmBbS.js → vendor-codemirror-lang-angular-DdjXl9e2.js} +1 -1
  58. package/dist/assets/vendor-codemirror-lang-cpp--aMr7NVt.js +1 -0
  59. package/dist/assets/vendor-codemirror-lang-css-CZ_qxZY9.js +1 -0
  60. package/dist/assets/{vendor-codemirror-lang-go-C2KHbcll.js → vendor-codemirror-lang-go-Ca-y2Alu.js} +2 -2
  61. package/dist/assets/vendor-codemirror-lang-html-COZ0L5wT.js +1 -0
  62. package/dist/assets/vendor-codemirror-lang-java-D3Rf3QNJ.js +1 -0
  63. package/dist/assets/{vendor-codemirror-lang-javascript-DpTUrvx8.js → vendor-codemirror-lang-javascript-DwJ-IvCs.js} +2 -2
  64. package/dist/assets/vendor-codemirror-lang-jinja-D_5lod6k.js +1 -0
  65. package/dist/assets/vendor-codemirror-lang-json-BG8C7OpC.js +1 -0
  66. package/dist/assets/vendor-codemirror-lang-less-CVEkoaTw.js +1 -0
  67. package/dist/assets/vendor-codemirror-lang-liquid-U9vj0m8w.js +1 -0
  68. package/dist/assets/vendor-codemirror-lang-markdown-DqlYH9gY.js +1 -0
  69. package/dist/assets/vendor-codemirror-lang-php-BFEiEVA1.js +1 -0
  70. package/dist/assets/vendor-codemirror-lang-python-Cz1dQXQd.js +3 -0
  71. package/dist/assets/vendor-codemirror-lang-rust-C_CoD9mj.js +1 -0
  72. package/dist/assets/vendor-codemirror-lang-sass-BuR0aKh5.js +1 -0
  73. package/dist/assets/{vendor-codemirror-lang-sql-C_RazIaB.js → vendor-codemirror-lang-sql-DggNUjdM.js} +2 -2
  74. package/dist/assets/{vendor-codemirror-lang-vue-BYL0r7KR.js → vendor-codemirror-lang-vue-DFZHi2J3.js} +1 -1
  75. package/dist/assets/vendor-codemirror-lang-wast-zuTN3SHT.js +1 -0
  76. package/dist/assets/vendor-codemirror-lang-xml-CrcvhI-k.js +1 -0
  77. package/dist/assets/vendor-codemirror-lang-yaml-DcVWsakb.js +1 -0
  78. package/dist/assets/{vendor-codemirror-language-data-DglcKYWT.js → vendor-codemirror-language-data-CCLITgCF.js} +2 -2
  79. package/dist/assets/{vendor-codemirror-search-DaE6R5gH.js → vendor-codemirror-search-H7NOEdbX.js} +2 -2
  80. package/dist/assets/{vendor-lezer-cpp-Dt99h3WT.js → vendor-lezer-cpp-C8aD2KAr.js} +1 -1
  81. package/dist/assets/{vendor-lezer-css-DNU_fzPI.js → vendor-lezer-css-2lbTJF-Y.js} +1 -1
  82. package/dist/assets/{vendor-lezer-go-BEFtcNyS.js → vendor-lezer-go-Bw6LFTrZ.js} +1 -1
  83. package/dist/assets/{vendor-lezer-html-DDGRhRUz.js → vendor-lezer-html-D7ym2z7S.js} +1 -1
  84. package/dist/assets/{vendor-lezer-java-DmfZtW09.js → vendor-lezer-java-CZhK7w21.js} +1 -1
  85. package/dist/assets/{vendor-lezer-javascript-oje4tdp_.js → vendor-lezer-javascript-rpKeTHZp.js} +1 -1
  86. package/dist/assets/{vendor-lezer-json-BRXb_bDX.js → vendor-lezer-json-C7jwsd2G.js} +1 -1
  87. package/dist/assets/{vendor-lezer-lr-BU2qmu_5.js → vendor-lezer-lr-DR-ylqNN.js} +1 -1
  88. package/dist/assets/{vendor-lezer-markdown-CicYv7V9.js → vendor-lezer-markdown-Bir0m5nB.js} +1 -1
  89. package/dist/assets/{vendor-lezer-php-COORrTpE.js → vendor-lezer-php-y0hIEfo1.js} +1 -1
  90. package/dist/assets/{vendor-lezer-python-Cuvm9X9Y.js → vendor-lezer-python-D64A9lNV.js} +1 -1
  91. package/dist/assets/{vendor-lezer-rust-C_zOfHbX.js → vendor-lezer-rust-E3ZA9T2L.js} +1 -1
  92. package/dist/assets/{vendor-lezer-sass-DWP4w7O1.js → vendor-lezer-sass-C5UFI9SP.js} +1 -1
  93. package/dist/assets/{vendor-lezer-xml-Br6nOYeG.js → vendor-lezer-xml-DOy7FzCR.js} +1 -1
  94. package/dist/assets/{vendor-lezer-yaml-CYQmm6Sb.js → vendor-lezer-yaml-kEjaSCvZ.js} +1 -1
  95. package/dist/assets/{vendor-replit-codemirror-vim-CZy3BUVv.js → vendor-replit-codemirror-vim-BLfh0LPy.js} +1 -1
  96. package/dist/assets/{web-components-v9fuidaX.js → web-components-C7CmoFxi.js} +1 -1
  97. package/dist/index.html +4 -4
  98. package/dist/mini-chat.html +3 -3
  99. package/dist/mobile.html +3 -3
  100. package/package.json +1 -1
  101. package/server/lib/pi/routes.js +1 -0
  102. package/server/lib/pi/session-daemon/DOCUMENTATION.md +1 -1
  103. package/server/lib/pi/session-daemon/supervisor.js +13 -1
  104. package/server/lib/pi/session-daemon/supervisor.test.js +92 -0
  105. package/server/lib/relay/DOCUMENTATION.md +4 -0
  106. package/server/lib/terminal/DOCUMENTATION.md +1 -0
  107. package/dist/assets/DiagramView-GKGxPczP.js +0 -1
  108. package/dist/assets/FileSaveConflictDialog-BRM9TJo0.js +0 -3
  109. package/dist/assets/GitHubLinkPicker-B9xgIW8y.js +0 -1
  110. package/dist/assets/MarkdownRendererImpl-1HameF6j.js +0 -12
  111. package/dist/assets/PullRequestsSurface-Dec20SIg.js +0 -2
  112. package/dist/assets/SessionSwitcherContent-DEw4nz7K.js +0 -1
  113. package/dist/assets/SessionSwitcherDropdown-DmLhbRzE.js +0 -2
  114. package/dist/assets/SettingsView-CwSspvq-.js +0 -6
  115. package/dist/assets/SettingsWindow-DkPv9MaU.js +0 -1
  116. package/dist/assets/ToolOutputDialog-DDwbOpTO.js +0 -8
  117. package/dist/assets/ToolPartDiffPreview-DZRP7p-Q.js +0 -1
  118. package/dist/assets/index-CkMnC_GK.js +0 -1
  119. package/dist/assets/index-Dd2OcIUY.js +0 -10
  120. package/dist/assets/index-DvN8zlLT.css +0 -1
  121. package/dist/assets/miniChat-BzfobBDq.js +0 -2
  122. package/dist/assets/mobile-DAzZE2EL.js +0 -2
  123. package/dist/assets/renderElectronMiniChatApp-DGYSIihR.js +0 -2
  124. package/dist/assets/renderMobileApp-CwgWG0lU.js +0 -11
  125. package/dist/assets/runtimeEndpointReset-CmI6dBKM.js +0 -62
  126. package/dist/assets/useAppFontEffects--lKKtKVo.js +0 -212
  127. package/dist/assets/vendor-aparajita-capacitor-secure-storage-5IShChL0.js +0 -1
  128. package/dist/assets/vendor-boot-DyL2td56.js +0 -69
  129. package/dist/assets/vendor-capacitor-app-BrDJj9I_.js +0 -1
  130. package/dist/assets/vendor-capacitor-core-B4EWRrHz.js +0 -1
  131. package/dist/assets/vendor-capacitor-keyboard-CYccoJjr.js +0 -1
  132. package/dist/assets/vendor-capacitor-push-notifications-KNe1zSBF.js +0 -1
  133. package/dist/assets/vendor-capacitor-status-bar-B-N0EOVk.js +0 -1
  134. package/dist/assets/vendor-codemirror-lang-cpp-GOE7Gjd0.js +0 -1
  135. package/dist/assets/vendor-codemirror-lang-css-Dwf2XpnZ.js +0 -1
  136. package/dist/assets/vendor-codemirror-lang-html-DcKqyeGk.js +0 -1
  137. package/dist/assets/vendor-codemirror-lang-java-6eGbyB2k.js +0 -1
  138. package/dist/assets/vendor-codemirror-lang-jinja-xSUJjXhr.js +0 -1
  139. package/dist/assets/vendor-codemirror-lang-json-CLGxdOCz.js +0 -1
  140. package/dist/assets/vendor-codemirror-lang-less-6nXi1rS9.js +0 -1
  141. package/dist/assets/vendor-codemirror-lang-liquid-B9hmb9P8.js +0 -1
  142. package/dist/assets/vendor-codemirror-lang-markdown-DmFP9s6x.js +0 -1
  143. package/dist/assets/vendor-codemirror-lang-php-DC6To8iX.js +0 -1
  144. package/dist/assets/vendor-codemirror-lang-python-yuxIkjit.js +0 -3
  145. package/dist/assets/vendor-codemirror-lang-rust-di1Sjz-0.js +0 -1
  146. package/dist/assets/vendor-codemirror-lang-sass-BWpV9NPV.js +0 -1
  147. package/dist/assets/vendor-codemirror-lang-wast-BiVarhcz.js +0 -1
  148. package/dist/assets/vendor-codemirror-lang-xml-Cn1lY1ts.js +0 -1
  149. package/dist/assets/vendor-codemirror-lang-yaml-BZ6mZw9L.js +0 -1
@@ -1,2 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SessionSwitcherDropdown-DmLhbRzE.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-boot-DyL2td56.js","assets/vendor-react-DASdDPIk.js","assets/vendor-clsx-B-dksMZM.js","assets/useAppFontEffects--lKKtKVo.js","assets/index-Dd2OcIUY.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-DvN8zlLT.css","assets/runtimeSurface-B1GRkkKC.js"])))=>i.map(i=>d[i]);
2
- import{j as e,aJ as ye}from"./vendor-boot-DyL2td56.js";import{R as c,a as me}from"./vendor-react-DASdDPIk.js";/* empty css */import{o as G,u as K,aF as ge,E as q,t as ie,aB as U,R as we,V as ve,z as le,w as je,B as be}from"./index-Dd2OcIUY.js";import{f as Se,u as Ie,a as Ce,s as Ne}from"./pi-session-focus-preference-D2-1HWmY.js";import{bR as De,I as J,aY as Pe,a9 as Me,aa as Ee,ac as ke,bS as _e,bT as Le,f as j,b8 as Oe,a as ae,H as P,as as ce,bU as Te,p as Re,aD as Ae,bF as Be,bu as Fe,B as de,bJ as ze,bV as ue,bW as Ue,t as $e,g as We,R as He,E as Ve,T as Ge,U as Je,W as Ke,V as Ye,Y as Xe,Z as Ze,bX as qe,bG as Qe,a0 as et,a1 as tt,a2 as st,a3 as rt}from"./useAppFontEffects--lKKtKVo.js";import{_ as nt}from"./vendor-vite-runtime-DD1OZmLC.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-zustand-CUi8eEds.js";import"./vendor-tailwind-merge-CPcsbTWB.js";import"./vendor-fuse.js-Dw8P0qyA.js";import"./runtimeSurface-B1GRkkKC.js";const ot=({mode:t,children:r})=>e.jsx(De.Provider,{value:t,children:r}),it=_e,at=Le,ct=({totalTokens:t,percentage:r,colorPercentage:n,contextLimit:a,outputLimit:o,size:u="default",isMobile:l=!1,hideIcon:D=!1,showPercentIcon:k=!1,className:p,valueClassName:f,percentIconClassName:_,onClick:M,pressed:O=!1,cacheRead:x,cacheWrite:C,cacheHitPercent:h})=>{const[b,i]=c.useState(!1),g=typeof n=="number"?n:r,m=it(r)??0,y=at(g),Y=y==="critical"?"var(--status-error)":y==="warn"?"var(--status-warning)":"var(--status-success)",w=I=>I>=1e6?`${(I/1e6).toFixed(1)}M`:I>=1e3?`${(I/1e3).toFixed(1)}K`:I.toFixed(1).replace(/\.0$/,""),N=I=>I>=90?"text-status-error":I>=75?"text-status-warning":"text-status-success",E=20,$=3,W=(E-$)/2,re=2*Math.PI*W,X=re*(1-m/100),R=typeof o=="number"?Math.max(o,0):0,A=typeof x=="number"&&typeof C=="number",Q=A?Math.max(0,x):0,B=A?Math.max(0,C):0,L=typeof h=="number"&&Number.isFinite(h),T=[`Used tokens: ${w(t)}`,`Context limit: ${w(a)}`,`Output limit: ${w(R)}`,...A?[`Cache read: ${w(Q)}`,`Cache write: ${w(B)}`]:[],...L?[`Cache hit: ${h.toFixed(1)}%`]:[],`${Math.min(r,999).toFixed(1)}% used`],F=!l&&typeof M=="function",v=e.jsxs(e.Fragment,{children:[!l&&!D&&e.jsx(J,{name:"donut-chart",className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:G("font-medium inline-flex items-center gap-1.5",f),children:k?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{viewBox:`0 0 ${E} ${E}`,className:G("h-3.5 w-3.5 -rotate-90",_),role:"progressbar","aria-valuenow":Math.round(m),"aria-valuemin":0,"aria-valuemax":100,children:[e.jsx("circle",{cx:E/2,cy:E/2,r:W,fill:"none",stroke:"var(--interactive-border)",strokeWidth:$}),e.jsx("circle",{cx:E/2,cy:E/2,r:W,fill:"none",stroke:Y,strokeWidth:$,strokeLinecap:"round",strokeDasharray:re,strokeDashoffset:X,className:"transition-[stroke-dashoffset,stroke] duration-300"})]}),e.jsxs("span",{className:"text-foreground",children:[Math.min(r,999).toFixed(1),"%"]})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:N(g),children:Math.min(r,999).toFixed(1)}),"%"]})})]}),S=G("app-region-no-drag flex items-center gap-1.5 select-none",u==="compact"?"typography-micro":"typography-meta",F?G("rounded-md px-2 py-1.5 text-foreground transition-colors","hover:bg-interactive-hover","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"):"text-muted-foreground/60",p),H=F?e.jsx("button",{type:"button",className:S,"aria-label":"Context usage","aria-pressed":O,onClick:M,children:v}):e.jsx("div",{className:S,"aria-label":"Context usage",onClick:l?()=>i(!0):void 0,children:v});return l?e.jsxs(e.Fragment,{children:[H,e.jsx(Pe,{open:b,onClose:()=>i(!1),title:"Context Usage",children:e.jsx("div",{className:"flex flex-col gap-1.5",children:e.jsxs("div",{className:"rounded-xl border border-border/40 bg-sidebar/30 px-3 py-2 space-y-1",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:w(t)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:w(a)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:w(R)})]}),A?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Cache read"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:w(Q)})]}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Cache write"}),e.jsx("span",{className:"typography-meta text-foreground font-medium",children:w(B)})]})]}):null,L?e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Cache hit"}),e.jsxs("span",{className:"typography-meta text-foreground font-medium",children:[h.toFixed(1),"%"]})]}):null,e.jsxs("div",{className:"flex justify-between items-center pt-1 border-t border-border/40",children:[e.jsx("span",{className:"typography-meta text-muted-foreground",children:"Usage"}),e.jsxs("span",{className:G("typography-meta font-semibold",N(g)),children:[Math.min(r,999).toFixed(1),"%"]})]})]})})})]}):e.jsxs(Me,{children:[e.jsx(Ee,{asChild:!0,children:H}),e.jsx(ke,{children:e.jsx("div",{className:"space-y-0.5",children:T.map(I=>e.jsx("p",{className:"typography-micro leading-tight",children:I},I))})})]})},lt=c.lazy(()=>nt(()=>import("./SessionSwitcherDropdown-DmLhbRzE.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(t=>({default:t.SessionSwitcherDropdown}))),dt=t=>{const r=typeof t=="string"?t.trim():"";if(!r)return"";const n=typeof window<"u"?window.__PICHAMBER_HOME__:"";if(n&&r===n)return"~";if(n&&r.startsWith(`${n}/`))return`~/${r.slice(n.length+1)}`;const a=r.split("/").filter(Boolean);return a.length<=3?r:`.../${a.slice(-3).join("/")}`},se=t=>{const r=typeof t=="string"?t.trim():"";if(!r)return"";const n=r.replace(/\\/g,"/");return n==="/"?"/":n.replace(/\/+$/,"")},ut=({mode:t})=>{const r=j(s=>s.currentSessionId),n=j(s=>!!s.newSessionDraft?.open),a=j(s=>s.newSessionDraft?.selectedProjectId??null),o=K(s=>s.currentDirectory),u=ae(s=>s.projects),l=ae(s=>s.getActiveProject()),D=P(s=>s.getCurrentModel),k=P(s=>s.providers),p=ce(),f=Te(r??""),_=Re(),M=Ae(s=>s.ensureStatus),O=j(s=>s.newSessionDraft?.open?se(s.newSessionDraft.directoryOverride??""):""),[x,C]=c.useState(!1),h=typeof window<"u"?window.__PICHAMBER_MACOS_MAJOR__??0:0,b=Number.isFinite(h)&&h>0,i=Be(),g=b?h>=26?"h-12":h<=15?"h-14":"":"",m=c.useMemo(()=>r?p.find(s=>s.id===r)??null:null,[r,p]);c.useEffect(()=>{ge()&&q("desktop_get_window_pinned").then(s=>{typeof s?.pinned=="boolean"&&C(s.pinned)})},[]);const y=m?.title?.trim()||(n||t==="draft"?"New session":"Session"),Y=se(m?.directory??null),w=se(o),N=Y||O||w,E=dt(N);c.useEffect(()=>{N&&M(N,_.git).catch(()=>{})},[M,N,_.git]);const $=c.useMemo(()=>{const s=N;return s?u.map(d=>({...d,normalizedPath:se(d.path)})).filter(d=>d.normalizedPath&&(d.normalizedPath===s||s.startsWith(`${d.normalizedPath}/`))).sort((d,V)=>V.path.length-d.path.length)[0]??null:null},[N,u]),W=c.useMemo(()=>{const s=$??l;if(!s)return E||"PiChamber";const d=s.label?.trim();return d||(s.path.split(/[\\/]/).filter(Boolean).at(-1)??s.path)},[l,E,$]),X=Fe(N||null),R=X&&X!=="HEAD"?X:null,A=D(),Q=c.useMemo(()=>{for(let s=f.length-1;s>=0;s-=1){const d=f[s];if(d.role!=="assistant"||typeof d.providerID!="string"||typeof d.modelID!="string")continue;const te=k.find(Z=>Z.id===d.providerID)?.models.find(Z=>Z.id===d.modelID);if(te)return te}},[f,k]),B=A?.limit?A:Q,L=B&&typeof B.limit=="object"&&B.limit!==null?B.limit:null,T=L&&typeof L.context=="number"?L.context:0,F=L&&typeof L.output=="number"?L.output:0,v=c.useMemo(()=>{if(!r||f.length===0)return null;let s,d;for(let ne=f.length-1;ne>=0;ne-=1){const oe=f[ne];if(oe.role!=="assistant")continue;const z=oe.tokens;if(!z)continue;if(z.input+z.output+z.reasoning+(z.cache?.read??0)+(z.cache?.write??0)>0){s=z,d=oe.id;break}}if(!s)return null;const V=s.input+s.output+s.reasoning+(s.cache?.read??0)+(s.cache?.write??0),te=T>0?T:2e5,Z=T>0?Math.round(V/T*100):0,xe=F>0?Math.round(s.output/F*100):void 0;return{totalTokens:V,percentage:Z,contextLimit:T||0,outputLimit:F||void 0,normalizedOutput:xe,thresholdLimit:te,lastMessageId:d}},[T,r,f,F]),[S,H]=c.useState(null),I={WebkitAppRegion:"drag"},ee={WebkitAppRegion:"no-drag"};c.useEffect(()=>{if(!r){H(s=>s===null?s:null);return}if(v&&v.totalTokens>0){H(s=>s&&s.totalTokens===v.totalTokens&&s.percentage===v.percentage&&s.contextLimit===v.contextLimit&&(s.outputLimit??0)===(v.outputLimit??0)&&(s.normalizedOutput??0)===(v.normalizedOutput??0)&&s.thresholdLimit===v.thresholdLimit&&s.lastMessageId===v.lastMessageId?s:v);return}H(s=>s===null?s:null)},[v,r]);const fe=S&&S.contextLimit>0?Math.min(999,S.totalTokens/S.contextLimit*100):0,pe=c.useCallback(()=>{const s=!x;C(s),q("desktop_set_window_pinned",{pinned:s}).catch(()=>{C(!s)})},[x]),he=c.useCallback(()=>{const s=r?{sessionId:r,directory:m?.directory??o??""}:{mode:"draft",directory:N||o||"",projectId:a};q("desktop_focus_main_window",s).then(d=>d?.focused===!0?q("desktop_close_current_window"):null)},[o,r,a,N,m]);return e.jsxs("header",{className:G("flex items-center gap-3 bg-background pr-3",b?"pl-[5.5rem]":"pl-3",i?"h-12":g||"min-h-14"),style:I,children:[e.jsx(me.Suspense,{fallback:e.jsxs("button",{type:"button","aria-label":"Open session switcher",style:ee,className:"flex min-w-0 max-w-full flex-col items-start rounded-md px-1 py-0.5 text-left transition-colors hover:bg-interactive-hover/60 focus-visible:outline-none focus-visible:bg-interactive-hover/60",children:[e.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:y}),e.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[e.jsx("span",{className:"truncate",children:W}),R?e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[e.jsx(J,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"truncate",children:R})]}):null]})]}),children:e.jsx(lt,{children:e.jsxs("button",{type:"button","aria-label":"Open session switcher",style:ee,className:"flex min-w-0 max-w-full flex-col items-start rounded-md px-1 py-0.5 text-left transition-colors hover:bg-interactive-hover/60 focus-visible:outline-none focus-visible:bg-interactive-hover/60",children:[e.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:y}),e.jsxs("span",{className:"flex min-w-0 max-w-full items-center gap-1.5 truncate typography-micro text-[10.5px] font-normal leading-tight text-muted-foreground/75",children:[e.jsx("span",{className:"truncate",children:W}),R?e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[e.jsx(J,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),e.jsx("span",{className:"truncate",children:R})]}):null]})]})})}),e.jsx("div",{className:"min-w-0 flex-1"}),S&&S.totalTokens>0?e.jsx(ct,{totalTokens:S.totalTokens,percentage:fe,colorPercentage:S.percentage,contextLimit:S.contextLimit,outputLimit:S.outputLimit??0,className:"h-9 shrink-0 pl-1 pr-1 typography-ui-label",valueClassName:"font-semibold leading-none",hideIcon:!0,showPercentIcon:!0,percentIconClassName:"h-4.5 w-4.5"}):null,e.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:pe,"aria-label":x?"Unpin Mini Chat window":"Pin Mini Chat window",title:x?"Unpin window":"Pin above other windows",style:ee,children:x?e.jsx(J,{name:"pushpin-2-fill",className:"h-4 w-4"}):e.jsx(J,{name:"pushpin-2",className:"h-4 w-4"})}),e.jsx(de,{type:"button",variant:"ghost",size:"icon",onClick:he,"aria-label":"Open session in main window",title:"Open in main window",style:ee,children:e.jsx(J,{name:"external-link",className:"h-4 w-4"})}),e.jsx(ze,{visible:i})]})},mt=({mode:t,autoOpenDraft:r=!1,unavailable:n=!1})=>{const a=j(o=>o.currentSessionId);return e.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background text-foreground",children:[e.jsx(ut,{mode:t}),e.jsx("main",{className:"min-h-0 flex-1",children:n?e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-center typography-ui-label text-muted-foreground",children:e.jsxs("div",{className:"max-w-sm rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-4 py-3",children:[e.jsx("div",{className:"font-medium text-foreground",children:"Session unavailable"}),e.jsx("div",{className:"mt-1 typography-small text-muted-foreground",children:"This session could not be loaded. It may have been deleted, archived, or opened from a different project context."})]})}):e.jsx(ot,{mode:"mini-chat",children:e.jsx(Oe,{autoOpenDraft:r},a??"no-session")})})]})},ft=()=>{const t=ie(o=>o.shortcutOverrides),r=K(o=>o.currentDirectory),n=ae(o=>o.getActiveProject()),a=j(o=>o.openNewSessionDraft);c.useEffect(()=>{const o=l=>ve(l,t),u=l=>{if(U(l,o("focus_input"))){l.preventDefault(),ue();return}if(we()&&U(l,o("new_mini_chat"))){l.preventDefault(),q("desktop_open_draft_mini_chat_window",{directory:r||n?.path||"",projectId:n?.id??null})?.catch(p=>{console.warn("[mini-chat-shortcuts] failed to open draft mini chat window",p)});return}if(U(l,o("new_chat"))){l.preventDefault(),a({selectedProjectId:n?.id??null,directoryOverride:r||n?.path||null,preserveDirectoryOverride:!!(r||n?.path)}),ue();return}if(U(l,o("open_model_selector"))){l.preventDefault();const{isModelSelectorOpen:p,setModelSelectorOpen:f}=ie.getState();f(!p);return}if(U(l,o("cycle_thinking_variant"))){if(P.getState().getCurrentModelVariants().length===0)return;l.preventDefault(),Ue(1).catch(()=>{$e.error("Couldn't update thinking")});return}const D=U(l,o("cycle_favorite_model_forward")),k=U(l,o("cycle_favorite_model_backward"));if(D||k){const{favoriteModels:p,addRecentModel:f}=ie.getState();if(p.length===0)return;l.preventDefault();const{currentProviderId:_,currentModelId:M,setProvider:O,setModel:x}=P.getState(),C=p.findIndex(i=>i.providerID===_&&i.modelID===M),b=p[(C+(D?1:-1)+p.length)%p.length];O(b.providerID),x(b.modelID),f(b.providerID,b.modelID)}};return window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)},[n?.id,n?.path,r,a,t])},pt="pichamber:mini-chat-presence",ht=()=>{const t=typeof window<"u"?new URLSearchParams(window.location.search):new URLSearchParams,r=t.get("mode")==="session"?"session":"draft",n=t.get("sessionId")?.trim()||null,a=t.get("directory")?.trim()||null,o=t.get("projectId")?.trim()||null;return{mode:r,sessionId:n,directory:a,projectId:o}},xt=({config:t})=>{const r=ce(),n=K(i=>i.currentDirectory),a=K(i=>i.setDirectory),o=j(i=>i.currentSessionId),u=j(i=>!!i.newSessionDraft?.open),l=j(i=>i.newSessionDraft?.open?i.newSessionDraft.bootstrapPendingDirectory??i.newSessionDraft.directoryOverride??"":""),D=j(i=>i.setCurrentSession),k=j(i=>i.openNewSessionDraft),p=P(i=>i.initializeApp),f=P(i=>i.isInitialized),_=P(i=>i.isConnected),M=P(i=>i.loadProviders),O=P(i=>i.providers.length),x=Qe();c.useEffect(()=>{p()},[p]),c.useEffect(()=>{if(f)return;let i=!0,g=0;const m=window.setInterval(()=>{if(i){if(g+=1,g>10){window.clearInterval(m);return}P.getState().isInitialized||P.getState().initializeApp()}},1e3);return()=>{i=!1,window.clearInterval(m)}},[f]);const C=c.useRef(!1);c.useEffect(()=>{if(!C.current&&t.mode==="session"&&t.directory){if(n===t.directory){C.current=!0;return}a(t.directory,{showOverlay:!1}),C.current=!0}},[t.directory,t.mode,n,a]),c.useEffect(()=>{t.mode!=="draft"||!u||o||!l||n===l||a(l,{showOverlay:!1})},[t.mode,n,o,l,u,a]),c.useEffect(()=>{_&&O===0&&M({source:"electronMiniChat:recovery"})},[_,M,O]);const h=c.useRef(!1);c.useEffect(()=>{if(h.current||t.mode!=="session"||!t.sessionId)return;if(o===t.sessionId){h.current=!0;return}if(o){h.current=!0;return}const i=r.find(m=>m.id===t.sessionId);if(!i){x.ensureSessionRenderable(t.sessionId);return}const g=i.directory??t.directory;D(t.sessionId,g),h.current=!0},[t,o,r,D,x]),c.useEffect(()=>{const i=g=>{const m=g.detail,y=typeof m?.sessionId=="string"?m.sessionId.trim():"";if(!y||j.getState().currentSessionId===y)return;const Y=typeof m?.directory=="string"&&m.directory.trim().length>0?m.directory.trim():r.find(w=>w.id===y)?.directory??null;x.ensureSessionRenderable(y),D(y,Y),h.current=!0};return window.addEventListener("pichamber:open-session",i),()=>window.removeEventListener("pichamber:open-session",i)},[r,D,x]),c.useEffect(()=>{t.mode!=="draft"||u||o||k({selectedProjectId:t.projectId,directoryOverride:t.directory,preserveDirectoryOverride:!!t.directory})},[t,o,u,k]);const b=c.useRef(!1);return c.useEffect(()=>{if(b.current||!f)return;const i=()=>{if(b.current)return;b.current=!0;const y=typeof document<"u"?document.getElementById("initial-loading"):null;y&&(y.classList.add("fade-out"),window.setTimeout(()=>y.remove(),300))},g=t.mode==="session"?o===t.sessionId:u,m=window.setTimeout(i,g?100:1500);return()=>window.clearTimeout(m)},[f,t.mode,t.sessionId,o,u]),null},yt=()=>{const t=j(n=>n.currentSessionId),r=K(n=>n.currentDirectory);return c.useEffect(()=>{if(!t||!r||typeof BroadcastChannel>"u")return;const n=new BroadcastChannel(pt),a=l=>{n.postMessage({type:"mini-chat-session-presence",sessionId:t,directory:r,viewed:l})};a(!0);const o=window.setInterval(()=>a(!0),5e3),u=()=>a(!1);return window.addEventListener("beforeunload",u),()=>{window.clearInterval(o),window.removeEventListener("beforeunload",u),a(!1),n.close()}},[r,t]),null},gt=t=>{const r=ce(),n=j(u=>u.currentSessionId),[a,o]=c.useState(!1);return c.useEffect(()=>{if(t.mode!=="session"||!t.sessionId||n===t.sessionId){o(!1);return}if(r.some(l=>l.id===t.sessionId)){o(!1);return}const u=window.setTimeout(()=>o(!0),5e3);return()=>window.clearTimeout(u)},[t.mode,t.sessionId,n,r]),a};function wt({apis:t}){const r=c.useMemo(()=>ht(),[]),n=K(a=>a.currentDirectory);return c.useEffect(()=>{const a=n||r.directory;if(!a)return;const o=r.mode==="session"?{sessionId:r.sessionId,directory:r.directory}:null;We().focusProject(a,Se(a,o))},[r.directory,r.mode,r.sessionId,n]),c.useEffect(()=>(le(t),()=>le(null)),[t]),He(),ft(),Ie({enabled:!0}),e.jsx(Ve,{children:e.jsx(Ge,{directory:n||r.directory,children:e.jsxs(Je,{apis:t,children:[e.jsx(Ke,{}),e.jsx(Ye,{delayDuration:300,skipDelayDuration:150,children:e.jsxs("div",{className:"h-full text-foreground bg-background",children:[e.jsx(vt,{config:r}),e.jsx(Xe,{}),e.jsx(Ze,{})]})})]})})})}const vt=({config:t})=>{const r=gt(t);return e.jsxs(e.Fragment,{children:[e.jsx(xt,{config:t}),e.jsx(yt,{}),e.jsx(qe,{embeddedBackgroundWorkEnabled:!0}),e.jsx(mt,{mode:t.mode,autoOpenDraft:t.mode==="draft",unavailable:r})]})},jt=()=>{(async()=>{try{await Promise.all([be(),Ce()])}catch(t){console.error("[mini-chat-main] settings init failed:",t)}st(),rt(),Ne()})()};function Tt(t){const r=t??je();if(!r)throw new Error("Runtime APIs not registered");jt();const n=document.getElementById("root");if(!n)throw new Error("Root element not found");ye.createRoot(n).render(e.jsx(me.StrictMode,{children:e.jsx(et,{children:e.jsx(tt,{children:e.jsx(wt,{apis:r})})})}))}export{Tt as renderElectronMiniChatApp};
@@ -1,11 +0,0 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/FilesView-CEeQzjc6.js","assets/vendor-boot-DyL2td56.js","assets/vendor-react-DASdDPIk.js","assets/vendor-clsx-B-dksMZM.js","assets/index-Dd2OcIUY.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-DvN8zlLT.css","assets/useAppFontEffects--lKKtKVo.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/runtimeSurface-B1GRkkKC.js","assets/vendor-codemirror-lang-javascript-DpTUrvx8.js","assets/vendor-lezer-javascript-oje4tdp_.js","assets/vendor-lezer-lr-BU2qmu_5.js","assets/vendor-codemirror-autocomplete-DsFn4GLp.js","assets/vendor-codemirror-lang-json-CLGxdOCz.js","assets/vendor-lezer-json-BRXb_bDX.js","assets/vendor-codemirror-lang-css-Dwf2XpnZ.js","assets/vendor-lezer-css-DNU_fzPI.js","assets/vendor-codemirror-lang-html-DcKqyeGk.js","assets/vendor-lezer-html-DDGRhRUz.js","assets/vendor-codemirror-lang-markdown-DmFP9s6x.js","assets/vendor-lezer-markdown-CicYv7V9.js","assets/vendor-codemirror-language-data-DglcKYWT.js","assets/vendor-codemirror-lang-python-yuxIkjit.js","assets/vendor-lezer-python-Cuvm9X9Y.js","assets/shell-CjFT_Tl9.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-BRM9TJo0.js","assets/vendor-react-drawio-Duu5LgQA.js","assets/runtimeEndpointReset-CmI6dBKM.js","assets/SessionUnreadDot-CJFawQpo.js","assets/permissionStore-B9Hkrqny.js","assets/runtimeEndpointReset-BV3KOtdA.css","assets/vendor-xterm-xterm-css-DDGTF8rc.css","assets/useFilesViewSearch-D1jsGQrN.js","assets/JsonTreeView-X2Auiy_q.js","assets/web-components-v9fuidaX.js","assets/computeVirtualFileMetrics-3PpRLd5B.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-wpC51ZBQ.js","assets/renderFileWithHighlighter-BvDoP7ob.js","assets/vendor-codemirror-search-DaE6R5gH.js","assets/vendor-replit-codemirror-vim-CZy3BUVv.js","assets/GitView-DV3d0oSJ.js","assets/gitStatusPredicates-BvzxqidP.js","assets/GitHubDetailScaffold-q4YP8iyJ.js","assets/vendor-dompurify-r8glNMJW.js","assets/collapsible-Ce85nuXX.js","assets/vendor-base-ui-DIkTOIJS.js","assets/PierreDiffViewer-0X__nypk.js","assets/VirtualizedFileDiff-CUWx7JVZ.js","assets/renderDiffWithHighlighter-l8hZWWBO.js","assets/vendor-diff-C3JhlQdm.js","assets/PullRequestsSurface-Dec20SIg.js","assets/useGitHubRemoteSearch-zNgy2bSt.js","assets/GitHubListPrimitives-XkALat1v.js","assets/IssuesSurface-OTyt9f3A.js","assets/githubLink-iQ51wqRa.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{j as n,aH as Ke,aI as bt,aJ as ds}from"./vendor-boot-DyL2td56.js";import{a as Ct,R as a}from"./vendor-react-DASdDPIk.js";/* empty css */import{a as fe,b as Rn,d as Xt,e as it,i as ee,f as Ye,h as ae,s as Ne,j as fs,k as Qe,r as ps,l as Tn,m as Nn,p as hs,n as ms,o as K,u as In,q as ys,t as Ie,v as bs,w as Et,x as gs,y as xs,z as qt,A as vs,B as Pn,C as ws,D as ks}from"./index-Dd2OcIUY.js";import{f as Ss,u as js,a as Cs,s as Es}from"./pi-session-focus-preference-D2-1HWmY.js";import{u as Rs,M as Ts,a as Ns,i as Is,D as Jt,b as Yt,c as Qt,g as Ps,d as Zt,e as As,s as _s,S as Ds,f as Ms,T as Ls,h as en,j as tn,k as Os,r as zs,l as Us,m as Bs,n as $s,H as Ks,A as Ws,C as Hs,o as Fs,p as Vs,q as Gs,F as Xs,t as qs,v as Js,W as Ys,w as Qs,x as Zs}from"./runtimeEndpointReset-CmI6dBKM.js";import{g as Ge,l as er,u as tr,a as An,b as nr,c as sr,r as _n,d as rr,e as Be,t as gt,o as ar,I as F,B as le,P as Se,f as me,h as ir,i as or,j as lr,k as cr,E as de,C as st,m as Dn,n as ur,p as dr,q as nn,s as fr,v as pr,w as hr,x as mr,y as yr,z as br,A as gr,D as xr,F as vr,G as wr,H as ke,J as kr,K as ve,L as Sr,M as jr,N as Cr,O as Er,Q as Rr,R as Tr,S as Nr,T as Ir,U as Pr,W as Ar,V as _r,X as Dr,Y as Mr,Z as Lr,_ as Or,$ as zr,a0 as Ur,a1 as Br,a2 as $r,a3 as Kr}from"./useAppFontEffects--lKKtKVo.js";import{Capacitor as Wr}from"./vendor-capacitor-core-B4EWRrHz.js";import{p as Hr}from"./vendor-aparajita-capacitor-secure-storage-5IShChL0.js";import{_ as Ce}from"./vendor-vite-runtime-DD1OZmLC.js";import{S as Fr,A as Vr}from"./SettingsView-CwSspvq-.js";import{f as Gr,S as Xr,a as qr,g as Mn}from"./SessionUnreadDot-CJFawQpo.js";import{u as Jr}from"./useSwitcherItems-OCRYcHeu.js";let Ln=null,sn=!1;const Yr=new Promise(e=>{Ln=e});function Qr(){sn||(sn=!0,Ln?.())}const Zr=6,ea=e=>e.parentID??null,rn=e=>{const t=e.replace(/\/+$/,"");return t.slice(t.lastIndexOf("/")+1)||t},ta=e=>e.replace(/\\/g,"/").replace(/\/+$/,""),na=(e,t)=>{if(!e)return"";let r=null,s=-1;for(const o of t){const i=ta(o.path);(e===i||e.startsWith(`${i}/`))&&i.length>s&&(r=o,s=i.length)}return r?r.label?.trim()||rn(r.path):rn(e)},sa=()=>{const e=Ge().getState().catalog,t=[];for(const d of e.byId.values())d.archived||t.push(er(d));const r=tr.getState().index.session.unseenCount,s=An.getState().projects,o=nr.getState().ids,i=sr.getState().rankById;let l=0;const c=[];for(const d of t){const p=ea(d)!==null,S=(r[d.id]??0)>0;S&&(l+=1),p||c.push({session:d,unread:S,project:na(_n(d),s)})}c.sort(rr(o,i,d=>d.session));const u=c.slice(0,Zr).map(({session:d,unread:p,project:m})=>({id:d.id,title:d.title??"",unread:p,project:m}));return{runtimeKey:fe(),attentionCount:l,recentSessions:u}},ra="__PICHAMBER_WIDGET_SNAPSHOT__",aa=()=>{typeof window>"u"||(window[ra]=()=>{try{return JSON.stringify(sa())}catch{return null}})},xt="mobile-app-update-available",an="mobile-app-update-toast-dismissed-version",ia=()=>{const e=Be(i=>i.available),t=Be(i=>i.runtimeType),r=Be(i=>i.info?.version),s=Be(i=>i.info?.downloadUrl),o=Ct.useRef(new Set);return Ct.useEffect(()=>{if(Rn()!=="android"||t!=="mobile"||!e||!r||!s){gt.dismiss(xt);return}Xt().getItem(an)!==r&&(o.current.has(r)||(o.current.add(r),gt.info("PiChamber update available",{id:xt,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:()=>{ar(s)}},cancel:{label:"Dismiss",onClick:()=>{Xt().setItem(an,r),gt.dismiss(xt)}}})))},[e,s,t,r]),null},oa=e=>{const{persisted:t,persistedDirectory:r,stale:s,ready:o,catalog:i,runtimeKey:l,capturedRuntimeKey:c,storeIdentityMatches:u,generationMatches:d}=e;if(!t||!r)return{action:"wait"};if(s||l!==c||!u||!d)return{action:"wait"};if(!o||!i)return{action:"wait"};const p=i.byId.get(t.sessionId);return!p||p.archived?{action:"clear"}:{action:"select",sessionId:p.id,directory:p.directory??r}},ot="pichamber.mobile.connections.v1",la="pichamber.mobile.",on="pichamber.mobile.deviceId",On=12,ca=8e3,ua=2500,da=3e3,lt=2500,We=15e3,fa=1500,pa=5e3,ha=()=>{try{const e=window.localStorage.getItem(on);if(e&&e.trim())return e.trim();const t=it();return window.localStorage.setItem(on,t),t}catch{return it()}},ln=()=>`mobile:${ha()}`,cn=()=>{try{const e=Wr.getPlatform();return e==="ios"||e==="android"?e:void 0}catch{return}},zn=()=>{let e=0;return{begin:()=>(e+=1,e),cancel:()=>{e+=1},isCurrent:t=>t===e}},Oe=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(/\/+$/,"")},Je=e=>{try{return new URL(e).host}catch{return e}},He=e=>{try{return Oe(e)}catch{return e.trim().replace(/\/+$/g,"")}},Pt=(e,t)=>He(e)===He(t),At=e=>`relay:${e.serverId}@${e.relayUrl.trim()}`,ma=e=>`relay://${e.serverId}`,ft=e=>e.candidates.filter(t=>t.kind==="direct"),Me=e=>{const t=e.candidates.find(r=>r.kind==="relay");return t&&t.kind==="relay"?t.relay:null},xe=e=>{const t=ft(e)[0];if(t)return t.url;const r=Me(e);return r?ma(r):""},q=e=>{const t=Me(e);if(t)return At(t);const r=ft(e)[0];return r?He(r.url):""},ct=(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=>He(i.url)));return t.some(i=>i.kind==="relay"?s!==null&&i.relay.serverId===s:o.has(He(i.url)))},_t=e=>{const t=(()=>{try{return Oe(e)}catch{return""}})();return t?[{kind:"direct",url:t}]:[]},un=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(..._t(e.url)),e.relay&&t.push({kind:"relay",relay:e.relay}),t},Dt=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}}},ya=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=Dt(t.relay);return r?{kind:"relay",relay:r}:null}return null},ba=e=>{if(e.mode==="relay"){const t=Dt(e.relay);return t?[{kind:"relay",relay:t}]:[]}return typeof e.url=="string"?_t(e.url):[]},Ze=e=>e.kind==="relay"?{kind:"relay",relay:{relayUrl:e.relay.relayUrl,serverId:e.relay.serverId,hostEncPubJwk:e.relay.hostEncPubJwk}}:{kind:"direct",url:e.url},ze=()=>{if(typeof window>"u")return[];let e;try{e=JSON.parse(window.localStorage.getItem(ot)||"[]")}catch{return[]}if(!Array.isArray(e))return[];const t=ee();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(ya).filter(u=>!!u):ba(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:Je(xe({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)},Mt=e=>{if(typeof window>"u")return;const t=ee(),r=e.slice(0,On).map(s=>{const o={id:s.id,label:s.label,candidates:s.candidates.map(Ze),lastUsedAt:s.lastUsedAt};return t?{...o,hasToken:!!(s.hasToken||s.clientToken)}:{...o,clientToken:s.clientToken}});try{window.localStorage.setItem(ot,JSON.stringify(r))}catch(s){console.warn("[mobile-storage] failed to persist connection metadata",s)}},Un=(e,t)=>{const r=e.find(i=>t.id&&i.id===t.id||ct(i.candidates,t.candidates)),s=ee(),o={id:t.id||r?.id||it(),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&&!ct(i.candidates,t.candidates))].slice(0,On)},Lt=Hr,ga=0,Ot=e=>`${la}token.${encodeURIComponent(e)}`,xa=async(e,t)=>{let r;const s=new Promise(o=>{r=window.setTimeout(()=>o(t),da)});try{return await Promise.race([e.catch(()=>t),s])}finally{r!==void 0&&window.clearTimeout(r)}},zt=async(e,t,r)=>ee()?xa(t().catch(s=>(console.warn(`[mobile-storage] ${e} failed`,s),r)),r):r,et=async e=>{const t=await zt("secure:read",async()=>(await Lt.internalGetItem({prefixedKey:Ot(e),sync:!1})).data,null);return typeof t=="string"&&t.trim()?t:void 0},Pe=async(e,t)=>zt("secure:write",async()=>(await Lt.internalSetItem({prefixedKey:Ot(e),data:t,sync:!1,access:ga}),!0),!1),va=async e=>{await zt("secure:delete",async()=>(await Lt.internalRemoveItem({prefixedKey:Ot(e),sync:!1}),!0),!1)},Bn=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:d,...p}=l;return{...p,hasToken:!0}})),migrated:r,failed:s}},$n=async()=>{if(typeof window>"u"||!ee())return;let e;try{e=JSON.parse(window.localStorage.getItem(ot)||"[]")}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 Bn(e,async(s,o)=>{const i=He(s);return await Pe(i,o)?await et(i)===o:!1});if(r.migrated>0)try{window.localStorage.setItem(ot,JSON.stringify(r.records))}catch(s){console.warn("[mobile-storage] failed to finalize secure token migration",s)}},Kn=async()=>(await $n(),ze()),tt=async e=>{const t=Un(ze(),e);return Mt(t),ee()&&e.clientToken&&await Pe(q({candidates:e.candidates}),e.clientToken),t},Wn=async e=>{const t=ze(),r=t.find(o=>o.id===e)??null,s=t.filter(o=>o.id!==e);return Mt(s),r&&ee()&&await va(q(r)),s},Ut=e=>{try{return JSON.stringify(e)}catch{return String(e)}},Q=(e,t={})=>{console.info("[mobile-connect]",e,Ut(t)),ps("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})},wa=e=>{if(typeof e!="string")return e;try{return JSON.parse(e)}catch{return e}},ka=e=>{if(typeof e!="string")return e??void 0;try{return JSON.parse(e)}catch{return e}},Sa=async(e,t)=>{if(!ee())return null;try{const{CapacitorHttp:r}=await Ce(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:ka(t?.body)});return{ok:o.status>=200&&o.status<300,status:o.status,source:"native-http",json:async()=>wa(o.data)}}catch(r){return console.warn("[mobile-connect]","native-http failed",Ut({url:e,error:r instanceof Error?r.message:String(r)})),null}},ja=async(e,t)=>{const r=await fetch(e,t).catch(s=>(console.warn("[mobile-connect]","browser-fetch failed",Ut({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},Ee=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)}},Le=async(e,t,r)=>{const s=r?.totalTimeoutMs??ca,o=Date.now(),i=await Ee(Math.min(ua,s),Sa(e,t));if(i)return i;const l=new AbortController,c=Math.max(500,s-(Date.now()-o));return Ee(c,ja(e,{...t,signal:l.signal}),()=>l.abort())},pt=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}},Ca=async(e,t,r,s=We,o)=>{if(o?.shouldAbort?.())return{outcome:"unreachable"};const i=Tn({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 Ee(s,i.fetch("/auth/session",{headers:c}).catch(()=>null));if(Q("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 d=await pt(u);return d&&d.disabled!==!0&&d.authenticated===!1?l(t?"auth-failed":"needs-login"):l("ok")}catch(c){throw i.close(),c}},Ea=(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&&fs(l,o),Ne({apiBaseUrl:i,clientToken:t,runtimeKey:s??At(e),relay:l})},ut=async(e,t,r)=>{const s=r?.shouldAbort,o=r?.fast?{totalTimeoutMs:lt}:void 0,i=Me({candidates:e})?.serverId??null,l=e.find(p=>p.kind==="relay")??null,c=e.filter(p=>p.kind==="direct"),u=async()=>{for(const p of c){if(s?.())return{status:"unreachable"};const m=Oe(p.url)||p.url,S=t?{Authorization:`Bearer ${t}`}:void 0,k=await Le(`${m}/health`,{method:"GET"},o);if(s?.())return{status:"unreachable"};if(!k?.ok)continue;if(i){const I=await k.json().catch(()=>null),P=I&&typeof I=="object"?I.serverId:null;if(typeof P=="string"&&P&&P!==i){Q("probe:server-id-mismatch",{url:m});continue}}const w=await Le(`${m}/auth/session`,{method:"GET",credentials:t?"omit":"include",headers:S},o);if(s?.())return{status:"unreachable"};if(w?.status===401)return{status:"needs-login"};if(!w||!w.ok&&w.status!==404)continue;const E=await pt(w);if(E&&E.disabled!==!0&&E.authenticated===!1)return{status:"needs-login"};const _=E?.disabled===!0;return!t&&ee()&&!_&&E?.scope!=="client"?{status:"needs-login"}:{status:"ok",transport:{kind:"direct",url:m}}}return{status:"unreachable"}},d=async()=>{if(!l)return{status:"unreachable"};if(s?.())return{status:"unreachable"};const{outcome:p,tunnel:m}=await Ca(l.relay,t,void 0,r?.fast?lt:void 0,{keepTunnel:!0,...s?{shouldAbort:s}:{}});return s?.()?(m?.close(),{status:"unreachable"}):p==="ok"?{status:"ok",transport:{kind:"relay",relay:l.relay,tunnel:m}}:p==="needs-login"||p==="auth-failed"?{status:"needs-login"}:{status:"unreachable"}};return l?c.length===0?d():new Promise(p=>{let m=!1,S=!1,k,w=null,E=null;const _=h=>{h?.status==="ok"&&h.transport.kind==="relay"&&h.transport.tunnel?.close()},I=h=>{m||(m=!0,p(h))},P=()=>{S||m||s?.()||(k!==void 0&&(window.clearTimeout(k),k=void 0),d().then(h=>{if(E=h,m||S){_(h);return}if(h.status==="ok"||h.status==="needs-login"){I(h);return}w&&I(w)}))};u().then(h=>{if(w=h,!m){if(h.status==="ok"||h.status==="needs-login"){S=!0,k!==void 0&&window.clearTimeout(k),_(E),I(h);return}if(E){I(E);return}P()}}),k=window.setTimeout(P,fa)}):u()},_e=(e,t,r)=>{e.kind==="relay"?Ea(e.relay,t,r?.grant,r?.runtimeKey,e.tunnel):Ne({apiBaseUrl:e.url,clientToken:t,runtimeKey:r?.runtimeKey}),Xn()},Ae=()=>{const e=ze()[0];return e?.label?.trim()?e.label:null},at=async()=>{const e=Ye(),t=`${fe()}|${ae()}`,r=()=>Ye()!==e||`${fe()}|${ae()}`!==t;if(await $n(),r())return{status:"no-candidate"};const s=ze()[0];if(!s)return{status:"no-candidate"};let o;if(ee()){if(!s.hasToken)return{status:"no-candidate"};if(o=await et(q(s)),!o)return{status:"no-candidate"}}else if(o=s.clientToken,!o)return{status:"no-candidate"};const i=await ut(s.candidates,o,{fast:!0});return r()?(Tt(i),{status:"no-candidate"}):i.status==="needs-login"?{status:"needs-login",label:s.label}:i.status!=="ok"?{status:"unreachable",label:s.label}:(await tt({id:s.id,label:s.label,candidates:s.candidates}),r()?(dt(i.transport),{status:"no-candidate"}):(_e(i.transport,o,{runtimeKey:q(s)}),{status:"connected"}))},Hn=async(e,t)=>{let r="";try{r=Oe(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:lt}:void 0;if(!(await Le(`${r}/health`,{method:"GET",headers:o},i))?.ok)return!1;const c=await Le(`${r}/auth/session`,{method:"GET",credentials:s?"omit":"include",headers:o},i);if(!c||!c.ok&&c.status!==404)return!1;const u=await pt(c);return!(u&&u.disabled!==!0&&u.authenticated===!1)},dn=async e=>{const t=Me({candidates:e})?.serverId??null;for(const r of e){if(r.kind==="relay"){const i=Tn(r.relay),l=await Ee(We,i.fetch("/health").catch(()=>null));if(Q("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=Oe(r.url)||r.url,o=await Le(`${s}/health`,{method:"GET"});if(Q("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){Q("establish:server-id-mismatch",{url:s});continue}}return{kind:"direct",url:s}}}return null},Ra=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=Dt({relayUrl:t.relayUrl,serverId:t.serverId,hostEncPubJwk:t.hostEncPubJwk});return r?[{kind:"relay",relay:r}]:[]}return _t(t.url)}),Fn=async(e,t)=>{if(!Qe())return Hn(e,t);const r=await Ee(t?.fast?lt:We,Nn("/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 pt(r);return!(s&&s.disabled!==!0&&s.authenticated===!1)},Ta=e=>e.kind==="relay"?Qe():!Qe()&&Pt(e.url,ae()),ht=()=>{const e=fe();return e?ze().find(t=>q(t)===e)??null:null},Rt=e=>{const t=fe();return!!t&&q(e)===t},Bt=e=>({generation:Ye(),runtimeKey:fe(),apiBaseUrl:ae(),connectionId:e.id,secureKey:q(e),candidatesJson:JSON.stringify(e.candidates.map(Ze))}),Vn=e=>{if(Ye()!==e.generation||fe()!==e.runtimeKey||ae()!==e.apiBaseUrl)return!0;const t=ht();if(!t||t.id!==e.connectionId||q(t)!==e.secureKey)return!0;try{if(JSON.stringify(t.candidates.map(Ze))!==e.candidatesJson)return!0}catch{return!0}return!1},dt=e=>{try{e?.kind==="relay"&&e.tunnel?.close()}catch{}},Tt=e=>{e.status==="ok"&&dt(e.transport)},Na=e=>e?`${e.generation}|${e.runtimeKey}|${e.apiBaseUrl}|${e.connectionId}|${e.secureKey}|${e.candidatesJson}`:`noselection|${Ye()}|${fe()}`;let De=null,Nt="";const fn=(e,t)=>{const r=t.finally(()=>{De===r&&(De=null,Nt="")});return De=r,Nt=e,r},$t=()=>{const e=ht(),t=e?Bt(e):null,r=Na(t);if(De&&Nt===r)return De;if(De){const o=De.then(()=>vt(),()=>vt());return fn(r,o)}return fn(r,vt())},vt=async()=>{const e=ht();if(!e)return"no-connection";const t=Bt(e),r=()=>Vn(t);let s;if(ee()){if(s=e.hasToken?await et(q(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(d=>Ta(d.kind==="relay"?{kind:"relay",relay:d.relay}:{kind:"direct",url:d.url})),i=o>=0?e.candidates.slice(0,o):e.candidates,l=await ut(i,s,{fast:!0,shouldAbort:r});if(r())return Tt(l),"no-connection";if(l.status==="ok")return await tt({id:e.id,label:e.label,candidates:e.candidates}),r()?(dt(l.transport),"no-connection"):(_e(l.transport,s,{runtimeKey:q(e)}),"switched");if(l.status==="needs-login")return"needs-login";if(o>=0){if(r())return"no-connection";const d=await Fn({url:t.apiBaseUrl,clientToken:s},{fast:!0});if(r())return"no-connection";if(d)return Xn(),"unchanged"}const c=o>=0?e.candidates.slice(o+1):[];if(c.length===0)return"unreachable";const u=await ut(c,s,{fast:!0,shouldAbort:r});return r()?(Tt(u),"no-connection"):u.status==="ok"?(await tt({id:e.id,label:e.label,candidates:e.candidates}),r()?(dt(u.transport),"no-connection"):(_e(u.transport,s,{runtimeKey:q(e)}),"switched")):u.status==="needs-login"?"needs-login":"unreachable"};let wt=!1;const Gn=async()=>{if(wt)return"skipped";const e=ht();if(!e)return Q("candidates:refresh-skip",{reason:"no-active-connection"}),"skipped";const t=Me(e);if(!t)return Q("candidates:refresh-skip",{reason:"no-relay-candidate"}),"skipped";const r=Bt(e),s=()=>Vn(r);wt=!0;try{const o=await Ee(We,Nn("/api/client-auth/connection/candidates").then(m=>m).catch(()=>null));if(!o?.ok)return Q("candidates:refresh-skip",{reason:"fetch-failed",status:o?.status??null}),"skipped";if(s())return Q("candidates:refresh-skip",{reason:"selection-changed"}),"skipped";const i=await o.json().catch(()=>null);if(!i||i.serverId!==t.serverId)return Q("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 S=m;if(!(S.type!=="lan"||typeof S.url!="string"))try{const k=Oe(S.url);k&&!c.includes(k)&&c.push(k)}catch{}}if(c.length===0)return Q("candidates:refresh-skip",{reason:"no-lan-reported"}),"skipped";const u=ft(e).filter(m=>m.url.startsWith("https://")),d=[...c.map(m=>({kind:"direct",url:m})),...u,{kind:"relay",relay:t}];return JSON.stringify(e.candidates.map(Ze))===JSON.stringify(d.map(Ze))?"unchanged":s()?(Q("candidates:refresh-skip",{reason:"selection-changed"}),"skipped"):(Q("candidates:refreshed",{lanCount:c.length}),await tt({id:e.id,label:e.label,candidates:d}),"updated")}finally{wt=!1}},Xn=()=>{typeof window>"u"||window.setTimeout(()=>{(async()=>{const e=await Gn().catch(()=>"skipped");Q("candidates:refresh-result",{result:e}),e==="updated"&&Qe()&&await $t().catch(()=>null)})()},pa)},Kt=e=>{const[t,r]=a.useState(()=>ze()),[s,o]=a.useState(null),[i,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(t),p=a.useRef(null),m=a.useRef(zn()),S=a.useCallback(x=>{d.current=x,r(x)},[]),k=a.useCallback(x=>{p.current=x,o(x)},[]),w=a.useCallback(x=>{p.current===x&&(p.current=null,o(null))},[]);a.useEffect(()=>{let x=!1;return Kn().then(j=>{x||S(j)}),()=>{x=!0}},[S]);const E=a.useCallback(x=>{const j=Un(d.current,x);return S(j),Mt(j),j},[S]),_=a.useCallback(async x=>{l(null),k("connect");try{const j=un(x);if(j.length===0){l("Enter a server URL.");return}const C=x.id?d.current.find(M=>M.id===x.id):d.current.find(M=>ct(M.candidates,j)),L=x.label?.trim()||C?.label||Je(xe({candidates:j})),z=x.relayGrant;let A=x.clientToken?.trim()||void 0;const f=!!A;A||(ee()?C?.hasToken&&(A=await et(q({candidates:j}))):A=C?.clientToken),Q("connect:start",{candidates:j.map(M=>M.kind),hasToken:!!A});const D=await ut(j,A);if(Q("connect:probe",{status:D.status}),D.status==="unreachable"){l("Could not reach that PiChamber server.");return}if(D.status==="needs-login"){E({id:C?.id,label:L,candidates:j}),u({id:C?.id??it(),label:L,candidates:j,relay:Me({candidates:j})??void 0,relayGrant:z});return}A&&f&&ee()&&await Pe(q({candidates:j}),A),E({id:C?.id,label:L,candidates:j,clientToken:A}),_e(D.transport,A??null,{runtimeKey:q({candidates:j}),grant:z}),e()}catch(j){console.warn("[mobile-connect] connect threw",j),l("That server URL is not valid.")}finally{w("connect")}},[k,w,e,E]),I=a.useCallback(async x=>{if(p.current==="pairing")return;l(null),k("pairing");const j=Ra(x.candidates);let C=null,L=!1;try{if(C=await dn(j),!C){l("Could not reach that PiChamber server.");return}const z=JSON.stringify({pairingId:x.pairingId,secret:x.secret,clientLabel:"PiChamber Mobile",clientKind:"mobile",deviceName:"PiChamber Mobile",devicePlatform:cn(),dedupeKey:ln()}),A={method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:z},f=C.kind==="relay"?await Ee(We,C.tunnel.fetch("/api/client-auth/pairing/redeem",A).catch(()=>null)):await Le(`${C.url}/api/client-auth/pairing/redeem`,A);if(!f?.ok){l("This server needs a password or client token.");return}const D=await f.json().catch(()=>null),M=typeof D?.clientToken=="string"?D.clientToken.trim():"";if(!M){l("This server needs a password or client token.");return}const v=typeof D?.server?.label=="string"?D.server.label:"",N=x.label||v||Je(xe({candidates:j}));if(ee()&&!await Pe(q({candidates:j}),M)){l("This server needs a password or client token.");return}E({label:N,candidates:j,clientToken:M}),_e(C.kind==="relay"?{kind:"relay",relay:C.relay,tunnel:C.tunnel}:{kind:"direct",url:C.url},M,{runtimeKey:q({candidates:j})}),L=C.kind==="relay",e()}catch(z){console.warn("[mobile-connect] pairing threw",z),l("This server needs a password or client token.")}finally{!L&&C?.kind==="relay"&&C.tunnel.close(),w("pairing")}},[k,w,e,E]),P=a.useCallback(async x=>{if(!c||!x.trim()||p.current==="password")return;l(null),k("password");const j=m.current.begin(),C=()=>m.current.isCurrent(j),{id:L,label:z,candidates:A}=c;let f=null,D=!1;try{if(f=await dn(A),!C())return;if(!f){l("Could not reach that PiChamber server.");return}const M={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:cn(),dedupeKey:ln()})};Q("password:start",{transport:f.kind});const v=f.kind==="relay"?await Ee(We,f.tunnel.fetch("/auth/session",M).catch(()=>null)):await Le(`${f.url}/auth/session`,M);if(!C())return;if(Q("password:done",{ok:v?.ok===!0,status:v?.status??null}),!v?.ok){l("Could not unlock that server. Check the password.");return}const N=await v.json().catch(()=>null);if(!C())return;const J=typeof N?.clientToken=="string"?N.clientToken.trim():"";if(Q("password:token",{issued:!!J}),!J){if(f.kind==="direct"&&!ee()){E({id:L,label:z,candidates:A}),u(null),_e({kind:"direct",url:f.url},null,{runtimeKey:q({candidates:A})}),e();return}l("This server needs a password or client token.");return}if(ee()&&(!C()||(await Pe(q({candidates:A}),J),!C()))||!C()||(E({id:L,label:z,candidates:A,clientToken:J}),u(null),_e(f.kind==="relay"?{kind:"relay",relay:f.relay,tunnel:f.tunnel}:{kind:"direct",url:f.url},J,{runtimeKey:q({candidates:A})}),D=f.kind==="relay",!C()))return;e()}catch(M){if(!C())return;console.warn("[mobile-connect] password threw",M),l("Could not unlock that server. Check the password.")}finally{!D&&f?.kind==="relay"&&f.tunnel.close(),C()&&w("password")}},[k,w,e,c,E]),h=a.useCallback(()=>{m.current.cancel(),w("password"),u(null),l(null)},[w]),y=a.useCallback(async x=>{l(null);let j=un(x);const C=x.id?d.current.find(f=>f.id===x.id)??null:null;if(C){const f=j.filter(v=>v.kind==="direct"),D=ft(C).filter(v=>v.url.startsWith("https://")&&!f.some(N=>Pt(N.url,v.url))),M=Me(C);j=[...f,...D,...M?[{kind:"relay",relay:M}]:[]]}if(j.length===0)return l("Enter a server URL."),null;const L=x.clientToken?.trim()||void 0,z=x.label?.trim()||Je(xe({candidates:j}));if(ee()){const f=q({candidates:j});if(L)await Pe(f,L);else if(C?.hasToken){const D=q(C);if(D&&f&&D!==f){const M=await et(D);M&&await Pe(f,M)}}}return E({id:x.id,label:z,candidates:j,clientToken:L}).find(f=>ct(f.candidates,j))??null},[E]),U=a.useCallback(async x=>{const j=d.current.find(L=>L.id===x)??null,C=await Wn(x);return S(C),j},[S]);return{connections:t,isBusy:s!==null,isPasswordBusy:s==="password",error:i,pendingConnection:c,connect:_,redeemPairingConnection:I,submitPassword:P,cancelPassword:h,saveConnection:y,removeConnection:U,setError:l}},Pi=Object.freeze(Object.defineProperty({__proto__:null,autoConnectLastInstance:at,connectionDisplayUrl:xe,createMobilePasswordOperationTracker:zn,deleteMobileConnection:Wn,getAutoConnectTargetLabel:Ae,getConnectionLabel:Je,isActiveRuntimeConnection:Rt,isSameConnectionUrl:Pt,loadMobileConnections:Kn,migrateLegacyInlineTokenRecords:Bn,normalizeConnectionUrl:Oe,refreshActiveConnectionCandidates:Gn,relayConnectionRuntimeKey:At,reprobeActiveConnection:$t,upsertMobileConnection:tt,useMobileConnection:Kt,validateActiveRuntimeSession:Fn,validateMobileConnectionSession:Hn},Symbol.toStringTag,{value:"Module"})),qn=()=>{if(typeof window>"u")return null;const t=window.Capacitor?.Plugins?.BarcodeScanner;return t&&(typeof t.scan=="function"||typeof t.startScan=="function")?t:null},Ia=()=>window.Capacitor?.getPlatform?.()==="android",Jn=e=>{const t=e.trim();if(!t)return null;if(/^pichamber:\/\//i.test(t)){const r=hs(t);return r?{pairing:r}:null}return/^https?:\/\//i.test(t)?{url:t}:null},Yn=(e,t)=>{const r=Jn(e);if(!r&&t?.pairingStringFallback){const s=ms(e);if(s)return{status:"pairing",pairing:s}}return r?"pairing"in r?{status:"pairing",...r}:{status:"ok",...r}:{status:"invalid"}},Pa=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(d=>{i=d}),c=d=>{o||(o=!0,i(d))},u=()=>c({status:"cancelled"});t?.addEventListener("abort",u,{once:!0});try{return(await Promise.allSettled([Promise.resolve(e.addListener("barcodesScanned",({barcodes:p})=>{const m=p?.[0],S=(m?.rawValue??m?.displayValue??"").trim();S&&c(Yn(S,{pairingStringFallback:!0}))})).then(p=>{r=p}),Promise.resolve(e.addListener("scanError",()=>c({status:"failed"}))).then(p=>{s=p})])).some(({status:p})=>p==="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()])}},It=()=>qn()!==null,Qn=async e=>{const t=qn();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(Ia())return Pa(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?Yn(o):{status:"cancelled"}}catch{return{status:"failed"}}},$e={autoComplete:"off",autoCorrect:"off",spellCheck:!1},Xe="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",Zn=({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]),Ke.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(le,{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)},es=()=>Ke.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(Se,{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),Aa=({onConnected:e,notice:t=null})=>{const r=Kt(e),{connections:s,isBusy:o,isPasswordBusy:i,error:l,pendingConnection:c}=r,[u,d]=a.useState(""),[p,m]=a.useState(""),[S,k]=a.useState(""),[w,E]=a.useState(!1),[_,I]=a.useState(!1),P=a.useRef(null),h=a.useMemo(()=>It(),[]),[y,U]=a.useState(()=>!It()),[x,j]=a.useState(null),[C,L]=a.useState(""),z=a.useCallback(v=>{v.preventDefault(),r.connect({url:u,clientToken:S,label:p})},[S,r,p,u]),A=a.useCallback(v=>{if(/^pichamber:\/\//i.test(v.trim())){const N=Jn(v);if(N){if("pairing"in N){r.redeemPairingConnection(N.pairing);return}d(N.url),N.label&&m(N.label),N.clientToken&&k(N.clientToken);return}}d(v)},[r]),f=a.useCallback(async()=>{if(P.current||o)return;r.setError(null),E(!0);const v=new AbortController;P.current=v;try{const N=await Qn({signal:v.signal});switch(P.current===v&&(P.current=null,E(!1)),N.status){case"ok":I(!0),d(N.url),N.label&&m(N.label),N.clientToken&&k(N.clientToken),await r.connect({url:N.url,clientToken:N.clientToken,label:N.label});break;case"pairing":I(!0),await r.redeemPairingConnection(N.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{I(!1),P.current===v&&(P.current=null,E(!1))}},[r,o]);a.useEffect(()=>()=>P.current?.abort(),[]);const D=a.useCallback(v=>{v.preventDefault(),r.submitPassword(C)},[r,C]),M=a.useCallback(()=>{L(""),r.cancelPassword()},[r]);return n.jsxs(n.Fragment,{children:[w?n.jsx(Zn,{onCancel:()=>P.current?.abort()}):null,_?n.jsx(es,{}):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(Se,{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:D,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(v=>v.kind==="direct")?xe(c):"via PiChamber Relay"})]})]}),n.jsx("input",{...$e,value:C,onChange:v=>L(v.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:Xe}),l?n.jsx("p",{className:"px-1 text-center typography-small text-[var(--status-error)]",children:l}):null,n.jsx(le,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",disabled:i||!C.trim(),children:i?"Connecting...":"Unlock and connect"}),n.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:M,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(le,{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&&!y?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(v=>{const N=x===v.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:()=>{j(v.id),r.connect({id:v.id,candidates:v.candidates,clientToken:v.clientToken,label:v.label}).finally(()=>j(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:v.label}),n.jsx("span",{className:K("block truncate typography-small",N?"text-foreground":"text-muted-foreground"),children:N?"Connecting...":v.candidates.some(J=>J.kind==="direct")?xe(v):"via PiChamber Relay"})]}),N?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"})]},v.id)})})]}):null,n.jsxs("div",{className:"flex w-full flex-col",children:[h?n.jsxs("button",{type:"button",onClick:()=>U(v=>!v),"aria-expanded":y,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",y&&"rotate-180")})]}):null,n.jsx("div",{className:"grid transition-[grid-template-rows] duration-200 ease-out",style:{gridTemplateRows:y?"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:z,children:[n.jsx("input",{...$e,value:u,onChange:v=>A(v.target.value),placeholder:"http://192.168.1.74:2606","aria-label":"Server URL",type:"url",inputMode:"url",autoCapitalize:"none",tabIndex:y?void 0:-1,className:K(Xe,"text-center")}),n.jsx("input",{value:p,onChange:v=>m(v.target.value),placeholder:"Optional display name","aria-label":"Name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,tabIndex:y?void 0:-1,className:K(Xe,"text-center")}),n.jsx("input",{...$e,value:S,onChange:v=>k(v.target.value),placeholder:"Paste access token","aria-label":"Client token",tabIndex:y?void 0:-1,autoCapitalize:"none",className:K(Xe,"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(le,{type:"submit",variant:h?"outline":"default",size:"lg",className:"h-12 w-full",disabled:o||w||!u.trim(),children:o?"Connecting...":"Connect"})]})})})]})]})]})})]})},_a=10,Da=(e,t)=>Mn(e,t),Ma=({session:e,meta:t,active:r,onSelect:s})=>{const o=ir(e.id),i=or(e.id),l=o?.type??"idle",c=l==="busy"||l==="retry",u=!c&&i>0&&!r,d=lr(e.id,c),p=c&&d,m=Gr(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:Da(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(Xr,{label:"Session complete"}):null,p?n.jsx(qr,{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]})},La=({open:e,onClose:t,anchorRef:r})=>{const{panelRef:s,wrapperRef:o,shouldRender:i,isExiting:l,anchorLeft:c,isPopover:u}=Rs({open:e,onClose:t,anchorRef:r}),d=me(w=>w.currentSessionId),p=me(w=>w.setCurrentSession),m=An(w=>w.setActiveProjectIdOnly),S=Jr(e||i,{maxParents:_a}),k=a.useCallback(w=>{p(w.id,_n(w)),t()},[t,p]);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(${Ts}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:S.length===0?n.jsx("p",{className:"px-3 py-6 text-center typography-small text-muted-foreground",children:"No recent sessions"}):S.map(w=>{const E=w.node.session,_=[w.secondaryMeta?.projectLabel,w.secondaryMeta?.branchLabel].filter(Boolean).join(" · ");return n.jsx(Ma,{session:E,meta:_,active:E.id===d,onSelect:()=>{w.projectId&&m(w.projectId),k(E)}},E.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},Oa=({onOpenSessions:e,onOpenWorkspace:t,compactTitle:r=!1})=>{const[s,o]=a.useState(!1),[i,l]=a.useState(!1),c=a.useRef(null),u=In(h=>h.currentDirectory),d=me(h=>h.currentSessionId),m=me(a.useCallback(h=>d?h.getDirectoryForSession(d):null,[d]))||u,S=cr(d),k=me(h=>!!h.newSessionDraft?.open),E=S?.title?.trim()||(d?Mn(S,"Untitled session"):"New session");a.useEffect(()=>{o(!1),l(!1)},[d,m]);const _=a.useCallback(()=>{o(!1),l(!1),e()},[e]),I=a.useCallback(h=>{o(y=>{const U=typeof h=="function"?h(y):h;return U&&l(!1),U})},[]),P=a.useCallback(()=>{l(h=>{const y=!h;return y&&o(!1),y})},[]);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:_,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:P,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:E}),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(Ns,{open:s,onOpenChange:I,currentSessionId:d,effectiveDirectory:m,isNewSessionDraftOpen:k}),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(La,{open:i,onClose:()=>l(!1),anchorRef:c})]})},za=({onActiveConnectionDeleted:e,onConnect:t})=>{const r=Kt(t),{connections:s,isBusy:o,isPasswordBusy:i,error:l,pendingConnection:c,connect:u,submitPassword:d,cancelPassword:p,saveConnection:m,removeConnection:S,setError:k}=r,[w,E]=a.useState(null),_=w?s.find(T=>T.id===w)??null:null,[I,P]=a.useState(null),[h,y]=a.useState(""),[U,x]=a.useState(""),[j,C]=a.useState(""),[L,z]=a.useState(""),[A,f]=a.useState(!1),[D,M]=a.useState(!1),[v,N]=a.useState(!1),[J,X]=a.useState(null),V=a.useRef(null),ne=a.useMemo(()=>It(),[]),[R,W]=a.useState(!1),[te,Te]=a.useState(null),ye=a.useCallback(()=>{E(null),y(""),x(""),C(""),k(null),W(!1)},[k]),pe=a.useCallback(T=>{T.preventDefault(),m({id:w??void 0,url:h,label:U,clientToken:j}).then($=>{$&&ye()})},[j,w,U,ye,m,h]),ce=a.useCallback(async()=>{if(V.current)return;k(null),f(!0);const T=new AbortController;V.current=T;try{const $=await Qn({signal:T.signal});switch(V.current===T&&(V.current=null,f(!1)),$.status){case"ok":y($.url),$.label&&x($.label),$.clientToken&&C($.clientToken),W(!0);break;case"pairing":M(!0),await r.redeemPairingConnection($.pairing);break;case"permission-denied":k("Camera access is off. Enable it in Settings to scan a QR code.");break;case"invalid":k("That QR code is not an PiChamber connection code.");break;case"unsupported":k("QR scanning is only available in the installed mobile app.");break;case"failed":k("Could not scan that QR code. Try again or enter the URL manually.");break;default:break}}finally{M(!1),V.current===T&&(V.current=null,f(!1))}},[r,k]);a.useEffect(()=>()=>V.current?.abort(),[]);const b=a.useCallback(T=>{T.preventDefault(),d(L)},[L,d]),B=a.useCallback(()=>{z(""),p()},[p]),G=a.useCallback(async()=>{if(!v){X(null),N(!0);try{const T=await ys();X(T==="copied"?"Diagnostics copied to the clipboard.":T==="downloaded"?"Diagnostics downloaded.":"Diagnostics ready to share.")}catch{X("Diagnostics export was cancelled or unavailable.")}finally{N(!1)}}},[v]),O=a.useCallback(T=>{P($=>$===T?null:T)},[]),H=a.useCallback(T=>{P(null),w===T&&ye();const $=s.length===1;S(T).then(Y=>{Y&&($||Rt(Y))&&e()})},[s.length,w,e,S,ye]),se=Xe;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:b,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(T=>T.kind==="direct")?xe(c):"via PiChamber Relay"})]})]}),n.jsx("input",{...$e,value:L,onChange:T=>z(T.target.value),placeholder:"PiChamber password","aria-label":"Password",type:"password",autoFocus:!0,className:se}),l?n.jsx("p",{className:"px-1 typography-small text-[var(--status-error)]",children:l}):null,n.jsx(le,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",disabled:i||!L.trim(),children:i?"Connecting...":"Unlock and connect"}),n.jsx(le,{type:"button",variant:"ghost",size:"sm",className:"w-full",onClick:B,children:"Use another server"})]})})}):n.jsxs(n.Fragment,{children:[A?n.jsx(Zn,{onCancel:()=>V.current?.abort()}):null,D?n.jsx(es,{}):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(T=>{const $=I===T.id,Y=Rt(T),Z=te===T.id,be=Z?"Connecting...":Y?Qe()?"Connected · Private relay":"Connected · Local network":T.candidates.some(he=>he.kind==="direct")?xe(T):"via PiChamber Relay";return n.jsxs("div",{className:K("flex items-center border-b border-border/70 transition-colors last:border-b-0",$&&"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||(Te(T.id),u({id:T.id,candidates:T.candidates,clientToken:T.clientToken,label:T.label}).finally(()=>Te(null)))},disabled:o&&!Z||$,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:T.label}),n.jsx("span",{className:K("block truncate typography-small",Y&&!Z?"text-[var(--status-success)]":"text-muted-foreground"),children:be})]}),Z?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:[$?n.jsxs("button",{type:"button","aria-label":`Confirm deleting ${T.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:()=>H(T.id),style:{touchAction:"manipulation"},children:[n.jsx(F,{name:"delete-bin",className:"size-[18px]"}),n.jsx("span",{className:"typography-ui-label",children:"Delete"})]}):T.candidates.some(he=>he.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:()=>{E(T.id),y(xe(T)),x(T.label),C(T.clientToken||""),k(null)},style:{touchAction:"manipulation"},children:n.jsx(F,{name:"edit",className:"size-[18px]"})}):null,n.jsx("button",{type:"button","aria-label":$?`Keep ${T.label}`:`Delete ${T.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:()=>O(T.id),style:{touchAction:"manipulation"},children:n.jsx(F,{name:$?"close":"delete-bin",className:"size-[18px]"})})]})]},T.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(le,{type:"button",variant:"outline",size:"lg",className:"h-12 w-full",onClick:()=>{G()},disabled:v,children:[n.jsx(F,{name:"download",className:"size-[18px]"}),v?"Preparing diagnostics…":"Export diagnostics"]}),J?n.jsx("p",{className:"px-1 text-center typography-small text-muted-foreground",children:J}):null]}),!R&&!_?n.jsxs("div",{className:"space-y-2",children:[ne?n.jsxs(le,{type:"button",size:"lg",className:"h-12 w-full",onClick:()=>{ce()},disabled:A,children:[n.jsx(F,{name:"scan-2",className:K("size-[18px]",A&&"animate-pulse")}),"Scan QR code"]}):null,n.jsxs(le,{type:"button",variant:ne?"ghost":"outline",size:"lg",className:"h-12 w-full",onClick:()=>{k(null),W(!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:pe,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:_?"Edit instance":"Add instance"}),n.jsx(le,{type:"button",variant:"ghost",size:"xs",onClick:ye,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",{...$e,value:h,onChange:T=>y(T.target.value),placeholder:"http://192.168.1.74:2606",type:"url",inputMode:"url",autoCapitalize:"none",className:se})]}),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:T=>x(T.target.value),placeholder:"Optional display name",autoComplete:"off",autoCapitalize:"words",autoCorrect:"off",spellCheck:!1,className:se})]}),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",{...$e,value:j,onChange:T=>C(T.target.value),placeholder:"Paste access token",autoCapitalize:"none",className:se}),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(le,{type:"submit",size:"lg",className:"mt-1 h-12 w-full",children:_?"Save changes":"Save instance"})]})]})})})]})},Fe=320,Re="cubic-bezier(0.22, 1, 0.36, 1)",ts=({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,d=o.current;if(!u||!d)return;let p=!1,m=!1,S=!1,k=0,w=0,E=0,_=0;const I=c?0:Fe,P=e==="left"?"translateX(-100%)":"translateX(100%)",h=()=>({drawer:I?`transform ${I}ms ${Re}`:"none",scrim:I?`opacity ${I}ms ${Re}`:"none"}),y=()=>{const f=h();u.style.transition=f.drawer,d.style.transition=f.scrim,u.style.transform="none",d.style.opacity="1",d.style.pointerEvents="auto"},U=()=>{p=!1,m=!1,S=!1},x=()=>{if(!(p||m)){U();return}y(),U()},j=f=>{if(f.touches.length!==1){(p||m)&&x();return}if(Is(f.target,u,{excludeInteractive:!1}))return;u.style.transition&&u.style.transition!=="none"&&(u.style.transition="none",d.style.transition="none");const D=f.touches[0];k=D.clientX,w=D.clientY,E=Date.now(),_=u.offsetWidth||window.innerWidth*l,_<10&&(_=window.innerWidth*l),p=!0,m=!1,S=!1},C=f=>{if(!p)return;if(f.touches.length!==1){x();return}const D=f.touches[0],M=D.clientX-k,v=D.clientY-w;if(!S){if(Math.abs(M)<Jt&&Math.abs(v)<Jt)return;if(Math.abs(v)>Math.abs(M)*Yt||!Qt(e,M)){p=!1;return}S=!0,m=!0,u.style.transition="none",d.style.transition="none"}if(!m)return;f.cancelable&&f.preventDefault();const N=Zt(e,M,_);u.style.transform=Ps(e,N),d.style.opacity=String(N)},L=(f,D,M)=>{if(!p)return;const v=f-k,N=D-w,J=Math.max(1,Date.now()-E),X=Zt(e,v,_),V=_s({side:e,dx:v,dy:N,dt:J,progress:X,isDragging:m}),ne=h();u.style.transition=ne.drawer,d.style.transition=ne.scrim,u.style.transform=V?P:"none",d.style.opacity=V?"0":"1",d.style.pointerEvents=V?"none":"auto",U(),V&&i()},z=f=>{const D=f.changedTouches[0];if(!D){x();return}const M=D.clientX-k,v=D.clientY-w,N=Math.abs(M)>=As&&Math.abs(v)<=Math.abs(M)*Yt&&Qt(e,M);p&&(m||N)&&f.cancelable&&f.preventDefault(),L(D.clientX,D.clientY)},A=()=>{x()};return u.addEventListener("touchstart",j,{passive:!0}),u.addEventListener("touchmove",C,{passive:!1}),u.addEventListener("touchend",z,{passive:!1}),u.addEventListener("touchcancel",A,{passive:!0}),()=>{try{x()}catch{}u.removeEventListener("touchstart",j),u.removeEventListener("touchmove",C),u.removeEventListener("touchend",z),u.removeEventListener("touchcancel",A)}},[s,t,i,r,c,o,e,l])},Ua=16,pn=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 y=typeof document<"u"?document.activeElement:null;y instanceof HTMLElement&&c.current?.contains(y)&&y.blur(),r(!1)},[r]),[d,p]=a.useState(!1),m=a.useRef(null),S=a.useRef(null),k=o??m,w=i??S,E=a.useCallback(y=>{c.current=y,l&&(l.current=y)},[l]),_=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]);a.useEffect(()=>{const y=c.current;if(!y||t)return;const U=document.activeElement;U&&y.contains(U)&&U.blur()},[t]),a.useEffect(()=>{if(s!=="sidebar"){if(t){const y=window.setTimeout(()=>p(!0),_?0:Ua);return()=>window.clearTimeout(y)}p(!1)}},[t,_,s]),a.useEffect(()=>{if(s==="sidebar"||!t)return;const y=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=y,document.removeEventListener("keydown",U)}},[u,t,s]);const I=s==="sidebar",P=n.jsx(Ds,{mobileVariant:!I,isVisible:t,allowReselect:!0,onSessionSelected:I?void 0:u,onNavigateAway:I?void 0:u});if(ts({side:"left",enabled:s==="drawer",open:t,drawerRef:k,scrimRef:w,onClose:u,widthRatio:.72,prefersReducedMotion:_}),s==="sidebar")return n.jsx("aside",{className:"relative flex h-full w-full flex-col bg-sidebar",children:P});if(typeof document>"u")return null;const h=_?0:Fe;return Ke.createPortal(n.jsxs("div",{ref:E,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:d?1:0,transition:`opacity ${h}ms ${Re}`},"data-mobile-sessions-scrim":"true"}),n.jsx("div",{ref:k,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:d?"none":"translateX(-100%)",transition:h?`transform ${h}ms ${Re}`:"none",touchAction:"pan-x pan-y"},"data-mobile-sessions-drawer":"true",children:P})]}),document.body)}),hn="mobile-surface-root",kt=16,rt=200,Ba=()=>{if(typeof document>"u")return null;let e=document.getElementById(hn);return e||(e=document.createElement("div"),e.id=hn,document.body.appendChild(e)),e},St=({open:e,onClose:t,title:r,subtitle:s,trailing:o,disableEscapeDismiss:i=!1,headerless:l=!1,noHeaderBorder:c=!1,ariaLabel:u,variant:d="fullscreen",dialogAlign:p="chat",children:m})=>{const S=a.useRef(null),[k,w]=a.useState(!1),[E,_]=a.useState(!1),I=a.useRef(null),P=a.useRef(null),h=a.useRef(t);if(a.useEffect(()=>{h.current=t},[t]),typeof document<"u"&&!S.current&&(S.current=Ba()),a.useEffect(()=>{if(!e){w(!1);return}const x=window.setTimeout(()=>w(!0),kt);return()=>window.clearTimeout(x)},[e]),a.useEffect(()=>{if(!e){_(!1);return}const x=window.setTimeout(()=>_(!0),kt+rt+80);return()=>window.clearTimeout(x)},[e]),a.useEffect(()=>{if(!e)return;const x=document.body.style.overflow;P.current=document.activeElement instanceof HTMLElement?document.activeElement:null,document.body.style.overflow="hidden";const j=()=>{const z=I.current;if(!z)return;(z.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')??z).focus({preventScroll:!0})},C=window.setTimeout(j,kt),L=z=>{if(z.key==="Escape"&&!i){h.current();return}if(z.key!=="Tab")return;const A=I.current;if(!A)return;const f=Array.from(A.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])')).filter(N=>!N.hasAttribute("disabled")&&N.getAttribute("aria-hidden")!=="true");if(f.length===0){z.preventDefault(),A.focus({preventScroll:!0});return}const D=f[0],M=f[f.length-1],v=document.activeElement;z.shiftKey&&v===D?(z.preventDefault(),M.focus({preventScroll:!0})):!z.shiftKey&&v===M&&(z.preventDefault(),D.focus({preventScroll:!0}))};return document.addEventListener("keydown",L),()=>{window.clearTimeout(C),document.body.style.overflow=x,document.removeEventListener("keydown",L),P.current?.focus?.({preventScroll:!0}),P.current=null}},[i,e]),!e||!S.current)return null;const y=d==="dialog",U=n.jsxs("section",{ref:I,role:"dialog","aria-modal":"true","aria-label":u,tabIndex:-1,className:K("flex flex-col bg-background text-foreground",y?"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:y?{opacity:k?1:0,transform:k?"none":"scale(0.97)",transition:`opacity ${rt}ms ease-out, transform ${rt}ms cubic-bezier(0.32, 0.72, 0, 1)`}:{paddingTop:"var(--oc-safe-area-top, 0px)",transform:k?"none":"translateX(100%)",transition:`transform ${rt}ms cubic-bezier(0.32, 0.72, 0, 1)`},onTransitionEnd:x=>{k&&x.target===x.currentTarget&&x.propertyName==="transform"&&_(!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:E?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 y?Ke.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:k?1:0,paddingLeft:p==="chat"?"max(1rem, var(--oc-chat-inset-left, 0px))":"1rem",paddingRight:p==="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})}),S.current):Ke.createPortal(U,S.current)},$a=a.lazy(()=>Ce(()=>import("./FilesView-CEeQzjc6.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])).then(e=>({default:e.FilesView}))),Ka=a.lazy(()=>Ce(()=>import("./GitView-DV3d0oSJ.js"),__vite__mapDeps([70,10,1,2,3,9,4,5,6,7,8,11,48,49,50,51,52,71,72,73,74,75,76,55,56,57,32,33,34,35,36,37,38,39,40,41,42,43,44,45,58,30,31,59,60,61,62,63,64,65,77,78,79,28,29])).then(e=>({default:e.GitView}))),Wa=a.lazy(()=>Ce(()=>import("./PullRequestsSurface-Dec20SIg.js"),__vite__mapDeps([80,10,1,2,3,81,4,5,6,7,8,9,11,48,49,50,51,52,82,72,73,76,55,56,57,32,33,34,35,36,37,38,39,40,41,42,43,44,45,58,30,31,59,60,61,62,63,64,65,77,78,79,28,29])).then(e=>({default:e.PullRequestsSurface}))),Ha=a.lazy(()=>Ce(()=>import("./IssuesSurface-OTyt9f3A.js"),__vite__mapDeps([83,1,2,3,81,4,5,6,7,8,9,10,11,48,49,50,51,52,82,72,73,84])).then(e=>({default:e.IssuesSurface}))),mn="mobile-surface-root",Fa=16,yn=a.memo(function({open:t,onClose:r,tab:s,onTabChange:o,pendingChangesDiff:i,variant:l="drawer",drawerRefExternal:c,scrimRefExternal:u,rootRefExternal:d,githubTabsAvailable:p=!1}){const m=a.useRef(null),S=a.useRef(null),k=a.useRef(null),w=a.useRef(null),E=c??S,_=u??k,I=d??w,P=a.useCallback(R=>{w.current=R,d&&(d.current=R)},[d]),h=a.useCallback(()=>{const R=typeof document<"u"?document.activeElement:null;R instanceof HTMLElement&&I.current?.contains(R)&&R.blur(),r()},[r]),[y,U]=a.useState(!1),[x,j]=a.useState(t),C=`mobile-workspace-tab-${a.useId()}`,L=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[z,A]=a.useState(()=>new Set),[f,D]=a.useState(null),[M,v]=a.useState(null);if(a.useEffect(()=>{t&&A(R=>{if(R.has(s))return R;const W=new Set(R);return W.add(s),W})},[t,s]),typeof document<"u"&&!m.current){let R=document.getElementById(mn);R||(R=document.createElement("div"),R.id=mn,document.body.appendChild(R)),m.current=R}if(a.useEffect(()=>{if(t){j(!0);const W=window.setTimeout(()=>U(!0),L?0:Fa);return()=>window.clearTimeout(W)}U(!1);const R=window.setTimeout(()=>j(!1),Fe+40);return()=>window.clearTimeout(R)},[t,L]),a.useEffect(()=>{if(!t)return;const R=document.body.style.overflow;l==="drawer"&&(document.body.style.overflow="hidden");const W=te=>{te.key==="Escape"&&s!=="terminal"&&h()};return document.addEventListener("keydown",W),()=>{l==="drawer"&&(document.body.style.overflow=R),document.removeEventListener("keydown",W)}},[h,t,s,l]),a.useEffect(()=>{const R=I.current;if(!R||t||l!=="drawer")return;const W=document.activeElement;W&&R.contains(W)&&W.blur()},[t,l]),ts({side:"right",enabled:l==="drawer",open:t,drawerRef:E,scrimRef:_,onClose:h,widthRatio:1,prefersReducedMotion:L}),l==="drawer"&&!m.current)return null;const N=L?0:Fe,J=Ms(p),X=L?{duration:0}:{type:"spring",stiffness:520,damping:40,mass:.8},V=n.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-0.5 py-1 overflow-x-auto overflow-y-hidden scrollbar-none",role:"tablist","aria-label":"Workspace","data-no-drawer-swipe":"true",children:J.map(R=>{const W=s===R.id;return n.jsxs(bt.button,{layout:"position",transition:X,type:"button",role:"tab","aria-selected":W,"aria-label":R.label,onClick:()=>o(R.id),className:K("relative flex min-h-[44px] items-center justify-center gap-1 rounded-lg py-2 typography-ui-label transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",W?"min-w-0 shrink px-2.5 text-foreground":"size-11 shrink-0 text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[W?n.jsx(bt.span,{layoutId:C,transition:X,className:"absolute inset-0 bg-interactive-selection",style:{borderRadius:8},"aria-hidden":"true"}):null,n.jsx(F,{name:R.icon,className:"relative size-5 shrink-0"}),W?n.jsx(bt.span,{initial:L?!1:{opacity:0,x:-4},animate:{opacity:1,x:0},transition:X,className:"relative truncate",children:R.label},R.id):null]},R.id)})}),ne=n.jsxs(n.Fragment,{children:[l==="panel"?null:n.jsxs("div",{className:"flex h-[var(--oc-header-height,56px)] shrink-0 items-center gap-1 px-2",children:[V,n.jsx("button",{type:"button",onClick:h,"aria-label":"Close workspace panel",className:"flex size-11 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:[z.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(Ka,{isActive:t&&s==="changes",chrome:"mobile",initialDiffPath:i?.path??null,initialDiffStaged:i?.staged===!0})})})},i?`changes:${i.path}:${i.staged}`:"changes"):null,z.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($a,{chrome:"mobile",mode:"editor-only",isVisible:t&&s==="files"})})})}):null,z.has("terminal")?n.jsx("div",{className:K("h-full",s!=="terminal"&&"hidden"),children:n.jsx(de,{children:n.jsx(Ls,{visible:t&&s==="terminal"})})}):null,z.has("pull-requests")?n.jsx("div",{className:K("h-full",s!=="pull-requests"&&"hidden"),children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[n.jsx(en,{icon:st.find(R=>R.id==="pull-requests")?.icon,title:st.find(R=>R.id==="pull-requests")?.label??"Pull requests",actions:n.jsx("div",{ref:R=>{D(R)},className:"flex items-center gap-1"})}),n.jsx("div",{className:"min-h-0 flex-1",children:n.jsx(de,{children:n.jsx(a.Suspense,{fallback:null,children:n.jsx(Wa,{hideFilesTab:!0,headerActionsSlot:t&&s==="pull-requests"?f:null,headerActionsPresentation:"drawer"})})})})]})}):null,z.has("issues")?n.jsx("div",{className:K("h-full",s!=="issues"&&"hidden"),children:n.jsxs("div",{className:"flex h-full min-h-0 flex-col bg-background",children:[n.jsx(en,{icon:st.find(R=>R.id==="issues")?.icon,title:st.find(R=>R.id==="issues")?.label??"Issues",actions:n.jsx("div",{ref:R=>{v(R)},className:"flex items-center gap-1"})}),n.jsx("div",{className:"min-h-0 flex-1",children:n.jsx(de,{children:n.jsx(a.Suspense,{fallback:null,children:n.jsx(Ha,{headerActionsSlot:t&&s==="issues"?M:null,headerActionsPresentation:"drawer"})})})})]})}):null]})]});return l==="panel"?n.jsx("div",{className:"flex h-full min-h-0 flex-col bg-sidebar",children:ne}):Ke.createPortal(n.jsxs("div",{ref:P,className:"fixed inset-0 z-50",inert:!t,style:{pointerEvents:t?"auto":"none",visibility:x?"visible":"hidden"},"data-mobile-workspace-root":"true",children:[n.jsx("button",{ref:_,type:"button",className:"absolute inset-0 cursor-default bg-black/70","aria-label":"Close workspace panel",onClick:h,tabIndex:t?0:-1,style:{opacity:y?1:0,transition:N?`opacity ${N}ms ${Re}`:"none"},"data-mobile-workspace-scrim":"true"}),n.jsx("section",{ref:E,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:y?"none":"translateX(100%)",transition:N?`transform ${N}ms ${Re}`:"none",touchAction:"pan-x pan-y"},"data-mobile-workspace-drawer":"true",children:ne})]}),m.current)}),Va="pichamber",Ga=e=>e.replace(/^\/+|\/+$/g,""),Xa=e=>{const t=Ga(e.pathname).split("/").filter(Boolean);return e.host?[e.host,...t]:t};function qa(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=Xa(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 oe={},ns=!1,qe=null;const Ja=e=>{switch(e.type){case"session":return me.getState().setCurrentSession(e.sessionId,e.directory??null),!0;case"new-session":{const t=me.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 oe.openSessions?(oe.openSessions(e.filter),!0):!1;case"status":return oe.openSessions?(oe.openSessions(),!0):!1;case"view":return oe.openView?(oe.openView(e.target),!0):!1;case"changes":return oe.openChanges?(oe.openChanges({path:e.path,staged:e.staged}),!0):!1;case"settings":return oe.openSettings?(oe.openSettings(e.section),!0):!1}},Wt=()=>{if(!ns||!qe)return;const e=qe;qe=null,Ja(e)||(qe=e)},ss=e=>{qe=e,Wt()},bn=e=>{const t=qa(e);t&&ss(t)},Ya=e=>{ns=e,Wt()},Qa=e=>{a.useEffect(()=>(oe=e,Wt(),()=>{oe===e&&(oe={})}),[e])},Za=e=>{const{ready:t}=e;a.useEffect(()=>{Ya(t)},[t]),a.useEffect(()=>{if(!ee())return;let r=!1;const s=[];return Ce(()=>import("./vendor-capacitor-app-BrDJj9I_.js"),__vite__mapDeps([85,10,86])).then(async({App:o})=>{if(r)return;const i=await o.addListener("appUrlOpen",l=>{bn(l?.url)});if(r){i.remove();return}s.push(()=>{i.remove()})}).catch(()=>{}),Ce(()=>import("./vendor-capacitor-push-notifications-KNe1zSBF.js"),__vite__mapDeps([87,86])).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){bn(u);return}const d=typeof c?.sessionId=="string"?c.sessionId:void 0;d&&ss({type:"session",sessionId:d})});if(r){i.remove();return}s.push(()=>{i.remove()})}).catch(()=>{}),()=>{r=!0,s.forEach(o=>o())}},[])},gn=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")},xn=(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)}},vn=(e,t,r)=>{const s=r.drawer.current,o=r.scrim.current,i=r.root.current;s&&(s.style.transition=`transform ${Fe}ms ${Re}`,s.style.transform=t?"none":e==="left"?"translateX(-100%)":"translateX(100%)"),o&&(o.style.transition=`opacity ${Fe}ms ${Re}`,o.style.opacity=t?"1":"0",o.style.pointerEvents=t?"auto":"none"),i&&(i.style.pointerEvents=t?"auto":"none",i.style.visibility=t?"visible":"")},wn=e=>{const t=e.shell.current,r=e.inner.current;t&&(t.style.overflow="visible"),r&&(r.style.transition="none")},kn=(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)`},Sn=(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))},jn=({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)]")})}),ei=320,ti=380,Cn=280,ni=560,si=900;function En(e,t,r,s=ni){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(Cn,h)):r}),[c,u]=a.useState(!1),d=a.useRef(0),p=a.useRef(i),m=a.useRef(null),S=a.useRef(null),k=a.useCallback(h=>Math.min(s,Math.max(Cn,Math.round(h))),[s]),w=a.useCallback(h=>{const y=o.current;y&&(y.style.width=`${h}px`,y.style.minWidth=`${h}px`,y.style.maxWidth=`${h}px`,y.style.setProperty("--oc-ipad-sidebar-width",`${h}px`))},[]),E=a.useCallback(h=>{try{h.currentTarget.setPointerCapture(h.pointerId)}catch{}S.current=h.pointerId,d.current=h.clientX,p.current=i,m.current=i,u(!0),h.preventDefault()},[i]),_=a.useCallback(h=>{if(S.current!==h.pointerId)return;const y=h.clientX-d.current,U=k(p.current+(e==="left"?y:-y));m.current!==U&&(m.current=U,w(U))},[w,k,e]),I=a.useCallback(h=>{if(S.current!==h.pointerId)return;try{h.currentTarget.releasePointerCapture(h.pointerId)}catch{}const y=k(m.current??p.current);S.current=null,m.current=null,u(!1),l(y);try{window.localStorage.setItem(t,String(y))}catch{}},[k,t]),P=a.useMemo(()=>({onPointerDown:E,onPointerMove:_,onPointerUp:I,onPointerCancel:I}),[E,I,_]);return{asideRef:o,width:i,isResizing:c,handleProps:P}}const ri=a.memo(Hs),ai=({onActiveConnectionDeleted:e})=>{const[t,r]=a.useState(!1),[s,o]=a.useState(null),[i,l]=a.useState(!1),[c,u]=a.useState("changes"),d=a.useCallback(g=>{u(tn(g))},[]),p=c,[m,S]=a.useState("nav"),[k,w]=a.useState(null),E=a.useRef([]),_=a.useCallback(()=>{E.current.forEach(g=>window.clearTimeout(g)),E.current=[]},[]);a.useEffect(()=>()=>_(),[_]);const I=a.useRef(null),P=a.useRef(null),h=a.useRef(null),y=a.useRef(null),U=a.useRef(null),x=a.useRef(null),j=a.useRef(null),C=a.useRef(null),L=a.useRef(0),z=a.useRef(0),A=a.useCallback(g=>{_(),r(g)},[_]),f=a.useCallback(g=>{_(),l(g)},[_]),D=Ie(g=>g.setSettingsPage),M=Ie(g=>g.isArchivePageOpen),v=Ie(g=>g.setArchivePageOpen),N=Be(g=>g.available),J=Be(g=>g.runtimeType),X=a.useMemo(()=>Dn(),[]),V=!X&&N&&(J==="desktop"||J==="web"),ne=ur()??"",R=ne?bs(ne):"",W=dr().github??null,te=nn(g=>g.ensureScope);a.useEffect(()=>{!R||!W||te(R,W)},[R,W,te]);const Te=nn(g=>R?g.entriesByDirectory[R]??null:null),ye=a.useMemo(()=>fr(Te),[Te]),pe=pr(ye);a.useEffect(()=>{!pe&&Os(c)&&u(zs(c))},[pe,c]);const ce=a.useCallback(()=>{o(null)},[]),b=a.useCallback(g=>{o(g)},[]),B=a.useCallback(()=>{f(!1)},[f]),G=a.useCallback(g=>{S(g),b("settings")},[b]),{enabled:O,roomyForPanels:H}=hr(),T=mr()==="portrait",$=yr(),Y=Ie(g=>g.setSidebarOpen),Z=Ie(g=>g.isSidebarOpen),be=a.useRef(!1);a.useLayoutEffect(()=>{O&&!be.current&&Y(br().roomyForPanels),!O&&be.current&&Y(!1),be.current=O},[O,Y]);const he=a.useCallback(()=>{w(null),d("files"),f(!0)},[d,f]),nt=a.useCallback((g=null)=>{w(g),d("changes"),f(!0)},[d,f]),ie=En("left","pichamber.ipad.leftSidebarWidth",ei),ue=En("right","pichamber.ipad.rightSidebarWidth",ti,si),Ht=H,ge=Ht&&i?ue.width:0,rs=Us(O&&Z),Ve=O&&Z?ie.width:0,as=a.useCallback(g=>{const re=tn(g);i&&p===re?f(!1):(d(re),f(!0))},[i,p,d,f]),is=a.useCallback(()=>{f(!i)},[i,f]),os=a.useCallback(g=>{!g&&!H&&Y(!1)},[H,Y]);a.useEffect(()=>{if(typeof document>"u")return;const g=document.documentElement;return g.style.setProperty("--oc-chat-inset-left",`${Ve}px`),g.style.setProperty("--oc-chat-inset-right",`${ge}px`),()=>{g.style.removeProperty("--oc-chat-inset-left"),g.style.removeProperty("--oc-chat-inset-right")}},[Ve,ge]),a.useEffect(()=>{if(typeof document>"u")return;const g=O&&(T||$),re=document.documentElement;return re.classList.toggle("oc-keep-draft-starters",g),()=>re.classList.remove("oc-keep-draft-starters")},[$,O,T]);const Ft=a.useCallback(()=>{A(!1),f(!1)},[A,f]),ls=a.useMemo(()=>({openChanges:({diffPath:g,staged:re}={})=>{nt(g?{path:g,staged:re===!0}:null)},openFiles:()=>he(),openSettings:g=>{g&&D(g),G(g?"page-content":"nav")},openInstances:X?()=>b("instances"):void 0,instanceLabel:X?Ae():null,openUpdate:V?()=>b("update"):void 0,closeDrawers:Ft}),[Ft,nt,he,G,b,D,X,V]),cs=a.useMemo(()=>({openSessions:()=>{O?Y(!0):A(!0)},openView:g=>{if(g==="files"){he();return}(g==="instances"||g==="update"||g==="mcp")&&b(g)},openChanges:({path:g,staged:re}={})=>{nt(g?{path:g,staged:re===!0}:null)},openSettings:g=>{g&&D(g),G(g?"page-content":"nav")}}),[O,nt,he,G,b,D,A,Y]);Qa(cs);const Vt=a.useRef(null);Bs(Vt,{leftOpen:O?Z:t,rightOpen:i,leftWidth:()=>O?ie.width:I.current?.offsetWidth||window.innerWidth*.72,rightWidth:()=>O?ue.width:y.current?.offsetWidth||window.innerWidth,onLeftProgress:g=>{if(L.current=g,O){kn({inner:j},g,ie.width,"left");return}xn({drawer:I,scrim:P},"left",g)},onRightProgress:g=>{if(z.current=g,O&&H){kn({inner:C},g,ue.width,"right");return}xn({drawer:y,scrim:U},"right",g)},onLeftOpen:()=>{O?Y(!0):A(!0)},onLeftClose:()=>{O?Y(!1):A(!1)},onRightOpen:()=>f(!0),onRightClose:()=>f(!1),onDragStart:g=>{if(_(),g==="left"){L.current=O?Z?1:0:t?1:0,O?wn({shell:ie.asideRef,inner:j}):gn({drawer:I,scrim:P,root:h});return}z.current=i?1:0,O&&H?wn({shell:ue.asideRef,inner:C}):gn({drawer:y,scrim:U,root:x})},onDragEnd:(g,re)=>{if(g==="left"){const Ue=typeof re=="boolean"?re:L.current>.5;if(L.current=Ue?1:0,O){const Gt=Sn({shell:ie.asideRef,inner:j},Ue,ie.width,"left");Gt!==void 0&&E.current.push(Gt)}else vn("left",Ue,{drawer:I,scrim:P,root:h});return}const yt=typeof re=="boolean"?re:z.current>.5;if(z.current=yt?1:0,O&&H){const Ue=Sn({shell:ue.asideRef,inner:C},yt,ue.width,"right");Ue!==void 0&&E.current.push(Ue)}else vn("right",yt,{drawer:y,scrim:U,root:x})}});const us=a.useCallback(()=>M?(v(!1),!0):s?(ce(),!0):i?(B(),!0):t?(A(!1),!0):!1,[s,ce,B,M,t,v,A,i]);gr(us);const mt=O?"dialog":"fullscreen";return n.jsx(xr,{actions:ls,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:[O?n.jsxs("aside",{ref:ie.asideRef,className:K("relative flex h-full shrink-0 flex-col overflow-hidden border-r border-border/70 bg-sidebar motion-reduce:transition-none",!Z&&"border-r-0"),style:{width:Ve,minWidth:Ve,maxWidth:Ve,"--oc-ipad-sidebar-width":`${ie.width}px`,overflowX:"clip",paddingTop:"var(--oc-safe-area-top, 0px)"},inert:!Z,"data-page-scroll-lock":"true",children:[n.jsx("div",{ref:j,className:K("flex h-full shrink-0 flex-col",ie.isResizing&&"pointer-events-none",!Z&&"pointer-events-none select-none"),style:{width:"var(--oc-ipad-sidebar-width)",overflowX:"hidden",transform:ie.isResizing||rs.slidIn?"translateX(0)":"translateX(-100%)",transition:ie.isResizing?"none":"transform 200ms cubic-bezier(0.22, 1, 0.36, 1)"},children:n.jsx(de,{children:n.jsx(pn,{open:Z,variant:"sidebar",onOpenChange:os})})}),Z?n.jsx(jn,{side:"left",isResizing:ie.isResizing,ariaLabel:"Resize left panel",handleProps:ie.handleProps}):null]}):null,n.jsxs("div",{className:"relative flex h-full min-w-0 flex-1 flex-col","data-page-scroll-lock":"true",children:[O?n.jsxs(n.Fragment,{children:[n.jsx($s,{}),n.jsx(Ks,{onToggleRightDrawer:is,rightDrawerOpen:i,tabletWorkspaceTab:p,onSelectTabletWorkspaceTab:as,tabletGitHubTabsAvailable:pe})]}):n.jsx(Oa,{onOpenSessions:()=>A(!0),onOpenWorkspace:()=>f(!0)}),n.jsx("main",{ref:Vt,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(ri,{})})})})]}),O?null:n.jsx(pn,{open:t,onOpenChange:A,drawerRefExternal:I,scrimRefExternal:P,rootRefExternal:h}),O?n.jsxs("aside",{ref:ue.asideRef,className:K("relative flex h-full shrink-0 flex-col overflow-hidden border-l border-border/70 bg-background motion-reduce:transition-none",!ge&&"border-l-0"),style:{width:ge,minWidth:ge,maxWidth:ge,"--oc-ipad-sidebar-width":`${ue.width}px`,overflowX:"clip",paddingTop:"var(--oc-safe-area-top, 0px)"},inert:!ge,"data-page-scroll-lock":"true",children:[n.jsx("div",{ref:C,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",ue.isResizing&&"pointer-events-none",!ge&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-ipad-sidebar-width)",overflowX:"hidden",transform:ge?"translateX(0)":"translateX(100%)",transition:ue.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(yn,{open:i,onClose:B,tab:p,onTabChange:d,pendingChangesDiff:k,variant:Ht?"panel":"drawer",githubTabsAvailable:pe,drawerRefExternal:y,scrimRefExternal:U,rootRefExternal:x})})}),ge?n.jsx(jn,{side:"right",isResizing:ue.isResizing,ariaLabel:"Resize right panel",handleProps:ue.handleProps}):null]}):n.jsx(yn,{open:i,onClose:B,tab:p,onTabChange:d,pendingChangesDiff:k,githubTabsAvailable:pe,drawerRefExternal:y,scrimRefExternal:U,rootRefExternal:x}),s==="instances"&&X?n.jsx(St,{open:!0,variant:mt,dialogAlign:"app",onClose:ce,ariaLabel:"Instances",title:"Instances",children:n.jsx(za,{onConnect:ce,onActiveConnectionDeleted:e})}):null,s==="settings"?n.jsx(St,{open:!0,variant:mt,dialogAlign:"app",onClose:ce,ariaLabel:"Settings",headerless:!0,children:n.jsx(de,{children:n.jsx(Fr,{forceMobile:!O,isWindowed:!0,initialMobileStage:m,onClose:ce})})}):null,s==="update"?n.jsx(St,{open:!0,variant:mt,dialogAlign:"app",onClose:ce,ariaLabel:"Update",title:"Update",children:n.jsx(de,{children:n.jsx("div",{className:"h-full overflow-auto px-5 py-4",children:n.jsx(Vr,{initialUpdateDialogOpen:!0})})})}):null,n.jsx(de,{children:n.jsx(Ws,{})})]})})},ii=8,oi=6e4,jt=[1e3,2e3,4e3,8e3,15e3,3e4,3e4,3e4],li=(e,t)=>{if(t?.offline||t?.hidden)return oi;if(e<=0)return jt[0];const r=Math.min(e-1,jt.length-1);return jt[r]??3e4},je=()=>typeof navigator<"u"&&typeof navigator.onLine=="boolean"?!navigator.onLine:!1,we=()=>typeof document<"u"&&typeof document.visibilityState=="string"?document.visibilityState==="hidden":!1;class ci{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(je()||we())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||je()||we())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>=ii){this.exhausted=!0,this.running=!1,this.callbacks.onExhausted();return}const r=this.attempt+1,s=li(r,{offline:je(),hidden:we()});this.callbacks.onAttempt?.(r,s);const o=()=>{je()||we()||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(je()||we()){this.scheduleNext(t);return}this.runAttempt(t)}},s)}async runAttempt(t){if(t!==this.generation||!this.running||this.exhausted||this.probingGeneration===t)return;if(je()||we()){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 ui(e=2500){const{uiFont:t}=vr(),[r,s]=a.useState(!1);return a.useEffect(()=>{let o=!1;const i=()=>{o||s(!0)},l=()=>{requestAnimationFrame(()=>requestAnimationFrame(i))},c=Promise.all([wr(t).catch(()=>{}),document.fonts?.ready?.then(()=>{}).catch(()=>{})??Promise.resolve(),Yr.catch(()=>{})]).then(()=>{}),u=new Promise(d=>{window.setTimeout(d,e)});return Promise.race([c,u]).then(l),()=>{o=!0}},[t,e]),r}const di=()=>{if(typeof window>"u")return;const e=window.__PICHAMBER_APNS_ENV__;if(e==="development")return"sandbox";if(e==="production")return"production"},fi=()=>{if(typeof window>"u")return!1;const t=window.Capacitor?.getPlatform?.();return t==="ios"||t==="android"},pi=e=>{const{enabled:t}=e,r=Ie(o=>o.nativeNotificationsEnabled),s=a.useRef(null);a.useEffect(()=>{if(!t||!r||!fi())return;let o=!1;const i=[];return Ce(()=>import("./vendor-capacitor-push-notifications-KNe1zSBF.js"),__vite__mapDeps([87,86])).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",p=>{s.current=p.value,Et()?.push?.registerApnsToken?.({token:p.value,platform:Rn(),environment:di()})}),d=await l.addListener("registrationError",p=>{console.warn("[Push] Native registration error:",p)});if(await l.register().catch(()=>{}),o){u.remove(),d.remove();return}i.push(()=>{u.remove()},()=>{d.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,Et()?.push?.unregisterApnsToken?.({token:o})},[r])},hi=1e3;function mi({apis:e}){const t=ke(b=>b.initializeApp),r=ke(b=>b.isInitialized),s=ke(b=>b.isConnected),o=ke(b=>b.connectionPhase),i=ke(b=>b.providers.length),l=ke(b=>b.loadProviders),c=In(b=>b.currentDirectory),u=me(b=>b.error),d=me(b=>b.clearError),p=Ie(b=>b.setIsMobile),[m,S]=a.useState(0),[k,w]=a.useState(0),[E,_]=a.useState(!1),[I,P]=a.useState("idle"),h=kr(),y=a.useRef(null),U=a.useRef(I);U.current=I;const[x,j]=a.useState("pending"),[C,L]=a.useState(null),z=a.useMemo(()=>Ae(),[]),[,A]=a.useReducer(b=>b+1,0),f=a.useMemo(()=>Dn(),[]),D=a.useRef(0),M=a.useRef(0),v=a.useRef(!1);a.useEffect(()=>{const b=new ci(()=>$t(),{onHealthy:B=>{if(P("idle"),ve(!1),B==="unchanged"){ks(),ke.getState().initializeApp();const G=ke.getState();G.providers.length===0&&G.loadProviders({source:"mobileApp:recovery"})}},onAuthExpired:()=>{P("idle"),ve(!1),L({kind:"auth-expired",label:Ae()??""}),Ne({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),S(B=>B+1)},onNoConnection:()=>{P("idle"),ve(!1),Ne({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),S(B=>B+1)},onExhausted:()=>{P("exhausted")}},()=>`${fe()}|${ae()}`);return y.current=b,()=>{b.cancel(),y.current=null}},[]);const N=a.useCallback(()=>{if(!f||!ae())return;const b=y.current;if(b){if(b.isRunning){b.retryNow();return}P("recovering"),ve(!0),b.start()}},[f]),J=a.useCallback(()=>{y.current?.cancel(),P("idle"),ve(!1)},[]),X=a.useCallback(b=>{y.current?.cancel(),P("idle"),ve(!1),b&&L(b),Ne({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),S(B=>B+1)},[]),V=a.useCallback(()=>{const b=Date.now();b-D.current>=hi&&(D.current=b,window.dispatchEvent(new Event("pichamber:system-resume")))},[]),ne=a.useCallback(()=>{const b=ae(),B=M.current+1;if(M.current=B,!b){if(v.current)return;v.current=!0,at().catch(()=>{}).finally(()=>{v.current=!1});return}if(y.current?.isRunning){y.current.retryNow(),V();return}if(U.current==="exhausted"){if(je()||we())return;P("recovering"),ve(!0),y.current?.start(),V();return}if(je()||we()){N();return}const G=()=>{t(),i===0&&l({source:"mobileApp:nativeResume"})},O=y.current;O&&(O.probeOnce().then(H=>{if(H!==null&&M.current===B){if(H==="no-connection"){X(null);return}if(H==="needs-login"){X({kind:"auth-expired",label:Ae()??""});return}if(H==="unreachable"){N();return}H!=="switched"&&G()}}),V())},[X,V,t,l,i,N]);Sr(),jr(ne),a.useEffect(()=>gs(),[]),a.useEffect(()=>{if(!f)return;let b;const B=()=>{if(y.current?.isRunning){y.current.retryNow();return}if(U.current==="exhausted"){if(we())return;P("recovering"),ve(!0),y.current?.start();return}window.clearTimeout(b),b=window.setTimeout(()=>ne(),1500)};return window.addEventListener("online",B),()=>{window.removeEventListener("online",B),window.clearTimeout(b)}},[f,ne]),a.useEffect(()=>{if(f)return xs(()=>{ae()&&X({kind:"auth-expired",label:Ae()??""})})},[X,f]),a.useEffect(()=>(qt(e),()=>qt(null)),[e]),a.useEffect(()=>vs(b=>{if(!!b.runtimeKey&&b.runtimeKey===b.previousRuntimeKey){Fs(),A();return}y.current?.cancel(),P("idle"),ve(!1),Vs(b),w(G=>G+1),S(G=>G+1)}),[]),a.useEffect(()=>{Pn()},[k]),a.useEffect(()=>{if(!f||s||ae()){j("done");return}let b=!1;return j("attempting"),at().catch(()=>({status:"no-candidate"})).then(B=>{b||(B.status==="unreachable"?L({kind:"unreachable",label:B.label}):B.status==="needs-login"&&L({kind:"auth-expired",label:B.label}),j("done"))}),()=>{b=!0}},[]),a.useEffect(()=>{if(!f||!ae())return;let b=!1;const B=O=>{O&&L(O),Ne({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),S(H=>H+1)},G=y.current;if(G)return G.probeOnce().then(async O=>{if(b||O===null||O==="switched"||O==="unchanged")return;const H=Ae();if(O==="needs-login"){B({kind:"auth-expired",label:H??""});return}if(O==="unreachable"){B(H?{kind:"unreachable",label:H}:null);return}const se=await at().catch(()=>({status:"no-candidate"}));b||se.status==="connected"||(se.status==="needs-login"?B({kind:"auth-expired",label:se.label}):se.status==="unreachable"?B({kind:"unreachable",label:se.label}):B(null))}),()=>{b=!0}},[]),a.useEffect(()=>{p(!0)},[p]),a.useEffect(()=>{f&&!ae()||t()},[m,t,f]),a.useEffect(()=>{s&&i===0&&l({source:"mobileApp:recovery"})},[s,l,i]);const R=a.useRef(!1),[W,te]=a.useState(f);a.useEffect(()=>{if(!f||!s||R.current)return;if(me.getState().currentSessionId){R.current=!0,te(!1);return}const b=fe(),B=Cr(b);if(!B){R.current=!0,te(!1);return}const G=ws(B.directory??null);if(!G){R.current=!0,te(!1);return}const O=Ge();let H=0;try{H=O.getRuntimeGeneration()}catch{H=0}let se=!1;const T=window.setTimeout(()=>te(!1),6e3);return(async()=>{let $=null;try{$=await Er([G])}catch{$=null}if(se)return;if(!$){te(!1);return}const Y=Ge();let Z=H;try{Z=Y.getRuntimeGeneration()}catch{Z=H}const be=oa({persisted:B,persistedDirectory:G,stale:$.stale,ready:$.readyDirectories.has(G),catalog:$.catalog,runtimeKey:fe(),capturedRuntimeKey:b,storeIdentityMatches:Y===O,generationMatches:Z===H});if(be.action==="wait"){te(!1);return}if(R.current=!0,be.action==="clear"){Rr(b),te(!1);return}const he=me.getState();if(fe()!==b||Ge()!==O){te(!1);return}he.currentSessionId||he.setCurrentSession(be.sessionId,be.directory),te(!1)})(),()=>{se=!0,window.clearTimeout(T)}},[m,s,f]),a.useEffect(()=>{s&&Ge().focusProject(c,Ss(c))},[c,s]),a.useEffect(()=>{if(!u)return;const b=window.setTimeout(()=>d(),5e3);return()=>window.clearTimeout(b)},[d,u]),a.useEffect(()=>{if(f&&I!=="idle"){_(!1);return}if(!(!s&&(f?!!ae():!0))){_(!1);return}const B=window.setTimeout(()=>{_(!0)},f?4e3:8e3);return()=>window.clearTimeout(B)},[s,f,m,I,k]),Tr(),js({enabled:!0}),Gs(),pi({enabled:f&&s}),Za({ready:f&&s&&r});const Te=ui(),ye=!s&&o==="reconnecting",pe=!!ae(),ce=f&&pe&&I!=="idle";return Te?f&&!ce&&(!pe||!s&&!ye)?pe?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(Se,{width:120,height:120,isAnimated:!E}),E?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(le,{type:"button",variant:"outline",onClick:()=>{X(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(Se,{width:120,height:120,isAnimated:!0}),z?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(Nr,{text:z,showElapsed:!1})})]}):null]}):n.jsx(n.Fragment,{children:n.jsx(Aa,{onConnected:()=>S(b=>b+1),notice:C})}):!s&&!ye?E?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(Se,{width:120,height:120,isAnimated:!0})}):n.jsx(de,{children:n.jsx(Ir,{children:n.jsxs(Pr,{apis:e,children:[n.jsx(Ar,{}),n.jsx(_r,{delayDuration:300,skipDelayDuration:150,children:n.jsxs(Xs,{children:[n.jsx(qs,{}),n.jsxs("div",{className:"h-full bg-background text-foreground",children:[f&&W?n.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-background",children:n.jsx(Se,{width:120,height:120,isAnimated:!0})}):null,n.jsx(Dr,{embeddedBackgroundWorkEnabled:r&&!h}),ce?n.jsxs("div",{role:"status","aria-live":"polite",className:"pointer-events-none fixed inset-x-0 top-[calc(var(--oc-safe-area-top,0px)+var(--oc-header-height,56px)+10px)] z-40 flex justify-center",children:[n.jsx("span",{className:"flex size-11 items-center justify-center rounded-full border border-border/70 bg-[var(--surface-elevated)] text-[var(--surface-elevated-foreground)] shadow-sm",children:n.jsx(Se,{width:24,height:24,isAnimated:!0})}),n.jsx("span",{className:"sr-only",children:I==="exhausted"?"Server unreachable":"Reconnecting…"})]}):null,n.jsx(ia,{}),n.jsx(ai,{onActiveConnectionDeleted:()=>{J(),Ne({apiBaseUrl:"",clientToken:null,runtimeKey:"mobile-disconnected"}),S(b=>b+1)}}),n.jsx(Js,{}),n.jsx(Ys,{}),n.jsx(Mr,{position:"top-center",offset:"calc(var(--oc-safe-area-top, 0px) + 16px)"}),n.jsx(Lr,{})]})]})})]})},k)}):n.jsx("main",{className:"flex min-h-dvh items-center justify-center bg-background text-foreground",children:n.jsx(Se,{width:120,height:120,isAnimated:!0})})}const yi=()=>{(async()=>{try{await Promise.all([Pn(),Cs()])}catch(e){console.error("[mobile-main] settings init failed:",e)}$r(),Kr(),Zs(),Es()})().finally(()=>{Qr()})};function bi(e){window.__PICHAMBER_SURFACE__="mobile",Or(),yi(),aa(),zr();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??Et();if(!o)throw new Error("Runtime APIs not registered");const i=s?{...o,notifications:{notify:async()=>!1,canNotify:()=>!1}}:o,l=n.jsx(mi,{apis:i});ds.createRoot(t).render(n.jsx(Ct.StrictMode,{children:n.jsx(Ur,{children:n.jsx(Qs,{children:s?l:n.jsx(Br,{children:l})})})}))}const Ai=Object.freeze(Object.defineProperty({__proto__:null,renderMobileApp:bi},Symbol.toStringTag,{value:"Module"}));export{Pi as m,Ai as r};