@pi-chamber/web 1.0.4-rc.4 → 1.0.5-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +21 -2
  3. package/bin/cli.test.js +164 -4
  4. package/bin/lib/DOCUMENTATION.md +3 -3
  5. package/bin/lib/cli-args.js +96 -13
  6. package/bin/lib/commands-connect-url-tailscale.test.js +136 -0
  7. package/bin/lib/commands-connect-url.js +146 -39
  8. package/bin/lib/commands-connect-url.test.js +126 -0
  9. package/bin/lib/commands-serve.js +45 -2
  10. package/bin/lib/commands-status.js +28 -5
  11. package/bin/lib/commands-status.test.js +107 -0
  12. package/bin/lib/commands-tunnel.js +36 -10
  13. package/dist/assets/{DiagramView--BGR3PRZ.js → DiagramView-D-OSWTbO.js} +1 -1
  14. package/dist/assets/DiffView-BKT-MIH4.js +18 -0
  15. package/dist/assets/{FileSaveConflictDialog-CcrWHRvd.js → FileSaveConflictDialog-DBkVFssC.js} +2 -2
  16. package/dist/assets/FilesView-B7GIuRlh.js +6 -0
  17. package/dist/assets/{GitHubDetailScaffold-BZhP67Va.js → GitHubDetailScaffold-C9rCZMUT.js} +2 -2
  18. package/dist/assets/{GitHubLinkPicker-CJZmDljp.js → GitHubLinkPicker-Bm09hvhJ.js} +1 -1
  19. package/dist/assets/{GitHubListPrimitives-DhF42guB.js → GitHubListPrimitives-DlhAlxI6.js} +1 -1
  20. package/dist/assets/{GitView-JK-QCK9R.js → GitView-BgqdMb0m.js} +4 -4
  21. package/dist/assets/{IssuesSurface-CAqQzrsv.js → IssuesSurface-BZXAvt49.js} +3 -3
  22. package/dist/assets/{JsonTreeView-CKTqB1CD.js → JsonTreeView-BKgCQjh_.js} +1 -1
  23. package/dist/assets/{MarkdownRendererImpl-B5kJy9Nt.js → MarkdownRendererImpl-BdcyMPw-.js} +1 -1
  24. package/dist/assets/{PatchDiff-BQnRFN30.js → PatchDiff-2MmWXcGe.js} +1 -1
  25. package/dist/assets/PierreDiffViewer-D1F2WvD0.js +135 -0
  26. package/dist/assets/PullRequestsSurface-CN2z3DFv.js +2 -0
  27. package/dist/assets/SessionSwitcherContent-CCljxAZb.js +1 -0
  28. package/dist/assets/SessionSwitcherDropdown-DtNt3qw4.js +2 -0
  29. package/dist/assets/SessionUnreadDot-B9bHMy5q.js +1 -0
  30. package/dist/assets/SettingsView-DaZVCInW.js +6 -0
  31. package/dist/assets/{SettingsWindow-CAxKgYOu.js → SettingsWindow-C-ydfopH.js} +1 -1
  32. package/dist/assets/StickyHorizontalScrollbar-BMITjK4e.js +8 -0
  33. package/dist/assets/{ToolOutputDialog-lz5exVQ4.js → ToolOutputDialog-DJUAx_Oj.js} +4 -4
  34. package/dist/assets/{ToolPartDiffPreview-nIUiNLpP.js → ToolPartDiffPreview-DFyuJM4c.js} +1 -1
  35. package/dist/assets/{VirtualizedFileDiff-IWqCJNXu.js → VirtualizedFileDiff-BS-af6rn.js} +4 -4
  36. package/dist/assets/{Virtualizer-Cp_cJWbI.js → Virtualizer-DP6HbEeC.js} +1 -1
  37. package/dist/assets/{collapsible-C7oyikVm.js → collapsible-BOcd0lzY.js} +1 -1
  38. package/dist/assets/{computeVirtualFileMetrics-CyhUKEfv.js → computeVirtualFileMetrics-BI6wORhM.js} +1 -1
  39. package/dist/assets/{contextFileOpenGuard-DkjmJ-NU.js → contextFileOpenGuard-DUMSGR4M.js} +1 -1
  40. package/dist/assets/{gitStatusPredicates-DBmUY3kA.js → gitStatusPredicates-FdKYDZe3.js} +1 -1
  41. package/dist/assets/{githubLink-BdbPMMAK.js → githubLink-B3-BaGpb.js} +5 -5
  42. package/dist/assets/index-DWSrsQWl.js +11 -0
  43. package/dist/assets/{index-CKgYIOis.js → index-Df-vmvzu.js} +1 -1
  44. package/dist/assets/index-DsQIBAWK.css +1 -0
  45. package/dist/assets/main-61_cd7S7.js +2 -0
  46. package/dist/assets/main-q43jqZ2I.js +136 -0
  47. package/dist/assets/{markdownCore-D7V46WY9.js → markdownCore-CqHYlXi_.js} +2 -2
  48. package/dist/assets/{miniChat-PanPmbEK.js → miniChat-vOuWN5pV.js} +2 -2
  49. package/dist/assets/mobile-mrXWV5ky.js +2 -0
  50. package/dist/assets/{nativeFileSave-BzhtrDoD.js → nativeFileSave-CFuugNKV.js} +1 -1
  51. package/dist/assets/pi-session-focus-preference-BEufpwC6.js +9 -0
  52. package/dist/assets/{renderDiffWithHighlighter-ByZtK9za.js → renderDiffWithHighlighter-BD9CAhZU.js} +1 -1
  53. package/dist/assets/renderElectronMiniChatApp-QQFXkY5Y.js +2 -0
  54. package/dist/assets/{renderFileWithHighlighter-CnN0Tv_8.js → renderFileWithHighlighter-KiEWMtzI.js} +1 -1
  55. package/dist/assets/renderMobileApp-DIZYvrhi.js +11 -0
  56. package/dist/assets/runtimeEndpointReset-BA2uP2rj.js +62 -0
  57. package/dist/assets/{runtimeSurface-DBiUWYK2.js → runtimeSurface-Der4qUnI.js} +1 -1
  58. package/dist/assets/useAppFontEffects-Bfw_d5eB.js +212 -0
  59. package/dist/assets/{useFilesViewSearch-BWABG6pS.js → useFilesViewSearch-Budwejnx.js} +3 -3
  60. package/dist/assets/useGitHubRemoteSearch-gUdylYy3.js +1 -0
  61. package/dist/assets/{useSwitcherItems-BSTSev5C.js → useSwitcherItems-yHSMduoo.js} +1 -1
  62. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-BYohCVY0.js → vendor-aparajita-capacitor-secure-storage-BDrMx_CE.js} +1 -1
  63. package/dist/assets/{vendor-base-ui-BscvGUFt.js → vendor-base-ui-CKRUCG-f.js} +1 -1
  64. package/dist/assets/{vendor-boot-Dgb9NVFe.js → vendor-boot-EC6IyLt1.js} +13 -13
  65. package/dist/assets/{vendor-capacitor-app-BjdQVib9.js → vendor-capacitor-app-BaupizkW.js} +1 -1
  66. package/dist/assets/{vendor-capacitor-keyboard-eTtI5go3.js → vendor-capacitor-keyboard-9BVxykO7.js} +1 -1
  67. package/dist/assets/{vendor-capacitor-status-bar-9rNIGxlO.js → vendor-capacitor-status-bar-BsrUwiaA.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-autocomplete-DxS3jwvE.js → vendor-codemirror-autocomplete-CGpAsPWp.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-angular-DdjXl9e2.js → vendor-codemirror-lang-angular-CDJoHJSY.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-cpp--aMr7NVt.js → vendor-codemirror-lang-cpp-BmHofQls.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-css-CZ_qxZY9.js → vendor-codemirror-lang-css-RM2HqXZ0.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-go-Ca-y2Alu.js → vendor-codemirror-lang-go-Crwca_X7.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-html-COZ0L5wT.js → vendor-codemirror-lang-html-CHSHUpwq.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-java-D3Rf3QNJ.js → vendor-codemirror-lang-java-lhQXgWu0.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-javascript-DwJ-IvCs.js → vendor-codemirror-lang-javascript-Dw4kFO4e.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-jinja-D_5lod6k.js → vendor-codemirror-lang-jinja-_pAC3UTN.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-json-BG8C7OpC.js → vendor-codemirror-lang-json-B-b1vAv-.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-lang-less-CVEkoaTw.js → vendor-codemirror-lang-less-xIgOi1ze.js} +1 -1
  79. package/dist/assets/{vendor-codemirror-lang-liquid-U9vj0m8w.js → vendor-codemirror-lang-liquid-CP49m5dB.js} +1 -1
  80. package/dist/assets/{vendor-codemirror-lang-markdown-DqlYH9gY.js → vendor-codemirror-lang-markdown-BTht2ATe.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-lang-php-BFEiEVA1.js → vendor-codemirror-lang-php-BguZDhaO.js} +1 -1
  82. package/dist/assets/{vendor-codemirror-lang-python-Cz1dQXQd.js → vendor-codemirror-lang-python-CH6_em9L.js} +1 -1
  83. package/dist/assets/{vendor-codemirror-lang-rust-C_CoD9mj.js → vendor-codemirror-lang-rust-EG_DtGyi.js} +1 -1
  84. package/dist/assets/{vendor-codemirror-lang-sass-BuR0aKh5.js → vendor-codemirror-lang-sass-BknY5Qpo.js} +1 -1
  85. package/dist/assets/{vendor-codemirror-lang-sql-DggNUjdM.js → vendor-codemirror-lang-sql-B0f-qCZo.js} +1 -1
  86. package/dist/assets/{vendor-codemirror-lang-vue-DFZHi2J3.js → vendor-codemirror-lang-vue-CyGn9snv.js} +1 -1
  87. package/dist/assets/{vendor-codemirror-lang-wast-zuTN3SHT.js → vendor-codemirror-lang-wast-CsFfSyyB.js} +1 -1
  88. package/dist/assets/{vendor-codemirror-lang-xml-CrcvhI-k.js → vendor-codemirror-lang-xml-Cdan_Jp1.js} +1 -1
  89. package/dist/assets/{vendor-codemirror-lang-yaml-DcVWsakb.js → vendor-codemirror-lang-yaml-COI5hck8.js} +1 -1
  90. package/dist/assets/{vendor-codemirror-language-data-CCLITgCF.js → vendor-codemirror-language-data-CqU7kHmg.js} +2 -2
  91. package/dist/assets/{vendor-codemirror-search-H7NOEdbX.js → vendor-codemirror-search-DUfSCF9S.js} +1 -1
  92. package/dist/assets/{vendor-lezer-cpp-C8aD2KAr.js → vendor-lezer-cpp-DMZOJzBa.js} +1 -1
  93. package/dist/assets/{vendor-lezer-css-2lbTJF-Y.js → vendor-lezer-css-DUkkbMp7.js} +1 -1
  94. package/dist/assets/{vendor-lezer-go-Bw6LFTrZ.js → vendor-lezer-go-CHIhCNY6.js} +1 -1
  95. package/dist/assets/{vendor-lezer-html-D7ym2z7S.js → vendor-lezer-html-B3h0MOrG.js} +1 -1
  96. package/dist/assets/{vendor-lezer-java-CZhK7w21.js → vendor-lezer-java-tMazV_6X.js} +1 -1
  97. package/dist/assets/{vendor-lezer-javascript-rpKeTHZp.js → vendor-lezer-javascript-ctwLWf4v.js} +1 -1
  98. package/dist/assets/{vendor-lezer-json-C7jwsd2G.js → vendor-lezer-json-BP_UAzLL.js} +1 -1
  99. package/dist/assets/{vendor-lezer-lr-DR-ylqNN.js → vendor-lezer-lr-B8TQctNw.js} +1 -1
  100. package/dist/assets/{vendor-lezer-markdown-Bir0m5nB.js → vendor-lezer-markdown-aGLZf_3h.js} +1 -1
  101. package/dist/assets/{vendor-lezer-php-y0hIEfo1.js → vendor-lezer-php-D5zCNzlt.js} +1 -1
  102. package/dist/assets/{vendor-lezer-python-D64A9lNV.js → vendor-lezer-python-EJ4Im4y2.js} +1 -1
  103. package/dist/assets/{vendor-lezer-rust-E3ZA9T2L.js → vendor-lezer-rust-DO5c7OtA.js} +1 -1
  104. package/dist/assets/{vendor-lezer-sass-C5UFI9SP.js → vendor-lezer-sass-CMi6zfXI.js} +1 -1
  105. package/dist/assets/{vendor-lezer-xml-DOy7FzCR.js → vendor-lezer-xml-0MHMeZDp.js} +1 -1
  106. package/dist/assets/{vendor-lezer-yaml-kEjaSCvZ.js → vendor-lezer-yaml-BE2EFjpA.js} +1 -1
  107. package/dist/assets/{vendor-replit-codemirror-vim-BLfh0LPy.js → vendor-replit-codemirror-vim-AnOuN8yJ.js} +1 -1
  108. package/dist/assets/{web-components-CdMfsnXE.js → web-components-CeHLxvED.js} +3 -3
  109. package/dist/index.html +4 -4
  110. package/dist/mini-chat.html +3 -3
  111. package/dist/mobile.html +3 -3
  112. package/dist/sw.js +1 -1
  113. package/package.json +1 -2
  114. package/server/index.js +69 -30
  115. package/server/lib/client-auth/DOCUMENTATION.md +15 -1
  116. package/server/lib/client-auth/pairing.js +2 -12
  117. package/server/lib/client-auth/remote-clients.js +2 -12
  118. package/server/lib/cloudflare-tunnel.js +0 -132
  119. package/server/lib/fs/DOCUMENTATION.md +8 -0
  120. package/server/lib/fs/atomic-write.js +111 -0
  121. package/server/lib/fs/atomic-write.test.js +133 -0
  122. package/server/lib/notifications/DOCUMENTATION.md +43 -32
  123. package/server/lib/notifications/pi-notification-watcher.js +8 -7
  124. package/server/lib/notifications/pi-notification-watcher.test.js +88 -2
  125. package/server/lib/pi/routes-extension-events.test.js +231 -0
  126. package/server/lib/pi/routes.js +137 -4
  127. package/server/lib/pi/routes.test.js +248 -2
  128. package/server/lib/pi/session-daemon/DOCUMENTATION.md +17 -4
  129. package/server/lib/pi/session-daemon/daemon-process.js +2 -0
  130. package/server/lib/pi/session-daemon/engines/index.js +6 -0
  131. package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +1 -1
  132. package/server/lib/pi/session-daemon/extension-bridge.js +24 -0
  133. package/server/lib/pi/session-daemon/extension-message-render.js +74 -0
  134. package/server/lib/pi/session-daemon/extension-message-render.test.js +164 -0
  135. package/server/lib/pi/session-daemon/extension-tool-render.js +13 -6
  136. package/server/lib/pi/session-daemon/pending-input.js +188 -0
  137. package/server/lib/pi/session-daemon/pending-input.test.js +202 -0
  138. package/server/lib/pi/session-daemon/session-daemon-engines.test.js +828 -0
  139. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +296 -6
  140. package/server/lib/pi/session-daemon/session-daemon-turn.e2e.test.js +9 -0
  141. package/server/lib/pi/session-daemon/session-daemon.js +219 -19
  142. package/server/lib/pi/session-daemon/session-daemon.test.js +30 -2
  143. package/server/lib/pi/session-daemon/session-engine-router.js +390 -0
  144. package/server/lib/pi/session-daemon/session-engine-router.test.js +515 -0
  145. package/server/lib/pi/session-daemon/session-engines.js +467 -0
  146. package/server/lib/pi/session-daemon/session-engines.test.js +383 -0
  147. package/server/lib/pi/snippets-store.js +8 -17
  148. package/server/lib/pi/ui-settings-store.js +6 -10
  149. package/server/lib/pi/ui-settings-store.test.js +37 -1
  150. package/server/lib/relay/DOCUMENTATION.md +6 -4
  151. package/server/lib/relay/identity-store.js +116 -0
  152. package/server/lib/relay/identity-store.test.js +169 -0
  153. package/server/lib/relay/identity.js +6 -4
  154. package/server/lib/relay/server-id.js +63 -0
  155. package/server/lib/relay/server-id.test.js +132 -0
  156. package/server/lib/relay/signing-key.js +14 -11
  157. package/server/lib/security/bind-host.js +6 -2
  158. package/server/lib/security/bind-host.test.js +17 -0
  159. package/server/lib/server/core-routes.js +27 -1
  160. package/server/lib/server/lan-addresses.js +18 -6
  161. package/server/lib/server/lan-addresses.test.js +28 -0
  162. package/server/lib/server/tunnel-auth.js +47 -7
  163. package/server/lib/server/tunnel-auth.rate-limit.test.js +164 -0
  164. package/server/lib/server/tunnel-service.DOCUMENTATION.md +3 -4
  165. package/server/lib/server/tunnel-service.js +23 -20
  166. package/server/lib/server/tunnel-service.test.js +19 -2
  167. package/server/lib/stt/config-store.js +5 -15
  168. package/server/lib/tailscale/DOCUMENTATION.md +264 -0
  169. package/server/lib/tailscale/routes.js +45 -0
  170. package/server/lib/tailscale/service.js +959 -0
  171. package/server/lib/tailscale/tailscale.js +302 -0
  172. package/server/lib/tailscale/tailscale.test.js +1861 -0
  173. package/server/lib/tunnels/DOCUMENTATION.md +3 -4
  174. package/server/lib/tunnels/providers/cloudflare.js +1 -22
  175. package/server/lib/tunnels/types.js +0 -2
  176. package/server/lib/ui-auth/DOCUMENTATION.md +31 -0
  177. package/server/lib/ui-auth/ui-auth.js +80 -6
  178. package/server/lib/ui-auth/ui-auth.test.js +136 -0
  179. package/server/lib/ui-auth/ui-passkeys.js +2 -13
  180. package/server/lib/update-job-store.js +4 -6
  181. package/dist/assets/DiffView-hz90_htv.js +0 -18
  182. package/dist/assets/FilesView-DaqkPMqx.js +0 -6
  183. package/dist/assets/PierreDiffViewer-BeGpdI0x.js +0 -134
  184. package/dist/assets/PullRequestsSurface-D9beq2x9.js +0 -2
  185. package/dist/assets/SessionSwitcherContent-DElQ_cjm.js +0 -1
  186. package/dist/assets/SessionSwitcherDropdown-JaIDcDIj.js +0 -2
  187. package/dist/assets/SessionUnreadDot-Czfvjbdi.js +0 -1
  188. package/dist/assets/SettingsView-C_GC1Mx3.js +0 -6
  189. package/dist/assets/index-BnZVqcki.js +0 -11
  190. package/dist/assets/index-BnieExes.css +0 -1
  191. package/dist/assets/main-6YKi4QM2.js +0 -2
  192. package/dist/assets/main-CWdWdhdL.js +0 -136
  193. package/dist/assets/mobile-0LY-2fxw.js +0 -2
  194. package/dist/assets/pi-session-focus-preference-BC-ze1oC.js +0 -10
  195. package/dist/assets/renderElectronMiniChatApp-DETQLjFi.js +0 -2
  196. package/dist/assets/renderMobileApp-DS0FDQLg.js +0 -11
  197. package/dist/assets/runtimeEndpointReset-BqqXMwE9.js +0 -62
  198. package/dist/assets/useAppFontEffects-BisjofNZ.js +0 -212
  199. package/dist/assets/useGitHubRemoteSearch-Bsf2YeQP.js +0 -1
  200. package/dist/assets/vendor-capacitor-push-notifications-CBKq2Arn.js +0 -1
  201. package/server/lib/notifications/delivery-runtime.js +0 -314
  202. package/server/lib/notifications/delivery-runtime.test.js +0 -85
  203. package/server/lib/notifications/routes.js +0 -74
  204. package/server/lib/relay/service.js +0 -9
@@ -0,0 +1,62 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-Df-vmvzu.js","assets/useAppFontEffects-Bfw_d5eB.js","assets/index-DWSrsQWl.js","assets/vendor-zustand-CUi8eEds.js","assets/vendor-react-DASdDPIk.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-CPcsbTWB.js","assets/vendor-fuse.js-Dw8P0qyA.js","assets/index-DsQIBAWK.css","assets/vendor-boot-EC6IyLt1.js","assets/runtimeSurface-Der4qUnI.js","assets/nativeFileSave-CFuugNKV.js","assets/computeVirtualFileMetrics-BI6wORhM.js","assets/vendor-shiki-Bbf2GEcE.js","assets/vendor-shikijs-core-CGM_jqPK.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-BgLrS_2D.js","assets/vendor-hast-util-to-html-BKBhbTDb.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-rJCbAzvX.js","assets/vendor-zwitch-C2o2j-tx.js","assets/vendor-stringify-entities-CsH1VEn9.js","assets/vendor-character-entities-legacy-BpoLgcEt.js","assets/vendor-character-entities-html4-D7taRCQ7.js","assets/vendor-ccount-c2V3InAJ.js","assets/vendor-comma-separated-tokens-D8TqSuIK.js","assets/vendor-space-separated-tokens-DD3iYX1K.js","assets/vendor-hast-util-whitespace-D4Wp6AEg.js","assets/vendor-shikijs-engine-oniguruma-DPWuIF1G.js","assets/themeResolver-yJ9XpNMI.js","assets/vendor-pierre-theming-Dgp7B_O4.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/renderFileWithHighlighter-KiEWMtzI.js","assets/renderDiffWithHighlighter-BD9CAhZU.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-DOPmc7GU.js","assets/appThemeRegistry-gegrE2dq.js","assets/registerCustomTheme-DmolaWWZ.js","assets/vendor-capacitor-keyboard-9BVxykO7.js","assets/SessionSwitcherDropdown-DtNt3qw4.js"])))=>i.map(i=>d[i]);
2
+ import{_ as ft}from"./vendor-vite-runtime-DD1OZmLC.js";import{k as s,b2 as Ed,b3 as Rd,b4 as Dd,b5 as Pd,b6 as Md,b7 as Td,b8 as Fd,aO as Bo,aP as Mn,aQ as Ld,aR as _o,aS as zo,aV as Od,b9 as Bd,ba as _d,bb as zd,bc as Ca,bd as ka,be as Aa,bf as Na,bg as Ia,bh as Ea,bi as Ra,aT as Da,a$ as Pa,aY as Ma,aZ as Ta,aW as Uo,aX as $o,bj as ro,aL as Ud}from"./vendor-boot-EC6IyLt1.js";import{a as Re,R as a}from"./vendor-react-DASdDPIk.js";import{b4 as Zs,b5 as $d,t as ae,a as dt,h as Te,ae as dn,B as Ne,I as P,as as Tn,b6 as Fa,au as es,av as ts,aw as Ss,ax as ds,ay as js,az as Ls,aW as Ms,v as xs,b7 as Ts,b8 as Kd,g as Js,b9 as Or,ba as vi,bb as Si,aP as Nn,e as tr,o as La,at as Is,bc as ji,ao as ws,aj as Ue,ak as $e,am as Ke,bd as oo,be as Wd,bf as Gd,bg as Hd,bh as qd,bi as Yd,bj as io,bk as Vd,ai as Wt,al as Gt,an as Ht,O as $t,bl as Qd,bm as Jd,bn as Xd,bo as Zd,bp as eu,bq as tu,aT as ao,r as In,G as Ko,aD as su,aO as nu,aS as Oa,br as Ba,Z as vs,bs as ru,bt as ou,bu as iu,bv as au,d as _a,z as Os,aN as za,bw as vr,bx as Ci,by as Ua,bz as mt,bA as lu,bB as cu,aU as $a,bC as Ka,bD as Wa,bE as Ga,ap as ut,bF as Ha,aI as du,i as qa,p as uu,bG as fu,j as hu,u as Ya,k as mu,m as pu,bH as Va,n as gu,q as ki,bI as bu,bJ as qs,b as Ai,c as xu,bK as yu,aV as wu,aY as vu,bL as lo,bM as Su,bN as ju,aX as Cu,bO as ku,bP as Au,a4 as Nu,aq as nn,aA as Qa,M as Iu,y as Eu,bQ as Ru,w as Du,bR as Pu,bS as Ja,bT as Mu,bU as Tu,bV as Fu,bW as Lu,bX as Ou,bY as Bu,bZ as _u,b_ as zu,b$ as Uu,c0 as $u,af as Ku,c1 as Wu}from"./useAppFontEffects-Bfw_d5eB.js";import{T as Ni,q as Gu,U as Hu,z as rn,V as Xa,W as Za,X as qu,Y as Yu,u as on,F as Vu,Z as Qu,_ as Ju,f as de,v as Mt,e as _,$ as Xu,a0 as Xe,a as Pt,m as Bn,p as Ee,a1 as Fn,a2 as Kt,a3 as co,a4 as uo,a5 as el,n as cs,N as Wo,O as cr,a6 as Zu,t as tl,a7 as ef,a8 as sl,B as tf,L as nl,w as En,a9 as fo,h as ho,d as Wn,aa as sf,ab as nf,ac as rf,ad as Ii,ae as xn,af as Br,ag as mo,A as dr,ah as Es,ai as Ei,aj as po,ak as rl,al as go,am as of,an as af,ao as lf,ap as cf,aq as df,ar as uf,as as ff,at as hf,au as mf,S as ol,av as pf,aw as gf,K as bf,ax as xf,E as yf}from"./index-DWSrsQWl.js";import{b as wf,g as il,r as vf,d as al,s as sr,c as ll,e as Fs,h as an,i as Sf,j as jf,k as Cf,l as kf,m as Go,n as cl,f as Af,a as Ri,S as Nf,t as If,o as Ef}from"./SessionUnreadDot-B9bHMy5q.js";import{c as Bs,d as Sr,p as dl,a as Rf}from"./vendor-zustand-CUi8eEds.js";/* empty css */import{saveOrShareFile as Df}from"./nativeFileSave-CFuugNKV.js";import{usePermissionStore as Pf}from"./permissionStore-B9Hkrqny.js";const Mf="chat";function ul(e){const t=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&t.set(Zs.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return t.set(Zs.SETTINGS,n),t}return e.tab!==Mf&&t.set(Zs.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&t.set(Zs.FILE,e.diffFile),t}function Tf(e,t){const n=typeof window<"u"?window.location.pathname:"/",r=n.startsWith("/session")||n.startsWith("/s/")?"/":n,o=e.toString();return o?`${r}?${o}`:r}function Ff(e){if(typeof window>"u")return!0;try{const t=new URLSearchParams(window.location.search),n=ul(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!t.has(Zs.SESSION)&&t.set(Zs.SESSION,o);const i=[...t.entries()].sort((c,d)=>c[0].localeCompare(d[0])),l=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(i.length!==l.length)return!1;for(let c=0;c<i.length;c++)if(i[c][0]!==l[c][0]||i[c][1]!==l[c][1])return!1;return!0}catch{return!0}}function bo(e,t={}){if(!(typeof window>"u")&&!(!t.force&&Ff(e)))try{const n=ul(e),r=Tf(n);t.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const Lf=["typescript","javascript","tsx","jsx","json","markdown"],fl={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let Di=null;const hl=()=>(Di??=Promise.all([ft(()=>import("./index-Df-vmvzu.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])),ft(()=>import("./workerFactory-tw7cIdmV.js"),[]),ft(()=>import("./appThemeRegistry-gegrE2dq.js"),__vite__mapDeps([43,44,30,31,5,15,16,17,18,19,20,21,22,23,24,25,26,27,28]))]).then(([e,t,n])=>({WorkerPoolManager:e.WorkerPoolManager,workerFactory:t.workerFactory,ensurePierreThemeRegistered:n.ensurePierreThemeRegistered})),Di),Ln={},Pi=new Set,xo=new Set;let nr={light:"pierre-light",dark:"pierre-dark"};const Of=()=>{for(const e of xo)e()},ml=(e,t)=>{t.setRenderOptions({theme:nr,lineDiffType:fl[e].lineDiffType})},yo=e=>{typeof window>"u"||Pi.has(e)||(Pi.add(e),hl().then(t=>{if(Ln[e])return;const n=fl[e],r=new t.WorkerPoolManager({workerFactory:t.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:Lf,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),Ln[e]=r,ml(e,r),Of()}))},Bf=e=>(xo.add(e),()=>xo.delete(e)),_f=e=>{if(!(nr.light===e.light&&nr.dark===e.dark)){nr=e;for(const t of Object.keys(Ln)){const n=Ln[t];n&&ml(t,n)}}},bx=({children:e})=>{const t=$d(),n=Ni(!1),r=Ni(!0),o=t?.lightThemeId??n.metadata.id,i=t?.darkThemeId??r.metadata.id,l=t?.availableThemes.find(d=>d.metadata.id===o)??n,c=t?.availableThemes.find(d=>d.metadata.id===i)??r;return Re.useEffect(()=>{let d=!1;return hl().then(u=>{d||(u.ensurePierreThemeRegistered(l),u.ensurePierreThemeRegistered(c),_f({light:l.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,l]),Re.useEffect(()=>{if(typeof window>"u")return;const d=()=>{yo("unified"),yo("split")};if(typeof window.requestIdleCallback=="function"){const f=window.requestIdleCallback(d,{timeout:5e3});return()=>window.cancelIdleCallback(f)}const u=window.setTimeout(d,2e3);return()=>window.clearTimeout(u)},[]),s.jsx(s.Fragment,{children:e})},xx=(e="unified")=>{const t=Re.useSyncExternalStore(Bf,()=>Ln[e],()=>{});return Re.useEffect(()=>{yo(e)},[e]),t};let Gn=null;const yx=()=>{if(typeof window>"u"||typeof document>"u"||Gn)return()=>{};const e=()=>{document.visibilityState!=="hidden"&&Gu()};document.addEventListener("visibilitychange",e),window.addEventListener("focus",e),window.addEventListener("online",e);let t=!1;const n=()=>{t||(t=!0,document.removeEventListener("visibilitychange",e),window.removeEventListener("focus",e),window.removeEventListener("online",e),Gn===n&&(Gn=null))};return Gn=n,n},zf=e=>e==="/",ln=e=>e.replace(/\\/g,"/"),cn=e=>{if(!e||zf(e))return e;let t=e;for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t},tn=e=>e.endsWith("/"),ur=e=>{const t=e.trim();return!t||tn(t)?t:`${t}/`},Ho=e=>e.lastIndexOf("/"),pl=e=>{if(tn(e))return e;const t=Ho(e);return t<0?e:e.slice(0,t+1)},gl=e=>{const t=Ho(e);return e.slice(t+1)},bl=e=>{const t=cn(e.trim());if(!t||t==="~"||t==="~/"||t==="/")return null;const n=Ho(t);return n<0?null:t.startsWith("~/")&&n<=1?"~/":n===0?"/":`${t.slice(0,n)}/`},xl=e=>tn(e)&&bl(e)!==null,Uf=e=>{if(!xl(e))return null;const t=cn(e.trim());return gl(t)||t},$f=(e,t)=>`${pl(e)}${t}/`,Rs=e=>{if(!e)return null;const t=cn(ln(e.trim()));return t?t.toLowerCase():null},Mi=(e,t)=>{const n=e.trim();return n==="~"?t:n.startsWith("~/")?`${t}${n.slice(1)}`:n},Kf=(e,t)=>{const n=cn(ln(e.trim())),r=cn(ln(t.trim()));if(!n)return"";if(!r)return ur(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:ur(n)},Wf=e=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,wo=e=>{if(!e)return;e.focus({preventScroll:!0});const t=e.value.length;e.setSelectionRange(t,t),e.scrollLeft=e.scrollWidth},Gf=async()=>Hu({fresh:!0}),Hf=()=>{const[e,t]=Re.useState(!1),[n,r]=Re.useState(!1);Re.useEffect(()=>{t(rn()),r(Xa())},[]);const o=Re.useCallback(async c=>e?await Za(c):{success:!0,path:c},[e]),i=Re.useCallback(async c=>e?await qu():{success:!0},[e]),l=Re.useCallback(async c=>e?await Yu():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:i,stopAccessing:l}};function qf({open:e,addedProjectPaths:t,shouldSuppressAutoFocus:n}){const r=on(te=>te.homeDirectory),{canRequestAccess:o,startAccessing:i}=Hf(),l=a.useRef(null),c=a.useRef(new Map),[d,u]=a.useState(""),[f,p]=a.useState("~/"),[x,y]=a.useState([]),[m,h]=a.useState(!1),[b,g]=a.useState(!1),[S,v]=a.useState(null),[E,k]=a.useState(0),[C,j]=a.useState(0),[w,N]=a.useState(!1),[M,F]=a.useState(!1),[$,U]=a.useState("right"),K=a.useRef("~/"),L=d||r;a.useEffect(()=>{if(!e)return;p("~/"),y([]),j(0),N(!1),F(!1),K.current="~/",U("right"),n||requestAnimationFrame(()=>wo(l.current));let te=!1;return(async()=>{const Ae=await Gf();te||(u(Ae||r||""),n||requestAnimationFrame(()=>wo(l.current)))})(),()=>{te=!0}},[r,e,n]);const D=a.useMemo(()=>pl(f),[f]),R=a.useMemo(()=>tn(f)?"":gl(f),[f]),I=a.useMemo(()=>L?Mi(D,L):"",[D,L]);a.useEffect(()=>{const te=K.current;te!==D&&(U(D.length>=te.length?"right":"left"),K.current=D)},[D]),a.useEffect(()=>{if(!e||!I){y([]),v(null);return}let te=!1;return h(!0),g(!1),v(null),Vu(I).then(le=>{if(te)return;g(!1),v(null);const Ae=le.filter(Se=>Se.isDirectory).map(Se=>({name:Se.name,path:ln(Se.path)})).sort((Se,Ge)=>Se.name.localeCompare(Ge.name));y(Ae)}).catch(le=>{if(!te){y([]);const Ae=Qu(le)?le.reason:"unknown";v(Ae),g(Ae==="not-found")}}).finally(()=>{te||h(!1)}),()=>{te=!0}},[I,E,e]);const T=a.useMemo(()=>{const te=R.toLowerCase(),le=M||R.startsWith(".");return x.filter(Ae=>Ae.name.toLowerCase().startsWith(te)&&(le||!Ae.name.startsWith(".")))},[R,x,M]),W=a.useMemo(()=>Uf(f),[f]),G=a.useMemo(()=>bl(f),[f]),B=a.useMemo(()=>{const te=[],le=Rs(I);xl(f)&&W&&G&&te.push({type:"parent",value:"browse:up",name:W,path:G,alreadyAdded:!!(le&&t.has(le))});for(const Ae of T){const Se=Rs(Ae.path);te.push({type:"directory",value:`browse:${Ae.path}`,name:Ae.name,path:Ae.path,alreadyAdded:!!(Se&&t.has(Se))})}return te},[t,I,W,T,G,f]);a.useEffect(()=>{j(0)},[f,B.length]);const be=a.useMemo(()=>L?cn(Mi(f,L)):"",[L,f]),V=Rs(be),Ce=!!(V&&t.has(V)),De=a.useMemo(()=>R?T.find(te=>te.name===R)??null:null,[R,T]),H=!!(be&&!Ce&&(S===null||S==="not-found")&&(tn(f)&&b||!tn(f)&&R.trim().length>0&&De===null)),z=B[C]??null,Q=!!z,X=a.useCallback(te=>{p(ur(te))},[]),ne=a.useCallback(te=>{p($f(f,te.name))},[f]),we=a.useCallback(te=>{if(te){if(te.type==="parent"){X(te.path);return}ne(te)}},[X,ne]),me=a.useCallback(async te=>{const le=await i(te);if(!le.success)return ae.error("Failed to open directory",{description:le.error||"Desktop could not grant file access."}),!1;const Ae=L?Kf(te,L):ur(ln(te));return X(Ae),!0},[X,L,i]),q=a.useCallback(async()=>{if(!w){N(!0);try{if(Xa()){const le=await Za(be);if(!le.success||!le.path){le.error&&le.error!=="Directory selection cancelled"&&ae.error("Failed to select directory",{description:le.error});return}await me(le.path);return}const te=await Ju(be);if(te.status==="cancelled")return;if(te.status!=="picked"){ae.error("Couldn't open a folder picker",{description:te.error});return}await me(te.path)}catch(te){ae.error("Failed to select directory",{description:te instanceof Error?te.message:"Unknown error occurred."})}finally{N(!1)}}},[me,w,be]);return{inputRef:l,rowRefs:c,query:f,setQuery:p,isLoading:m,isBrowseDirectoryMissing:b,browseErrorReason:S,browseReloadKey:E,setBrowseReloadKey:k,highlightedIndex:C,setHighlightedIndex:j,isPickingLocation:w,showHidden:M,setShowHidden:F,folderEnterFrom:$,explorerRootDirectory:L,browseDirectoryDisplayPath:D,browseDirectoryAbsolutePath:I,browseFilterQuery:R,filteredEntries:T,rows:B,targetPath:be,isAlreadyAdded:Ce,shouldCreateTarget:H,highlightedRow:z,hasHighlightedBrowseItem:Q,canRequestAccess:o,browseToDisplayPath:X,browseToEntry:ne,executeRow:we,applyPickedLocation:me,handleBrowseLocation:q}}function Yf({open:e,onClose:t,isMobile:n,addedProjectPaths:r,targetPath:o,shouldCreateTarget:i,browseErrorReason:l,browseDirectoryAbsolutePath:c,isAlreadyAdded:d,isPickingLocation:u}){const f=dt(F=>F.addProject),p=de(F=>F.setActiveMainTab),x=de(F=>F.setSessionSwitcherOpen),y=Te(F=>F.openNewSessionDraft),[m,h]=a.useState(!1),[b,g]=a.useState(!1),[S,v]=a.useState("");a.useEffect(()=>{e&&(h(!1),g(!1),v(""))},[e]);const E=a.useCallback((F,$)=>{p("chat"),n&&x(!1),y({selectedProjectId:F,directoryOverride:$}),t()},[n,t,y,p,x]),k=a.useCallback(async F=>{if(!F||m)return;const $=Rs(F);if($&&r.has($))return;let U=F;h(!0);try{const K=!b&&i&&Rs(F)===Rs(o);if(b){const D=S.trim();if(!D){ae.error("Enter a repository URL before cloning.");return}const R=await Mt("/api/fs/clone",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({remoteUrl:D,destinationPath:F})});if(!R.ok)throw new Error("Failed to clone git repository");U=(await R.json()).path||F}else if(K&&!(await Mt("/api/fs/mkdir",{method:"POST",headers:{"Content-Type":"application/json"},query:c?{directory:c}:void 0,body:JSON.stringify({path:F})})).ok)throw new Error("Failed to select directory");const L=f(U);if(!L){ae.error("Failed to add folder",{description:"Please select a valid directory path."});return}E(L.id,L.path)}catch(K){ae.error("Failed to select directory",{description:K instanceof Error?K.message:"Unknown error occurred."})}finally{h(!1)}},[f,r,c,S,b,m,E,i,o]),C=!m&&!u&&!d&&l!=="os-permission"&&l!=="invalid-response"&&l!=="unknown"&&!!o,j=C&&S.trim().length>0,w=b?j:C,N=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform)?"⌘":"Ctrl";return{isConfirming:m,isCloneMode:b,setIsCloneMode:g,cloneRemoteUrl:S,setCloneRemoteUrl:v,canSubmit:w,submitActionLabel:d?"Already added":b?m?"Cloning...":"Clone & add":m?"Adding...":i?"Create & add":"Add folder",submitModifierLabel:N,finalizeSelection:k}}const Vf=({open:e,onOpenChange:t})=>{const n=dt(q=>q.projects),{isMobile:r,isTablet:o}=dn(),i=r||o,l=a.useMemo(()=>new Set(n.map(q=>Rs(q.path)).filter(q=>!!q)),[n]),c=a.useCallback(()=>{t(!1)},[t]),{inputRef:d,rowRefs:u,query:f,setQuery:p,isLoading:x,browseErrorReason:y,setBrowseReloadKey:m,highlightedIndex:h,setHighlightedIndex:b,isPickingLocation:g,showHidden:S,setShowHidden:v,folderEnterFrom:E,browseDirectoryDisplayPath:k,browseDirectoryAbsolutePath:C,rows:j,targetPath:w,isAlreadyAdded:N,shouldCreateTarget:M,highlightedRow:F,hasHighlightedBrowseItem:$,canRequestAccess:U,executeRow:K,handleBrowseLocation:L}=qf({open:e,addedProjectPaths:l,shouldSuppressAutoFocus:i}),{isConfirming:D,isCloneMode:R,setIsCloneMode:I,cloneRemoteUrl:T,setCloneRemoteUrl:W,canSubmit:G,submitActionLabel:B,submitModifierLabel:be,finalizeSelection:V}=Yf({open:e,onClose:c,isMobile:r,addedProjectPaths:l,targetPath:w,shouldCreateTarget:M,browseErrorReason:y,browseDirectoryAbsolutePath:C,isAlreadyAdded:N,isPickingLocation:g});a.useLayoutEffect(()=>{const q=d.current;q&&(q.scrollLeft=q.scrollWidth)},[d,f]),a.useLayoutEffect(()=>{!e||i||wo(d.current)},[d,e,i]),a.useLayoutEffect(()=>{const q=j[h];q&&u.current.get(q.value)?.scrollIntoView({block:"nearest"})},[h,u,j]);const Ce=a.useCallback(q=>{if(q.key==="ArrowDown"){q.preventDefault(),b(te=>Math.min(j.length-1,te+1));return}if(q.key==="ArrowUp"){q.preventDefault(),b(te=>Math.max(0,te-1));return}if(q.key==="Enter"){if(q.preventDefault(),Wf(q)){V(w);return}$&&K(F);return}q.key==="Backspace"&&f===""&&(q.preventDefault(),c())},[K,V,c,$,F,f,j.length,b,w]),De=s.jsxs("button",{type:"button",onClick:()=>v(q=>!q),className:"flex flex-shrink-0 items-center gap-2 rounded-lg px-2 py-1 typography-meta text-muted-foreground transition-colors hover:bg-interactive-hover/40",children:[S?s.jsx(P,{name:"checkbox",className:"h-4 w-4 text-primary"}):s.jsx(P,{name:"checkbox-blank",className:"h-4 w-4"}),"Show hidden"]}),H=s.jsx("div",{className:"py-1.5",children:s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(P,{name:"folder-3",className:"pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground/80"}),s.jsx(Tn,{ref:d,value:f,onChange:q=>p(ln(q.target.value)),onKeyDown:Ce,placeholder:"Enter a folder path...",className:"border-transparent bg-transparent pl-9 font-mono typography-ui-label shadow-none focus-visible:ring-0",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})]}),s.jsxs(Ne,{variant:"outline",size:"xs",className:"h-8 shrink-0 gap-1 px-2",disabled:D||g,onMouseDown:q=>q.preventDefault(),onClick:()=>{L()},title:"Browse location","aria-label":"Browse location",children:[s.jsx(P,{name:"folder-open",className:"h-3.5 w-3.5"}),g?"Opening...":"Browse"]})]})}),z=j.some(q=>q.type==="parent"),Q=s.jsx("div",{className:"relative min-h-0 flex-1 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)] shadow-sm",children:s.jsxs("div",{className:"max-h-[min(28rem,58vh)] overflow-y-auto p-2",children:[s.jsxs("div",{className:"flex items-center justify-between gap-2 px-2 pb-1 pt-0.5",children:[s.jsx("div",{className:"typography-meta font-medium uppercase tracking-wide text-muted-foreground/80",children:"Directories"}),s.jsxs(Ne,{variant:"ghost",size:"xs",className:"h-6 shrink-0 gap-1 text-muted-foreground","aria-pressed":R,disabled:D||g,onClick:()=>I(q=>!q),children:[s.jsx(P,{name:"git-repository",className:"h-3.5 w-3.5"}),"Clone"]})]}),R?s.jsxs("div",{className:"mb-2 space-y-1.5 px-2 pb-1",children:[s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Clone into the folder path above."}),s.jsx("div",{className:"flex items-center gap-1.5",children:s.jsx(Tn,{value:T,onChange:q=>W(q.target.value),placeholder:"Repository URL (HTTPS or SSH)",className:"min-w-0 flex-1 font-mono typography-ui-label",spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off"})})]}):null,N?s.jsx("p",{className:"px-2 pb-2 typography-meta text-muted-foreground",children:"This folder is already added. Open a subfolder to add that instead."}):null,s.jsx("div",{className:_("mt-3","animate-in fade-in-0 duration-200 motion-reduce:animate-none",E==="left"?"slide-in-from-left-2":"slide-in-from-right-2"),children:x?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"Loading directories..."}):y&&y!=="not-found"?s.jsxs("div",{className:"flex flex-col items-center gap-3 px-4 py-10 text-center",children:[s.jsx("div",{className:"typography-ui-label text-status-error",children:y==="os-permission"?"PiChamber needs access to this folder.":"Could not load this folder."}),s.jsxs("div",{className:"flex items-center gap-2",children:[y==="os-permission"&&U?s.jsx(Ne,{size:"xs",onClick:()=>{L()},disabled:g,children:"Grant access"}):null,s.jsx(Ne,{variant:"outline",size:"xs",onClick:()=>m(q=>q+1),children:"Try again"})]})]}):j.length===0?s.jsx("div",{className:"py-10 text-center typography-ui-label text-muted-foreground",children:"No matching directories."}):s.jsx("div",{className:"space-y-0.5",children:j.map((q,te)=>{const le=te===h,Ae=q.type==="directory"&&z;return s.jsxs("button",{ref:Se=>{Se?u.current.set(q.value,Se):u.current.delete(q.value)},type:"button","aria-label":q.type==="parent"?q.alreadyAdded?`Go back from ${q.name}, already added`:`Go back from ${q.name}`:q.alreadyAdded?`Open ${q.name}, already added`:`Open ${q.name}`,onMouseEnter:()=>b(te),onMouseDown:Se=>Se.preventDefault(),onClick:()=>K(q),className:_("flex w-full cursor-pointer items-center gap-2 rounded-lg px-2 py-1.5 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",le&&"bg-interactive-selection text-interactive-selection-foreground",!le&&"hover:bg-interactive-hover/50"),children:[s.jsxs("span",{className:_("flex min-w-0 flex-1 items-center gap-2",Ae&&"pl-4"),children:[q.type==="parent"?s.jsx(P,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}):s.jsx(P,{name:"folder-6",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80"}),s.jsx("span",{className:"truncate typography-ui-label text-foreground",children:q.name})]}),q.alreadyAdded?s.jsx("span",{className:_("inline-flex shrink-0 items-center rounded-md px-1.5 py-0.5 typography-meta font-medium",le?"bg-interactive-selection-foreground/15 text-interactive-selection-foreground":"bg-[var(--surface-muted)] text-foreground"),children:"Added"}):null,q.type==="parent"?s.jsx(P,{name:"arrow-up-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"}):s.jsx(P,{name:"arrow-right-s",className:"h-4 w-4 flex-shrink-0 text-muted-foreground/80","aria-hidden":"true"})]},q.value)})})},k)]})}),X=s.jsxs("div",{className:"flex min-h-0 flex-1 flex-col gap-3",children:[H,Q]}),ne=s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 typography-micro text-muted-foreground",children:[s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(P,{name:"arrow-up-s",className:"h-3.5 w-3.5"}),s.jsx(P,{name:"arrow-down-s",className:"-ml-1 h-3.5 w-3.5"}),"Navigate"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx(P,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Open folder"]}),s.jsxs("span",{className:"inline-flex items-center gap-1",children:[s.jsx("span",{children:be}),s.jsx(P,{name:"corner-down-left",className:"h-3.5 w-3.5"}),"Add folder"]})]}),we=s.jsx(Ne,{size:r?"xs":"default",onClick:()=>{V(w)},disabled:!G,className:_(r&&"w-full flex-1"),children:B}),me=()=>s.jsxs(s.Fragment,{children:[r?null:ne,s.jsx("div",{className:_("flex w-full flex-row justify-end gap-2 sm:w-auto",r&&"justify-stretch"),children:we})]});return r?s.jsx(Fa,{open:e,onClose:c,title:"Add folder",className:"h-[88dvh] max-h-[720px]",contentMaxHeightClassName:"flex-1",footer:s.jsx("div",{className:"flex flex-col gap-2",children:me()}),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-col gap-3",children:[s.jsx("div",{className:"flex justify-end",children:De}),X]})}):s.jsx(es,{open:e,onOpenChange:t,children:s.jsxs(ts,{className:"flex w-full max-w-xl flex-col gap-0 overflow-hidden p-0 sm:max-h-[80vh]",initialFocus:!1,children:[s.jsx(Ss,{className:"px-5 pb-2 pt-5",children:s.jsxs("div",{className:"flex items-start justify-between gap-4",children:[s.jsxs("div",{children:[s.jsx(ds,{children:"Add folder"}),s.jsx(js,{className:"mt-2",children:"Choose a folder from the path above, then add it."})]}),De]})}),s.jsx("div",{className:"min-h-0 flex-1 px-5 pb-0",children:X}),s.jsx(Ls,{className:"flex w-full flex-col gap-3 px-5 py-3 sm:flex-row sm:items-center sm:justify-between",children:me()})]})})},Hn=e=>e?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,wx=()=>{const[e,t]=a.useState(!1),[n,r]=a.useState(null),[o,i]=a.useState(!1),l=Te(C=>C.deleteSession),c=Te(C=>C.deleteSessions),d=de(C=>C.showDeletionDialog),u=de(C=>C.setShowDeletionDialog),{isMobile:f,isTablet:p,hasTouchInput:x}=dn(),y=f||p||x;a.useEffect(()=>Xu(()=>{t(!1)}),[]);const m=a.useCallback(C=>{r({sessions:C.sessions,dateLabel:C.dateLabel})},[]),h=a.useCallback(()=>{r(null),i(!1)},[]),b=a.useCallback(async C=>{if(C.sessions.length===0)return;if(C.sessions.length===1){const M=C.sessions[0];await l(M.id)?ae.success("Session deleted"):ae.error("Failed to delete session");return}const j=C.sessions.map(M=>M.id),{deletedIds:w,failedIds:N}=await c(j);if(w.length>0){const M=N.length>0?N.length===1?`${N.length} session could not be deleted.`:`${N.length} sessions could not be deleted.`:C.dateLabel?`Removed all sessions from ${C.dateLabel}.`:void 0;ae.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:Hn(M)})}N.length>0&&ae.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:Hn("Please try again in a moment.")})},[l,c]);a.useEffect(()=>Ms.onDeleteRequest(C=>{if(!d){b(C);return}m(C)}),[m,d,b]),a.useEffect(()=>Ms.onDirectoryRequest(()=>{t(!0)}),[]);const g=a.useCallback(async()=>{if(n){i(!0);try{if(n.sessions.length===1){const C=n.sessions[0];if(!await l(C.id)){ae.error("Failed to delete session"),i(!1);return}ae.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const C=n.sessions.map(M=>M.id),j=await c(C),w=j.deletedIds,N=j.failedIds;if(w.length>0){const M=N.length>0?N.length===1?`${N.length} session could not be deleted.`:`${N.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;ae.success(w.length===1?"Deleted {count} session":`Deleted ${w.length} sessions`,{description:Hn(M),action:{label:"OK",onClick:()=>{}}})}if(N.length>0&&(ae.error(N.length===1?`Failed to delete ${N.length} session`:`Failed to delete ${N.length} sessions`,{description:Hn("Please try again in a moment.")}),w.length===0)){i(!1);return}}h()}finally{i(!1)}}},[n,l,c,h]),S=n?n.sessions.length===1?n.dateLabel?`This action permanently removes 1 session from ${n.dateLabel}.`:"This action permanently removes 1 session.":n.dateLabel?`This action permanently removes ${n.sessions.length} sessions from ${n.dateLabel}.`:`This action permanently removes ${n.sessions.length} sessions.`:"",v=n?s.jsxs("div",{className:"space-y-2",children:[n.sessions.length>0&&s.jsx("div",{className:"space-y-1.5 rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsxs("ul",{className:"space-y-0.5",children:[n.sessions.slice(0,5).map(C=>s.jsx("li",{className:"typography-micro text-muted-foreground/80",children:s.jsx("span",{className:"truncate",children:xs(C)})},C.id)),n.sessions.length>5&&s.jsx("li",{className:"typography-micro text-muted-foreground/70",children:`+${n.sessions.length-5} more`})]})}),s.jsx("div",{className:"rounded-xl border border-border/40 bg-sidebar/60 p-3",children:s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,E=s.jsxs("div",{className:"flex w-full items-center justify-between gap-3",children:[s.jsxs("button",{type:"button",onClick:()=>u(!d),className:"inline-flex items-center gap-1.5 typography-meta text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!d,children:[d?s.jsx(P,{name:"checkbox-blank",className:"size-4"}):s.jsx(P,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ne,{variant:"ghost",onClick:h,disabled:o,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",onClick:g,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),k=n?.sessions.length===1?"Delete session":"Delete sessions";return s.jsxs(s.Fragment,{children:[y?s.jsx(Fa,{open:!!n,onClose:()=>{o||h()},title:k,footer:s.jsx("div",{className:"flex justify-end gap-2",children:E}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[S&&s.jsx("p",{className:"typography-meta text-muted-foreground/80",children:S}),v]})}):s.jsx(es,{open:!!n,onOpenChange:C=>{if(!C){if(o)return;h()}},children:s.jsxs(ts,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[s.jsxs(Ss,{children:[s.jsx(ds,{children:k}),S&&s.jsx(js,{children:S})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:v}),s.jsx(Ls,{className:"mt-2 gap-2 pt-1 pb-1",children:E})]})}),s.jsx(Vf,{open:e,onOpenChange:t})]})},vx=()=>{const e=Ts(t=>t.entries);return a.useEffect(()=>{for(const t of e.values())!Kd(t)||!t.receipt||(Ts.getState().markNotificationSent(t.key),ae.success("Worktree ready",{id:`worktree-ready:${t.key}`,description:t.receipt.branch||t.receipt.path}))},[e]),null},Qf=[{slug:"home",title:"Settings",group:"general",kind:"single",description:"Search and jump to common pages.",keywords:["search","settings"]},{slug:"general",title:"General",group:"general",kind:"single",keywords:["general","startup","launch at login","autostart","tray","password","passkey","security","privacy","telemetry","transport","network","lan","binary","cli","diagnostics","performance"]},{slug:"projects",title:"Projects",group:"projects",kind:"single",keywords:["project","projects","worktree","worktrees","repo","repository","directory"]},{slug:"remote-access",title:"Remote Access",group:"projects",kind:"single",description:"How other devices reach this computer.",keywords:["remote","access","mobile","phone","pair","qr","device","devices","tailscale","funnel","lan","network","wifi","password","passkey"],isAvailable:e=>!e.isMobile&&(e.isDesktop||e.isWeb)},{slug:"servers",title:"Servers",group:"projects",kind:"single",description:"Which PiChamber server this app uses.",keywords:["server","servers","instance","switch","connect","import link","host"],isAvailable:e=>!e.isMobile&&e.isDesktop||e.isMobile&&e.isCapacitor===!0},{slug:"remote-instances",title:"Remote Instances",group:"projects",kind:"single",keywords:["ssh","remote","instances","tunnels","forwarding","connection"],isAvailable:()=>!1},{slug:"providers",title:"Providers",group:"agent",kind:"single",keywords:["provider","providers","models","model","api key","api keys","openai","anthropic","ollama","credentials"]},{slug:"behavior",title:"Behavior",group:"agent",kind:"single",keywords:["behavior","agents.md","system prompt","global rules","instructions","override"]},{slug:"skills.installed",title:"Skills",group:"agent",kind:"single",keywords:["skill","skills","instructions","install","catalog"]},{slug:"git",title:"Git",group:"projects",kind:"single",keywords:["git","github","ssh","commit","oauth","prs","issues"]},{slug:"appearance",title:"Appearance",group:"general",kind:"single",keywords:["theme","font","spacing","padding","corner radius","radius","input bar","keyboard","viewport","mobile","terminal","pwa","install name","app shortcuts"]},{slug:"chat",title:"Chat",group:"general",kind:"single",keywords:["tools","diff","reasoning","dotfiles","draft","queue","output","copy","image","split messages","message actions"]},{slug:"dictation",title:"Dictation",group:"general",kind:"single",description:"Record speech and insert a final transcript into the composer.",keywords:["voice","speech","microphone","transcription","stt","whisper","parakeet"]},{slug:"shortcuts",title:"Shortcuts",group:"general",kind:"single",keywords:["keyboard","hotkeys","shortcuts","bindings"]},{slug:"sessions",title:"Sessions",group:"general",kind:"single",keywords:["defaults","default agent","default model","retention","memory","limits","zen"]},{slug:"snippets",title:"Snippets",group:"agent",kind:"single",keywords:["snippet","snippets","text expansion"]},{slug:"prompt-templates",title:"Prompt templates",group:"agent",kind:"single",keywords:["prompt template","prompt templates","slash command","slash commands"]},{slug:"notifications",title:"Notifications",group:"general",kind:"single",keywords:["alerts","native","summary","summarization"]},{slug:"tunnel",title:"External Tunnel",group:"projects",kind:"single",keywords:["tunnel","external","cloudflare","qr","remote","mobile","share"],isAvailable:()=>!1},{slug:"about",title:"About",group:"general",kind:"single",keywords:["about","version","updates","release","changelog","pi","pichamber","open source"]}],Jf={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function Xf(e){const t=e.trim().toLowerCase();return Qf.find(n=>n.slug===t)??null}function Zf(e){const t=(e??"").trim().toLowerCase();if(!t)return"home";if(t==="remote-instances")return"remote-access";const n=Jf[t];if(n)return n;const r=Xf(t);return r?r.slug:"home"}function Sx(e){switch(e){case"general":return"equalizer";case"projects":return"folders";case"remote-access":return"server";case"servers":return"server";case"remote-instances":return"server";case"appearance":return"brush";case"chat":return"chat-1";case"dictation":return"voiceprint";case"snippets":return"sticky-note";case"prompt-templates":return"terminal-box";case"notifications":return"notification-3";case"shortcuts":return"command";case"sessions":return"history";case"providers":return"cloud";case"behavior":return"brain";case"skills.installed":return"puzzle";case"git":return"git-repository";case"tunnel":return"global";case"about":return"pichamber";case"home":return null;default:return"robot-2"}}function jx(){const e=a.useRef(!1),t=a.useRef(!1),n=Te(f=>f.setCurrentSession),r=de(f=>f.setActiveMainTab),o=de(f=>f.setSettingsDialogOpen),i=de(f=>f.setSettingsPage),l=de(f=>f.navigateToDiff),c=a.useCallback(async f=>{if(!t.current){t.current=!0;try{if(f.sessionId){const p=Te.getState().currentSessionId,x=Js().getState().selectedSessionId;if(f.sessionId!==p||f.sessionId!==x){const y=Te.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,y)}}if(f.settingsPath){i(Zf(f.settingsPath)),o(!0);return}de.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&l(f.diffFile)}finally{t.current=!1}}},[n,r,o,i,l]),d=a.useCallback(()=>{const f=Te.getState(),p=Js().getState(),x=de.getState();return{sessionId:Or({currentSessionId:f.currentSessionId,piSelectedSessionId:p.selectedSessionId,draft:f.newSessionDraft}),tab:x.activeMainTab,isSettingsOpen:x.isSettingsDialogOpen,settingsPath:x.settingsPage,diffFile:x.pendingDiffFile}},[]),u=a.useCallback((f={})=>{if(t.current)return;const p=d();bo(p,f)},[d]);a.useEffect(()=>{if(e.current||(e.current=!0,!vi()))return;const f=Si();(async()=>(await c(f),bo({...d(),sessionId:f.sessionId??Or({currentSessionId:Te.getState().currentSessionId,piSelectedSessionId:Js().getState().selectedSessionId,draft:Te.getState().newSessionDraft}),tab:f.tab??de.getState().activeMainTab,settingsPath:f.settingsPath??de.getState().settingsPage,diffFile:f.diffFile??de.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),a.useEffect(()=>{const f=()=>{const b=Te.getState(),g=Js().getState();return Or({currentSessionId:b.currentSessionId,piSelectedSessionId:g.selectedSessionId,draft:b.newSessionDraft})};let p=f(),x=Te.getState().newSessionDraft?.open===!0;const y=()=>{const b=Te.getState(),g=f(),S=b.newSessionDraft?.open===!0;g===p&&S===x||t.current||(p=g,x=S,u({replace:!0}))},m=Te.subscribe(()=>{y()}),h=Js().subscribe(()=>{y()});return()=>{m(),h()}},[u]),a.useEffect(()=>{let f=de.getState().activeMainTab,p=de.getState().isSettingsDialogOpen,x=de.getState().settingsPage,y=de.getState().pendingDiffFile;return de.subscribe(h=>{if(t.current)return;const b=h.activeMainTab!==f,g=h.isSettingsDialogOpen!==p,S=h.settingsPage!==x,v=h.pendingDiffFile!==y&&h.activeMainTab==="diff";f=h.activeMainTab,p=h.isSettingsDialogOpen,x=h.settingsPage,y=h.pendingDiffFile,(b||g||S||v)&&u()})},[u]),a.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const p=Si();if(vi())c(p);else{const x=de.getState();x.isSettingsDialogOpen&&o(!1),x.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function eh(e=!0){const t=tr(r=>r.checkForUpdates),n=a.useRef(t);a.useEffect(()=>{n.current=t},[t]),a.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,i=300*1e3,l=1440*60*1e3;let c=!1,d=null;const u=p=>{const x=Math.round(p*1e3);return Math.max(i,Math.min(l,x))},f=p=>{c||(d=window.setTimeout(async()=>{const x=await n.current(),y=typeof x=="number"&&Number.isFinite(x)?u(x):o;f(y)},p))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function Cx(){const e=Nn(t=>t.connection==="ready",void 0,"chrome");return eh(e),null}const Ti=12,th=[{id:"left",x:22,y:58,delay:0,radius:120,colorVar:"--status-success"},{id:"center",x:50,y:42,delay:120,radius:150,colorVar:"--primary-base"},{id:"right",x:78,y:55,delay:200,radius:130,colorVar:"--status-info"}],sh=({isActive:e,burstKey:t=0,className:n,durationMs:r=900,bursts:o=th,onComplete:i})=>{const l=Re.useRef(!1);Re.useEffect(()=>{!e&&l.current&&i?.(),e&&(l.current=!0)},[e,i]);const c=Re.useMemo(()=>Array.from({length:Ti},(d,u)=>{const f=Math.PI*2*u/Ti;return{x:Math.cos(f),y:Math.sin(f),delay:u*18}}),[]);return e?s.jsx("div",{className:_("fireworks-overlay pointer-events-none",n),"aria-hidden":"true","data-burst-key":t,children:o.map(d=>{const u={"--burst-delay":`${d.delay}ms`,"--burst-x":`${d.x}%`,"--burst-y":`${d.y}%`,"--firework-color":`var(${d.colorVar})`,"--firework-duration":`${r}ms`};return s.jsx("div",{className:"firework-burst",style:u,children:c.map((f,p)=>{const x=f.x*d.radius,y=f.y*d.radius,m={"--translate-x":`${x}px`,"--translate-y":`${y}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return s.jsx("span",{className:"firework-particle",style:m},`${d.id}-${p}-${t}`)})},`${d.id}-${t}`)})}):null},nh=({durationMs:e=3400}={})=>{const[t,n]=Re.useState({isActive:!1,cycle:0}),r=Re.useRef(null),o=Re.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),i=Re.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),l=Re.useCallback(()=>{o(),n(c=>({isActive:!0,cycle:c.cycle+1})),r.current=window.setTimeout(()=>{n(c=>c.isActive?{...c,isActive:!1}:c),r.current=null},e)},[o,e]);return Re.useEffect(()=>()=>o(),[o]),{isActive:t.isActive,burstKey:t.cycle,triggerFireworks:l,dismissFireworks:i}},yl=a.createContext(void 0),kx=({children:e})=>{const{isActive:t,burstKey:n,triggerFireworks:r,dismissFireworks:o}=nh(),i=a.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return s.jsxs(yl.Provider,{value:i,children:[e,s.jsx(sh,{isActive:t,burstKey:n})]})},rh={triggerFireworks:()=>{},dismissFireworks:()=>{}},Ax=()=>a.useContext(yl)??rh,fr=2e3,wl=600*1e3;async function oh(){try{const e=await Mt("/api/pi/update-install",{method:"POST",headers:{"Content-Type":"application/json"}});if(!e.ok){const n=await e.json().catch(()=>({}));return{success:!1,error:n.error||`Server error: ${e.status}`,commands:Array.isArray(n.commands)?n.commands.filter(r=>typeof r=="string"):void 0}}const t=await e.json().catch(()=>({}));return{success:!0,autoRestart:t.autoRestart!==!1,jobId:typeof t.jobId=="string"?t.jobId:void 0,channel:t.channel==="rc"?"rc":t.channel==="stable"?"stable":void 0,targetVersion:typeof t.targetVersion=="string"?t.targetVersion:void 0}}catch(e){return{success:!1,error:e instanceof Error?e.message:void 0}}}async function ih(e,t=Math.ceil(wl/fr),n=fr,r=Xe()){for(let o=0;o<t;o++){if(Xe()!==r)return{applied:!1,stale:!0};try{const i=await Mt("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(Xe()!==r)return{applied:!1,stale:!0};if(i.ok){const l=await i.json().catch(()=>null);if(Xe()!==r)return{applied:!1,stale:!0};if(typeof l?.error=="string"&&l.error.length>0)return{applied:!1,error:l.error};if(l&&l.available===!1)return{applied:!0};if(l&&typeof l.currentVersion=="string"&&typeof e=="string"&&l.currentVersion!==e)return{applied:!0}}else if(i.status===401||i.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."}}catch{if(Xe()!==r)return{applied:!1,stale:!0}}await new Promise(i=>setTimeout(i,n))}return{applied:!1}}async function ah(e,t,n=Math.ceil(wl/fr),r=fr,o=Xe()){for(let i=0;i<n;i++){if(Xe()!==o)return{applied:!1,stale:!0};try{const l=await Mt(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(Xe()!==o)return{applied:!1,stale:!0};if(l.ok){const c=await l.json().catch(()=>null);if(Xe()!==o)return{applied:!1,stale:!0};if(c?.state==="complete")return{applied:!0};if(c?.state==="failed")return{applied:!1,error:c.error||"Update failed"};c?.state==="restarting"?t("restarting"):(c?.state==="queued"||c?.state==="installing"||c?.state==="verifying")&&t("updating")}else{if(l.status===401||l.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(l.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(l.status===503){const c=await l.json().catch(()=>null);if(Xe()!==o)return{applied:!1,stale:!0};if(c?.error==="Update status is unavailable")return{applied:!1,error:c.error};t("reconnecting")}else t("reconnecting")}}catch{if(Xe()!==o)return{applied:!1,stale:!0};t("reconnecting")}await new Promise(l=>setTimeout(l,r))}return{applied:!1}}const Fi="https://github.com/RyderAsKing/PiChamber/releases";function lh(e){const t=new Date(`${e}T00:00:00`);return Number.isNaN(t.getTime())?e:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"short",day:"numeric"}).format(t)}function ch(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Li(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function dh(e,t){const n=u=>{const f=u.indexOf("-");return f<0?[u,""]:[u.slice(0,f),u.slice(f+1)]},[r,o]=n(e),[i,l]=n(t),c=r.split(".").map(u=>Number.parseInt(u,10)),d=i.split(".").map(u=>Number.parseInt(u,10));for(let u=0;u<3;u+=1){const f=Number.isFinite(c[u])?c[u]:0,p=Number.isFinite(d[u])?d[u]:0;if(f!==p)return p-f}return!o||!l?(o?1:0)-(l?1:0):l.localeCompare(o,void 0,{numeric:!0})}function uh(e){const t=/^## \[(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\] - (\d{4}-\d{2}-\d{2})\s*$/gm,n=[];let r;for(;(r=t.exec(e))!==null;)n.push({version:r[1]??"",date:r[2]??"",start:r.index});return n.length===0?[]:n.map((o,i)=>{const l=n[i+1]?.start??e.length,c=e.slice(o.start,l).trim();return{version:o.version,date:o.date,start:o.start,end:l,raw:c}})}const vl=({open:e,onOpenChange:t,info:n,downloading:r,downloaded:o,progress:i,error:l,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,p]=Re.useState(null),[x,y]=Re.useState("idle"),[m,h]=Re.useState(null),[b,g]=Re.useState(null),[S,v]=Re.useState({}),E=n?.version?n.releaseUrl||`${Fi}/tag/v${n.version}`:Fi,k=n?.downloadUrl||E,C=i?.total?Math.round(i.downloaded/i.total*100):0,j=u==="web",w=u==="mobile",N=n?.updateCommand||"pichamber update",M=S.version||n?.version,F=S.channel||n?.channel;Re.useEffect(()=>{e||(y("idle"),h(null),g(null),v({}))},[e]);const $=async(I=N)=>{(await ws(I)).ok&&(p(I),setTimeout(()=>p(null),2e3))},U=Re.useCallback(async I=>{await La(I)},[]),K=Re.useCallback(async()=>{const I=Xe();y("updating"),h(null),g(null),v({});const T=await oh();if(Xe()!==I)return;if(!T.success){y("error"),h(T.error||"Update failed"),g(T.commands??null);return}if(v({version:T.targetVersion,channel:T.channel}),T.jobId){const G=await ah(T.jobId,B=>{Xe()===I&&y(B)},void 0,void 0,I);if(G.stale||Xe()!==I)return;if(G.applied){window.location.reload();return}y("error"),h(G.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}y(T.autoRestart?"restarting":"reconnecting");const W=await ih(n?.currentVersion,void 0,void 0,I);if(!(W.stale||Xe()!==I)){if(W.applied){window.location.reload();return}y("error"),h(W.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[n?.currentVersion]),L=Re.useCallback(()=>{U(k)},[U,k]),D=x!=="idle"&&x!=="error",R=Re.useMemo(()=>{if(!n?.body)return null;const I=n.body.trim();if(!I)return null;const T=uh(I);return T.length===0?{kind:"raw",title:"What's new",content:Li(I)}:{kind:"sections",title:"What's new",sections:[...T].sort((G,B)=>dh(G.version,B.version)).map(G=>({version:G.version,dateLabel:lh(G.date),content:Li(ch(G.raw)||I)}))}},[n?.body]);return s.jsx(es,{open:e,onOpenChange:D?void 0:t,children:s.jsxs(ts,{className:"max-w-4xl p-4 sm:p-5 bg-background border-[var(--interactive-border)]",showCloseButton:!0,children:[s.jsxs("div",{className:"mb-1 space-y-1 pr-8",children:[s.jsxs(ds,{className:"flex items-center gap-2.5",children:[s.jsx(P,{name:"download-cloud",className:"h-5 w-5 shrink-0 text-[var(--primary-base)]"}),s.jsx("span",{className:"text-lg font-semibold text-foreground",children:x==="restarting"||x==="reconnecting"?"Updating PiChamber...":"Update available"})]}),(n?.currentVersion||M||j&&F)&&s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pl-[1.875rem]",children:[(n?.currentVersion||M)&&s.jsxs("div",{className:"flex items-center gap-2 whitespace-nowrap font-mono text-sm",children:[n?.currentVersion&&s.jsx("span",{className:"text-muted-foreground",children:n.currentVersion}),n?.currentVersion&&M&&s.jsx("span",{className:"text-muted-foreground/50","aria-hidden":"true",children:"→"}),M&&s.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:M})]}),j&&F&&s.jsx("span",{className:"whitespace-nowrap typography-meta text-muted-foreground",children:F==="rc"?"RC channel":"Stable channel"})]})]}),s.jsxs("div",{className:"space-y-2",children:[j&&D&&s.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/30 p-5 border border-[var(--surface-subtle)]",children:[s.jsxs("div",{className:"flex items-center gap-3",children:[s.jsx(P,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),s.jsxs("div",{className:"typography-ui-label text-foreground",children:[x==="updating"&&"Installing update...",x==="restarting"&&"Server restarting...",x==="reconnecting"&&"Waiting for server..."]})]}),s.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:"The page will reload automatically when the update is complete."})]}),R&&!D&&s.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:s.jsx(Is,{className:"max-h-[min(400px,50dvh)] p-0",fillContainer:!1,children:R.kind==="raw"?s.jsx("div",{className:"p-4 typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:I=>{const W=I.target.closest("a");W&&W.href&&(I.preventDefault(),I.stopPropagation(),U(W.href))},children:s.jsx(ji,{content:R.content,disableLinkSafety:!0,enableFileReferences:!1})}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:R.sections.map(I=>s.jsxs("div",{className:"p-4",children:[s.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[s.jsxs("span",{className:"typography-ui-label font-mono text-[var(--primary-base)] bg-[var(--primary-base)]/10 px-1.5 py-0.5 rounded",children:["v",I.version]}),s.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:I.dateLabel})]}),s.jsx("div",{className:"typography-markdown-body text-foreground leading-relaxed break-words [&_a]:!text-[var(--primary-base)] [&_a]:!no-underline [&_a:hover]:!underline",onClickCapture:T=>{const G=T.target.closest("a");G&&G.href&&(T.preventDefault(),T.stopPropagation(),U(G.href))},children:s.jsx(ji,{content:I.content,disableLinkSafety:!0,enableFileReferences:!1})})]},I.version))})})}),(l||m)&&s.jsx("div",{className:"p-3 mt-4 bg-[var(--status-error-background)] border border-[var(--status-error-border)] rounded-lg",children:s.jsx("p",{className:"text-sm text-[var(--status-error)]",children:l||m})}),j&&x==="error"&&(b??[N]).length>0&&s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsxs("div",{className:"flex items-center gap-2 typography-meta text-muted-foreground",children:[s.jsx(P,{name:"terminal",className:"h-4 w-4"}),s.jsx("span",{children:b?"Run these commands:":"Or update via terminal:"})]}),(b??[N]).map(I=>s.jsxs("div",{className:"flex items-center gap-2 p-1 pl-3 bg-[var(--surface-elevated)]/50 rounded-md border border-[var(--surface-subtle)]",children:[s.jsx("code",{className:"flex-1 font-mono text-sm text-foreground overflow-x-auto whitespace-nowrap",children:I}),s.jsx(Ne,{variant:"ghost",size:"icon",onClick:()=>{$(I)},className:f===I?"text-[var(--status-success)]":void 0,title:f===I?"Copied!":"Copy command","aria-label":f===I?"Copied!":"Copy command",children:f===I?s.jsx(P,{name:"check",className:"h-4 w-4"}):s.jsx(P,{name:"clipboard",className:"h-4 w-4"})})]},I))]}),!j&&!w&&r&&s.jsxs("div",{className:"space-y-2 mt-4",children:[s.jsxs("div",{className:"flex items-center justify-between text-sm",children:[s.jsx("span",{className:"text-muted-foreground",children:"Downloading update payload..."}),s.jsxs("span",{className:"font-mono text-foreground",children:[C,"%"]})]}),s.jsx("div",{className:"h-1.5 bg-[var(--surface-subtle)] rounded-full overflow-hidden",children:s.jsx("div",{className:"h-full bg-[var(--primary-base)] transition-all duration-300",style:{width:`${C}%`}})})]})]}),s.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[s.jsxs("a",{href:E,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground transition-colors shrink-0",children:[s.jsx(P,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),s.jsxs("div",{className:"flex-1 flex justify-end",children:[!j&&!w&&!o&&!r&&s.jsxs(Ne,{onClick:c,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Download update"]}),!j&&!w&&r&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!j&&!w&&o&&s.jsxs("button",{onClick:d,className:"flex items-center justify-center gap-2 px-5 py-2 rounded-md text-sm font-medium bg-[var(--status-success)] text-white hover:opacity-90 transition-opacity",children:[s.jsx(P,{name:"restart",className:"h-4 w-4"}),"Restart to Update"]}),w&&s.jsxs(Ne,{onClick:L,size:"default",children:[s.jsx(P,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),j&&!D&&s.jsxs(Ne,{onClick:K,children:[s.jsx(P,{name:"download",className:"h-4 w-4"}),"Update now"]}),j&&D&&s.jsxs(Ne,{disabled:!0,children:[s.jsx(P,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},Sl=a.memo(function({checked:t,onChange:n,disabled:r=!1,ariaLabel:o,decorative:i=!1,className:l,iconClassName:c}){const d=a.useCallback(x=>{x.preventDefault(),x.stopPropagation(),!r&&!t&&n()},[t,r,n]),u=a.useCallback(x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),!r&&!t&&n())},[t,r,n]),f=s.jsx("span",{"aria-hidden":!0,className:_("block h-[5px] w-[5px] rounded-full bg-white",!t&&"opacity-0",c)}),p=_("relative flex h-[14px] w-[14px] min-h-[14px] min-w-[14px] shrink-0 self-center items-center justify-center rounded-full","transition-[background-color,box-shadow] duration-200 ease-out",t?"bg-[color-mix(in_srgb,var(--primary-base)_80%,transparent)] shadow-none":"bg-[var(--surface-muted)] shadow-[inset_0_0_0_1px_var(--interactive-border)]");return i?s.jsx("span",{"aria-hidden":!0,className:_(p,r&&"opacity-50",l),children:f}):s.jsx("button",{type:"button",role:"radio",onClick:d,onKeyDown:u,disabled:r,"aria-checked":t,"aria-label":o,className:_("group/radio outline-none",p,t?"hover:bg-[var(--primary-base)]":"hover:bg-[var(--interactive-hover)]","focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background","disabled:cursor-not-allowed disabled:opacity-50",l),children:f})}),_n=({children:e,className:t,contentClassName:n})=>{const[r,o]=a.useState(!1),i=a.useRef(null);return a.useEffect(()=>{if(!r)return;const l=c=>{const d=i.current;d&&c.target instanceof Node&&d.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",l,!0),()=>document.removeEventListener("pointerdown",l,!0)},[r]),s.jsxs(Ue,{open:r,onOpenChange:o,children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{ref:i,type:"button","aria-label":"More information","aria-expanded":r,onClick:l=>{l.preventDefault(),l.stopPropagation(),o(c=>!c)},className:_("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-muted-foreground/60 hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t),children:s.jsx(P,{name:"information",className:"h-3.5 w-3.5"})})}),s.jsx(Ke,{sideOffset:8,className:_("max-w-sm",n),children:e})]})},Nx="w-full min-w-40 max-w-48",Ix="settings",fh="w-full min-w-40 max-w-48",Ex="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",hh="w-full max-w-[24rem]",Rx="min-w-0 flex-1",Dx="flex w-full min-w-0 items-center gap-2",Px="typography-meta shrink-0 text-muted-foreground tabular-nums",jl="space-y-3.5",mh="space-y-1.5",Mx="typography-settings-page-title text-muted-foreground",ph="typography-settings-section-title text-foreground",Cl="typography-settings-group-title text-foreground",qo="typography-settings-field-label text-foreground",gh="typography-settings-description text-muted-foreground",zn="typography-meta text-muted-foreground",Tx="typography-meta font-medium text-foreground",Fx="typography-settings-section-title text-foreground",bh=({title:e,description:t,titleAccessory:n,info:r,headerAction:o,children:i,divider:l=!0,className:c,contentClassName:d,settingsItem:u})=>{const f=e!=null||t!=null||o!=null||r!=null;return s.jsxs("section",{"data-settings-item":u,className:_("space-y-4",l?"border-t border-border/60 py-6":"pb-6",c),children:[f?s.jsxs("div",{className:"flex items-start justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0 space-y-1",children:[e!=null?s.jsxs("div",{className:"flex items-center gap-2",children:[typeof e=="string"||typeof e=="number"?s.jsx("h2",{className:ph,children:e}):e,n,r!=null?s.jsx(_n,{children:r}):null]}):null,t!=null?s.jsx("div",{className:gh,children:t}):null]}),o?s.jsx("div",{className:"shrink-0",children:o}):null]}):null,s.jsx("div",{className:_(d),children:i})]})},Lx=({children:e,className:t})=>s.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",t),children:e}),xh=({children:e,className:t,as:n="h3"})=>s.jsx(n,{className:_(Cl,t),children:e}),Ox=({title:e,description:t,info:n,children:r,className:o,contentClassName:i,settingsItem:l})=>s.jsxs("div",{"data-settings-item":l,className:_("space-y-2",o),children:[e!=null||t!=null||n!=null?s.jsxs("div",{className:"space-y-0.5",children:[e!=null?s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx(xh,{children:e}),n!=null?s.jsx(_n,{children:n}):null]}):null,t!=null?s.jsx("p",{className:zn,children:t}):null]}):null,s.jsx("div",{className:_(i),children:r})]}),Rn=({label:e,description:t,info:n,descriptionPlacement:r="before",children:o,settingsItem:i,className:l,controlClassName:c})=>{const d=t!=null?s.jsx("p",{className:zn,children:t}):null;return s.jsxs("div",{"data-settings-item":i,className:_("space-y-2",l),children:[s.jsxs("div",{className:"space-y-0.5",children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:qo,children:e}),n!=null?s.jsx(_n,{children:n}):null]}),r==="before"?d:null]}),s.jsx("div",{className:_("flex min-w-0 max-w-[24rem] items-center gap-2",c),children:o}),r==="after"?d:null]})},Bx=({label:e,description:t,info:n,children:r,settingsItem:o,className:i,labelClassName:l,controlClassName:c,alignEnd:d=!0})=>s.jsxs("div",{"data-settings-item":o,className:_("flex flex-col gap-2 py-0.5 @xl:flex-row @xl:items-center @xl:gap-8",i),children:[s.jsxs("div",{className:_("min-w-0 @xl:w-56 @xl:shrink-0",l),children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:qo,children:e}),n!=null?s.jsx(_n,{children:n}):null]}),t!=null?s.jsx("p",{className:_(zn,"mt-0.5"),children:t}):null]}),s.jsx("div",{className:_("flex min-w-0 flex-1 items-center gap-2 @xl:w-fit @xl:flex-none",d&&"@xl:justify-end",c),children:r})]}),_x=({children:e,className:t,settingsItem:n})=>s.jsx("div",{"data-settings-item":n,className:_("pt-4",t),children:e}),zx=({label:e,children:t,divider:n=!0,className:r,contentClassName:o})=>s.jsxs("details",{className:_("group/disclosure",n?"border-t border-border/60 py-6":"pb-6",r),children:[s.jsxs("summary",{className:"flex w-fit cursor-pointer list-none items-center gap-1.5 rounded-md typography-ui-label text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] [&::-webkit-details-marker]:hidden",children:[s.jsx(P,{name:"arrow-right-s",className:"size-4 transition-transform group-open/disclosure:rotate-90"}),e]}),s.jsx("div",{className:_("pt-4",o),children:t})]}),yh=({checked:e,onChange:t,label:n,description:r,disabled:o=!1,ariaLabel:i,settingsItem:l,className:c,labelAccessory:d,info:u})=>{const f=()=>{o||t(!e)},p=r!=null;return s.jsxs("div",{"data-settings-item":l,className:_("group flex cursor-pointer gap-2 py-0.5",p?"items-start":"items-center",o&&"cursor-not-allowed opacity-60",c),role:"button",tabIndex:o?-1:0,"aria-pressed":e,"aria-disabled":o||void 0,onClick:f,onKeyDown:x=>{(x.key===" "||x.key==="Enter")&&(x.preventDefault(),f())},children:[s.jsx(oo,{checked:e,onChange:t,disabled:o,ariaLabel:i}),s.jsxs("div",{className:"flex min-w-0 flex-col",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx("span",{className:qo,children:n}),d,u!=null?s.jsx(_n,{children:u}):null]}),p?s.jsx("span",{className:zn,children:r}):null]})]})},Ux=({selected:e,onSelect:t,label:n,description:r,ariaLabel:o,disabled:i=!1,className:l})=>s.jsxs("div",{className:_("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",l),role:"button",tabIndex:i?-1:0,"aria-pressed":e,"aria-disabled":i||void 0,onClick:()=>{i||t()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),i||t())},children:[s.jsx(Sl,{checked:e,onChange:t,disabled:i,ariaLabel:o,className:r!=null?"mt-0.5":void 0}),s.jsxs("div",{className:"flex min-w-0 flex-col",children:[s.jsx("span",{className:_("typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n}),r!=null?s.jsx("span",{className:zn,children:r}):null]})]}),$x=({selected:e,onSelect:t,label:n,preview:r,ariaLabel:o,disabled:i=!1,className:l})=>s.jsxs("div",{className:_("group/preview flex min-w-0 cursor-pointer flex-col gap-2",i&&"cursor-not-allowed opacity-60",l),role:"radio",tabIndex:i?-1:0,"aria-checked":e,"aria-label":o,"aria-disabled":i||void 0,onClick:()=>{i||t()},onKeyDown:c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),i||t())},children:[s.jsx("div",{"aria-hidden":!0,className:_("aspect-[4/3] overflow-hidden rounded-lg border transition-colors",e?"border-[var(--primary-base)] ring-1 ring-[var(--primary-base)]":"border-border group-hover/preview:border-foreground/30"),children:r}),s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx(Sl,{checked:e,onChange:t,disabled:i,decorative:!0}),s.jsx("span",{className:_("min-w-0 truncate typography-settings-field-label font-normal",e?"text-foreground":"text-foreground/50"),children:n})]})]}),Kx=({"aria-label":e,children:t,className:n})=>s.jsx("div",{role:"radiogroup","aria-label":e,className:_(mh,n),children:t});function Wx({value:e,options:t,onChange:n,className:r,"aria-label":o}){return s.jsx("div",{role:"group","aria-label":o,className:_("flex flex-wrap items-center gap-1",r),children:t.map(i=>s.jsx(Ne,{type:"button",variant:"chip",size:"xs",disabled:i.disabled,"aria-pressed":e===i.value,className:"!font-normal",onClick:()=>n(i.value),children:i.label},i.value))})}const vo="pichamber:server-update-channel-changed",Gx=()=>{typeof window<"u"&&window.dispatchEvent(new Event(vo))},wh=e=>typeof window>"u"?()=>{}:(window.addEventListener(vo,e),()=>window.removeEventListener(vo,e));class vh extends a.Component{constructor(t){super(t),this.state={hasError:!1}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){this.setState({error:t,errorInfo:n})}handleReset=()=>{this.setState({hasError:!1,error:void 0,errorInfo:void 0})};render(){return this.state.hasError?s.jsx("div",{className:"flex items-center justify-center min-h-screen p-4",children:s.jsxs(Wd,{className:"w-full max-w-md",children:[s.jsx(Gd,{className:"text-center",children:s.jsxs(Hd,{className:"flex items-center justify-center gap-2 text-destructive",children:[s.jsx(P,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),s.jsxs(qd,{className:"space-y-4",children:[s.jsx("p",{className:"text-sm text-muted-foreground text-center",children:this.props.texts.description}),this.props.sessionId&&s.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:[this.props.texts.sessionLabel,": ",this.props.sessionId]}),this.state.error&&s.jsxs("details",{className:"text-xs font-mono bg-muted p-3 rounded",children:[s.jsx("summary",{className:"cursor-pointer hover:bg-interactive-hover/80",children:this.props.texts.detailsSummary}),s.jsx("pre",{className:"mt-2 max-h-48 overflow-auto",children:this.state.error.toString()})]}),s.jsx("div",{className:"flex gap-2",children:s.jsxs(Ne,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[s.jsx(P,{name:"restart",className:"h-4 w-4 mr-2"}),this.props.texts.resetAction]})}),s.jsx("div",{className:"text-xs text-muted-foreground text-center",children:this.props.texts.persistentHint})]})]})}):this.props.children}}function Sh(e){return s.jsx(vh,{...e,texts:{title:"Chat Error",description:"The chat interface encountered an error. This might be due to a temporary network issue or corrupted message data.",sessionLabel:"Session",detailsSummary:"Error details",resetAction:"Reset Chat",persistentHint:"If the problem persists, try refreshing the page."}})}const Hx=({active:e=!0})=>{const t=Te(n=>n.currentSessionId);return s.jsx(Sh,{sessionId:t||void 0,children:s.jsx(Yd,{active:e},t??"no-session")})};function jh({onResizeStart:e,ariaLabel:t}){return s.jsx("div",{role:"separator","aria-orientation":"horizontal","aria-label":t,onPointerDown:e,className:"pointer-events-auto -m-2 flex size-7 cursor-ns-resize items-end justify-end p-2 touch-none select-none",children:s.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg","aria-hidden":!0,children:s.jsx("path",{d:"M9.11111 2L2 9.11111M10 6.44444L6.44444 10",className:"stroke-muted-foreground",strokeLinecap:"round"})})})}const kl=Re.forwardRef(({className:e,outerClassName:t,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:i,hasError:l,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:p,...x},y)=>{const m=Re.useRef(null),h=Re.useRef(null),[b,g]=Re.useState(null),S=c??b,v=Re.useCallback(k=>{const C=m.current;if(!C)return;h.current={startY:k.clientY,startHeight:C.getBoundingClientRect().height};const j=k.currentTarget;j.setPointerCapture(k.pointerId);const w=M=>{const F=h.current;if(!F)return;const $=F.startHeight+(M.clientY-F.startY),U=Math.max(82,$);d?d(U):g(U)},N=()=>{h.current=null,j.removeEventListener("pointermove",w),j.removeEventListener("pointerup",N),j.removeEventListener("pointercancel",N)};j.addEventListener("pointermove",w),j.addEventListener("pointerup",N),j.addEventListener("pointercancel",N),k.preventDefault()},[d]),E=Re.useCallback(k=>{if(k.target.closest('textarea, button, [role="separator"]'))return;const j=m.current?.querySelector("textarea");j&&document.activeElement!==j&&(k.preventDefault(),j.focus())},[]);return f?s.jsx(Is,{as:"textarea",ref:y,disableHorizontal:!0,fillContainer:r,useScrollShadow:o,scrollShadowSize:i,outerClassName:t,scrollbarClassName:n,className:_("block w-full appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","px-3 py-2 md:typography-ui-label","placeholder:text-muted-foreground focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",r?"[field-sizing:fixed]":"field-sizing-content",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}):s.jsx("div",{ref:m,onPointerDown:E,style:S!==null?{height:`${S}px`}:void 0,className:_("group/textarea relative flex w-full flex-col rounded-[var(--radius-xl)] bg-[var(--surface-elevated)] pb-2.5","ring-1 ring-inset ring-border/60 transition duration-200 ease-out","hover:[&:not(:focus-within)]:bg-[var(--surface-subtle)]","has-[[disabled]]:pointer-events-none has-[[disabled]]:bg-[var(--surface-subtle)] has-[[disabled]]:ring-transparent",!l&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],l&&["ring-[var(--status-error)]","focus-within:ring-2 focus-within:ring-[var(--status-error)]"],t),children:s.jsxs("div",{className:"flex h-full min-h-0 flex-1 flex-col gap-2",children:[s.jsx("textarea",{ref:y,className:_("block w-full flex-1 min-h-0 appearance-none resize-none bg-transparent text-foreground typography-markdown outline-none","min-h-[82px] pl-3 pr-2.5 pt-2.5 md:typography-ui-label","focus-visible:outline-none disabled:cursor-not-allowed",!u&&["placeholder:select-none placeholder:text-muted-foreground placeholder:transition placeholder:duration-200 placeholder:ease-out","group-hover/textarea:placeholder:text-foreground/80","focus:placeholder:text-foreground/80"],u&&"text-muted-foreground/60 placeholder:text-muted-foreground/60",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...x}),s.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[p,s.jsx(jh,{onResizeStart:v,ariaLabel:"Resize textarea"})]})]})})});kl.displayName="Textarea";const Al=[{key:"play",label:"Play",Icon:"play"},{key:"build",label:"Build",Icon:"hammer"},{key:"lint",label:"Lint",Icon:"checkbox-circle"},{key:"terminal",label:"Terminal",Icon:"terminal-box"},{key:"tools",label:"Tools",Icon:"tools"},{key:"bug",label:"Bug",Icon:"bug"},{key:"flask",label:"Flask",Icon:"flask"},{key:"rocket",label:"Rocket",Icon:"rocket"},{key:"code",label:"Code",Icon:"code"},{key:"server",label:"Server",Icon:"server"},{key:"branch",label:"Branch",Icon:"git-branch"},{key:"search",label:"Search",Icon:"search"},{key:"settings",label:"Settings",Icon:"settings-3"},{key:"brain",label:"Brain",Icon:"brain-ai-3"},{key:"stack",label:"Stack",Icon:"stack"},{key:"robot",label:"Robot",Icon:"robot-2"},{key:"command",label:"Command",Icon:"command"},{key:"file",label:"File",Icon:"file-text"}],Dn=Object.fromEntries(Al.map(e=>[e.key,e.Icon])),So="pichamber:project-actions-updated",Nl=e=>{const t=(e||"").trim().replace(/\\/g,"/");return t?t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t:""},as=(e,t)=>`${Nl(e)}::${t}`,Il=({title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,children:l,className:c,contentClassName:d,divider:u=!0})=>s.jsx(bh,{title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,divider:u,className:c,contentClassName:d,children:l}),jo=e=>e.name.trim().length>0&&e.command.trim().length>0,Ch=e=>e.name.trim().length===0&&e.command.trim().length===0,kh=e=>!jo(e)&&!Ch(e),Ah=(e,t)=>e.some(r=>t.has(r.id)&&!jo(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(jo)},Nh=450,Ih=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Eh=()=>({id:Ih(),name:"",command:"",icon:"play"}),Rh=({projectRef:e})=>{const[t,n]=a.useState([]),[r,o]=a.useState(!1),[i,l]=a.useState(null),[c,d]=a.useState(new Set),u=a.useRef(!1);a.useEffect(()=>{let g=!1;return o(!0),(async()=>{try{const S=await io(e);if(g)return;n(S.actions),l(JSON.stringify({actions:S.actions})),d(new Set(S.actions.map(v=>v.id)))}catch{if(g)return;n([]),l(JSON.stringify({actions:[]})),d(new Set)}finally{g||o(!1)}})(),()=>{g=!0}},[e]);const f=a.useMemo(()=>Ah(t,c),[t,c]),p=a.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),x=i!==null&&f.canPersist&&p!==i,y=a.useCallback(async g=>await Vd(e,{actions:g,primaryActionId:null})?(l(JSON.stringify({actions:g})),d(new Set(g.map(v=>v.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(So,{detail:{projectId:e.id}})),!0):(ae.error("Failed to save actions"),!1),[e]);a.useEffect(()=>{if(!x||r||u.current)return;const g=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await y(f.actions)}finally{u.current=!1}})())},Nh);return()=>{window.clearTimeout(g)}},[x,r,y,f.actions]);const m=a.useCallback(()=>{const g=Eh();n(S=>[...S,g])},[]),h=a.useCallback(g=>{n(S=>S.filter(v=>v.id!==g))},[]),b=a.useCallback((g,S)=>{n(v=>v.map(E=>E.id===g?S(E):E))},[]);return s.jsx(Il,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:s.jsxs(Ne,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:m,children:[s.jsx(P,{name:"add",className:"h-3.5 w-3.5"}),"Add action"]}),contentClassName:"space-y-4",children:r?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Loading..."}):t.length===0?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"No actions configured yet."}):s.jsx("div",{className:_("space-y-6",hh),children:t.map((g,S)=>{const v=g.icon||"play",E=Dn[v]||"play",k=g.name.trim()||`Action ${S+1}`,C=kh(g);return s.jsxs("div",{className:jl,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:Cl,children:k}),s.jsx(Ne,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>h(g.id),"aria-label":`Delete ${k}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsxs(Rn,{label:"Name",controlClassName:"w-full max-w-none",children:[s.jsxs(Wt,{children:[s.jsx(Gt,{asChild:!0,children:s.jsx("button",{type:"button",className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md border border-[var(--interactive-border)] text-foreground hover:bg-[var(--interactive-hover)]","aria-label":"Select icon",children:s.jsx(P,{name:E,className:"h-4 w-4"})})}),s.jsx(Ht,{align:"start",className:"w-56 p-2",children:s.jsx("div",{className:"grid grid-cols-6 gap-1",children:Al.map(j=>{const w=j.Icon,N=(g.icon||"play")===j.key;return s.jsx("button",{type:"button",onClick:()=>b(g.id,M=>({...M,icon:j.key})),className:_("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",N&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${j.label}`,children:s.jsx(P,{name:w,className:"h-4 w-4"})},j.key)})})})]}),s.jsx(Tn,{value:g.name,onChange:j=>b(g.id,w=>({...w,name:j.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),s.jsx(Rn,{label:"Command",controlClassName:"w-full max-w-none",children:s.jsx(kl,{value:g.command,onChange:j=>b(g.id,w=>({...w,command:j.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),C?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,s.jsx(yh,{checked:g.autoOpenUrl===!0,onChange:j=>b(g.id,w=>({...w,...j?{autoOpenUrl:!0}:{autoOpenUrl:void 0,openUrl:void 0}})),label:"Auto-open URL",info:"Opens a URL from command output, or a custom URL if you set one.",ariaLabel:`Auto-open URL for ${k}`}),g.autoOpenUrl===!0?s.jsx(s.Fragment,{children:s.jsx(Rn,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:s.jsx(Tn,{value:g.openUrl||"",onChange:j=>b(g.id,w=>({...w,openUrl:j.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},g.id)})})})},Dh={searchPlaceholder:"Search models",noResults:"No models found",favorites:"Favorites",recent:"Recent",favorite:"Favorite",unfavorite:"Unfavorite",capabilities:"Capabilities",capabilityToolCalling:"Tool calling",capabilityReasoning:"Reasoning",input:"Input",output:"Output",costPerMillion:"Cost ($/1M tokens)"},Ph=({value:e,noneLabel:t,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:i,onChange:l})=>{const c=$t(w=>w.providers),d=$t(w=>w.modelsMetadata),u=de(w=>w.hiddenModels),f=de(w=>w.isFavoriteModel),p=de(w=>w.toggleFavoriteModel),x=de(w=>w.reorderFavoriteModel),{favoriteModelsList:y,recentModelsList:m}=Qd(),[h,b]=a.useState(!1),[g,S]=a.useState("");a.useEffect(()=>{h?$t.getState().ensureModelMetadata():S("")},[h]);const v=e?c.find(w=>w.id===e.providerId):void 0,E=e&&v?(Array.isArray(v.models)?v.models:[]).find(w=>w.id===e.modelId):void 0,k=e?Jd(E,e.modelId):t,C=a.useMemo(()=>e?u.filter(w=>!(w.providerID===e.providerId&&w.modelID===e.modelId)):u,[u,e]),j=a.useCallback(w=>{l({providerId:w.providerID,modelId:w.modelID}),b(!1)},[l]);return s.jsxs(Wt,{modal:!1,open:h,onOpenChange:w=>{r||b(w)},children:[s.jsx(Gt,{asChild:!0,disabled:r,children:s.jsxs("button",{type:"button","aria-label":n,disabled:r,className:_(Zd({size:"default"}),fh,"min-w-0",o),children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?s.jsx(Xd,{providerId:e.providerId,className:"size-4 shrink-0"}):null,s.jsx("span",{className:_("truncate",e?"text-foreground":"text-muted-foreground"),children:k})]}),s.jsx(P,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),s.jsx(Ht,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:s.jsx(eu,{providers:c,favoriteModels:y,recentModels:m,modelsMetadata:d,searchQuery:g,onSearchQueryChange:S,onSelect:j,labels:{...Dh,notSelected:t},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:C,isModelAllowed:i,includeNotSelected:!0,onSelectNone:()=>{l(null),b(!1)},disabled:r,autoFocus:!0,onEscape:()=>b(!1),isFavorite:w=>f(w.providerID,w.modelID),onToggleFavorite:w=>p(w.providerID,w.modelID),onReorderFavorite:(w,N)=>x(w.providerID,w.modelID,N.providerID,N.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},_r="w-full max-w-none",Mh=({form:e})=>{const{name:t,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:i}=e,l=$t(c=>c.loadProviders);return a.useEffect(()=>{l({source:"projectSettings"})},[l]),i?s.jsx(Il,{title:"Project",divider:!1,children:s.jsxs("div",{className:jl,children:[s.jsx(Rn,{label:"Name",settingsItem:"projects.name",controlClassName:_r,children:s.jsx(Tn,{value:t,onChange:c=>n(c.target.value),placeholder:"Project name","aria-label":"Project name",className:"h-8 w-full rounded-md px-3"})}),s.jsx(Rn,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:_r,children:s.jsx(Ph,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:_r,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Th=e=>{const[t,n]=a.useState(""),[r,o]=a.useState(void 0);a.useEffect(()=>{if(!e){n(""),o(void 0);return}n(e.label??""),o(e.defaultModel)},[e]);const i=a.useMemo(()=>tu(r),[r]),l=!!e&&(t.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=a.useCallback((u,f)=>{o(u&&f?`${u}/${f}`:void 0)},[]),d=a.useCallback(async()=>{if(!e)return null;const u=t.trim();return u?{label:u,defaultModel:r??null}:null},[r,t,e]);return{name:t,setName:n,defaultModel:r,parsedDefaultModel:i,handleDefaultModelChange:c,hasChanges:l,prepareSaveData:d,project:e}},Fh=450,Lh=(e,t)=>{const{hasChanges:n,name:r,defaultModel:o,prepareSaveData:i}=e,l=a.useRef(!1);a.useEffect(()=>{if(!n||!r.trim()||l.current)return;const c=window.setTimeout(()=>{l.current||(l.current=!0,(async()=>{try{const d=await i();if(d)try{await t(d)}catch{ae.error("Failed to save project settings")}}finally{l.current=!1}})())},Fh);return()=>{window.clearTimeout(c)}},[o,n,r,t,i])},Oh=({project:e,onIdentitySave:t})=>{const n=Th(e),r=a.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=a.useCallback(async i=>{await t(i)},[t]);return Lh(n,o),!e||!r?null:s.jsxs("div",{className:"space-y-0",children:[s.jsx(Mh,{form:n}),s.jsx(Rh,{projectRef:r})]})},Bh=6e4,_h=3e4,yn=new Map;let Oi=0,Bi=!1;const zh=()=>{if(Bi||typeof window>"u")return;Bi=!0;const e=()=>{const t=Date.now();t-Oi<_h||typeof document<"u"&&document.hidden||(Oi=t,ft(async()=>{const{getRegisteredRuntimeAPIs:n}=await import("./index-DWSrsQWl.js").then(r=>r.cA);return{getRegisteredRuntimeAPIs:n}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:n})=>{const r=n()?.github;r&&jr.getState().refresh(r)}).catch(()=>{}))};window.addEventListener("focus",e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.hidden||e()})},jr=Bs()(Sr((e,t)=>({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:Pt(),resetForRuntimeSwitch:n=>{const r=n??Pt();yn.clear(),e({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:r})},refresh:async(n,r)=>{zh();const o=Pt();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t(),l=Date.now();if(!r?.force&&i.status&&i.fetchedAt&&l-i.fetchedAt<Bh)return i.status;const c=yn.get(o);if(c)return c;const d=n??null;if(!d)return t().status;const u=(async()=>{e({isLoading:!0});try{const f=await d.status();return Pt()!==o?null:(e({status:f,fetchedAt:Date.now(),isLoading:!1,error:null,runtimeKey:o}),f)}catch(f){return Pt()!==o?null:(e({isLoading:!1,error:f instanceof Error?f.message:"GitHub status check failed"}),t().status)}})();yn.set(o,u);try{return await u}finally{yn.get(o)===u&&yn.delete(o)}}}),{name:"github-status-store"}));typeof window<"u"&&Bn(e=>{jr.getState().resetForRuntimeSwitch(e.runtimeKey)});const Uh=()=>jr(e=>(e.status?.hosts??[]).find(n=>n.authenticated)?.login??null),qn=100;function qx(){const e=de(w=>w.isArchivePageOpen),t=de(w=>w.setArchivePageOpen),n=de(w=>w.setActiveMainTab),r=Te(w=>w.setCurrentSession),o=Te(w=>w.unarchiveSession),i=on(w=>w.homeDirectory),l=ao({archived:!0}),[c,d]=a.useState(""),[u,f]=a.useState(null),[p,x]=a.useState(qn),y=c.trim().toLowerCase(),m=a.useMemo(()=>e?[...l].sort((w,N)=>(N.time?.archived??0)-(w.time?.archived??0)):[],[l,e]),h=a.useMemo(()=>{const w=new Map;for(const N of m){const M=Ee(In(N))??"",F=w.get(M);if(F){F.sessions.push(N);continue}w.set(M,{directory:M,label:M?Fn(M,i)||M:"other projects",sessions:[N]})}return[...w.values()].sort((N,M)=>M.sessions.length-N.sessions.length)},[i,m]),b=a.useMemo(()=>y?m.filter(w=>(w.title??"").toLowerCase().includes(y)):u===null?m:h.find(w=>w.directory===u)?.sessions??[],[h,y,u,m]),g=b.slice(0,p),S=b.length-g.length,v=l.length,E=a.useCallback(w=>{f(w),x(qn)},[]),k=a.useCallback(w=>{const N=Ee(In(w));r(w.id,N??void 0),n("chat"),t(!1)},[n,r,t]),C=a.useCallback(w=>{o(w.id).then(N=>{N?ae.success("Session restored"):ae.error("Failed to restore session")})},[o]);if(!e)return null;const j=(w,N,M,F,$,U,K)=>s.jsxs("div",{className:"group/dir relative",children:[s.jsxs("button",{type:"button",onClick:$,title:U,className:_("flex w-full min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-left typography-ui-label transition-[padding] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",K?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",F?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground"),children:[s.jsx("span",{className:"min-w-0 flex-1 truncate",children:N}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground/70",children:M})]}),K?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>Ms.requestDelete({sessions:K,mode:"session"}),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity hover:text-destructive group-hover/dir:opacity-100 focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete all archived sessions in ${N}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},w);return s.jsx(Ed,{open:e,onOpenChange:t,children:s.jsxs(Rd,{children:[s.jsx(Dd,{className:"fixed inset-0 z-50 bg-black/25 dark:bg-black/40 transition-opacity duration-150 data-[starting-style]:opacity-0 data-[ending-style]:opacity-0"}),s.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center p-4 max-[640px]:p-2 pointer-events-none",children:s.jsxs(Pd,{className:"pointer-events-auto relative flex h-[min(84vh,720px)] max-h-[calc(100dvh-2rem)] w-[min(92vw,960px)] flex-col overflow-hidden rounded-2xl border border-border/80 bg-background shadow-2xl transition-all duration-150 data-[starting-style]:scale-[0.98] data-[starting-style]:opacity-0 data-[ending-style]:scale-[0.98] data-[ending-style]:opacity-0 max-[640px]:h-[calc(100dvh-1rem)] max-[640px]:max-h-none max-[640px]:w-[calc(100vw-1rem)] max-[640px]:rounded-xl",children:[s.jsx(Md,{className:"sr-only",children:"Archived sessions"}),s.jsx(Td,{className:"sr-only",children:"Browse and restore archived sessions."}),s.jsx(Fd,{"aria-label":"Close archived sessions",className:"absolute right-3 top-3 z-10 inline-flex size-8 items-center justify-center rounded-md bg-background/80 text-muted-foreground backdrop-blur-sm hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:s.jsx(P,{name:"close",className:"size-4"})}),s.jsxs("div",{className:"flex min-h-0 flex-1",children:[s.jsx("div",{className:"flex w-64 flex-shrink-0 flex-col border-r border-border/50 max-[640px]:w-40",children:s.jsxs("div",{className:"flex-1 space-y-0.5 overflow-y-auto p-2",children:[j("__all__","All directories",v,u===null,()=>E(null)),h.map(w=>j(w.directory||"__none__",w.label,w.sessions.length,u===w.directory,()=>E(w.directory),w.directory||void 0,w.sessions))]})}),s.jsxs("div",{className:"flex min-w-0 flex-1 flex-col",children:[s.jsxs("div",{className:"flex items-center gap-3 px-6 pr-12 pt-3",children:[s.jsxs("div",{className:"relative min-w-0 flex-1",children:[s.jsx(P,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{value:c,onChange:w=>{d(w.target.value),x(qn)},placeholder:"Search archived sessions",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-3 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50"})]}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-muted-foreground",children:b.length===1?`${b.length} archived session`:`${b.length} archived sessions`})]}),s.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto px-6 py-3",children:s.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-0.5",children:[g.length===0?s.jsx("div",{className:"py-10 text-center text-muted-foreground",children:s.jsx("p",{className:"typography-ui-label font-semibold",children:y?"No matching archived sessions":"No archived sessions"})}):g.map(w=>{const N=Ee(In(w))??"",M=N?Fn(N,i)||N:null;return s.jsxs("div",{className:"group relative flex cursor-pointer items-center gap-3 rounded-md py-1 pl-2 pr-2 transition-[padding] hover:bg-interactive-hover/40 hover:pr-14 focus-within:pr-14",onClick:()=>k(w),role:"button",tabIndex:0,onKeyDown:F=>{(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),k(w))},children:[s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:xs(w)}),y&&M?s.jsx("span",{className:"max-w-40 flex-shrink-0 truncate text-[0.72rem] text-muted-foreground/70",title:N,children:M}):null,s.jsx("span",{className:"flex-shrink-0 text-[0.72rem] text-muted-foreground/75",children:wf(w.time?.archived??w.time?.updated??w.time?.created??Date.now())}),s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),C(w)},className:"absolute right-7 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-foreground group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Restore ${xs(w)}`,children:s.jsx(P,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:F=>{F.stopPropagation(),Ms.requestDelete({sessions:[w],mode:"session"})},className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground opacity-0 transition-opacity pointer-events-none hover:text-destructive group-hover:opacity-100 group-hover:pointer-events-auto focus-visible:opacity-100 focus-visible:pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete ${xs(w)}`,children:s.jsx(P,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},w.id)}),S>0?s.jsx("button",{type:"button",onClick:()=>x(w=>w+qn),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-muted-foreground/70 leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const $h=e=>{if(!e||typeof e!="object")return{percent:0,hasInput:!1};const t=e.input??0,n=e.cache&&typeof e.cache=="object"?e.cache.read??0:0,r=e.cache&&typeof e.cache=="object"?e.cache.write??0:0,o=t+n+r;if(o<=0)return{percent:0,hasInput:!1};const i=Math.max(0,n);return{percent:Math.min(100,Math.max(0,i/o*100)),hasInput:!0}},Kh=e=>{if(!e||typeof e!="object")return 0;const t=typeof e.input=="number"&&Number.isFinite(e.input)&&e.input>=0?e.input:0,n=typeof e.cacheRead=="number"&&Number.isFinite(e.cacheRead)&&e.cacheRead>=0?e.cacheRead:0,r=typeof e.cacheWrite=="number"&&Number.isFinite(e.cacheWrite)&&e.cacheWrite>=0?e.cacheWrite:0;return t+n+r},Jt=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,Wh=e=>{if(!e||typeof e!="object")return null;const t=Jt(e.input),n=Jt(e.output),r=Jt(e.cacheRead),o=Jt(e.cacheWrite);return{input:t,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:t+n+r+o}},_i=e=>{const t=Wh(e.info.usage);if(t)return t;const n=e.info.tokens,r=n!==void 0?n:e.parts.find(f=>f.tokens!==void 0)?.tokens;if(typeof r=="number")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:Jt(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,i=Jt(o.input),l=Jt(o.output),c=Jt(o.reasoning),d=Jt(o.cache?.read),u=Jt(o.cache?.write);return{input:i,output:l,reasoning:c,cacheRead:d,cacheWrite:u,total:i+l+c+d+u}},El=380,zr=8,Gh=140;function Hh({open:e,onClose:t,anchorRef:n,closeOnWheel:r=!1}){const o=a.useRef(null),i=a.useRef(null),[l,c]=a.useState(e),[d,u]=a.useState(!1),[f,p]=a.useState(null),{enabled:x}=Ko();return a.useLayoutEffect(()=>{if(!e||!x||!l)return;const y=()=>{const b=n.current?.getBoundingClientRect(),g=i.current?.getBoundingClientRect();if(!b||!g){p(null);return}const S=b.left-g.left;p(Math.min(Math.max(S,zr),Math.max(zr,g.width-El-zr)))};y();const m=i.current;if(typeof ResizeObserver>"u"||!m)return;const h=new ResizeObserver(y);return h.observe(m),()=>h.disconnect()},[n,x,e,l]),a.useEffect(()=>{if(e){c(!0),u(!1);return}if(!l)return;u(!0);const y=window.setTimeout(()=>{c(!1),u(!1)},Gh);return()=>window.clearTimeout(y)},[e,l]),a.useEffect(()=>{if(!e)return;const y=m=>{m.key==="Escape"&&t()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[t,e]),a.useEffect(()=>{if(!e)return;const y=m=>{const h=m.target;if(!(h instanceof Node)){t();return}o.current?.contains(h)||n.current?.contains(h)||t()};return document.addEventListener("pointerdown",y,!0),r&&document.addEventListener("wheel",y,!0),()=>{document.removeEventListener("pointerdown",y,!0),r&&document.removeEventListener("wheel",y,!0)}},[n,r,t,e]),{panelRef:o,wrapperRef:i,shouldRender:l,isExiting:d,anchorLeft:f,isPopover:x&&f!==null}}const zi=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},hr=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),Yn=({icon:e,iconNode:t,label:n,children:r})=>s.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[s.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:t??(e?s.jsx(P,{name:e,className:"size-[18px]"}):null)}),s.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:n}),s.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:r})]}),qh=({open:e,onClose:t,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:i,shouldRender:l,isExiting:c,anchorLeft:d,isPopover:u}=Hh({open:e,onClose:t,anchorRef:n,closeOnWheel:!0});return l?s.jsxs("div",{ref:i,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:[s.jsx("div",{ref:o,role:"tooltip","aria-label":"Context usage for current conversation",className:_("overflow-y-auto overscroll-contain rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)] will-change-transform",u?"absolute origin-top-left":"mx-3 mt-2",c?"pointer-events-none":"pointer-events-auto"),style:{animation:`${c?"session-metadata-out":"session-metadata-in"} ${c?140:170}ms cubic-bezier(0.32, 0.72, 0, 1) forwards`,maxHeight:"min(72dvh, calc(100dvh - var(--oc-safe-area-top, 0px) - var(--oc-header-height, 56px) - 1rem))",...u?{top:8,left:d??8,width:`min(${El}px, calc(100% - 16px))`}:null},children:s.jsx("div",{className:"space-y-1",children:r?s.jsxs(s.Fragment,{children:[s.jsx(Yn,{iconNode:s.jsx(Oa,{percentage:r.percentage}),label:"Context",children:s.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[s.jsxs("span",{className:_("font-semibold",r.colorClass),children:[r.percentage.toFixed(1),"%"]}),s.jsx("span",{className:"text-muted-foreground",children:r.tokens})]})}),r.cacheRead!==null&&r.cacheWrite!==null?s.jsxs(s.Fragment,{children:[s.jsx(Yn,{icon:"stack",label:"Cache read",children:s.jsx("span",{className:"tabular-nums",children:hr(r.cacheRead)})}),s.jsx(Yn,{icon:"edit",label:"Cache write",children:s.jsx("span",{className:"tabular-nums",children:hr(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?s.jsx(Yn,{icon:"check",label:"Cache hit",children:s.jsxs("span",{className:"tabular-nums",children:[r.cacheHitPercent.toFixed(1),"%"]})}):null]}):s.jsx("div",{className:"px-2.5 py-2 typography-meta text-muted-foreground",children:"Context usage is not available for this conversation yet."})})}),s.jsx("style",{children:`
3
+ @keyframes session-metadata-in {
4
+ from { opacity: 0; transform: translateY(-8px) scale(0.985); }
5
+ to { opacity: 1; transform: translateY(0) scale(1); }
6
+ }
7
+ @keyframes session-metadata-out {
8
+ from { opacity: 1; transform: translateY(0) scale(1); }
9
+ to { opacity: 0; transform: translateY(-6px) scale(0.985); }
10
+ }
11
+ `})]}):null},Yh=a.memo(function({open:t,onOpenChange:n,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:i}){const l=a.useRef(null),c=su(r??""),d=$t(D=>D.providers),u=$t(D=>D.currentProviderId),f=$t(D=>D.currentModelId),p=$t(D=>D.getCurrentModel()),x=$t(D=>D.getModelMetadata);$t(D=>D.modelsMetadata.size);const y=nu(a.useCallback(D=>r?D.sessionModelSelections.get(r)??null:null,[r])),m=a.useMemo(()=>{for(let D=c.length-1;D>=0;D-=1){const R=c[D]?.info;if(R.role!=="user")continue;const I=R.model,T=I?.providerID??I?.providerId,W=I?.modelID??I?.modelId,G=typeof T=="string"&&T.trim().length>0?T:void 0,B=typeof W=="string"&&W.trim().length>0?W:void 0;if(G&&B)return{providerID:G,modelID:B}}return null},[c]),h=a.useMemo(()=>{for(let D=c.length-1;D>=0;D-=1){const R=c[D];if(R?.info.role==="assistant"&&_i(R).total>0)return R}return null},[c]),b=m??(()=>{const D=h?.info.model,R=D?.providerID??D?.providerId,I=D?.modelID??D?.modelId;return R&&I?{providerID:R,modelID:I}:null})()??(y?{providerID:y.providerId,modelID:y.modelId}:null)??(u&&f?{providerID:u,modelID:f}:null),S=(b?d.find(D=>D.id===b.providerID):void 0)?.models.find(D=>D.id===b?.modelID),v=b?x(b.providerID,b.modelID):void 0,E=zi(S?.limit,"context")??v?.limit?.context??zi(p?.limit,"context")??0,k=h?_i(h):null,C=h?.info?.usage,j=C?Kh(C):k?.total??0,w=!i&&j>0&&E>0?Math.min(j/E*100,999):null,N=w!==null?`${hr(j)}/${hr(E)}`:null,M=w===null?"":w>=90?"text-[var(--status-error)]":w>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",F=k?.cacheRead??null,$=k?.cacheWrite??null,U=k?$h({input:k.input,cache:{read:k.cacheRead,write:k.cacheWrite}}):{percent:0,hasInput:!1},K=U.hasInput?U.percent:null,L=w!==null&&N?{percentage:w,tokens:N,colorClass:M,cacheRead:F,cacheWrite:$,cacheHitPercent:K}:null;return s.jsxs(s.Fragment,{children:[s.jsx("button",{ref:l,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":"Show context usage for current conversation",title:"Context usage","aria-expanded":t,onClick:()=>n(D=>!D),style:{touchAction:"manipulation"},children:s.jsx(Oa,{percentage:L?.percentage??0,size:20,className:"size-5 -rotate-90"})}),s.jsx(qh,{open:t,onClose:()=>n(!1),anchorRef:l,contextDisplay:L})]})}),un="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:bg-interactive-hover transition-colors",Vh="app-region-no-drag inline-flex h-9 w-9 items-center justify-center gap-2 p-2 rounded-md typography-ui-label font-medium text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50 hover:text-foreground hover:bg-interactive-hover transition-colors",Qh=a.memo(function({visible:t=!0,title:n,ariaLabel:r,onClick:o,className:i,Icon:l,iconClassName:c,pressed:d=!1}){return t?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":d,className:_(i??un,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(P,{name:l,className:c??"h-[18px] w-[18px]"})})}),s.jsx(Ke,{children:s.jsx("p",{children:n})})]}):null}),Jh=e=>{let t=2166136261;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,16777619);return(t>>>0).toString(36).padStart(7,"0").slice(-6)},Rl=({variant:e="desktop"})=>{const t=Ts(f=>f.entries),[n,r]=a.useState(!1),o=a.useRef(null),i=a.useMemo(()=>[...t.values()].sort((f,p)=>p.startedAt-f.startedAt),[t]),l=i.filter(f=>f.state&&f.state.phase!=="failed"||Ba(f)).length,c=a.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),d=a.useCallback(()=>{c(),o.current=setTimeout(()=>r(!1),150)},[c]);if(a.useEffect(()=>()=>c(),[c]),i.length===0)return null;const u=f=>{if(!au(f))return;const p=f.receipt;if(!p)return;const x=Te.getState();x.newSessionDraft.open?x.setNewSessionDraftTarget({directoryOverride:p.path,worktreeIntent:null}):x.openNewSessionDraft({directoryOverride:p.path}),Ts.getState().clearEntry(f.key),de.getState().setActiveMainTab("chat"),r(!1)};return s.jsxs(Wt,{open:n,onOpenChange:r,children:[s.jsx(Gt,{asChild:!0,children:s.jsxs("button",{type:"button",className:_(e==="desktop"?un:"pointer-events-auto inline-flex h-10 w-full items-center justify-center gap-2 rounded-lg border border-border bg-sidebar px-3 typography-ui-label font-medium text-foreground shadow-lg hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",e==="desktop"&&"relative w-auto px-2.5"),"aria-label":"Background tasks",onPointerEnter:f=>{f.pointerType==="mouse"&&(c(),r(!0))},onPointerLeave:f=>{f.pointerType==="mouse"&&d()},children:[l>0?s.jsx(vs,{variant:"inline",text:null,animationType:"spinner"}):s.jsx(P,{name:"task",className:"size-[18px]"}),s.jsx("span",{children:"Background tasks"})]})}),s.jsxs(Ht,{align:"end",side:e==="mobile"?"top":"bottom",className:"w-[min(26rem,calc(100vw-2rem))] max-h-[70vh] overflow-y-auto p-0",onPointerEnter:c,onPointerLeave:d,children:[s.jsxs("div",{className:"border-b border-border px-3 py-2.5",children:[s.jsx("p",{className:"typography-ui-label font-medium text-foreground",children:"Background tasks"}),s.jsx("p",{className:"typography-micro text-muted-foreground",children:l===1?"1 worktree is being created":`${l} worktrees are being created`})]}),s.jsx("div",{className:"divide-y divide-border",children:i.map(f=>s.jsx(Xh,{entry:f,onOpen:()=>u(f)},f.key))})]})]})},Xh=({entry:e,onOpen:t})=>{const n=e.state?.phase==="failed",r=!!(e.state&&!n),o=Ba(e),i=ru(e),l=n?e.state?.label??"Worktree creation failed":r?e.state?.label??"Creating worktree...":o?"Sending prompt...":`Worktree ready: ${e.branch??e.receipt?.branch??"new worktree"}`;return s.jsxs("div",{className:"flex items-start gap-3 px-3 py-3",children:[s.jsx("div",{className:"mt-0.5 shrink-0",children:r||o?s.jsx(vs,{variant:"inline",text:null,animationType:"spinner"}):n?s.jsx(P,{name:"alert",className:"size-4 text-[var(--status-error)]"}):s.jsx(P,{name:"git-branch",className:"size-4 text-[var(--status-success)]"})}),s.jsxs("div",{className:"min-w-0 flex-1",children:[s.jsx("p",{className:"truncate typography-ui-label text-foreground",children:l}),s.jsx("p",{className:"mt-0.5 truncate typography-micro text-muted-foreground",children:n?e.state?.error:e.path??e.intent.sourceDirectory})]}),n?s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.failedSend?s.jsx(Ne,{type:"button",size:"xs","aria-label":`Restore draft for ${e.intent.sourceDirectory} from ${e.intent.startRef} (task ${Jh(e.key)})`,onClick:()=>{const c=ou(e.key),d=iu(c,"background-task");d&&ae.error(d.title,{description:d.description})},children:"Restore draft"}):null,s.jsx(Ne,{type:"button",variant:"ghost",size:"xs",onClick:()=>Ts.getState().dismissFailed(e.key),children:"Dismiss"})]}):null,i?s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Ne,{type:"button",size:"xs",onClick:t,children:"Open"}),s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>Ts.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:s.jsx(P,{name:"close",className:"size-3.5"})})]}):null]})},Zh=["pinned","today","yesterday","thisWeek","lastWeek","older"],em={pinned:"Pinned",today:"Today",yesterday:"Yesterday",thisWeek:"This week",lastWeek:"Last week",older:"Older"},tm=(e,t)=>{if(e==="sunday")return 0;if(e==="monday")return 1;try{const n=t||(typeof Intl<"u"&&Intl.DateTimeFormat?Intl.DateTimeFormat().resolvedOptions().locale:"en-US");if(typeof Intl<"u"&&typeof Intl.Locale=="function"){const r=new Intl.Locale(n),i=(typeof r.getWeekInfo=="function"?r.getWeekInfo():r.weekInfo)?.firstDay;if(i===7||i===0)return 0;if(i!==void 0)return 1}}catch{}return 1},Co=(e,t)=>{const n=new Date(e);n.setHours(0,0,0,0);const r=n.getTime(),o=new Date(r);o.setDate(o.getDate()-1),o.setHours(0,0,0,0);const i=o.getTime(),c=(n.getDay()-t+7)%7,d=new Date(r);d.setDate(d.getDate()-c),d.setHours(0,0,0,0);const u=d.getTime(),f=new Date(u);f.setDate(f.getDate()-7),f.setHours(0,0,0,0);const p=f.getTime();return{startOfToday:r,startOfYesterday:i,startOfThisWeek:u,startOfLastWeek:p}},sm=(e,t)=>!Number.isFinite(e)||e<=0?"older":e>=t.startOfToday?"today":e>=t.startOfYesterday?"yesterday":e>=t.startOfThisWeek?"thisWeek":e>=t.startOfLastWeek?"lastWeek":"older",nm=(e,t)=>{const n={pinned:[],today:[],yesterday:[],thisWeek:[],lastWeek:[],older:[]},{getTimestamp:r,isPinned:o,boundaries:i}=t,l=e.length;for(let d=0;d<l;d++){const u=e[d];if(o(u))n.pinned.push(u);else{const f=r(u),p=sm(f,i);n[p].push(u)}}const c=[];for(const d of Zh){const u=n[d];u.length>0&&c.push({id:d,items:u})}return c},rm=e=>{const t=new Date(e);return t.setDate(t.getDate()+1),t.setHours(0,0,0,0),t.getTime()},om=(e,t)=>{const[n,r]=a.useState(0),o=a.useMemo(()=>e?Co(Date.now(),t):null,[e,t,n]),i=o?.startOfToday??null;return a.useEffect(()=>{if(i===null||typeof window>"u"||typeof document>"u")return;const l=Date.now(),c=window.setTimeout(()=>{r(u=>u+1)},Math.max(50,rm(l)-l+50)),d=()=>{document.visibilityState==="visible"&&Co(Date.now(),t).startOfToday!==i&&r(u=>u+1)};return document.addEventListener("visibilitychange",d),()=>{window.clearTimeout(c),document.removeEventListener("visibilitychange",d)}},[i,t,n]),o},im=e=>{const{normalizedProjects:t,enabled:n=!0,ownership:r,hasAuthoritativeGlobalSessions:o,isWorktreeTopologyLoading:i,unresolvedWorktreeProjectPaths:l,foldersMap:c,createFolder:d,addSessionToFolder:u}=e;a.useEffect(()=>{!n||!o||i||t.forEach(f=>{if(l.has(f.normalizedPath))return;const p=il(f.normalizedPath),x=r.archivedSessionsByProject.get(f.id)??[],y=c[p]??[],m=new Map(y.map(h=>[h.name.toLowerCase(),h]));x.forEach(h=>{const b=vf(h,f.normalizedPath),g=b.toLowerCase();let S=m.get(g);S||(S=d(p,b),m.set(g,S)),S.sessionIds.includes(h.id)||u(p,S.id,h.id)})})},[t,n,r,o,i,l,c,d,u])},am=e=>({getOrderedGroups:a.useCallback((n,r)=>{const o=e.get(n);if(!o||o.length===0)return r;const i=new Map(r.map(u=>[u.id,u])),l=[];o.forEach(u=>{const f=i.get(u);f&&(l.push(f),i.delete(u))});const c=[],d=[];return r.forEach(u=>{i.has(u.id)&&(u.isArchivedBucket?d.push(u):c.push(u))}),[...c,...l,...d]},[e])}),lm=e=>{const{normalizedProjects:t,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:i,projectRootBranches:l,lastRepoStatus:c,buildGroupedSessions:d,hasSessionSearchQuery:u,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:p,buildGroupSearchText:x,foldersMap:y}=e,m=a.useRef(new Map),h=a.useMemo(()=>{const j=m.current,w=new Map;let N=0,M=0;const F=(U,K)=>U.length===K.length&&U.every((L,D)=>L===K[D]),$=t.map(U=>{const K=n(U.id),L=r(U.id),D=i.has(U.id)?!!i.get(U.id):c,R=l.get(U.id)??null,I=o.get(U.normalizedPath)??[],T=j.get(U.id);if(T&&T.project===U&&F(T.activeSessions,K)&&F(T.archivedSessions,L)&&T.rootBranch===R&&T.isRepo===D&&T.worktrees===I&&T.buildGroupedSessions===d)return N+=1,w.set(U.id,T),T.section;M+=1;const W=al([...K,...L]),G=d(W,U.normalizedPath,I,R,D),B={project:U,groups:G};return w.set(U.id,{project:U,activeSessions:K,archivedSessions:L,rootBranch:R,isRepo:D,worktrees:I,buildGroupedSessions:d,section:B}),B});return m.current=w,N>0&&Kt("ui.sidebar.project_section.reused",N),M>0&&Kt("ui.sidebar.project_section.rebuilt",M),$},[t,n,r,o,i,c,d,l]),b=a.useMemo(()=>h,[h]),g=a.useMemo(()=>{const j=new WeakMap;if(!u)return j;const w=N=>N.reduce((M,F)=>M+1+w(F.children),0);return b.forEach(N=>{N.groups.forEach(M=>{const F=p(M.sessions,f),$=w(F),U=x(M).includes(f),K=Ee(M.directory??null),D=(K?y[K]??[]:[]).filter(R=>R.name.toLowerCase().includes(f)).length;j.set(M,{filteredNodes:F,matchedSessionCount:$,folderNameMatchCount:D,groupMatches:U,hasMatch:U||$>0||D>0})})}),j},[u,b,p,f,x,y]),S=a.useMemo(()=>u?b.map(j=>({...j,groups:j.groups.filter(w=>g.get(w)?.hasMatch===!0)})).filter(j=>j.groups.length>0):b,[u,b,g]),v=u?S:b,E=a.useRef(new WeakMap),k=a.useMemo(()=>{const j=E.current;return v.map(w=>{const N=j.get(w);if(N&&N.query===f)return N.section;const M=w.groups.filter(R=>!R.isArchivedBucket),F=w.groups.filter(R=>R.isArchivedBucket),$=M.flatMap(R=>u?g.get(R)?.filteredNodes??[]:R.sessions),U=M.map(R=>({scopeKey:R.folderScopeKey??Ee(R.directory??null),directory:R.directory??null})).filter(R=>!!R.scopeKey),K=M.find(R=>R.isMain)??null,L={id:"flat",label:K?.label??"",branch:K?.branch??null,description:K?.description??null,isMain:!0,isArchivedBucket:!1,directory:K?.directory??w.project.normalizedPath,folderScopeKey:K?.folderScopeKey??w.project.normalizedPath,folderScopes:U,sessions:$};if(u){const R=M.map(I=>g.get(I)).filter(I=>!!I);g.set(L,{filteredNodes:$,matchedSessionCount:R.reduce((I,T)=>I+T.matchedSessionCount,0),folderNameMatchCount:R.reduce((I,T)=>I+T.folderNameMatchCount,0),groupMatches:R.some(I=>I.groupMatches),hasMatch:R.some(I=>I.hasMatch)})}const D={project:w.project,groups:[L,...F]};return j.set(w,{query:f,section:D}),D})},[g,u,f,v]),C=a.useMemo(()=>u?v.reduce((j,w)=>j+w.groups.reduce((N,M)=>{const F=g.get(M);if(!F)return N;const $=F.folderNameMatchCount+(F.groupMatches?1:0);return N+F.matchedSessionCount+$},0),0):0,[u,v,g]);return{projectSections:h,visibleProjectSections:b,groupSearchDataByGroup:g,searchableProjectSections:S,sectionsForRender:v,flatSectionsForRender:k,searchMatchCount:C}},cm=e=>{const{projectSections:t,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:i,handleSessionSelect:l,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:f,setSessionSwitcherOpen:p}=e,x=a.useMemo(()=>{const m=new Map,h=new Map,b=(g,S,v,E)=>{m.has(g)||m.set(g,new Map);const k=m.get(g);E.forEach(C=>{const j=Ee(C.session.directory??v??S);k.set(C.session.id,{directory:j}),h.has(g)||h.set(g,{id:C.session.id,directory:j}),C.children.length>0&&b(g,S,j,C.children)})};return t.forEach(g=>{g.groups.forEach(S=>{b(g.project.id,g.project.normalizedPath,S.directory,S.sessions)})}),{metaByProject:m,firstSessionByProject:h}},[t]),y=a.useRef(null);a.useLayoutEffect(()=>{if(!n)return;if(c){y.current=n;return}if(y.current===n)return;const m=t.find(C=>C.project.id===n);if(!m)return;y.current=n;const h=x.metaByProject.get(n);if(i&&h&&h.has(i)){o(C=>{if(C.get(n)===i)return C;const j=new Map(C);return j.set(n,i),j});return}const b=i?Array.from(x.metaByProject.entries()).some(([C,j])=>C!==n&&j.has(i)):!1;if(i&&h&&!b)return;if(!h||h.size===0){f("chat"),d&&p(!1),u({selectedProjectId:m.project.id,directoryOverride:m.project.normalizedPath});return}const g=r.get(n),S=g&&h.has(g)?g:null,v=x.firstSessionByProject.get(n)?.id??null,E=S??v;if(!E||E===i)return;const k=h.get(E)?.directory??null;l(E,k,{keepPanelOpen:!0})},[n,r,i,l,c,d,u,t,x,f,p,o]),a.useEffect(()=>{if(!n||!i)return;const m=x.metaByProject.get(n);!m||!m.has(i)||o(h=>{if(h.get(n)===i)return h;const b=new Map(h);return b.set(n,i),b})},[n,i,x,o])},dm=({initialActiveSessionByProject:e,persistActiveSessionByProject:t,...n})=>{const r=Te(c=>c.currentSessionId),o=Te(c=>!!c.newSessionDraft?.open),[i,l]=a.useState(()=>new Map(e));return cm({...n,activeSessionByProject:i,setActiveSessionByProject:l,currentSessionId:r,newSessionDraftOpen:o}),a.useEffect(()=>{t(i)},[i,t]),null},Ui=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],um=e=>{let t=5381;for(let n=0;n<e.length;n+=1)t=t*33^e.charCodeAt(n);return t>>>0},fm=(e,t,n)=>(n.get(e)??0)>0?e:t.get(e)??null,Dl=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const t=um(e.trim())%Ui.length;return Ui[t]},hm=(e,t)=>{const n=Dl(e);return n?t?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},$i=e=>!!e.time?.archived,mm=e=>{const t=a.useCallback(i=>[i.label,i.branch??"",i.description??"",i.directory??""].join(" ").toLowerCase(),[]),n=a.useCallback(i=>{const l=Ee(i.directory??null)??"";return`${xs(i)} ${l}`.toLowerCase()},[]),r=a.useCallback((i,l)=>l?i.flatMap(c=>{if(n(c.session).includes(l))return[c];const u=r(c.children,l);return u.length===0?[]:[{...c,children:u}]}):i,[n]),o=a.useCallback((i,l,c=[],d,u)=>{const f=Ee(l??null),p=al(i).sort(_a(e.pinnedSessionIds,e.sessionOrderRanks)),x=new Map(p.map(j=>[j.id,j])),y=new Map,m=new Map;p.forEach(j=>{const w=j.parentID??null,N=w?x.get(w):null,M=N&&$i(N)===$i(j)?w:null;y.set(j.id,M),M&&m.set(M,(m.get(M)??0)+1)});const h=c.map(j=>({worktree:j,directory:Ee(j.path)})).filter(j=>!!j.directory&&!j.worktree.isPrimary).sort((j,w)=>w.directory.length-j.directory.length),b=(j,w)=>w===j||w.startsWith(`${j}/`),g=j=>{const w=Ee(j.directory??null);return w?h.find(N=>b(N.directory,w))?.worktree??null:null},S=(j,w)=>{const N=fm(j.id,y,m);return{session:j,children:[],worktree:w,forkColorId:N}},v=[],E=new Map,k=[];for(const j of h)E.set(j.directory,[]);p.forEach(j=>{const w=g(j),N=S(j,w);j.time?.archived?k.push(N):w?E.get(Ee(w.path)??"")?.push(N):v.push(N)});const C=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:f?co(f,e.homeDirectory):null,isMain:!0,isArchivedBucket:!1,worktree:null,directory:f,folderScopeKey:f,sessions:v}];for(const{worktree:j,directory:w}of h)C.push({id:`worktree:${w}`,label:j.branch||(j.detached?"Detached HEAD":j.name),branch:j.branch,description:co(w,e.homeDirectory),isMain:!1,isArchivedBucket:!1,worktree:j,directory:w,folderScopeKey:w,sessions:E.get(w)??[]});return k.length>0&&C.push({id:"archived",label:"archived",branch:null,description:"Archived and unassigned sessions",isMain:!1,isArchivedBucket:!0,worktree:null,directory:null,folderScopeKey:f?il(f):null,sessions:k}),C},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:t,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},pm=({mobileVariant:e,isTablet:t})=>!e&&!t,gm=({enabled:e=!0,isSessionSearchOpen:t,setIsSessionSearchOpen:n,sessionSearchInputRef:r,sessionSearchContainerRef:o})=>{a.useEffect(()=>{if(!e||!t||typeof window>"u")return;const i=window.requestAnimationFrame(()=>{r.current?.focus(),r.current?.select()});return()=>window.cancelAnimationFrame(i)},[e,t,r]),a.useEffect(()=>{if(!e||!t||typeof document>"u")return;const i=l=>{o.current&&(o.current.contains(l.target)||n(!1))};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[e,t,n,o])},bm=e=>{const[t,n]=a.useState(null),r=a.useRef(null);a.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=a.useCallback((v,E,k)=>{uo("navigation.session_select"),de.getState().closeMainSurfaces();const C=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},j=k?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),v===Te.getState().currentSessionId){e.allowReselect&&j&&e.onSessionSelected?.(v),C();return}uo("navigation.session_state_set"),e.setCurrentSession(v,E??null),j&&e.onSessionSelected?.(v),C()},[e]),i=a.useCallback((v,E)=>{e.setEditingId(v),e.setEditTitle(E)},[e]),l=a.useCallback(async v=>{if(!e.editingId)return;const E=(v??e.editTitle).trim();E&&await e.updateSessionTitle(e.editingId,E),e.setEditingId(null),e.setEditTitle("")},[e]),c=a.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=a.useCallback(async(v,E)=>{try{return(await ws(v)).ok?(n(E),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=a.useCallback(async v=>{const E=await e.shareSession(v.id);if(!E?.share?.url){ae.error("Unable to share session");return}const k=await d(E.share.url,v.id);ae[k?"success":"warning"]("Session shared",{description:k?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),f=a.useCallback((v,E)=>{d(v,E).then(k=>{k||ae.error("Failed to copy URL")})},[d]),p=a.useCallback(v=>{ws(v).then(E=>{if(E.ok){ae.success("Session ID copied");return}ae.error("Failed to copy session ID")}).catch(()=>ae.error("Failed to copy session ID"))},[]),x=a.useCallback(async v=>{await e.unshareSession(v)?ae.success("Session unshared"):ae.error("Unable to unshare session")},[e]),y=a.useCallback(v=>{const E=[],k=C=>{(e.childrenMap.get(C)??[]).forEach(w=>{E.push(w),k(w.id)})};return k(v),E},[e.childrenMap]),m=a.useCallback((v,E)=>E?v:v.filter(k=>!k.time?.archived),[]),h=a.useCallback(async(v,E,k)=>{const C=E?.archivedBucket===!0||E?.hardDelete===!0,j=k?.descendantIds??m(y(v.id),C).map(F=>F.id);if(j.length===0){(C?await e.deleteSession(v.id):await e.archiveSession(v.id))?ae.success(C?"Session deleted":"Session archived"):ae.error(C?"Failed to delete session":"Failed to archive session");return}const w=[v.id,...j];if(C){const{deletedIds:F,failedIds:$}=await e.deleteSessions(w);if($.length===0){const U=F.length;ae.success(U===1?`Deleted ${U} session`:`Deleted ${U} sessions`)}else ae.error("Failed to delete session");return}const{archivedIds:N,failedIds:M}=await e.archiveSessions(w);N.length>0&&ae.success(N.length===1?`Archived ${N.length} session`:`Archived ${N.length} sessions`),M.length>0&&ae.error(M.length===1?`Failed to archive ${M.length} session`:`Failed to archive ${M.length} sessions`)},[e,y,m]),b=a.useCallback((v,E)=>{const k=E?.archivedBucket===!0||E?.hardDelete===!0,C=m(y(v.id),k).map(j=>j.id);if(!e.showDeletionDialog||E?.skipConfirm===!0){h(v,E,{descendantIds:C});return}e.setDeleteSessionConfirm({session:v,descendantCount:C.length,descendantIds:C,archivedBucket:k})},[e,y,h,m]),g=a.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:v,archivedBucket:E,descendantIds:k}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await h(v,{archivedBucket:E},{descendantIds:k})},[e,h]),S=a.useCallback(async v=>{await e.unarchiveSession(v.id)?ae.success("Session restored"):ae.error("Failed to restore session")},[e]);return{copiedSessionId:t,handleSessionSelect:o,handleSessionDoubleClick:i,handleSaveEdit:l,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:f,handleCopySessionId:p,handleUnshareSession:x,handleDeleteSession:b,handleRestoreSession:S,confirmDeleteSession:g}},xm=e=>{const{safeStorage:t,keys:n,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:i,setCollapsedProjects:l}=e,c=a.useRef(null),d=a.useRef(null),u=a.useCallback(()=>{const p=d.current;if(d.current=null,c.current=null,!p)return;const{projects:x}=dt.getState(),y=x.map(m=>({...m,sidebarCollapsed:p.has(m.id)}));el({projects:y}).catch(()=>{})},[]),f=a.useCallback(p=>{typeof window>"u"||(d.current=p,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{u()},700))},[u]);return a.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,d.current=null},[]),a.useEffect(()=>{try{const p=t.getItem(n.sessionExpanded);if(p){const y=JSON.parse(p);Array.isArray(y)&&i(new Set(y.filter(m=>typeof m=="string")))}const x=t.getItem(n.projectCollapse);if(x){const y=JSON.parse(x);Array.isArray(y)&&l(new Set(y.filter(m=>typeof m=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,t,l,i]),a.useEffect(()=>{try{const p=Object.fromEntries(r.entries());t.setItem(n.groupOrder,JSON.stringify(p))}catch{}},[r,n.groupOrder,t]),a.useEffect(()=>{try{t.setItem(n.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,n.groupCollapse,t]),{scheduleCollapsedProjectsPersist:f}},ym=3;let mr=0;const Pl=[],wm=()=>mr<ym?(mr+=1,Promise.resolve()):new Promise(e=>{Pl.push(e)}),vm=()=>{const e=Pl.shift();if(e){e();return}mr=Math.max(0,mr-1)},Sm=async e=>{await wm();try{return await e()}finally{vm()}},jm=5*6e4,Cm=e=>{const{normalizedProjects:t,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:i}=e,{git:l}=Os(),c=za(m=>m.ensureStatus),d=a.useMemo(()=>t.map(m=>m.normalizedPath).slice().sort().join("\0"),[t]),u=a.useRef(null);a.useEffect(()=>{if(!n||!l||t.length===0){u.current=null,o(new Map);return}const m=`${Pt()}\0${d}`;u.current!==m&&(u.current=m,t.forEach(h=>{Sm(()=>c(h.normalizedPath,l))}))},[n,t,d,l,c,o]);const f=a.useRef(null);a.useEffect(()=>{if(!n){f.current=null;return}const m=new Map;t.forEach(b=>{m.set(b.id,r.get(b.normalizedPath)?.isGitRepo??null)});const h=t.map(b=>`${b.id}:${String(m.get(b.id))}`).join("|");f.current!==h&&(f.current=h,o(m))},[n,t,d,r,o]);const p=a.useMemo(()=>t.map(m=>{const h=r.get(m.normalizedPath)?.branch??"";return`${m.id}:${h}`}).join("|"),[t,r]),x=a.useRef(new Map),y=a.useRef(new Map);a.useEffect(()=>{if(!n)return;let m=!1;const h=setTimeout(()=>{(async()=>{const g=new Set(t.map(C=>C.id));for(const C of x.current.keys())g.has(C)||(x.current.delete(C),y.current.delete(C));const S=Date.now();if(t.filter(C=>{const j=r.get(C.normalizedPath);if(j?.isGitRepo===!1)return x.current.delete(C.id),y.current.delete(C.id),!1;if(j?.isGitRepo!==!0||j.branch===null)return!1;const w=j.branch.trim(),N=`${C.normalizedPath}\0${w}`,M=x.current.get(C.id);if(M===N){const F=y.current.get(C.id);return F&&(F.at=S),!1}return!(M!==void 0&&S-(y.current.get(C.id)?.at??0)<jm)}).length===0)return;const E=[];if(t.forEach(C=>{const j=r.get(C.normalizedPath)?.branch?.trim()??"",w=`${C.normalizedPath}\0${j}`;j&&E.push({id:C.id,inputKey:w,branch:j})}),m||E.length===0)return;const k=Date.now();i(C=>{const j=new Map(C);return E.forEach(({id:w,branch:N})=>{N&&j.set(w,N)}),j}),E.forEach(({id:C,inputKey:j,branch:w})=>{x.current.set(C,j),w&&y.current.set(C,{branch:w,at:k})})})()},150);return()=>{m=!0,clearTimeout(h)}},[n,t,p,r,i])},km=e=>{const{ownership:t}=e,n=a.useCallback(o=>t.sessionsByProject.get(o)??[],[t]),r=a.useCallback(o=>t.archivedSessionsByProject.get(o)??[],[t]);return{getSessionsForProject:n,getArchivedSessionsForProject:r}},Am=e=>{const t=new Map;for(const n of e){const r=In(n);r&&t.set(n.id,{directory:r,sessionId:n.id})}return t},Nm=(e,t)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{t.has(o)||n.push(r)}),n},Im=e=>{const{enabled:t=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=a.useRef(null);a.useEffect(()=>{if(!t||!n)return;const i=Pt(),l=Am(r),c=o.current?.runtimeKey===i?o.current.identities:null;for(const d of Nm(c,l))Js().commitMissedDeletion(d.sessionId,d.directory);o.current={runtimeKey:i,identities:l}},[t,n,r])},Em=(e,t)=>e?t.kind!==e.kind?t.kind==="project":t.projectRoot.length!==e.projectRoot.length?t.projectRoot.length>e.projectRoot.length:t.projectId.localeCompare(e.projectId)<0:!0,Ki=(e,t,n)=>{Em(e.get(t),n)&&e.set(t,n)},Ml=e=>{const t=e;return Ee(t.directory)??Ee(t.project?.worktree)},Rm=(e,t,n)=>{if(e.time?.archived)return!0;const r=Ml(e);if(!r)return n?.allowUnknownDirectory??!0;if(vr(r,n?.homeDirectory))return!0;if(t.size===0)return n?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const i of t)if(Ee(i)?.toLowerCase()===o)return!0;return!1},Dm=e=>{if(e==="/"||/^[A-Z]:$/.test(e))return null;const t=e.lastIndexOf("/");return t<0?null:t===0?"/":t===2&&/^[A-Z]:\//.test(e)?e.slice(0,2):e.slice(0,t)},Pm=(e,t,n,r=[])=>{const o=new Map,i=new Map;for(const y of t){const m=Ee(y.normalizedPath);if(!m)continue;const h=i.get(m);(!h||y.id.localeCompare(h.id)<0)&&i.set(m,y),Ki(o,m,{projectId:y.id,projectRoot:m,scopeDirectory:m,kind:"project"})}if(n)for(const[y,m]of n){const h=Ee(y),b=h?i.get(h):void 0;if(!(!b||!h))for(const g of m||[]){const S=Ee(g?.path);S&&Ki(o,S,{projectId:b.id,projectRoot:h,scopeDirectory:S,kind:"worktree"})}}const l=new Map,c=new Map,d=new Map,u=new Map,f=new Map,p=y=>{if(!y)return null;if(l.has(y))return l.get(y)??null;const m=[];let h=y,b=null;for(;h;){if(l.has(h)){b=l.get(h)??null;break}if(m.push(h),b=o.get(h)??null,b)break;h=Dm(h)}for(const g of m)l.set(g,b);return b},x=(y,m,h)=>{for(const b of y){const g=Ml(b);if(vr(g))continue;const S=p(g);if(!S)continue;c.set(b.id,S);const v=m.get(S.projectId);if(v?v.push(b):m.set(S.projectId,[b]),!h)continue;const E=h.get(S.scopeDirectory);E?E.add(b.id):h.set(S.scopeDirectory,new Set([b.id]))}};return x(e,d,f),x(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:f,directoryResolutions:l.size}};function Tl({state:e,activeLabel:t,unreadLabel:n,inputLabel:r,className:o}){if(e==="input"){const i=r??"Needs input";return s.jsx("span",{className:_("inline-flex items-center",o),"aria-label":i,title:i,children:s.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-status-warning"})})}return e==="unread"?s.jsx("span",{className:_("inline-flex items-center",o),"aria-label":n??t,title:n??t,children:s.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-foreground"})}):s.jsx("span",{className:_("inline-flex items-center",o),"aria-label":t,title:t,children:s.jsx(vs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Mm=({folder:e,displayName:t,sessions:n,subFolderItems:r,isCollapsed:o,collapsedActivityState:i=null,onToggle:l,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:f,groupDirectory:p,projectId:x,mobileVariant:y=!1,alwaysShowActions:m=y,isRenaming:h=!1,renameDraft:b="",onRenameDraftChange:g,onRenameSave:S,onRenameCancel:v,droppableRef:E,isDropTarget:k=!1,onNewSession:C,depth:j=0,hideActions:w=!1,archivedBucket:N=!1})=>{const[M,F]=a.useState(!1),[$,U]=a.useState(""),K=a.useRef(null),L=h||M,D=h?b:$,R=a.useCallback(()=>{U(e.name),F(!0)},[e.name]),I=a.useCallback(()=>{const B=D.trim();B&&B!==e.name&&c(B),h&&S&&S(),F(!1),U("")},[D,e.name,h,c,S]),T=a.useCallback(()=>{h&&v&&v(),F(!1),U("")},[h,v]),W=a.useCallback(B=>{h&&g?g(B):U(B)},[h,g]);a.useEffect(()=>{if(!h)return;const B=()=>{const Ce=K.current;Ce&&(Ce.focus(),Ce.select())},be=requestAnimationFrame(B),V=window.setTimeout(B,0);return()=>{cancelAnimationFrame(be),window.clearTimeout(V)}},[h]);const G=o?"folder":"folder-open";return s.jsxs("div",{className:"oc-folder",children:[s.jsxs("div",{ref:E,className:_("group/folder relative flex items-center justify-between gap-2 px-3 py-1.5 min-w-0 rounded-lg transition-colors","cursor-pointer hover:bg-interactive-hover",k&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:L?void 0:B=>{B.currentTarget.blur(),l()},role:L?void 0:"button",tabIndex:L?void 0:0,onKeyDown:L?void 0:B=>{(B.key==="Enter"||B.key===" ")&&(B.preventDefault(),l())},"aria-label":o?`Expand folder ${e.name}`:`Collapse folder ${e.name}`,children:[s.jsxs("div",{className:_("min-w-0 flex items-center gap-1.5 flex-1 transition-[padding]",N?m?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":m?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[s.jsx(P,{name:G,className:_(sr,k?"text-primary":"text-muted-foreground")}),L?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:B=>B.stopPropagation(),onMouseDown:B=>B.stopPropagation(),onSubmit:B=>{B.preventDefault(),I()},children:[s.jsx("input",{ref:K,value:D,onChange:B=>W(B.target.value),className:"flex-1 min-w-0 bg-transparent typography-ui-label outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Folder name",onClick:B=>B.stopPropagation(),onPointerDown:B=>B.stopPropagation(),onMouseDown:B=>B.stopPropagation(),onKeyDown:B=>{if(B.key==="Escape"){B.stopPropagation(),T();return}(B.key===" "||B.key==="Enter")&&B.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:B=>B.stopPropagation(),onPointerDown:B=>B.stopPropagation(),onMouseDown:B=>B.stopPropagation(),children:s.jsx(P,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:B=>{B.stopPropagation(),T()},onPointerDown:B=>B.stopPropagation(),onMouseDown:B=>B.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(P,{name:"close",className:"size-4"})})]}):s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("span",{className:_(ll,k?"text-primary":"text-muted-foreground"),children:t??e.name})}),s.jsx(Ke,{side:"right",sideOffset:8,className:"max-w-xs",children:t??e.name})]}),s.jsxs("span",{className:"typography-micro text-muted-foreground/70 flex-shrink-0",children:["• ",n.length]}),i?s.jsx(Tl,{state:i,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?s.jsx(P,{name:"arrow-right-s",className:_(sr,"text-muted-foreground")}):s.jsx(P,{name:"arrow-down-s",className:_(sr,"text-muted-foreground")})]})]}),!L&&(!w||N)?s.jsx("div",{className:_("absolute right-0.5 top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5 transition-opacity",m?"opacity-100":"opacity-0 pointer-events-none group-hover/folder:opacity-100 group-hover/folder:pointer-events-auto group-focus-within/folder:opacity-100 group-focus-within/folder:pointer-events-auto"),children:s.jsxs("div",{className:"flex items-center gap-0.5",children:[!N&&C?s.jsx("button",{type:"button",onClick:B=>{B.stopPropagation(),C()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New session in ${e.name}`,title:"New session",children:s.jsx(P,{name:"add",className:"size-4"})}):null,N?null:s.jsx("button",{type:"button",onClick:B=>{B.stopPropagation(),R()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Rename folder ${e.name}`,children:s.jsx(P,{name:"pencil-ai",className:"size-4"})}),s.jsx("button",{type:"button",onClick:B=>{B.stopPropagation(),d()},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":N?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:s.jsx(P,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:s.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map(B=>s.jsx(a.Fragment,{children:u(B,0,p??null,x??null,N,void 0,"project",f?.(B))},B.session.id)):r?null:s.jsx("div",{className:"py-1 px-3 text-left typography-micro text-muted-foreground/70",children:"Empty folder"})]})]})},Tm=a.memo(Mm),Fm=({sessionId:e,sessionDirectory:t,sessionTitle:n,children:r})=>{const{attributes:o,listeners:i,setNodeRef:l,isDragging:c}=Bd({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:t,sessionTitle:n}}),d=a.useCallback(u=>{u.stopPropagation(),i?.onPointerDown&&i.onPointerDown(u)},[i]);return s.jsx("div",{ref:l,...o,onPointerDown:d,className:c?"opacity-30":void 0,children:r})},Lm=({folderId:e,children:t})=>{const{setNodeRef:n,isOver:r}=_d({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return s.jsx(s.Fragment,{children:t(n,r)})},Om=({scopeKey:e,hasFolders:t,onSessionDroppedOnFolder:n,children:r})=>{const o=Bo(Mn(Ld,{activationConstraint:{distance:8}})),[i,l]=a.useState(null),[c,d]=a.useState("Session"),[u,f]=a.useState(null),[p,x]=a.useState(null);if(!e)return s.jsx(s.Fragment,{children:r});const y=m=>{l(null),f(null),x(null);const{active:h,over:b}=m;if(!b)return;const g=h.data.current,S=b.data.current;g?.type==="session"&&g.sessionId&&S?.type==="folder"&&S.folderId&&n(g.sessionId,S.folderId)};return s.jsxs(_o,{sensors:o,collisionDetection:zo,onDragStart:m=>{const h=m.active.data.current;if(h?.type==="session"&&h.sessionId){l(h.sessionId),d(h.sessionTitle??"Session");const b=m.active.rect.current.initial?.width,g=m.active.rect.current.initial?.height;f(typeof b=="number"?b:null),x(typeof g=="number"?g:null)}},onDragCancel:()=>{l(null),f(null),x(null)},onDragEnd:y,children:[r,s.jsx(Od,{children:i&&t?s.jsxs("div",{style:{width:u?`${u}px`:"auto",height:p?`${p}px`:"auto"},className:"flex items-center rounded-lg border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-1 shadow-none pointer-events-none",children:[s.jsx(P,{name:"sticky-note",className:"h-4 w-4 text-muted-foreground mr-2 flex-shrink-0"}),s.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label font-normal text-foreground",children:c})]}):null})]})},Cr="gap-2",Fl="my-0.5 rounded-lg py-1.5",Yo=a.createContext("card"),Xt=({icon:e,children:t,onClick:n,className:r,mobileVariant:o=!1})=>{const i=a.useContext(Yo)==="tree";return s.jsxs("button",{type:"button",onClick:n,"data-sidebar-tree-row":i?"":void 0,className:_(o?Sf:jf,i&&Cr,i&&Fl,r),children:[s.jsx(P,{name:e,className:_(Fs(o),"text-muted-foreground")}),s.jsx("span",{className:_(an(o),"flex-1 text-muted-foreground"),children:t})]})},Wi=(e,t,n)=>{if(!t)return;const r=o=>{let i=o.session.id===t;for(const l of o.children)i=r(l)||i;return i&&n.add(o.session.id),i};for(const o of e)r(o)},ls=(e,t)=>{if(!t)return!1;if(e.session.id===t)return!0;for(const n of e.children)if(ls(n,t))return!0;return!1},Bm=(e,t)=>{const n=new Set(e);return e.map(r=>t.get(r)).filter(r=>{if(!r)return!1;const o=new Set;let i=r.session.parentID??null;for(;i&&!o.has(i);){if(n.has(i)&&t.has(i))return!1;o.add(i),i=t.get(i)?.session?.parentID??null}return!0})},Gi=new WeakMap;let Hi=1;const _m=e=>{const t=Gi.get(e);if(t!==void 0)return t;const n=Hi;return Hi+=1,Gi.set(e,n),n},ko=e=>e.children.length===0?"":e.children.map(n=>{const r=_m(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${ko(n)}`}).join("|"),Ll=(e,t,n,r,o,i)=>{const l=Pt(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const f=d.session.directory??o,p=u.session.directory??i,x=Ci(l,f??"",d.session.id),y=Ci(l,p??"",u.session.id);return(x?n.has(x):!1)!==(y?r.has(y):!1)?!0:d.children.some((m,h)=>c(m,u.children[h]))};return c(e,t)},pr=(e,t,n,r)=>{if(!t)return null;const o=r?"archived":"active";let i=null;const l=c=>{if(`${n}:${o}:${c.session.id}`===t)return i=c.session.id,!0;for(const u of c.children)if(l(u))return!0;return!1};return e.forEach(c=>l(c)),i},zm=5*6e4,Um=6e4,qi=5*6e4,Yi=100,wn=new Map,Xs=new Map,Ds=new Map,sn=new Map,On=(e,t)=>{const n=cs((e??"").trim()),r=(t??"").trim();return!n||!r?"":`${Pt()}
12
+ ${n}
13
+ ${r}`},Vi=()=>({pr:null,checks:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),$m=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"PR status check failed"}},Km=e=>{const t=Object.keys(e);if(t.length<=Yi)return e;const n=t.sort((o,i)=>(sn.get(o)??0)-(sn.get(i)??0)),r={...e};for(let o=0;o<n.length-Yi;o+=1){const i=n[o];delete r[i],sn.delete(i),Xs.delete(i);const l=Ds.get(i);l!==void 0&&(clearTimeout(l),Ds.delete(i))}return r},Ol=e=>e.pr?e.pr.state!=="open"?qi:e.checks?.state==="pending"?Um:qi:zm,Ao=(e,t,n,r)=>{if(typeof window>"u"||Ds.has(e))return;const o=Zt.getState().results[e];if(!o)return;const i=Ol(o),l=setTimeout(()=>{if(Ds.delete(e),!!Zt.getState().results[e]){if(typeof document<"u"&&document.hidden){Ao(e,t,n,r);return}Zt.getState().refresh(t,n,r)}},i);typeof l=="object"&&l!==null&&typeof l.unref=="function"&&l.unref(),Ds.set(e,l)},Zt=Bs()(Sr((e,t)=>({results:{},refresh:async(n,r,o,i)=>{const l=cs((n||"").trim()),c=(r||"").trim();if(!l||!c)return null;const d=On(l,c);if(!d)return null;const u=wn.get(d);if(u&&!i?.force)return u;const f=o??null;if(!f)return t().results[d]??null;const p=(Xs.get(d)??0)+1;Xs.set(d,p);const x=t().results[d]??Vi();e(m=>({results:{...m.results,[d]:{...x,isLoading:!0}}}));const y=(async()=>{try{const m=await f.prStatus(l,c);if(Xs.get(d)!==p||Pt()!==d.split(`
14
+ `)[0])return t().results[d]??null;const h={pr:m.pr??null,checks:m.checks??null,checksStale:m.checksStale,defaultBranch:m.defaultBranch??null,skippedDefaultBranch:m.skippedDefaultBranch,fetchedAt:m.fetchedAt??Date.now(),isLoading:!1,stale:!1,error:null};return sn.set(d,Date.now()),e(b=>({results:Km({...b.results,[d]:h})})),Ao(d,l,c,f),h}catch(m){if(Xs.get(d)!==p)return t().results[d]??null;const h=$m(m),b=x.pr||x.fetchedAt?{...x,isLoading:!1,stale:!0,error:h}:{...Vi(),error:h};return e(g=>({results:{...g.results,[d]:b}})),Ao(d,l,c,f),b}})();wn.set(d,y);try{return await y}finally{wn.get(d)===y&&wn.delete(d)}},load:async(n,r,o)=>{const i=cs((n||"").trim()),l=(r||"").trim();if(!i||!l)return null;const c=On(i,l);sn.set(c,Date.now());const d=t().results[c];return d&&(d.pr||d.fetchedAt)?(t().refresh(i,l,o),d):t().refresh(i,l,o)},resetForRuntimeSwitch:()=>{wn.clear(),Xs.clear(),sn.clear(),jn=null;for(const n of Ds.values())clearTimeout(n);Ds.clear(),e({results:{}})}}),{name:"github-pr-status-store"}));typeof window<"u"&&(Bn(()=>{Zt.getState().resetForRuntimeSwitch()}),document.addEventListener("visibilitychange",()=>{document.hidden||(async()=>{const e=await ft(async()=>{const{getRegisteredRuntimeAPIs:r}=await import("./index-DWSrsQWl.js").then(o=>o.cA);return{getRegisteredRuntimeAPIs:r}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:r})=>r()?.github??null).catch(()=>null);if(!e)return;const t=Date.now(),n=Object.entries(Zt.getState().results).filter(([,r])=>r.fetchedAt&&t-r.fetchedAt>=Ol(r)).map(([r])=>r);for(const r of n){const[,o,i]=r.split(`
15
+ `);if(!(!o||!i)){if(typeof document<"u"&&document.hidden)return;await Zt.getState().refresh(o,i,e).catch(()=>null)}}})()}));let jn=null;const Yx=e=>{if(jn&&jn.results===e)return jn.index;const t=new Map;for(const n of Object.values(e)){const r=n.pr?.url;!r||t.has(r)||t.set(r,n.checks?.state??null)}return jn={results:e,index:t},t},Wm=e=>{const t=e?.pr;if(!t)return null;if(t.state==="merged")return{visualState:"merged",number:t.number,draft:t.draft,title:t.title};if(t.state==="closed")return{visualState:"closed",number:t.number,draft:t.draft,title:t.title};if(t.draft)return{visualState:"draft",number:t.number,draft:!0,title:t.title,mergeableState:t.mergeableState??void 0,checks:e?.checks?{state:e.checks.state}:void 0};const n=e?.checks?.state,r=t.mergeableState??void 0;return r==="dirty"||r==="blocked"||n==="failure"?{visualState:"blocked",number:t.number,draft:!1,title:t.title,mergeableState:r,checks:e?.checks?{state:e.checks.state,total:e.checks.total,failure:e.checks.failure,pending:e.checks.pending,success:e.checks.success}:void 0}:{visualState:"open",number:t.number,draft:!1,title:t.title,mergeableState:r,checks:e?.checks?{state:e.checks.state,total:e.checks.total,failure:e.checks.failure,pending:e.checks.pending,success:e.checks.success}:void 0}},Bl=e=>{const t=Zt(n=>e?n.results[e]??null:null);return a.useMemo(()=>Wm(t),[t])},_l=(e,t,n)=>{const r=a.useMemo(()=>On(e,t),[e,t]),o=n??null;a.useEffect(()=>{if(!r||!e?.trim()||!t?.trim())return;let i=!1;return ft(async()=>{const{getRegisteredRuntimeAPIs:l}=await import("./index-DWSrsQWl.js").then(c=>c.cA);return{getRegisteredRuntimeAPIs:l}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:l})=>{if(i)return;const c=o??l()?.github??null;c&&Zt.getState().load(e,t,c)}).catch(()=>{}),()=>{i=!0}},[r,e,t,o])},zl=new Set,Vo=(e,t)=>e==="input"||t==="input"?"input":e==="active"||t==="active"?"active":e==="unread"||t==="unread"?"unread":null,No=(e,t,n,r=zl)=>{if(r.has(e.session.id))return"input";if(t.has(e.session.id)){for(const i of e.children)if(No(i,t,n,r)==="input")return"input";return"active"}let o=n.has(e.session.id)?"unread":null;for(const i of e.children)if(o=Vo(o,No(i,t,n,r)),o==="input")return o;return o},Ul=(e,t,n,r=zl)=>{let o=null;for(const i of e)if(o=Vo(o,No(i,t,n,r)),o==="input")return o;return o},Gm=50,Hm=28;function qm({visibleSessions:e,shouldVirtualize:t,hasExpandedParent:n,scrollContainerRef:r,groupDirectory:o,projectId:i,isArchivedBucket:l,renderSessionNode:c,getRenderExtras:d}){const u=a.useRef(null),[f,p]=a.useState(null),[x,y]=a.useState(0),[,m]=a.useState(0);a.useEffect(()=>{if(!t)return;const g=u.current;if(!g||typeof ResizeObserver>"u")return;const S=new ResizeObserver(()=>m(v=>v+1));return S.observe(g),()=>S.disconnect()},[t]),a.useLayoutEffect(()=>{if(!t){f!==null&&p(null),x!==0&&y(0);return}const g=u.current;if(!g)return;let S=f;const v=r?.current??null;if(v&&v.contains(g)){if(S=v,S!==f){p(S);return}}else if(!S||!S.contains(g)){let k=g.parentElement;for(;k;){const C=window.getComputedStyle(k);if(C.overflowY==="auto"||C.overflowY==="scroll"){S=k;break}k=k.parentElement}if(S!==f){p(S);return}}if(!S)return;const E=g.getBoundingClientRect().top-S.getBoundingClientRect().top+S.scrollTop;y(k=>Math.abs(k-E)<1?k:E)},[f,x,r,t]);const h=t&&f!==null,b=zd({count:e.length,enabled:h,getScrollElement:()=>f,initialOffset:()=>f?.scrollTop??0,estimateSize:()=>Hm,overscan:n?20:8,scrollMargin:x,getItemKey:g=>e[g]?.session.id??g});return s.jsx("div",{ref:u,children:t?s.jsx("div",{style:{height:b.getTotalSize(),position:"relative"},children:b.getVirtualItems().map(g=>{const S=e[g.index];return S?s.jsx("div",{"data-index":g.index,ref:b.measureElement,className:"[&_[data-session-row]]:my-px",style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${g.start-x}px)`},children:c(S,0,o,i,l,void 0,"project",d(S))},S.session.id):null})}):e.map(g=>s.jsx(a.Fragment,{children:c(g,0,o,i,l,void 0,"project",d(g))},g.session.id))})}const rr=(e,t)=>{if(!t)return e;const n=e.toLowerCase(),r=t.toLowerCase(),o=r.length;if(o===0)return e;const i=[];let l=0,c=n.indexOf(r,l);for(;c!==-1;){c>l&&i.push(e.slice(l,c));const d=e.slice(c,c+o);i.push(s.jsx("mark",{className:"bg-primary text-primary-foreground ring-1 ring-primary/90",children:d},`${c}-${d}`)),l=c+o,c=n.indexOf(r,l)}return l<e.length&&i.push(e.slice(l)),i.length>0?i:e},fn=e=>[Pt(),...e.map(t=>(t??"").toString())].join(`
16
+ `),Vn=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub request failed"}},Ym=200,en=(e={})=>{const t=e.maxEntries??Ym,n=new Map,r=new Map,o=new Map;let i=0;const l=new Map,c=new Map,d=h=>{const b=n.get(h)??null;return b&&l.set(h,i+=1),b},u=h=>{const b=c.get(h);if(b)for(const g of[...b])try{g()}catch{}},f=()=>{if(n.size<=t)return;const h=[...n.keys()].filter(g=>!r.has(g)&&(c.get(g)?.size??0)===0).sort((g,S)=>(l.get(g)??0)-(l.get(S)??0)),b=n.size-t;for(let g=0;g<b&&g<h.length;g+=1){const S=h[g];n.delete(S),l.delete(S),o.set(S,(o.get(S)??0)+1)}};let p=!1;const x=()=>{if(p||n.size<=t)return;p=!0;const h=()=>{p=!1,f()};typeof queueMicrotask=="function"?queueMicrotask(h):setTimeout(h,0)},y=(h,b)=>{const S={...n.get(h)??{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:null,generation:o.get(h)??0},...b};return n.set(h,S),l.set(h,i+=1),x(),u(h),S},m=async(h,b)=>{const g=r.get(h);if(g)return g;const S=(o.get(h)??0)+1;o.set(h,S);const v=n.get(h);y(h,{isLoading:!0,generation:S});const E=(async()=>{try{const k=await b();return o.get(h)!==S?n.get(h)??{data:k,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:S}:y(h,{data:k,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:S})}catch(k){return o.get(h)!==S?n.get(h)??{data:v?.data??null,fetchedAt:v?.fetchedAt??null,isLoading:!1,stale:!0,error:Vn(k),generation:S}:v?.data!=null?y(h,{isLoading:!1,stale:!0,error:Vn(k),generation:S}):y(h,{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:Vn(k),generation:S})}})();r.set(h,E);try{return await E}finally{r.get(h)===E&&r.delete(h),e.onSettle?.(h)}};return{getEntry:d,snapshot:()=>Object.fromEntries(n),subscribe:(h,b)=>{let g=c.get(h);return g||(g=new Set,c.set(h,g)),g.add(b),()=>{const S=c.get(h);S&&(S.delete(b),S.size===0&&c.delete(h))}},ensure:(h,b,g)=>!g?.force&&r.has(h)?r.get(h):!g?.force&&n.get(h)?.data!=null&&n.get(h)?.isLoading?r.get(h)??Promise.resolve(n.get(h)):!g?.force&&n.get(h)?.data!=null?(m(h,b),Promise.resolve(n.get(h))):m(h,b),refresh:(h,b)=>m(h,b),invalidate:async(h,b,g)=>{if(g?.exact??!0)return o.set(h,(o.get(h)??0)+1),n.delete(h),l.delete(h),r.has(h)&&r.delete(h),u(h),b?m(h,b):null;for(const v of[...n.keys()])(v===h||v.startsWith(h))&&(o.set(v,(o.get(v)??0)+1),n.delete(v),l.delete(v),r.delete(v),u(v));return null},markStale:h=>{const b=n.get(h);b?.data&&(b.stale||y(h,{stale:!0}))},setError:(h,b)=>{const g=n.get(h);return g?.data?y(h,{isLoading:!1,stale:!0,error:Vn(b)}):g??null},remove:h=>{o.set(h,(o.get(h)??0)+1),n.delete(h),l.delete(h),r.delete(h),u(h)},reset:()=>{const h=[...n.keys()];n.clear(),r.clear(),o.clear(),l.clear();for(const b of h)u(b)}}},hn=(e,t)=>Re.useSyncExternalStore(n=>t?e.subscribe(t,n):()=>{},()=>t?e.getEntry(t):null,()=>t?e.getEntry(t):null),Vx=e=>{const t=e.trim().match(/^#?(\d{1,7})$/);if(!t)return null;const n=Number(t[1]);return Number.isSafeInteger(n)&&n>0?n:null},$l=(e,t)=>!e||!t?!1:e.toLowerCase()===t.toLowerCase(),Io=e=>{if(!e)return[];const t=[];for(const n of e)n?.login&&t.push(n.login.toLowerCase());return t},Kl=e=>{const t=[],n=[];for(const r of e.trim().toLowerCase().split(/\s+/))r&&(r.startsWith("label:")&&r.length>6?n.push(r.slice(6)):t.push(r));return{tokens:t,labelTokens:n}},Qo=e=>{if(!e)return[];const t=[];for(const n of e)n?.name&&t.push(n.name.toLowerCase());return t},Wl=(e,t,n)=>{const r=Qo(e??null),o=t.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean);for(const i of[...o,...n])if(!r.some(l=>l===i||l.includes(i)))return!1;return!0},Vm=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??"",e.head.toLowerCase(),e.base.toLowerCase()];for(const n of Qo(e.labels))t.push(n);return t},Qm=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??""];for(const n of Qo(e.labels))t.push(n);return t},Gl=(e,t)=>{for(const n of t){let r=!1;for(const o of e)if(o.includes(n)){r=!0;break}if(!r)return!1}return!0},Qi=e=>e.state==="merged"||!!e.mergedAt,Jm=(e,t)=>t==="all"?e:t==="open"?e.filter(n=>n.state==="open"):t==="merged"?e.filter(n=>Qi(n)):e.filter(n=>n.state==="closed"&&!Qi(n)),Xm=(e,t)=>t==="all"?e:e.filter(n=>n.state===t),Zm=(e,t,n)=>t==="all"||!n?!0:t==="mine"?$l(e.author?.login,n):t==="review"?Io(e.requestedReviewers).includes(n.toLowerCase()):Io(e.assignees).includes(n.toLowerCase()),ep=(e,t,n)=>t==="all"||!n||t==="mentioned"?!0:t==="mine"?$l(e.author?.login,n):Io(e.assignees).includes(n.toLowerCase()),Ys=e=>{if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0},Hl=(e,t)=>{const n=[...e];return t==="newest"?(n.sort((r,o)=>Ys(o.createdAt)-Ys(r.createdAt)||o.number-r.number),n):t==="oldest"?(n.sort((r,o)=>Ys(r.createdAt)-Ys(o.createdAt)||r.number-o.number),n):(n.sort((r,o)=>Ys(o.updatedAt)-Ys(r.updatedAt)||o.number-r.number),n)},Qx=(e,t)=>{const{tokens:n,labelTokens:r}=Kl(t.search),o=[];for(const i of Jm(e,t.state))Zm(i,t.involvement,t.viewerLogin)&&Wl(i.labels,"",r)&&Gl(Vm(i),n)&&o.push(i);return Hl(o,t.sort)},Jx=(e,t)=>{const{tokens:n,labelTokens:r}=Kl(t.search),o=[];for(const i of Xm(e,t.state))ep(i,t.involvement,t.viewerLogin)&&Wl(i.labels,t.labels,r)&&Gl(Qm(i),n)&&o.push(i);return Hl(o,t.sort)},Qn=(e,t)=>{if(t.length===0)return e;const n=new Map;for(const i of t)n.set(i.number,i);const r=e.map(i=>n.get(i.number)??i),o=new Set(e.map(i=>i.number));for(const i of t)o.has(i.number)||r.push(i);return r},Xx=(e,t)=>e.filter(n=>!t.has(n.number)),tp=(e,t)=>{if(t.length===0)return e;const n=new Set(e.map(o=>o.id)),r=[...e];for(const o of t)n.has(o.id)||(n.add(o.id),r.push(o));return r},Ji=Object.freeze({repo:null,number:null}),Ur=e=>e.split(`
17
+ `)[1]??"",Eo=(e,t)=>`${cs(e)}
18
+ ${t}`,vn=(e,t)=>`${e}#${t}`,sp=(e,t)=>{const n=e?.body;return n&&typeof n.kind=="string"?n:{kind:"failed",message:e instanceof Error?e.message:t}},Ns=async(e,t)=>{if(e)try{await e.invalidate(t)}catch{}},Xi=(e,t)=>!e?.data||!e.fetchedAt?!1:Date.now()-e.fetchedAt<t,Zi=10,np=(e,t)=>{const n=en(),r=en({maxEntries:60}),o=en(),i=en(),l=new Map,c=new Map,d=async(L,D)=>{const R=c.get(L);if(R)return await R.catch(()=>null),{ran:!1,result:null};const I=D();c.set(L,I);try{return{ran:!0,result:await I}}finally{c.get(L)===I&&c.delete(L)}},u=(L,D)=>{if(D.length===0)return;const R=e.collectionKeyFor(L,e.openCollection);let I=l.get(R);I||(I=new Map,l.set(R,I));for(const T of D)I.set(T.number,T)},f=L=>{const D=Object.keys(r.snapshot()).filter(I=>Ur(I)===L&&!r.getEntry(I)?.isLoading);if(D.length<=Zi)return;const R=D.map(I=>({key:I,fetchedAt:r.getEntry(I)?.data?.fetchedAt??0})).sort((I,T)=>I.fetchedAt-T.fetchedAt);for(let I=0;I<R.length-Zi;I+=1)r.remove(R[I].key)},p=L=>{const D=n.getEntry(e.collectionKeyFor(L,e.openCollection))?.data?.items??[],R=n.getEntry(e.collectionKeyFor(L,e.closedCollection))?.data?.items??[],I=Qn(D,R),T=l.get(e.collectionKeyFor(L,e.openCollection));return!T||T.size===0?I:Qn(I,[...T.values()])},x=(L,D,R)=>{const I=Eo(L,D),T=t.get().filtersByScope[I]??e.defaultFilters;t.set(W=>({filtersByScope:{...W.filtersByScope,[I]:{...T,...R}}}))},y=(L,D)=>{const R=Eo(L,D);t.set(I=>({filtersByScope:{...I.filtersByScope,[R]:{...e.defaultFilters}}}))},m=(L,D,R)=>{const I=cs(L);I&&t.set(T=>({selectionByDirectory:{...T.selectionByDirectory,[I]:{repo:D,number:R}}}))},h=(L,D,R,I)=>{const T=e.collectionKeyFor(D,R);return n.ensure(T,async()=>{const W=await e.fetchList(I,L,D,e.buildCollectionQuery(R));return{items:W.items,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},b=(L,D,R)=>{const I=e.collectionKeyFor(D,e.closedCollection);n.getEntry(I)?.data||n.getEntry(I)?.isLoading||h(L,D,e.closedCollection,R).catch(()=>null)},g=async(L,D,R,I)=>{const T=R==="open"||R==="both",W=R==="closed"||R==="both",G=[],B=n.getEntry(e.collectionKeyFor(D,e.openCollection)),be=n.getEntry(e.collectionKeyFor(D,e.closedCollection));T&&(!Xi(B,e.freshWindowMs)||B?.stale)&&G.push(h(L,D,e.openCollection,I)),W&&(!Xi(be,e.freshWindowMs)||be?.stale)&&G.push(h(L,D,e.closedCollection,I)),await Promise.all(G.map(V=>V.catch(()=>null))),T&&!n.getEntry(e.collectionKeyFor(D,e.closedCollection))?.data&&b(L,D,I)},S=async(L,D,R,I)=>{const T=e.collectionKeyFor(D,R),W=n.getEntry(T),G=W?.data?.nextCursor??null;if(!G||W?.isLoading)return W;try{const B=await d(`${T}:more`,async()=>{const be=await e.fetchList(I,L,D,{...e.buildCollectionQuery(R),cursor:G}),V=n.getEntry(T)?.data,Ce={items:Qn(V?.items??[],be.items),nextCursor:be.nextCursor,fetchedAt:be.fetchedAt};return n.refresh(T,async()=>Ce)});return B.ran?B.result??n.getEntry(T):n.getEntry(T)}catch(B){return n.setError(T,B)??n.getEntry(T)}},v=async(L,D,R,I)=>{const T=R==="both"?[e.openCollection,e.closedCollection]:[R];await Promise.all(T.map(W=>{const G=e.collectionKeyFor(D,W);return n.refresh(G,async()=>{const B=await e.fetchList(I,L,D,e.buildCollectionQuery(W));return{items:B.items,nextCursor:B.nextCursor,fetchedAt:B.fetchedAt}}).catch(()=>null)}))},E=async(L,D,R,I)=>{const T=e.remoteKeyFor(D,R),W=await r.refresh(T,async()=>{const G=await e.fetchList(I,L,D,e.buildRemoteQuery(R));return{items:G.items,nextCursor:G.nextCursor,fetchedAt:G.fetchedAt}});return W.data&&(u(D,W.data.items),f(D)),W},k=async(L,D,R,I)=>{const T=e.remoteKeyFor(D,R),W=r.getEntry(T),G=W?.data?.nextCursor??null;if(!G||W?.isLoading)return W;try{const B=await e.fetchList(I,L,D,e.buildRemoteQuery(R,G)),be=r.getEntry(T)?.data,V={items:Qn(be?.items??[],B.items),nextCursor:B.nextCursor,fetchedAt:B.fetchedAt},Ce=await r.refresh(T,async()=>V);return Ce.data&&(u(D,Ce.data.items),f(D)),Ce}catch(B){return r.setError(T,B)??r.getEntry(T)}},C=L=>{for(const D of Object.keys(r.snapshot()))Ur(D)===L&&r.remove(D);for(const D of[...l.keys()])Ur(D)===L&&l.delete(D)},j=(L,D,R,I)=>{const T=e.detailKeyFor(D,R);return o.refresh(T,async()=>({detail:await e.fetchDetail(I,L,D,R)}))};return{initialState:{filtersByScope:{},selectionByDirectory:{}},resources:{collections:n,remote:r,details:o,comments:i},setFilters:x,resetFilters:y,select:m,ensureCollection:h,ensureCollectionsFresh:g,prefetchClosedCollection:b,loadMoreCollection:S,refreshCollections:v,searchRemote:E,loadMoreRemote:k,dropRemoteForRepo:C,refreshAllForScope:async(L,D,R)=>{await Ns(R,{directory:L,repo:D,kind:e.serverKind}),C(D),await v(L,D,"both",R).catch(()=>null);const I=t.get().selectionByDirectory[cs(L)];I?.repo===D&&typeof I.number=="number"&&await j(L,D,I.number,R).catch(()=>null)},ensureDetail:(L,D,R,I)=>{const T=e.detailKeyFor(D,R);return o.ensure(T,async()=>({detail:await e.fetchDetail(I,L,D,R)}))},refreshDetail:j,ensureComments:(L,D,R,I)=>{const T=e.commentsKeyFor(D,R);return i.ensure(T,async()=>{const W=await e.fetchComments(I,L,D,R);return{comments:W.comments,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},loadMoreComments:async(L,D,R,I)=>{const T=e.commentsKeyFor(D,R),W=i.getEntry(T),G=W?.data?.nextCursor??null;if(!G||W?.isLoading)return W;try{const B=await e.fetchComments(I,L,D,R,G),be=i.getEntry(T)?.data,V={comments:tp(be?.comments??[],B.comments),nextCursor:B.nextCursor,fetchedAt:B.fetchedAt};return await i.refresh(T,async()=>V)}catch(B){return i.setError(T,B)??i.getEntry(T)}},refreshComments:(L,D,R,I)=>{const T=e.commentsKeyFor(D,R);return i.refresh(T,async()=>{const W=await e.fetchComments(I,L,D,R);return{comments:W.comments,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}})},markCollectionsStale:L=>{n.markStale(e.collectionKeyFor(L,e.openCollection)),n.markStale(e.collectionKeyFor(L,e.closedCollection))},getLocalIndex:p,withSingleFlight:d,resetCore:()=>{n.reset(),r.reset(),l.clear(),o.reset(),i.reset(),c.clear(),t.set({filtersByScope:{},selectionByDirectory:{}})},toStoreError:L=>sp(L,e.errorFallback)}},Ro={state:"open",involvement:"all",search:"",sort:"updated"},rp=3e4,op=100,ip=50,ql=(e,t)=>fn([e,"pulls-collection",t]),Yl=(e,t)=>fn([e,"pulls-remote",t.state,t.involvement,t.q.trim()]),gr=(e,t)=>fn([e,"pull-detail",t]),Jo=(e,t)=>fn([e,"pull-comments",t]),Do=(e,t)=>fn([e,"pull-files",t]),Po=(e,t)=>fn([e,"pull-checks",t]),ap=e=>({state:e,perPage:op}),lp=(e,t)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,perPage:ip,...t?{cursor:t}:{}}),br=e=>`pichamber:pr-merge-method:${e}`,Vl=new Map,cp=e=>{try{if(typeof localStorage<"u")return localStorage.getItem(e)}catch{}return null},dp=(e,t)=>{try{if(typeof localStorage<"u"){localStorage.setItem(e,t);return}}catch{}},Zx=e=>{if(!e)return null;const t=cp(br(e));return t==="merge"||t==="squash"||t==="rebase"?t:Vl.get(br(e))??null},up=(e,t)=>{if(e){Vl.set(br(e),t);try{dp(br(e),t)}catch{}}},fp={set:e=>{typeof e=="function"?ys.setState(t=>{const n={filtersByScope:t.filtersByScope,selectionByDirectory:t.selectionByDirectory};return e(n)}):ys.setState(e)},get:()=>{const e=ys.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},Pe=np({openCollection:"open",closedCollection:"closed",defaultFilters:Ro,freshWindowMs:rp,serverKind:"pulls",errorFallback:"Pull request request failed",collectionKeyFor:ql,remoteKeyFor:Yl,detailKeyFor:gr,commentsKeyFor:Jo,buildCollectionQuery:e=>({...ap(e)}),buildRemoteQuery:(e,t)=>({...lp(e,t)}),fetchList:async(e,t,n,r)=>{const o=await e.pullsList(t,n,r);return{items:o.items,nextCursor:o.nextCursor,fetchedAt:o.fetchedAt}},fetchDetail:async(e,t,n,r)=>e.pullGet(t,n,r),fetchComments:async(e,t,n,r,o)=>{const i=await e.pullComments(t,n,r,o);return{comments:i.comments,nextCursor:i.nextCursor,fetchedAt:i.fetchedAt}}},fp),Qt=en(),or=en(),ys=Bs()(Sr((e,t)=>({...Pe.initialState,actionErrorByDetail:{},actingActions:{},setFilters:Pe.setFilters,resetFilters:Pe.resetFilters,selectPullRequest:Pe.select,ensureCollection:Pe.ensureCollection,ensureCollectionsFresh:Pe.ensureCollectionsFresh,prefetchClosedCollection:Pe.prefetchClosedCollection,loadMoreCollection:Pe.loadMoreCollection,refreshCollections:Pe.refreshCollections,searchRemote:Pe.searchRemote,loadMoreRemote:Pe.loadMoreRemote,dropRemoteForRepo:Pe.dropRemoteForRepo,refreshAllForScope:Pe.refreshAllForScope,ensureDetail:Pe.ensureDetail,refreshDetail:Pe.refreshDetail,ensureComments:Pe.ensureComments,loadMoreComments:Pe.loadMoreComments,refreshComments:Pe.refreshComments,ensureFiles:(n,r,o,i)=>{const l=Do(r,o);return Qt.ensure(l,async()=>i.pullFiles(n,r,o))},loadMoreFiles:async(n,r,o,i)=>{const l=Do(r,o),c=Qt.getEntry(l),d=c?.data?.nextCursor??null;if(!d||c?.isLoading)return c;try{const u=await Pe.withSingleFlight(`${l}:more`,async()=>{const f=await i.pullFiles(n,r,o,d),p=Qt.getEntry(l)?.data,x=new Set((p?.files??[]).map(m=>m.filename)),y={repo:f.repo,number:f.number,files:[...p?.files??[],...f.files.filter(m=>!x.has(m.filename))],nextCursor:f.nextCursor,fetchedAt:f.fetchedAt};return Qt.refresh(l,async()=>y)});return u.ran?u.result??Qt.getEntry(l):Qt.getEntry(l)}catch(u){return Qt.setError(l,u)??Qt.getEntry(l)}},ensureChecks:(n,r,o,i)=>{const l=Po(r,o);return or.ensure(l,async()=>i.pullChecks(n,r,o,!0))},refreshChecks:(n,r,o,i)=>{const l=Po(r,o);return or.refresh(l,async()=>i.pullChecks(n,r,o,!0))},performAction:async(n,r,o,i,l)=>{const c=vn(r,o),d=gr(r,o);if(t().actingActions[c])return{ok:!1,error:{kind:"failed",message:"Action already in progress"}};e(x=>({actingActions:{...x.actingActions,[c]:!0},actionErrorByDetail:{...x.actionErrorByDetail,[c]:null}}));const u=Pe.resources.details.getEntry(d)?.data?.detail??null,f=u?.pr??null,p=f?{...f,state:i==="close"?"closed":i==="reopen"?"open":i==="merge"||i==="squash"||i==="rebase"?"merged":f.state,draft:i==="ready"?!1:i==="draft"?!0:f.draft}:null;p&&u&&await Pe.resources.details.refresh(d,async()=>({detail:{...u,pr:p}})).catch(()=>null);try{return await l.pullAction(n,r,o,i),(i==="merge"||i==="squash"||i==="rebase")&&t().setMergeMethod(r,i),await Ns(l,{directory:n,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(n,r,"both",l).catch(()=>null),await t().refreshDetail(n,r,o,l).catch(()=>null),await t().refreshChecks(n,r,o,l).catch(()=>null),e(x=>({actingActions:{...x.actingActions,[c]:!1}})),{ok:!0}}catch(x){const y=Pe.toStoreError(x);return u&&await Pe.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(m=>({actingActions:{...m.actingActions,[c]:!1},actionErrorByDetail:{...m.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},updateTitleBody:async(n,r,o,i,l)=>{const c=vn(r,o),d=gr(r,o),u=Pe.resources.details.getEntry(d)?.data?.detail??null,f=u?.pr??null,p=f&&(i.title!==void 0||i.body!==void 0)?{...f,title:i.title??f.title,body:i.body??f.body}:null;p&&u&&await Pe.resources.details.refresh(d,async()=>({detail:{...u,pr:p}})).catch(()=>null);try{return await l.pullUpdate(n,r,o,i),await Ns(l,{directory:n,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(n,r,"both",l).catch(()=>null),await t().refreshDetail(n,r,o,l).catch(()=>null),{ok:!0}}catch(x){const y=Pe.toStoreError(x);return u&&await Pe.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},addComment:async(n,r,o,i,l)=>{const c=vn(r,o),d=Jo(r,o),u=i.trim(),f={id:-Date.now(),url:"",body:u,author:null,createdAt:new Date().toISOString(),updatedAt:null},p=Pe.resources.comments.getEntry(d)?.data??null;if(p){const x={comments:[...p.comments,f],nextCursor:p.nextCursor,fetchedAt:p.fetchedAt};await Pe.resources.comments.refresh(d,async()=>x).catch(()=>null)}try{return await l.pullComment(n,r,o,u),await Ns(l,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshComments(n,r,o,l).catch(()=>null),await t().refreshDetail(n,r,o,l).catch(()=>null),{ok:!0}}catch(x){const y=Pe.toStoreError(x);return p?await Pe.resources.comments.refresh(d,async()=>p).catch(()=>null):Pe.resources.comments.remove(d),e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[c]:y}})),{ok:!1,error:y}}},submitReview:async(n,r,o,i,l)=>{const c=vn(r,o);try{return await l.pullReview(n,r,o,{event:i.event,body:i.body,comments:i.comments}),await Ns(l,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,l).catch(()=>null),{ok:!0}}catch(d){const u=Pe.toStoreError(d);return e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[c]:u}})),{ok:!1,error:u}}},threadAction:async(n,r,o,i,l,c)=>{const d=vn(r,o);try{return await c.pullThread(n,r,o,i,l),await Ns(c,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,c).catch(()=>null),{ok:!0}}catch(u){const f=Pe.toStoreError(u);return e(p=>({actionErrorByDetail:{...p.actionErrorByDetail,[d]:f}})),{ok:!1,error:f}}},checkout:async(n,r,o,i,l)=>{try{const c=await l.pullCheckout(n,r,o,i);return{ok:!0,path:c.path,branch:c.branch}}catch(c){return{ok:!1,error:Pe.toStoreError(c)}}},createPullRequest:async(n,r)=>{try{const o=await r.pullCreate(n);return await Ns(r,{directory:n.directory,repo:n.repo,kind:"pulls"}),t().dropRemoteForRepo(n.repo),await t().refreshCollections(n.directory,n.repo,"both",r).catch(()=>null),{ok:!0,number:o.pr.number}}catch(o){return{ok:!1,error:Pe.toStoreError(o)}}},rerunFailedChecks:async(n,r,o,i)=>{try{return await i.checksRerun(n,r,o),{ok:!0}}catch(l){return{ok:!1,error:Pe.toStoreError(l)}}},setMergeMethod:(n,r)=>{up(n,r)},notifyAgentTurnComplete:n=>{const r=cs((n||"").trim());if(!r)return;const o=Zt.getState();for(const l of Object.keys(o.results)){const[,c]=l.split(`
19
+ `);if(c!==r)continue;const[,,d]=l.split(`
20
+ `);d&&ft(async()=>{const{getRegisteredRuntimeAPIs:u}=await import("./index-DWSrsQWl.js").then(f=>f.cA);return{getRegisteredRuntimeAPIs:u}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:u})=>{const f=u()?.github??null;if(f)return o.refresh(r,d,f,{force:!0})}).catch(()=>{})}const i=t().selectionByDirectory[r];i?.repo&&typeof i.number=="number"&&(Pe.markCollectionsStale(i.repo),ft(async()=>{const{getRegisteredRuntimeAPIs:l}=await import("./index-DWSrsQWl.js").then(c=>c.cA);return{getRegisteredRuntimeAPIs:l}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:l})=>{const c=l()?.github??null;if(c)return t().refreshDetail(r,i.repo,i.number,c)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{Pe.resetCore(),Qt.reset(),or.reset(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-pull-requests-store"}));typeof window<"u"&&(Bn(()=>{ys.getState().resetForRuntimeSwitch()}),window.addEventListener("focus",()=>{typeof document<"u"&&document.hidden}));const ey=e=>{if(typeof window>"u")return()=>{};let t=new Set,n=!1,r=!1,o=null;return ft(async()=>{const{useNotificationStore:i}=await import("./useAppFontEffects-Bfw_d5eB.js").then(l=>l.ea);return{useNotificationStore:i}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useNotificationStore:i})=>{if(r)return;const l=()=>{const c=i.getState().list,d=new Set(c.map(u=>`${u.type}:${u.session??""}:${u.time}`));if(!n){t=d,n=!0;return}for(const u of c){const f=`${u.type}:${u.session??""}:${u.time}`;t.has(f)||(t.add(f),u.type==="turn-complete"&&u.directory&&(ys.getState().notifyAgentTurnComplete(u.directory),e?.(u.directory)))}};l(),o=i.subscribe(l)}).catch(()=>{}),()=>{r=!0,o?.(),o=null}},ty=e=>Pe.getLocalIndex(e),sy=(e,t)=>Pe.getLocalIndex(e).find(n=>n.number===t)??null,ny=(e,t)=>hn(Pe.resources.collections,e?ql(e,t):null),ry=(e,t)=>hn(Pe.resources.remote,e?Yl(e,t):null),oy=(e,t)=>hn(Pe.resources.details,e!=null&&t!=null?gr(e,t):null),iy=(e,t)=>hn(Pe.resources.comments,e!=null&&t!=null?Jo(e,t):null),ay=(e,t)=>hn(Qt,e!=null&&t!=null?Do(e,t):null),ly=(e,t)=>hn(or,e!=null&&t!=null?Po(e,t):null),cy=(e,t)=>ys(n=>!e||!t?Ro:n.filtersByScope[Eo(e,t)]??Ro),dy=e=>ys(t=>e?t.selectionByDirectory[cs(e)]??Ji:Ji),Ql=(e,t,n)=>{ys.getState().selectPullRequest(e,t,n);const r=cs(e);ft(async()=>{const{useUIStore:o}=await import("./index-DWSrsQWl.js").then(i=>i.cD);return{useUIStore:o}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({useUIStore:o})=>{o.getState().openContextSurface(r,"pull-requests")}).catch(()=>{}),ft(async()=>{const{useGitHubScopeStore:o}=await import("./useAppFontEffects-Bfw_d5eB.js").then(i=>i.ec);return{useGitHubScopeStore:o}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useGitHubScopeStore:o})=>{o.getState().setSelectedRepo(e,t)}).catch(()=>{})},hp=({directory:e,number:t,color:n})=>{const r=Ua(e);return!e||!r?s.jsxs("span",{className:"ml-auto flex-shrink-0 text-[0.72rem] font-medium leading-none",style:n?{color:n}:void 0,children:["#",t]}):s.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),Ql(e,r,t)},className:"ml-auto flex-shrink-0 rounded text-[0.72rem] font-medium leading-none hover:bg-interactive-hover",style:n?{color:n}:void 0,title:`Open PR #${t} in Pull requests`,"aria-label":`Open pull request #${t} in Pull requests`,children:["#",t]})};function mp({group:e,groupKey:t,isCollapsed:n,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:i,groupHeaderRightPadding:l,dragHandleProps:c,groupPrColor:d,groupPrSummary:u,groupActivityIndicator:f,showBranchSubtitle:p,statusLine:x,allGroupSessions:y,projectId:m,activeProjectId:h,setActiveProjectIdOnly:b,setActiveMainTab:g,mobileVariant:S,setSessionSwitcherOpen:v,openNewSessionDraft:E}){return s.jsxs("div",{className:_("group/gh relative flex items-start justify-between gap-1 py-1 px-3 min-w-0 rounded-md","cursor-pointer"),onClick:()=>r(t),role:"button",tabIndex:0,onKeyDown:k=>{(k.key==="Enter"||k.key===" ")&&(k.preventDefault(),r(t))},"aria-label":n?`Expand ${e.label}`:`Collapse ${e.label}`,"aria-expanded":!n,children:[s.jsx("div",{ref:c?.setActivatorNodeRef,className:_("min-w-0 flex flex-1 items-start gap-1 overflow-hidden transition-[padding]",l),...c?.listeners??{},children:s.jsxs("div",{className:"min-w-0 flex flex-1 flex-col justify-center gap-0.5 overflow-hidden",children:[s.jsx("p",{className:"typography-ui-label font-normal truncate text-foreground/92",children:e.isArchivedBucket?s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[s.jsx(P,{name:"archive",className:_("size-4 shrink-0 text-muted-foreground",i?"hidden":"group-hover/gh:hidden")}),s.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?s.jsx(P,{name:"arrow-right-s",className:"size-4"}):s.jsx(P,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 flex-1 truncate",children:rr(e.label,o)}),f]}):!e.isMain||e.worktree?s.jsxs("span",{className:"flex w-full min-w-0 items-center gap-1.5",children:[s.jsxs("span",{className:"inline-flex size-4 shrink-0 items-center justify-center",children:[s.jsx(P,{name:"git-branch",className:_("size-4 shrink-0",!d&&"text-muted-foreground",i?"hidden":"group-hover/gh:hidden"),style:d?{color:d}:void 0}),s.jsx("span",{className:_("text-muted-foreground size-4 items-center justify-center",i?"inline-flex":"hidden group-hover/gh:inline-flex"),children:n?s.jsx(P,{name:"arrow-right-s",className:"size-4"}):s.jsx(P,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:rr(e.label,o)}),f,u?s.jsx(hp,{directory:e.directory??null,number:u.number,color:d}):null]}):s.jsxs("span",{className:"inline-flex min-w-0 max-w-full items-center gap-1",children:[s.jsx("span",{className:"min-w-0 truncate",children:rr(e.label,o)}),f]})}),p&&x?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[e.isArchivedBucket?s.jsx(P,{name:"archive",className:"size-4 flex-shrink-0 text-muted-foreground"}):s.jsx(P,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),s.jsx("span",{className:"min-w-0 truncate text-[11px] font-medium text-muted-foreground/80",children:x.label})]}):null]})}),e.isArchivedBucket&&y.length>0?s.jsx("div",{className:_("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",i?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:k=>{k.stopPropagation(),Ms.requestDelete({sessions:y,mode:"session"})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-destructive hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`Delete archived sessions in ${e.label}`,children:s.jsx(P,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Delete archived sessions"})})]})}):null,e.directory?s.jsx("div",{className:_("absolute right-0.5 top-1/2 -translate-y-1/2 z-10 transition-opacity",i?"opacity-100":"opacity-0 group-hover/gh:opacity-100 group-focus-within/gh:opacity-100"),children:s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:k=>{k.stopPropagation(),m&&m!==h&&b(m),g("chat"),S&&v(!1),E({selectedProjectId:m,directoryOverride:e.directory})},className:"inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":`New draft session in ${e.label}`,children:s.jsx(P,{name:"add",className:"h-4 w-4"})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New draft session"})})]})}):null]})}const Jn=(e,t)=>t?e.sessions.some(n=>ls(n,t)):!1,pp=(e,t,n)=>e.sessions.some(r=>Ll(r,r,t,n,e.directory,e.directory)),gp=(e,t,n)=>{const r=o=>{const i=o.session.id;return t.get(i)!==n.get(i)?!0:o.children.some(r)};return e.sessions.some(r)},ea=(e,t,n)=>{const r=o=>t.has(o.session.id)!==n.has(o.session.id)?!0:o.children.some(r);return e.sessions.some(r)},bp=(e,t,n)=>{const r=e.isArchivedBucket?"archived":"active",o=i=>{const l=`project:${r}:${i.session.id}`;return t.has(l)!==n.has(l)?!0:i.children.some(o)};return e.sessions.some(o)},xp=(e,t)=>{if(e.group!==t.group||e.groupKey!==t.groupKey||e.projectId!==t.projectId||e.hideGroupLabel!==t.hideGroupLabel||e.compactBodyPadding!==t.compactBodyPadding||e.groupSearchDataByGroup!==t.groupSearchDataByGroup||e.visibleSessionCount!==t.visibleSessionCount||e.collapsedGroups!==t.collapsedGroups&&e.collapsedGroups.has(e.groupKey)!==t.collapsedGroups.has(t.groupKey)||e.pinnedSessionIds!==t.pinnedSessionIds&&pp(t.group,e.pinnedSessionIds,t.pinnedSessionIds)||e.expandedParents!==t.expandedParents&&bp(t.group,e.expandedParents,t.expandedParents)||e.sessionOrderIndex!==t.sessionOrderIndex&&gp(t.group,e.sessionOrderIndex,t.sessionOrderIndex)||e.editingId!==t.editingId&&(Jn(e.group,e.editingId)||Jn(t.group,t.editingId))||e.editTitle!==t.editTitle&&(Jn(e.group,e.editingId)||Jn(t.group,t.editingId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=pr(e.group.sessions,e.openSidebarMenuKey,"project",!!e.group.isArchivedBucket),r=pr(t.group.sessions,t.openSidebarMenuKey,"project",!!t.group.isArchivedBucket);if(n||r)return!1}return e.activeActivitySessionIds!==t.activeActivitySessionIds&&ea(t.group,e.activeActivitySessionIds,t.activeActivitySessionIds)||e.unreadActivitySessionIds!==t.unreadActivitySessionIds&&ea(t.group,e.unreadActivitySessionIds,t.unreadActivitySessionIds)?!1:e.hasSessionSearchQuery===t.hasSessionSearchQuery&&e.normalizedSessionSearchQuery===t.normalizedSessionSearchQuery&&e.hideDirectoryControls===t.hideDirectoryControls&&e.collapsedFolderIds===t.collapsedFolderIds&&e.toggleFolderCollapse===t.toggleFolderCollapse&&e.renameFolder===t.renameFolder&&e.deleteFolder===t.deleteFolder&&e.showDeletionDialog===t.showDeletionDialog&&e.setDeleteFolderConfirm===t.setDeleteFolderConfirm&&e.renderSessionNode===t.renderSessionNode&&e.showMoreGroupSessions===t.showMoreGroupSessions&&e.resetGroupSessionLimit===t.resetGroupSessionLimit&&e.mobileVariant===t.mobileVariant&&e.alwaysShowActions===t.alwaysShowActions&&e.activeProjectId===t.activeProjectId&&e.setActiveProjectIdOnly===t.setActiveProjectIdOnly&&e.setActiveMainTab===t.setActiveMainTab&&e.setSessionSwitcherOpen===t.setSessionSwitcherOpen&&e.openNewSessionDraft===t.openNewSessionDraft&&e.addSessionToFolder===t.addSessionToFolder&&e.createFolderAndStartRename===t.createFolderAndStartRename&&e.renamingFolderId===t.renamingFolderId&&e.renameFolderDraft===t.renameFolderDraft&&e.setRenameFolderDraft===t.setRenameFolderDraft&&e.setRenamingFolderId===t.setRenamingFolderId&&e.onToggleCollapsedGroup===t.onToggleCollapsedGroup&&e.dragHandleProps===t.dragHandleProps&&e.scrollContainerRef===t.scrollContainerRef};function yp({group:e,sourceGroupNodes:t,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:i,unreadActivitySessionIds:l,inputActivitySessionIds:c,collectGroupSessions:d}){const u=mt(C=>C.foldersMap),f=e.folderScopeKey??Ee(e.directory??null),p=a.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:f?[{scopeKey:f,directory:e.directory??null}]:[],[f,e.directory,e.folderScopes]),x=a.useMemo(()=>p.flatMap(({scopeKey:C,directory:j})=>(u[C]??[]).map(w=>({folder:w,scopeKey:C,scopeDirectory:j}))),[p,u]),y=a.useMemo(()=>{const C=new Map,j=w=>{w.forEach(N=>{C.set(N.session.id,N),N.children.length>0&&j(N.children)})};return j(t),C},[t]),m=a.useMemo(()=>x.map(({folder:C,scopeKey:j,scopeDirectory:w})=>{const N=Bm(C.sessionIds,y).sort(o);return{folder:C,scopeKey:j,scopeDirectory:w,nodes:N}}),[x,y,o]),h=a.useMemo(()=>{const C=new Map(m.map(M=>[M.folder.id,M])),j=new Map;for(const{folder:M}of m){if(!M.parentId)continue;const F=j.get(M.parentId);F?F.push(M.id):j.set(M.parentId,[M.id])}const w=new Map,N=M=>{const F=w.get(M);if(F!==void 0)return F;const $=C.get(M);if(!$)return w.set(M,!1),!1;const U=j.get(M)??[];if(e.isArchivedBucket&&$.nodes.length===0){const D=U.some(R=>N(R));return w.set(M,D),D}if(!n||$.folder.name.toLowerCase().includes(r)||$.nodes.length>0)return w.set(M,!0),!0;const L=U.some(D=>N(D));return w.set(M,L),L};return m.filter(({folder:M})=>N(M.id))},[m,e.isArchivedBucket,n,r]),b=a.useMemo(()=>new Set(h.flatMap(C=>C.folder.sessionIds)),[h]),g=a.useMemo(()=>t.filter(C=>!b.has(C.session.id)),[t,b]),S=a.useMemo(()=>h.filter(({folder:C})=>!C.parentId),[h]),v=a.useMemo(()=>{const C=new Map;return h.forEach(j=>{if(!j.folder.parentId)return;const w=C.get(j.folder.parentId)??[];w.push(j),C.set(j.folder.parentId,w)}),C},[h]),E=a.useMemo(()=>{const C=new Map(h.map(N=>[N.folder.id,N])),j=new Map,w=(N,M)=>{const F=j.get(N);if(F!==void 0)return F;if(M.has(N))return null;M.add(N);const $=C.get(N);let U=$?Ul($.nodes,i,l,c):null;for(const K of v.get(N)??[])if(U=Vo(U,w(K.folder.id,M)),U==="input")break;return j.set(N,U),U};return h.forEach(({folder:N})=>w(N.id,new Set)),j},[i,h,v,c,l]),k=a.useMemo(()=>{if(!e.isArchivedBucket)return new Map;const C=new Map,j=new Map;for(const{folder:N}of h){if(!N.parentId)continue;const M=j.get(N.parentId)??[];M.push(N.id),j.set(N.parentId,M)}const w=(N,M)=>{if(M.has(N))return[];M.add(N);const F=h.find(({folder:K})=>K.id===N),$=F?d(F.nodes):[],U=j.get(N)??[];for(const K of U)$.push(...w(K,M));return $};for(const{folder:N}of h)C.set(N.id,w(N.id,new Set));return C},[h,d,e.isArchivedBucket]);return{folderScopeKey:f,folderScopes:p,allFoldersForGroup:h,rootFolders:S,ungroupedSessions:g,folderActivityStateById:E,folderSessionsForDeleteById:k}}function wp(e){const{group:t,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:f,collapsedFolderIds:p,toggleFolderCollapse:x,renameFolder:y,deleteFolder:m,showDeletionDialog:h,setDeleteFolderConfirm:b,renderSessionNode:g,showMoreGroupSessions:S,resetGroupSessionLimit:v,mobileVariant:E,alwaysShowActions:k,activeProjectId:C,setActiveProjectIdOnly:j,setActiveMainTab:w,setSessionSwitcherOpen:N,openNewSessionDraft:M,addSessionToFolder:F,createFolderAndStartRename:$,renamingFolderId:U,renameFolderDraft:K,setRenameFolderDraft:L,setRenamingFolderId:D,pinnedSessionIds:R,expandedParents:I,sessionOrderIndex:T,editingId:W,openSidebarMenuKey:G,activeActivitySessionIds:B,unreadActivitySessionIds:be,onToggleCollapsedGroup:V,dragHandleProps:Ce,compactBodyPadding:De=!1,scrollContainerRef:H}=e,z=a.useCallback((ke,Be)=>{const ge=T.get(ke.session.id),Oe=T.get(Be.session.id);if(ge!==void 0||Oe!==void 0){if(ge===void 0)return 1;if(Oe===void 0)return-1;if(ge!==Oe)return ge-Oe}return lu(ke.session,Be.session,R,$a)},[R,T]),Q=i?c.get(t):null,X=i?!1:u.has(n),ne=!t.isMain&&!t.isArchivedBucket&&!o?Ee(t.directory??null):null,we=!t.isMain&&!t.isArchivedBucket&&!o&&t.branch?.trim()||null,me=a.useMemo(()=>ne&&we?On(ne,we):null,[ne,we]),q=Bl(me);_l(ne,we);const te=q?`var(--pr-${q.visualState})`:void 0,le=f?10:5,Ae=Math.max(le,d??le),Se=i?Q?.groupMatches===!0:!1,Ge=i,Y=a.useMemo(()=>[...Ge?Q?.filteredNodes??[]:t.sessions].sort(z),[z,t.sessions,Q?.filteredNodes,Ge]),ce=a.useCallback(ke=>{const Be=[],ge=Oe=>{Oe.forEach(_e=>{Be.push(_e.session),_e.children.length>0&&ge(_e.children)})};return ge(ke),Be},[]),re=cu(),ue=a.useMemo(()=>new Set(re.map(ke=>ke.sessionId)),[re]),{folderScopeKey:ve,folderScopes:Le,allFoldersForGroup:xe,rootFolders:se,ungroupedSessions:pe,folderActivityStateById:fe,folderSessionsForDeleteById:je}=yp({group:t,sourceGroupNodes:Y,hasSessionSearchQuery:i,normalizedSessionSearchQuery:l,compareSessionNodes:z,activeActivitySessionIds:B,unreadActivitySessionIds:be,inputActivitySessionIds:ue,collectGroupSessions:ce}),He="project",We=a.useMemo(()=>{const ke=new Set;return Wi(Y,W,ke),xe.forEach(({nodes:Be})=>{Wi(Be,W,ke)}),ke},[Y,xe,W]),Ie=a.useMemo(()=>{if(!G)return null;const ke=pr(Y,G,He,!!t.isArchivedBucket);if(ke)return ke;for(const{nodes:Be}of xe){const ge=pr(Be,G,He,!!t.isArchivedBucket);if(ge)return ge}return null},[G,Y,xe,t.isArchivedBucket]),Ye=a.useCallback(ke=>{const Be=new WeakMap,ge=Oe=>{Be.set(Oe,ko(Oe));for(const _e of Oe.children)ge(_e)};return ke.forEach(ge),Be},[]),oe=a.useMemo(()=>Ye(Y),[Ye,Y]),Fe=a.useMemo(()=>{const ke=new WeakMap;return xe.forEach(({nodes:Be})=>{Be.forEach(ge=>ke.set(ge,ko(ge)))}),ke},[xe]),st=a.useCallback(ke=>oe.get(ke)??Fe.get(ke)??"",[oe,Fe]),bt=a.useCallback(ke=>({subtreeContainsEditing:We,menuOpenSessionId:Ie,nodeStructureKey:st(ke)}),[We,Ie,st]),Qe=pe.length,rt=t.isArchivedBucket||i?pe:pe.slice(0,Ae),ot=Qe-rt.length,qt=!t.isArchivedBucket&&!i&&Qe>le&&ot===0,Tt=t.isArchivedBucket===!0&&!i&&rt.length>=Gm,et=t.isArchivedBucket?"archived":"active",Ct=Tt&&rt.some(ke=>{if(ke.children.length===0)return!1;const Be=`project:${et}:${ke.session.id}`;return I.has(Be)}),ss=a.useMemo(()=>ce(Y),[ce,Y]);if(i&&!Se&&se.length===0&&pe.length===0)return null;const kt=!t.isMain&&!!t.branch,At=t.branch&&Cf(t.branch,t.label)?{label:t.branch,color:null}:null,Ft=X?Ul(Y,B,be,ue):null,xt=Ft?s.jsx(Tl,{state:Ft,activeLabel:"Session active",unreadLabel:"Unread updates",inputLabel:"Needs input"}):null,Je=(ke,Be)=>{const{folder:ge,scopeKey:Oe,scopeDirectory:_e,nodes:ht}=ke,yt=je.get(ge.id)??[],nt=i?!1:p.has(ge.id);return s.jsx(Lm,{folderId:ge.id,children:(ns,rs)=>s.jsx(Tm,{folder:ge,displayName:Be,sessions:ht,isCollapsed:nt,collapsedActivityState:nt?fe.get(ge.id)??null:null,onToggle:()=>x(ge.id),onRename:Ze=>{y(Oe,ge.id,Ze)},onDelete:()=>{if(t.isArchivedBucket){Ms.requestDelete({sessions:yt,mode:"session"});return}if(!h){m(Oe,ge.id);return}const Ze=xe.filter(({folder:lt})=>lt.parentId===ge.id).length,Ot=ht.length;b({scopeKey:Oe,folderId:ge.id,folderName:ge.name,subFolderCount:Ze,sessionCount:Ot})},renderSessionNode:g,getRenderExtras:st?Ze=>({subtreeContainsEditing:We,menuOpenSessionId:Ie,nodeStructureKey:st(Ze),childRenderExtrasFor:bt}):void 0,groupDirectory:_e??t.directory,projectId:r,mobileVariant:E,alwaysShowActions:k,isRenaming:U===ge.id,renameDraft:U===ge.id?K:void 0,onRenameDraftChange:Ze=>L(Ze),onRenameSave:()=>{const Ze=K.trim();Ze&&y(Oe,ge.id,Ze),D(null),L("")},onRenameCancel:()=>{D(null),L("")},droppableRef:ns,isDropTarget:rs,depth:0,onNewSession:()=>{r&&r!==C&&j(r),w("chat"),E&&N(!1),M({selectedProjectId:r,directoryOverride:_e??t.directory,targetFolderId:ge.id})},hideActions:!1,archivedBucket:t.isArchivedBucket===!0})},ge.id)},Lt=()=>{const ke=new Map;for(const Oe of xe){const _e=Oe.folder.parentId;if(!_e)continue;const ht=ke.get(_e);ht?ht.push(Oe):ke.set(_e,[Oe])}const Be=[],ge=(Oe,_e)=>{const ht=_e?`${_e} / ${Oe.folder.name}`:Oe.folder.name;Be.push(Je(Oe,ht)),!(!i&&p.has(Oe.folder.id))&&(ke.get(Oe.folder.id)??[]).forEach(nt=>ge(nt,ht))};return se.forEach(Oe=>ge(Oe,"")),Be},Yt=k?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",us=s.jsxs(Om,{scopeKey:Le[0]?.scopeKey??ve,hasFolders:xe.length>0,onSessionDroppedOnFolder:(ke,Be)=>{const ge=xe.find(({folder:_e})=>_e.id===Be);if(!ge)return;const Oe=mt.getState();for(const{scopeKey:_e}of Le)_e!==ge.scopeKey&&Oe.getSessionFolderId(_e,ke)&&Oe.removeSessionFromFolder(_e,ke);F(ge.scopeKey,Be,ke)},children:[Lt(),t.isArchivedBucket?s.jsx(qm,{visibleSessions:rt,shouldVirtualize:Tt,hasExpandedParent:Ct,scrollContainerRef:H,groupDirectory:t.directory,projectId:r,isArchivedBucket:t.isArchivedBucket===!0,renderSessionNode:g,getRenderExtras:ke=>({subtreeContainsEditing:We,menuOpenSessionId:Ie,nodeStructureKey:st(ke),childRenderExtrasFor:bt})}):rt.map(ke=>s.jsx(a.Fragment,{children:g(ke,0,t.directory,r,t.isArchivedBucket===!0,void 0,"project",{subtreeContainsEditing:We,menuOpenSessionId:Ie,nodeStructureKey:st(ke),childRenderExtrasFor:bt})},ke.session.id)),Qe===0&&xe.length===0?t.isArchivedBucket?s.jsx("div",{className:"py-1 px-3 text-left typography-ui-label text-muted-foreground",children:"No archived sessions yet."}):s.jsx(Xt,{icon:"chat-new",onClick:()=>{M({selectedProjectId:r,directoryOverride:t.directory})},children:"New session"}):null,ot>0?s.jsx(Xt,{icon:"arrow-down-s",onClick:()=>S(n,rt.length),children:ot===1?"Show 1 more session":`Show ${ot} more sessions`}):null,qt?s.jsx(Xt,{icon:"arrow-up-s",onClick:()=>v(n),children:"Show fewer sessions"}):null]});return o?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:"oc-group-body",children:us})}):s.jsxs("div",{className:"oc-group",children:[s.jsx(mp,{group:t,groupKey:n,isCollapsed:X,onToggleCollapsedGroup:V,normalizedSessionSearchQuery:l,alwaysShowActions:k,groupHeaderRightPadding:Yt,dragHandleProps:Ce,groupPrColor:te,groupPrSummary:q,groupActivityIndicator:xt,showBranchSubtitle:kt,statusLine:At,allGroupSessions:ss,projectId:r,activeProjectId:C,setActiveProjectIdOnly:j,setActiveMainTab:w,mobileVariant:E,setSessionSwitcherOpen:N,openNewSessionDraft:M}),X?null:s.jsx("div",{className:"oc-group-body",children:us})]})}const vp=a.memo(wp,xp);function Sp(e){const{hideDirectoryControls:t,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:i,instanceLabel:l,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:f,setIsSessionSearchOpen:p,sessionSearchInputRef:x,sessionSearchQuery:y,setSessionSearchQuery:m,hasSessionSearchQuery:h,searchMatchCount:b,selectionModeEnabled:g,onToggleSelectionMode:S,mobileVariant:v=!1}=e;if(t)return null;const E=_(u,"text-muted-foreground hover:text-foreground",!v&&"hover:bg-transparent");return s.jsx("div",{className:_("select-none flex-shrink-0",v?"px-2":"px-2 py-1"),children:s.jsxs("div",{className:_("flex flex-col",v?"gap-0":"h-auto min-h-8 gap-1"),children:[s.jsxs("div",{className:_("flex items-center justify-between",v?"h-[var(--oc-header-height,56px)] gap-1":"min-h-8 gap-2 px-2"),children:[s.jsxs("div",{className:_("flex min-w-0 items-center",v?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":v?"true":void 0,children:[o?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:E,"aria-label":"Settings",children:s.jsx(P,{name:"settings-3",className:d})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}):null,!v&&i?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:i,className:E,"aria-label":l?`Servers: ${l}`:"Servers",children:s.jsx(P,{name:"server",className:d})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:l||"Servers"})})]}):null,c?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:E,"aria-label":"Update",children:s.jsx(P,{name:"download",className:d})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Update"})})]}):null,v?null:s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:E,"aria-label":"Add project",children:s.jsx(P,{name:"folder-add",className:d})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Add project"})})]}),v?null:s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:E,"aria-label":"Archive",children:s.jsx(P,{name:"archive",className:d})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Archive"})})]})]}),s.jsxs("div",{className:_("flex shrink-0 items-center",v?"gap-1":"gap-1.5"),children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>p(k=>!k),className:E,"aria-label":"Search sessions","aria-expanded":f,children:s.jsx(P,{name:"search",className:d})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Search sessions"})})]}),s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:S,className:_(E,g&&"bg-interactive-hover text-primary"),"aria-label":g?"Exit selection":"Select sessions","aria-pressed":g,children:s.jsx(P,{name:"checkbox-multiple",className:d})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:g?"Exit selection":"Select sessions"})})]})]})]}),f?s.jsxs("div",{className:_(v?"pb-2":"pb-1"),children:[s.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-muted-foreground/80",children:h?s.jsx("span",{children:b===1?`${b} match`:`${b} matches`}):s.jsx("span",{})}),s.jsxs("div",{className:"relative",children:[s.jsx(P,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),s.jsx("input",{ref:x,value:y,onChange:k=>m(k.target.value),placeholder:"Search sessions...",className:"h-8 w-full rounded-md border border-border bg-transparent pl-8 pr-8 typography-ui-label text-foreground outline-none focus-visible:ring-2 focus-visible:ring-primary/50",onKeyDown:k=>{k.key==="Escape"&&(k.stopPropagation(),h?m(""):p(!1))}}),y.length>0?s.jsx("button",{type:"button",onClick:()=>m(""),className:"absolute right-1 top-1/2 inline-flex h-6 w-6 -translate-y-1/2 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Clear search",children:s.jsx(P,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}const $r="0.75rem";function jp(e){const t=de(o=>o.toggleSidebar),n=de(o=>o.shortcutOverrides),r=Wo(cr("toggle_sidebar",n));return s.jsxs("div",{className:"app-region-drag select-none flex h-[var(--oc-header-height,3rem)] shrink-0 items-center pr-3",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:`var(--oc-titlebar-left-inset, ${$r})`}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:`max(0px, calc(var(--oc-titlebar-overlay-width, 0px) - var(--oc-titlebar-left-inset, ${$r})))`}}),s.jsxs("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center gap-1.5",children:[s.jsxs("button",{type:"button",onClick:e.onNewSession,className:_("group flex min-w-0 flex-1 items-center gap-1.5 text-left text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e.touchFriendly&&"min-h-11"),style:{paddingLeft:`max(3px, calc(${kf} - max(var(--oc-titlebar-left-inset, ${$r}), var(--oc-titlebar-overlay-width, 0px))))`},children:[s.jsx(P,{name:"chat-new",className:_(sr,"text-current")}),s.jsx("span",{className:ll,children:"New session"})]}),e.showSidebarToggle?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,className:"inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50","aria-label":"Hide sessions",children:s.jsx(P,{name:"layout-left",className:"size-4"})})}),s.jsx(Ke,{children:s.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}function kr({...e}){return s.jsx(Ca,{...e})}function Ar({...e}){return s.jsx(ka,{...e})}function Nr({className:e,positionerClassName:t,children:n,style:r,...o}){return s.jsx(Aa,{children:s.jsx(Na,{className:_("app-region-no-drag z-50",t),children:s.jsx(Ia,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_(Ka,e),...o,children:n})})})}function Ps({className:e,...t}){return s.jsx(Ea,{className:_(Wa,e),...t})}function Jl({className:e,...t}){return s.jsx(Ra,{className:_(Ga,e),...t})}const Xl=500,Cp=({projectId:e,worktree:t,isSelected:n,hasActive:r,onSelect:o,onClose:i,mobileVariant:l=!1})=>{const[c,d]=a.useState(!1),u=a.useRef(null),f=t.branch||(t.detached?"Detached HEAD":t.name),p=a.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]);a.useEffect(()=>()=>p(),[p]);const x=a.useCallback(()=>{p(),u.current=window.setTimeout(()=>{u.current=null,d(!0)},Xl)},[p]);return s.jsxs(kr,{open:c,onOpenChange:d,children:[s.jsxs(Ar,{render:s.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:x,onTouchMove:p,onTouchEnd:p,onTouchCancel:p,style:{touchAction:"manipulation"},className:_(xr(l,n),"pl-6"),"aria-pressed":n,title:t.path}),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[s.jsx(P,{name:"git-branch",className:_(Fs(l),"text-muted-foreground")}),s.jsx("span",{className:an(l),children:f})]}),s.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?s.jsx(vs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),s.jsx(Nr,{className:"min-w-[160px]",children:s.jsxs(Ps,{disabled:!i,title:r?"Stop the active session before closing this worktree.":void 0,onClick:()=>i?.(e,t),className:"text-destructive focus:text-destructive",children:[s.jsx(P,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close worktree"})]})})]})},xr=(e,t)=>_("relative flex w-full items-center gap-1.5 rounded-xl px-3 py-2 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",e&&"py-1.5",t?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),kp=({project:e,label:t,isSelected:n,hasActive:r,hasWorktrees:o,worktreeError:i,isExpanded:l,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:p=!1})=>{const{listeners:x,setNodeRef:y,transform:m,transition:h,isDragging:b}=Uo({id:e.id,disabled:!c}),[g,S]=a.useState(!1),v=a.useRef(null),E=a.useCallback(()=>{v.current!==null&&(window.clearTimeout(v.current),v.current=null)},[]);a.useEffect(()=>()=>E(),[E]);const k=a.useCallback(()=>{E(),v.current=window.setTimeout(()=>{v.current=null,S(!0)},Xl)},[E]);return s.jsx("div",{ref:y,style:{transform:$o.Translate.toString(m),transition:h},className:_(b&&"opacity-60"),children:s.jsxs(kr,{open:g,onOpenChange:S,children:[s.jsxs(Ar,{render:s.jsx("button",{type:"button",onClick:()=>{g||d()},onTouchStart:k,onTouchMove:E,onTouchEnd:E,onTouchCancel:E,style:{touchAction:"manipulation"},className:xr(p,n),"aria-pressed":n}),children:[s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:[s.jsx("span",{className:_("inline-flex size-4 shrink-0 items-center justify-center",c&&"touch-none select-none cursor-grab active:cursor-grabbing"),"aria-label":c?`Reorder ${t}`:void 0,...c?x:{},children:s.jsx(P,{name:"folder",className:_(Fs(p),"text-muted-foreground")})}),s.jsx("span",{className:an(p),children:t})]}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?s.jsx(vs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null,i?s.jsx("span",{title:i,"aria-label":"Worktree discovery failed",children:s.jsx(P,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?s.jsx(P,{name:l?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),s.jsxs(Nr,{className:"min-w-[160px]",children:[s.jsxs(Ps,{onClick:()=>u(e.id),children:[s.jsx(P,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Edit folder"})]}),s.jsx(Jl,{}),s.jsxs(Ps,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[s.jsx(P,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close folder"})]})]})]})})},Ap=({projects:e,selectedProjectId:t,selectedWorktreePath:n=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:i,onSelectWorktree:l,onCloseWorktree:c,onOpenDirectoryDialog:d,onOpenProjectEditDialog:u,onRemoveProject:f,hasActiveSessionByProject:p,activeDirectoriesByProject:x,homeDirectory:y,className:m,mobileVariant:h=!1})=>{const b=t===null,g=dt(k=>k.reorderProjects),S=e.length>1,v=Bo(Mn(Ta,{activationConstraint:{distance:8}}),Mn(Ma,{activationConstraint:{delay:200,tolerance:6}})),E=a.useCallback(k=>{const{active:C,over:j}=k;if(!j||C.id===j.id)return;const w=dt.getState().projects,N=w.findIndex(F=>F.id===C.id),M=w.findIndex(F=>F.id===j.id);N<0||M<0||g(N,M)},[g]);return s.jsxs("div",{className:_("select-none px-2 pt-1 pb-2 border-b border-border/40 space-y-0.5",m),children:[s.jsx("button",{type:"button",onClick:()=>i(null),className:xr(h,b),"aria-pressed":b,children:s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx(P,{name:"chat-history",className:Fs(h)}),s.jsx("span",{className:an(h),children:"All sessions"})]})}),s.jsx(_o,{sensors:v,collisionDetection:zo,onDragEnd:E,children:s.jsx(Da,{items:e.map(k=>k.id),strategy:Pa,children:e.map(k=>{const C=t===k.id,j=C&&!n,w=r.get(k.normalizedPath)??[],N=Go(k.label?.trim()||Fn(k.normalizedPath,y)||k.normalizedPath),M=x?.get(k.id),F=Ee(k.normalizedPath)?.toLowerCase()??"",$=F?M?.has(F)??!1:!1,U=(M?.size??0)>0,K=p?.(k.id)??!1,L=x?C?$:U:K;return s.jsxs(a.Fragment,{children:[s.jsx(kp,{project:k,label:N,isSelected:j,hasActive:L,hasWorktrees:w.length>0,worktreeError:o.get(k.normalizedPath),isExpanded:C,canDrag:S,onSelect:()=>i(k.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:h}),C?w.map(D=>{const R=n===D.path,I=Ee(D.path)?.toLowerCase()??"",T=I?M?.has(I)??!1:!1,W=x?T:!1;return s.jsx(Cp,{projectId:k.id,worktree:D,isSelected:R,hasActive:W,onSelect:()=>l?.(k.id,D.path),onClose:c,mobileVariant:h},D.path)}):null]},k.id)})})}),s.jsxs("button",{type:"button",onClick:d,className:xr(h,!1),children:[s.jsx(P,{name:"add",className:Fs(h)}),s.jsx("span",{className:an(h),children:"Add folder"})]})]})},Kr="inline-flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";function Np({onOpenSettings:e,onOpenShortcuts:t,onOpenAbout:n,onOpenUpdate:r,showRuntimeButtons:o=!0,showUpdateButton:i=!0}){return!o&&!i?null:s.jsxs("div",{className:"flex shrink-0 items-center justify-start gap-1 px-3 py-2",children:[o?s.jsxs(s.Fragment,{children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:e,className:Kr,"aria-label":"Settings",children:s.jsx(P,{name:"settings-3",className:"size-4"})})}),s.jsx(Ke,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}),s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,className:Kr,"aria-label":"Shortcuts",children:s.jsx(P,{name:"command",className:"size-4"})})}),s.jsx(Ke,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Shortcuts"})})]}),s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:Kr,"aria-label":"About PiChamber",children:s.jsx(P,{name:"information",className:"size-4"})})}),s.jsx(Ke,{side:"top",sideOffset:4,children:s.jsx("p",{children:"About PiChamber"})})]})]}):null,i?s.jsx(Ne,{type:"button",variant:"default",size:"xs",className:"ml-auto border-[var(--status-info-border)] bg-[var(--status-info-background)] text-[var(--status-info)] hover:bg-[var(--status-info-background)]/80 hover:text-[var(--status-info)] dark:border-[var(--status-info-border)] dark:bg-[var(--status-info-background)] dark:hover:bg-[var(--status-info-background)]/80",onClick:r,children:"Update"}):null]})}const Zl=({projectLabel:e,mobileVariant:t=!1})=>{const n=Fs(t),r=an(t);return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:_("inline-flex shrink-0 items-center justify-center",n),children:s.jsx(P,{name:"folder",className:_(n,"text-muted-foreground/80")})}),s.jsx("span",{className:_(r,"text-foreground"),children:e})]})},ec=({isCollapsed:e,mobileVariant:t=!1,className:n})=>s.jsx("span",{className:_("ml-auto inline-flex shrink-0 items-center text-muted-foreground",n),children:s.jsx(P,{name:e?"arrow-right-s":"arrow-down-s",className:Fs(t)})}),Ip=({id:e,disabled:t=!1,projectLabel:n,projectDescription:r,isCollapsed:o,hideDirectoryControls:i,mobileVariant:l,alwaysShowActions:c,stickyHeader:d=!1,onToggle:u,onNewSession:f,onRenameStart:p,onClose:x,children:y,showCreateButtons:m=!0,hideHeader:h=!1,openSidebarMenuKey:b,setOpenSidebarMenuKey:g,statusIndicator:S=null})=>{const{listeners:v,setNodeRef:E,transform:k,transition:C,isDragging:j}=Uo({id:e,disabled:t}),w=a.useRef(!1),N=`project:${e}`,M=b===N,[F,$]=a.useState(!1),U=d&&!o,K=a.useCallback(G=>{G&&$(!1),g(G?N:null)},[N,g]),L=G=>s.jsxs(s.Fragment,{children:[m&&!i&&f&&s.jsxs(G,{onClick:f,children:[s.jsx(P,{name:"add",className:"mr-1.5 h-4 w-4"}),"New session"]}),s.jsxs(G,{onClick:p,children:[s.jsx(P,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),"Edit folder"]}),s.jsxs(G,{onClick:x,className:"text-destructive focus:text-destructive",children:[s.jsx(P,{name:"close",className:"mr-1.5 h-4 w-4"}),"Close folder"]})]}),D=a.useCallback(G=>{G.stopPropagation()},[]),R=a.useCallback(G=>{G.stopPropagation()},[]),I=a.useCallback(G=>{G.stopPropagation()},[]),T=a.useCallback(G=>{(G.button===2||G.button===0&&G.ctrlKey)&&(w.current=!0)},[]),W=a.useCallback(G=>{if(G.currentTarget.blur(),w.current){w.current=!1;return}u()},[u]);return s.jsxs("div",{ref:E,style:{transform:$o.Translate.toString(k),transition:C},className:_("relative",j&&"opacity-60"),children:[h?null:s.jsxs(kr,{open:F,onOpenChange:$,children:[s.jsxs(Ar,{render:s.jsx("div",{className:_("text-left group/project select-none",U&&"oc-sidebar-sticky-header sticky top-0 z-20 bg-sidebar before:pointer-events-none before:absolute before:inset-x-0 before:bottom-full before:h-2 before:bg-sidebar"),"data-sidebar-sticky-header":U?"true":void 0,onContextMenu:G=>{i||j||(G.preventDefault(),$(!0))}}),children:[s.jsxs("div",{"data-sidebar-tree-row":"",className:"relative flex items-center gap-1 py-1.5 px-3 rounded-xl transition-colors hover:bg-interactive-hover",children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsxs("button",{type:"button","aria-expanded":!o,style:{touchAction:"manipulation"},onMouseDown:T,onClick:W,...v,className:_(Cr,"flex-1 min-w-0 flex items-center text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md cursor-grab active:cursor-grabbing"),children:[s.jsx(Zl,{id:e,projectLabel:n,mobileVariant:l}),S?s.jsx("span",{className:"ml-1 inline-flex flex-shrink-0 items-center",children:S}):null,s.jsx(ec,{isCollapsed:o,mobileVariant:l,className:_("transition-[padding]",c?"pl-16":"pl-2 group-hover/project:pl-14 group-focus-within/project:pl-14")})]})}),s.jsx(Ke,{side:"right",sideOffset:8,children:r})]}),s.jsx("div",{className:"absolute right-[calc(3.25rem*var(--padding-scale,1))] top-1/2 z-10 -translate-y-1/2",children:i?null:s.jsxs(Wt,{open:M,onOpenChange:K,children:[s.jsx(Gt,{asChild:!0,children:s.jsx("button",{type:"button",className:_("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 hover:text-foreground",M?"opacity-100 pointer-events-auto":c?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":"Folder menu",onPointerDown:R,onMouseDown:I,onClick:D,children:s.jsx(P,{name:"more-2",className:"size-4"})})}),s.jsx(Ht,{align:"end",className:"min-w-[180px]",children:L(ut)})]})}),m&&!i&&f?s.jsx("div",{className:"absolute right-7 top-1/2 z-10 -translate-y-1/2",children:s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:G=>{G.stopPropagation(),f()},className:_("inline-flex h-6 w-6 items-center justify-center rounded-md text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",c?"opacity-100":"opacity-0 pointer-events-none group-hover/project:opacity-100 group-hover/project:pointer-events-auto group-focus-within/project:opacity-100 group-focus-within/project:pointer-events-auto"),"aria-label":"New session",children:s.jsx(P,{name:"add",className:"h-4 w-4"})})}),s.jsx(Ke,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session"})})]})}):null]}),U?s.jsx("span",{"aria-hidden":!0,className:"oc-sidebar-sticky-header-fade pointer-events-none absolute inset-x-0 top-full h-4 bg-gradient-to-b from-sidebar to-transparent"}):null]}),s.jsx(Nr,{className:"min-w-[180px]",children:L(Ps)})]}),y]})},Ep=({id:e,disabled:t=!1,children:n})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:i,transform:l,transition:c,isDragging:d}=Uo({id:e,disabled:t}),u=a.useMemo(()=>({listeners:r,setActivatorNodeRef:i}),[r,i]);return s.jsx("div",{ref:o,style:{transform:$o.Transform.toString(l),transition:c},className:_("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};a.memo(Ep);const ta="pt-0.5 pb-1",Rp=({sections:e,homeSection:t,homeDirectory:n,collapsedProjects:r,toggleProject:o,hasSessionSearchQuery:i,activeProjectId:l,hideDirectoryControls:c,mobileVariant:d,alwaysShowActions:u,isInlineEditing:f,stickyFolderHeaders:p,renderGroupSessions:x,renderSessionNode:y,getOrderedGroups:m,renderProjectStatusIndicator:h,scrollContainerRef:b,setActiveProjectIdOnly:g,setActiveMainTab:S,setSessionSwitcherOpen:v,openNewSessionDraft:E,openProjectEditDialog:k,removeProject:C,reorderProjects:j,openSidebarMenuKey:w,setOpenSidebarMenuKey:N,onOpenDirectoryDialog:M,emptyState:F,searchEmptyState:$})=>{const U=Bo(Mn(Ta,{activationConstraint:{distance:8}}),Mn(Ma,{activationConstraint:{delay:200,tolerance:6}})),K=e.length>1&&!i&&!f,L=a.useCallback(B=>{if(f||i)return;const{active:be,over:V}=B;if(!V||be.id===V.id)return;const Ce=dt.getState().projects,De=Ce.findIndex(z=>z.id===be.id),H=Ce.findIndex(z=>z.id===V.id);De<0||H<0||De===H||j(De,H)},[f,i,j]),[D,R]=a.useState(5);a.useEffect(()=>{R(5)},[i]);const I=a.useMemo(()=>t?t.groups.filter(B=>!B.isArchivedBucket).flatMap(B=>B.sessions):[],[t]),T=i?I:I.slice(0,D),W=I.length-T.length,G=i?!1:r.has("__home__");return e.length===0&&!t?i?$:F:s.jsxs("div",{className:"space-y-2",children:[s.jsx(_o,{sensors:U,collisionDetection:zo,onDragEnd:L,children:s.jsx(Da,{items:e.map(B=>B.project.id),strategy:Pa,children:e.map(B=>{const be=B.project,V=be.id,Ce=cl(be,n),De=co(be.normalizedPath,n),H=i?!1:r.has(V),z=H?[]:m(V,B.groups),Q=H?null:z.find(ne=>ne.isMain)??null,X=H?[]:Q?z.filter(ne=>ne.id!==Q.id):z;return s.jsx(Ip,{id:V,disabled:!K,projectLabel:Ce,projectDescription:De,isCollapsed:H,hideDirectoryControls:c,mobileVariant:d,alwaysShowActions:u,stickyHeader:p,statusIndicator:H?h?.(V,B.groups):null,onToggle:()=>o(V),onNewSession:()=>{V!==l&&g(V),S("chat"),d&&v(!1),E({selectedProjectId:V,directoryOverride:be.normalizedPath})},onRenameStart:()=>k(V),onClose:()=>C(V),openSidebarMenuKey:w,setOpenSidebarMenuKey:N,children:H?null:s.jsxs("div",{className:ta,children:[Q?x(Q,`${V}:${Q.id}`,V,!0,null,void 0,b):null,X.map(ne=>{const we=`${V}:${ne.id}`,me=z.length===1;return s.jsx(a.Fragment,{children:x(ne,we,V,me,null,void 0,b)},ne.id)})]})},V)})})}),t?s.jsxs("div",{children:[s.jsx("div",{"data-sidebar-tree-row":"",className:"relative flex items-center gap-1 py-1.5 px-3 rounded-xl transition-colors hover:bg-interactive-hover",children:s.jsxs("button",{type:"button","aria-expanded":!G,style:{touchAction:"manipulation"},onClick:()=>o("__home__"),className:`${Cr} flex-1 min-w-0 flex items-center text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 rounded-md`,children:[s.jsx(Zl,{id:"__home__",projectLabel:"No folder",mobileVariant:d}),s.jsx(ec,{isCollapsed:G,mobileVariant:d})]})}),G?null:s.jsxs("div",{className:ta,children:[T.map(B=>s.jsx(a.Fragment,{children:y?.(B,0,B.session.directory??"~","__home__",!1,{globalSession:!0},"project")},B.session.id)),!i&&W>0?s.jsx(Xt,{icon:"arrow-down-s",mobileVariant:d,onClick:()=>R(B=>B+7),children:W===1?"Show 1 more session":`Show ${W} more sessions`}):null,!i&&D>5&&I.length>5?s.jsx(Xt,{icon:"arrow-up-s",mobileVariant:d,onClick:()=>R(5),children:"Show fewer sessions"}):null]})]}):null,!c&&M?s.jsx(Xt,{icon:"add",mobileVariant:d,onClick:M,children:"Add folder"}):null]})},Dp=a.memo(Rp);function Pp(e){Kt("ui.sidebar_projects_list.render");const t=e.viewMode??"workspace",n=t==="timeline",r=a.useRef(new Map),o=a.useRef(e.getOrderedGroups);o.current!==e.getOrderedGroups&&(o.current=e.getOrderedGroups,r.current.clear());const i=(b,g)=>{const S=r.current,v=S.get(b);if(v&&v.groups===g)return v.ordered;const E=e.getOrderedGroups(b,g);if(S.set(b,{groups:g,ordered:E}),S.size>256){const k=S.keys().next().value;k!==void 0&&S.delete(k)}return E},l=a.useRef(null),c=!!(e.isAllFoldersView||n),d=a.useMemo(()=>{if(!c)return[];const b=[],g=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const S of g){const v=cl(S.project,e.homeDirectory);for(const E of S.groups)if(!E.isArchivedBucket)for(const k of E.sessions){const C=!!e.pinnedSessionIds?.has(k.session.id),j=k.session.time?.updated||k.session.time?.created||0;b.push({node:k,project:S.project,projectLabel:v,isPinned:C,timestamp:j,globalSession:S===e.allFoldersOnlySection})}}return b.sort((S,v)=>S.isPinned!==v.isPinned?S.isPinned?-1:1:v.timestamp-S.timestamp),b},[e.allFoldersOnlySection,c,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),[u,f]=a.useState(30);a.useEffect(()=>{f(30)},[e.hasSessionSearchQuery]);const p=a.useMemo(()=>d.slice(0,u),[d,u]),x=a.useMemo(()=>e.timelineBoundaries??Co(Date.now(),1),[e.timelineBoundaries]),y=a.useMemo(()=>n?nm(p,{getTimestamp:b=>b.timestamp,isPinned:b=>b.isPinned,boundaries:x}):[],[n,p,x]);if(e.sharedSessionsOnly)return s.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const m=(e.isAllFoldersView||t==="timeline"||t==="folder")&&!!e.allFoldersOnlySection;if(e.projectSections.length===0&&!m)return s.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.emptyState]})});if(e.sectionsForRender.length===0&&!m)return s.jsx(Is,{useScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("pt-2 pb-1",e.mobileVariant&&"pb-32"),children:s.jsx("div",{className:"space-y-1 px-2",children:e.searchEmptyState})});const h=()=>{const b=d.length-p.length;return s.jsxs(s.Fragment,{children:[b>0?s.jsx(Xt,{icon:"arrow-down-s",onClick:()=>f(g=>g+30),children:b===1?"Show 1 more session":`Show ${b} more sessions`}):null,u>30&&d.length>30?s.jsx(Xt,{icon:"arrow-up-s",onClick:()=>f(30),children:"Show fewer sessions"}):null]})};return s.jsx("div",{className:"relative flex min-h-0 flex-1",children:s.jsx(Is,{ref:l,useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:96,outerClassName:"flex-1 min-h-0",className:_("oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",e.mobileVariant&&"pb-32"),children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const b=e.sectionsForRender.find(E=>E.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!b)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const g=b.groups.find(E=>E.isMain&&E.sessions.length>0)??b.groups.find(E=>E.sessions.length>0)??b.groups.find(E=>E.isMain)??b.groups[0];if(!g)return s.jsx(Xt,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:b.project.id,directoryOverride:b.project.normalizedPath}),children:"New session"});const S=b.groups.find(E=>E.isArchivedBucket);return[g,...S&&S.id!==g.id?[S]:[]].map(E=>{const k=`${b.project.id}:${E.id}`,C=E.id===g.id;return s.jsx(a.Fragment,{children:e.renderGroupSessions(E,k,b.project.id,C,null,!0,l)},k)})})()}):t==="folder"?s.jsx(Yo.Provider,{value:"tree",children:s.jsx(Dp,{sections:e.sectionsForRender,homeSection:e.allFoldersOnlySection,homeDirectory:e.homeDirectory,collapsedProjects:e.collapsedProjects,toggleProject:e.toggleProject,hasSessionSearchQuery:e.hasSessionSearchQuery,activeProjectId:e.activeProjectId,hideDirectoryControls:e.hideDirectoryControls,mobileVariant:e.mobileVariant,alwaysShowActions:e.alwaysShowActions,isInlineEditing:e.isInlineEditing,stickyFolderHeaders:e.stickyFolderHeaders,renderGroupSessions:e.renderGroupSessions,renderSessionNode:e.renderSessionNode,getOrderedGroups:i,renderProjectStatusIndicator:e.renderProjectStatusIndicator,scrollContainerRef:l,setActiveProjectIdOnly:e.setActiveProjectIdOnly,setActiveMainTab:e.setActiveMainTab,setSessionSwitcherOpen:e.setSessionSwitcherOpen,openNewSessionDraft:e.openNewSessionDraft,openProjectEditDialog:e.openProjectEditDialog,removeProject:e.removeProject,reorderProjects:e.reorderProjects,openSidebarMenuKey:e.openSidebarMenuKey,setOpenSidebarMenuKey:e.setOpenSidebarMenuKey,onOpenDirectoryDialog:e.onOpenDirectoryDialog,emptyState:e.emptyState,searchEmptyState:e.searchEmptyState})}):t==="timeline"&&e.renderSessionNode?s.jsx("div",{children:d.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[y.map((b,g)=>{const S=em[b.id];return s.jsxs("section",{"aria-label":S,"data-timeline-bucket":b.id,children:[s.jsx("div",{role:"heading","aria-level":3,className:_("select-none px-3 pb-1 text-xs leading-4 font-medium text-muted-foreground",g===0?"pt-1":"pt-3"),children:S}),b.items.map(({node:v,project:E,projectLabel:k,globalSession:C})=>{const j=v.session.directory??E.normalizedPath;return s.jsx(a.Fragment,{children:e.renderSessionNode(v,0,j,E.id,!1,{projectLabel:k,showFolderLabel:!0,globalSession:C},"project")},v.session.id)})]},b.id)}),h()]})}):e.isAllFoldersView&&e.renderSessionNode?s.jsx("div",{children:d.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[p.map(({node:b,project:g,projectLabel:S,globalSession:v})=>{const E=b.session.directory??g.normalizedPath;return s.jsx(a.Fragment,{children:e.renderSessionNode(b,0,E,g.id,!1,{projectLabel:S,showFolderLabel:!0,globalSession:v},"project")},b.session.id)}),h()]})}):s.jsx("div",{children:e.sectionsForRender.map(b=>{const g=b.project.id,S=i(g,b.groups),v=S.find(k=>k.isMain)??null,E=v?S.filter(k=>k.id!==v.id):S;return s.jsxs("div",{children:[v?e.renderGroupSessions(v,`${g}:${v.id}`,g,!0,null,void 0,l):null,E.map(k=>{const C=`${g}:${k.id}`,j=S.length===1;return s.jsx(a.Fragment,{children:e.renderGroupSessions(k,C,g,j,null,void 0,l)},k.id)})]},g)})})]})})})}const Mp=a.memo(Pp);let Mo=!1;const To=new Set;let sa=!1;function Tp(){for(const e of To)e()}function Xo(e){Mo!==e&&(Mo=e,Tp())}function Fp(e){e.key==="Shift"&&Xo(!0)}function Lp(e){e.key==="Shift"&&Xo(!1)}function Op(){Xo(!1)}function Bp(){sa||typeof window>"u"||(sa=!0,window.addEventListener("keydown",Fp),window.addEventListener("keyup",Lp),window.addEventListener("blur",Op))}function _p(e){return Bp(),To.add(e),()=>{To.delete(e)}}function zp(){return Mo}function Up(){return!1}function $p(){return Re.useSyncExternalStore(_p,zp,Up)}const Kp=a.memo(function({archiveLabel:t,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:i,onMouseDown:l,onArchive:c,onDelete:d}){const u=$p(),f=u?n:t,p=x=>{if(u||x.shiftKey){d(x);return}c(x)};return s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",className:_("inline-flex items-center justify-center rounded-md focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 transition-opacity",u?"text-destructive hover:text-destructive":"text-muted-foreground hover:text-foreground",r),"aria-label":f,onPointerDown:i,onMouseDown:l,onClick:p,onKeyDown:x=>x.stopPropagation(),children:s.jsx(P,{name:u?"delete-bin":"archive",className:o})})}),s.jsx(Ke,{side:"left",sideOffset:8,children:f})]})}),Wp=a.memo(function({open:t,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,onExport:l}){return s.jsx(es,{open:t,onOpenChange:n,children:s.jsxs(ts,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Ss,{children:[s.jsx(ds,{children:"Export Markdown"}),s.jsx(js,{children:r===1?`This session has ${r} sub-agent task. Include it in the export?`:`This session has ${r} sub-agent tasks. Include them in the export?`})]}),s.jsxs("label",{className:"flex items-center gap-2 typography-ui-label cursor-pointer",children:[s.jsx("input",{type:"checkbox",checked:o,onChange:c=>i(c.target.checked),className:"h-4 w-4 rounded border-border accent-primary"}),"Include sub-agent tasks"]}),s.jsxs(Ls,{children:[s.jsx(Ne,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),s.jsx(Ne,{type:"button",onClick:()=>{n(!1),l(o)},size:"sm",children:"Export"})]})]})})});function Gp(e,t){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:i,archivedBucket:l,isElectron:c,pendingRenameRef:d,handleCopySessionId:u,togglePinnedSession:f,handleExportSession:p,handleOpenMiniChatWindow:x,handleDeleteSession:y,handleRestoreSession:m}=e,{Item:h,Separator:b}=t;return s.jsxs(s.Fragment,{children:[s.jsxs(h,{onClick:()=>{d.current={id:n.id,title:r}},className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),s.jsxs(h,{onClick:()=>u(n.id),className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),s.jsxs(h,{onClick:()=>o&&f({directory:o,sessionId:n.id}),className:"[&>svg]:mr-1",children:[i?s.jsx(P,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(P,{name:"pushpin",className:"mr-1 h-4 w-4"}),i?"Unpin session":"Pin session"]}),s.jsxs(h,{onClick:()=>{p()},className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?s.jsxs(h,{disabled:!o,onClick:x,className:"[&>svg]:mr-1",children:[s.jsx(P,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:"Open in Mini Chat Window"})]}):null,s.jsx(b,{}),l?null:s.jsxs(h,{className:"[&>svg]:mr-1",onClick:()=>y(n,{archivedBucket:l}),children:[s.jsx(P,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),l?s.jsxs(h,{className:"[&>svg]:mr-1",onClick:()=>m(n),children:[s.jsx(P,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Restore"]}):null,s.jsxs(h,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>y(n,{archivedBucket:l,hardDelete:!0}),children:[s.jsx(P,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function Hp(e){const{renamingFolderId:t,editingIdRef:n}=e;return s.jsx(Aa,{children:s.jsx(Na,{className:"app-region-no-drag z-50",children:s.jsx(Ia,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(t||n.current),style:{color:"var(--surface-elevated-foreground)"},className:_(Ka,"min-w-[180px]"),children:Gp(e,{Item:({className:r,...o})=>s.jsx(Ea,{className:_(Wa,r),...o}),Separator:({className:r,...o})=>s.jsx(Ra,{className:_(Ga,r),...o})})})})})}const Wr=new WeakMap,qp=e=>{if(typeof window>"u")return;const t=e.closest("[data-session-row]"),n=t?.closest(".overlay-scrollbar-container");if(!t||!n)return;Wr.get(n)?.();const r=t.getBoundingClientRect().top;let o=3,i=!1,l=null;const c=()=>{i=!0,l!==null&&window.cancelAnimationFrame(l),l=null,Wr.delete(n),n.removeEventListener("wheel",c),n.removeEventListener("touchstart",c)},d=()=>{if(i||!t.isConnected||!n.isConnected){c();return}const u=t.getBoundingClientRect().top-r;if(Math.abs(u)>.5&&(n.scrollTop+=u,Kt("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}l=window.requestAnimationFrame(d)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),Wr.set(n,c),l=window.requestAnimationFrame(d)};function Yp(e){if(typeof e!="number"||!Number.isFinite(e))return"";const t=new Date(e);if(Number.isNaN(t.getTime()))return"";const n=t.toLocaleString("en-US",{month:"short"}),r=t.getDate(),o=t.getFullYear(),i=String(t.getHours()).padStart(2,"0"),l=String(t.getMinutes()).padStart(2,"0");return`${n} ${r}, ${o}, ${i}:${l}`}function Vp(e){if(e.info.role==="user")return"";const t=typeof e.info.providerID=="string"?e.info.providerID.trim():"",n=typeof e.info.modelID=="string"?e.info.modelID.trim():"";return t&&n?`${t}/${n}`:n||t}function Qp(e){const t=e.info.role==="user"?"User":"Assistant",n=Yp(e.info.time?.created),r=Vp(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${t}**
21
+
22
+ *${o}*`:`**${t}**`}function Jp(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join("")}function tc(e){const t=Qp(e),n=Jp(e.parts).trim();return n?`${t}
23
+
24
+ ${n}`:""}function sc(e,t){const n="#".repeat(Math.min(t+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${n} Sub-agent: ${e.title}${r}
25
+
26
+ ---
27
+
28
+ `,i=e.records.map(tc).filter(Boolean).join(`
29
+
30
+ ---
31
+
32
+ `),l=[o+i];for(const c of e.children)l.push(sc(c,t+1));return l.join(`
33
+
34
+ ---
35
+
36
+ `)}function nc(e,t,n){const r=t?.trim()||"Session",o=new Date().toISOString().split("T")[0],i=`# ${r}
37
+
38
+ *Exported on ${o}*
39
+
40
+ ---
41
+
42
+ `,l=e.map(tc).filter(Boolean).join(`
43
+
44
+ ---
45
+
46
+ `);let c=i+l;if(n&&n.length>0){const d=n.map(u=>sc(u,1)).join(`
47
+
48
+ ---
49
+
50
+ `);c+=`
51
+
52
+ ---
53
+
54
+ `+d}return c}function rc(e,t){Df({filename:t,mimeType:"text/markdown;charset=utf-8",data:e}).catch(n=>console.warn("[export] Markdown save failed",n))}async function oc(e,t){const n=await Zu(t,e);return n||null}async function Xp(e){const t=tl()?.files;if(t?.revealPath)try{return!!(await t.revealPath(e))?.success}catch{return!1}return await ef(e)?!0:sl(e)}function Zp(){return tf()}function ic(e){const r=(e?.trim()||"session").normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"-").replace(/^-+|-+$/g,"").slice(0,60)||"session",o=new Date().toISOString().split("T")[0];return`${r}-${o}.md`}const yr=e=>{const t=[],n=r=>{r.children.forEach(o=>{t.push(o.session.id),n(o)})};return n(e),t};function eg(e,t){const[n,r]=a.useState(!1),[o,i]=a.useState(!0),l=e.session,c=a.useMemo(()=>yr(e).length,[e]),d=a.useCallback(async x=>{const y=[];let m=0;for(const h of x)try{if(!t)throw new Error("Session directory is required for export");const b=[],g=h.session.title||"Untitled Sub-agent",S=typeof h.session.agent=="string"?h.session.agent:void 0,v=await d(h.children);m+=v.skipped,y.push({title:g,agent:S,records:b,children:v.children})}catch{m+=yr(h).length+1}return{children:y,skipped:m}},[t]),u=a.useCallback(x=>{x<=0||ae.warning(x===1?`Exported session, but skipped ${x} sub-agent task that could not be loaded.`:`Exported session, but skipped ${x} sub-agent tasks that could not be loaded.`)},[]),f=a.useCallback(async x=>{if(!t){ae.error("Nothing to export");return}const y=[];if(y.length===0){ae.error("Nothing to export");return}let m,h=0;if(x&&e.children.length>0){const v=await d(e.children);m=v.children,h=v.skipped}const b=nc(y,l.title??null,m),g=ic(l.title??null),S=await oc(b,g);if(S){ae.success("Session exported",{action:{label:Zp(),onClick:()=>{Xp(S).then(v=>{v||ae.error("Failed to reveal path")})}}}),u(h);return}rc(b,g),ae.success("Session exported"),u(h)},[d,e.children,l.title,t,u]),p=a.useCallback(async()=>{if(e.children.length>0){i(!0),r(!0);return}await f(!1)},[f,e.children.length]);return{exportDialogOpen:n,setExportDialogOpen:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,descendantCount:c,handleExportSession:p,doExportSession:f}}const tg=(e,t)=>{if(!t)return Array.from(e);const n=[],r=new Set;for(const o of e){r.has(o)||(r.add(o),n.push(o));const i=t.get(o);if(i)for(const l of i)r.has(l)||(r.add(l),n.push(l))}return n},ct=Bs()((e,t)=>({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null,enable:()=>{t().enabled||e({enabled:!0})},disable:()=>{e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null})},toggleMode:()=>{t().enabled?e({enabled:!1,selectedIds:new Set,scopeKey:null,anchorId:null}):e({enabled:!0})},toggleSelected:(n,r,o)=>{const i=t(),l=new Set(i.selectedIds);let c=i.scopeKey,d=i.anchorId;r!==null&&i.scopeKey!==null&&r!==i.scopeKey?(l.clear(),c=r,d=null):c===null&&r!==null&&(c=r);const f=o&&o.length>0?[n,...o]:[n];if(l.has(n)){for(const x of f)l.delete(x);d===n&&(d=null)}else{for(const x of f)l.add(x);d=n}l.size===0?e({selectedIds:l,scopeKey:null,anchorId:null}):e({selectedIds:l,scopeKey:c,anchorId:d})},setRange:(n,r,o,i,l)=>{const c=t();if(o.length===0)return;const d=n&&o.includes(n)?n:o[0],u=o.indexOf(d),f=o.indexOf(r);if(u<0||f<0)return;const[p,x]=u<=f?[u,f]:[f,u],y=o.slice(p,x+1),m=tg(y,l),b=i!==null&&c.scopeKey!==null&&i!==c.scopeKey?new Set:new Set(c.selectedIds);for(const g of m)b.add(g);e({selectedIds:b,scopeKey:i??c.scopeKey,anchorId:d})},replaceAll:(n,r)=>{if(n.length===0){e({selectedIds:new Set,scopeKey:null,anchorId:null});return}e({selectedIds:new Set(n),scopeKey:r,anchorId:n[0]??null})},clear:()=>{e({selectedIds:new Set,scopeKey:null,anchorId:null})},removeMany:n=>{const r=t();if(r.selectedIds.size===0||n.length===0)return;const o=new Set(r.selectedIds);for(const i of n)o.delete(i);o.size!==r.selectedIds.size&&(o.size===0?e({selectedIds:o,scopeKey:null,anchorId:null}):e({selectedIds:o}))}})),na=e=>Ee(e.session.directory??null),sg=(e,t)=>(e?.projectLabel??null)===(t?.projectLabel??null)&&(e?.branchLabel??null)===(t?.branchLabel??null)&&(e?.showFolderLabel??!1)===(t?.showFolderLabel??!1),ng=e=>{if(!e.openSidebarMenuKey)return null;const t=e.archivedBucket?"archived":"active",n=`${e.renderContext??"project"}:${t}:`;return e.openSidebarMenuKey.startsWith(n)?e.openSidebarMenuKey.slice(n.length):null},Xn=e=>e.menuOpenSessionId??ng(e),Zn=(e,t,n)=>t?n.has(e.node.session.id)?!0:ls(e.node,t):!1,Fo=(e,t,n,r,o)=>{if(e.session.id!==t.session.id)return!0;const i=o(e);if(n.has(i)!==r.has(i)||e.children.length!==t.children.length)return!0;for(let l=0;l<e.children.length;l+=1)if(Fo(e.children[l],t.children[l],n,r,o))return!0;return!1},rg=(e,t)=>{if(e.hasSessionSearchQuery||t.hasSessionSearchQuery)return!1;const n=e.archivedBucket?"archived":"active",r=t.archivedBucket?"archived":"active";return Fo(e.node,t.node,e.expandedParents,t.expandedParents,o=>`${e.renderContext??"project"}:${n}:${o.session.id}`)||Fo(e.node,t.node,e.expandedParents,t.expandedParents,o=>`${t.renderContext??"project"}:${r}:${o.session.id}`)},og=(e,t)=>{if(e.node.session.id!==t.node.session.id||e.node.session!==t.node.session||e.depth!==t.depth||e.groupDirectory!==t.groupDirectory||e.projectId!==t.projectId||e.archivedBucket!==t.archivedBucket||(e.renderContext??"project")!==(t.renderContext??"project")||e.mobileVariant!==t.mobileVariant||e.alwaysShowActions!==t.alwaysShowActions||e.allowQuickArchiveAction!==t.allowQuickArchiveAction||e.hasSessionSearchQuery!==t.hasSessionSearchQuery||e.normalizedSessionSearchQuery!==t.normalizedSessionSearchQuery||e.nodeStructureKey!==t.nodeStructureKey||na(e.node)!==na(t.node)||!sg(e.secondaryMeta,t.secondaryMeta)||e.pinnedSessionIds!==t.pinnedSessionIds&&Ll(e.node,t.node,e.pinnedSessionIds,t.pinnedSessionIds,e.groupDirectory,t.groupDirectory)||e.expandedParents!==t.expandedParents&&rg(e,t)||e.editingId!==t.editingId&&(Zn(e,e.editingId,e.subtreeContainsEditing)||Zn(t,t.editingId,t.subtreeContainsEditing))||e.editTitle!==t.editTitle&&(Zn(e,e.editingId,e.subtreeContainsEditing)||Zn(t,t.editingId,t.subtreeContainsEditing))||e.copiedSessionId!==t.copiedSessionId&&(ls(e.node,e.copiedSessionId)||ls(t.node,t.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=Xn(e),r=Xn(t);if(ls(e.node,n)||ls(t.node,r))return!1}if(e.renamingFolderId!==t.renamingFolderId){const n=Xn(e),r=Xn(t);if(ls(e.node,n)||ls(t.node,r))return!1}return e.setEditingId===t.setEditingId&&e.setEditTitle===t.setEditTitle&&e.handleSaveEdit===t.handleSaveEdit&&e.handleCancelEdit===t.handleCancelEdit&&e.toggleParent===t.toggleParent&&e.handleSessionSelect===t.handleSessionSelect&&e.handleSessionDoubleClick===t.handleSessionDoubleClick&&e.togglePinnedSession===t.togglePinnedSession&&e.handleShareSession===t.handleShareSession&&e.handleCopyShareUrl===t.handleCopyShareUrl&&e.handleCopySessionId===t.handleCopySessionId&&e.handleUnshareSession===t.handleUnshareSession&&e.setOpenSidebarMenuKey===t.setOpenSidebarMenuKey&&e.getFoldersForScope===t.getFoldersForScope&&e.getSessionFolderId===t.getSessionFolderId&&e.removeSessionFromFolder===t.removeSessionFromFolder&&e.addSessionToFolder===t.addSessionToFolder&&e.createFolderAndStartRename===t.createFolderAndStartRename&&e.handleDeleteSession===t.handleDeleteSession&&e.handleRestoreSession===t.handleRestoreSession&&e.renderSessionNode===t.renderSessionNode};function ig({node:e,groupDirectory:t,projectId:n,secondaryMeta:r,pinnedSessionIds:o,expandedParents:i,expansionKey:l,hasSessionSearchQuery:c}){const d=e.session,u=Ee(d.directory??null)??Ee(t??null),f=Te(q=>q.currentSessionId===d.id),p=Ha(u),x=du(u),y=dt(a.useCallback(q=>{if(r?.projectLabel||!n)return null;const te=q.projects.find(le=>le.id===n);return te?te.label?.trim()||Fn(Ee(te.path)??te.path,null)||te.path:null},[n,r?.projectLabel])),m=r?.projectLabel??(y?Go(y):null),h=e.worktree,b=r?.branchLabel??h?.branch??(p&&p!=="HEAD"?p:null),g=b,S=x===!0||!!(b||h),v=e.children.length,E=d.agent,k=h?.branch?.trim()||b?.trim()||null,C=Ee(h?.path??u),j=a.useMemo(()=>k&&C?On(C,k):null,[k,C]),w=Bl(j);_l(C,k);const N=w?`var(--pr-${w.visualState})`:void 0,M=a.useMemo(()=>{if(!w)return null;switch(w.visualState){case"merged":return"Merged";case"open":return w.canMerge===!0||w.mergeableState==="clean"||w.checks?.state==="success"?"Ready to merge":"PR open";case"blocked":return w.mergeableState==="dirty"?"Merge conflicts":"Merge blocked";case"draft":return"Draft PR";case"closed":return"Closed";default:return null}},[w]),F=n??u??null,$=ct(q=>q.enabled),U=ct(a.useCallback(q=>q.selectedIds.has(d.id),[d.id])),K=ct(q=>q.toggleSelected),L=ct(q=>q.setRange),R=qa(d.id)?.type??"idle",I=R==="busy"||R==="retry",T=uu(d.id,I),W=xs(d,"Untitled session"),G=e.children.length>0,B=fu(o,u,d.id),be=c?!0:i.has(l),V=hu(d.id);Ya(a.useCallback(q=>q.index.session.unseenHasError[d.id]??!1,[d.id]));const Ce=mu(d.id),De=pu({pendingInput:Ce,isStreaming:I,unseenCount:V,isActive:f}),H=V>0||Va(Ce),z=d.time?.updated||d.time?.created||Date.now(),Q=Af(z),X=a.useMemo(()=>Dl(e.forkColorId),[e.forkColorId]),ne=a.useMemo(()=>hm(e.forkColorId,{active:f||U}),[e.forkColorId,f,U]),we=r?.globalSession&&!f&&!U?"var(--surface-elevated)":null,me=ne??we;return{session:d,sessionDirectory:u,prDirectory:C,prBranch:k,prNumber:w?.number??null,isActive:f,tooltipProjectLabel:m,tooltipBranchLabel:g,isGitRepo:S,subtaskCount:v,agentName:E,prSummary:w,prIconColor:N,prStatusLabel:M,selectionScopeKey:F,selectionModeEnabled:$,isRowSelected:U,toggleRowSelected:K,setRowRange:L,isStreaming:I,hasActivityDuration:T,sessionTitle:W,hasChildren:G,isPinnedSession:B,isExpanded:be,needsAttention:H,pendingInput:Ce,attention:De,sessionCompactUpdatedLabel:Q,forkSolid:X,rowBackground:me}}const ag=({prDirectory:e,prNumber:t,prStatusLabel:n,prIconColor:r})=>{const o=Ua(e);if(!e||!o)return s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",style:r?{color:r}:void 0,title:n?`PR #${t} — ${n}`:`PR #${t}`,children:[s.jsx(P,{name:"git-pull-request",className:"size-3.5 shrink-0"}),s.jsxs("span",{children:["#",t]})]});const i=l=>{l.stopPropagation(),l.preventDefault(),Ql(e,o,t)};return s.jsxs("span",{role:"button",tabIndex:0,onClick:i,onDoubleClick:l=>{l.stopPropagation(),l.preventDefault()},onKeyDown:l=>{if(!(l.key!=="Enter"&&l.key!==" ")){if(l.repeat){l.stopPropagation(),l.preventDefault();return}i(l)}},className:"inline-flex shrink-0 cursor-pointer items-center gap-1 rounded hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",style:r?{color:r}:void 0,title:n?`PR #${t} — ${n}. Open in Pull requests`:`Open PR #${t} in Pull requests`,"aria-label":n?`Open pull request #${t}, ${n}, in Pull requests`:`Open pull request #${t} in Pull requests`,children:[s.jsx(P,{name:"git-pull-request",className:"size-3.5 shrink-0"}),s.jsxs("span",{children:["#",t]})]})};function lg(e){Kt("ui.sidebar_session_node.render");const{node:t,depth:n=0,groupDirectory:r,projectId:o,archivedBucket:i=!1,pinnedSessionIds:l,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,editingId:f,setEditingId:p,editTitle:x,setEditTitle:y,handleSaveEdit:m,handleCancelEdit:h,toggleParent:b,handleSessionSelect:g,handleSessionDoubleClick:S,togglePinnedSession:v,handleShareSession:E,copiedSessionId:k,handleCopyShareUrl:C,handleCopySessionId:j,handleUnshareSession:w,openSidebarMenuKey:N,setOpenSidebarMenuKey:M,renamingFolderId:F,getFoldersForScope:$,getSessionFolderId:U,removeSessionFromFolder:K,addSessionToFolder:L,createFolderAndStartRename:D,handleDeleteSession:R,handleRestoreSession:I,alwaysShowActions:T,allowQuickArchiveAction:W,renderSessionNode:G,secondaryMeta:B,renderContext:be="project",subtreeContainsEditing:V,menuOpenSessionId:Ce,childRenderExtrasFor:De}=e,H=a.useContext(Yo)==="tree",z="size-3 shrink-0",Q=a.useMemo(()=>nl(),[]),X=!i&&W,ne=a.useRef(!1),we=a.useRef(f);we.current=f;const me=a.useRef(null),q=a.useRef(m);q.current=m;const[te,le]=a.useState(x),Ae=a.useRef(te);Ae.current=te;const Se=a.useRef(null),Ge=a.useRef(null),ce=`${be}:${i?"archived":"active"}:${t.session.id}`,{session:re,sessionDirectory:ue,prDirectory:ve,prNumber:Le,isActive:xe,tooltipProjectLabel:se,tooltipBranchLabel:pe,isGitRepo:fe,subtaskCount:je,agentName:He,prSummary:We,prIconColor:Ie,prStatusLabel:Ye,selectionScopeKey:oe,selectionModeEnabled:Fe,isRowSelected:st,toggleRowSelected:bt,setRowRange:Qe,isStreaming:rt,hasActivityDuration:ot,sessionTitle:qt,hasChildren:Tt,isPinnedSession:et,isExpanded:Ct,needsAttention:ss,pendingInput:kt,attention:At,sessionCompactUpdatedLabel:Ft,forkSolid:xt,rowBackground:Je}=ig({node:t,groupDirectory:r,projectId:o,secondaryMeta:B,pinnedSessionIds:l,expandedParents:c,expansionKey:ce,hasSessionSearchQuery:d}),{exportDialogOpen:Lt,setExportDialogOpen:Yt,exportIncludeSubtasks:us,setExportIncludeSubtasks:ke,descendantCount:Be,handleExportSession:ge,doExportSession:Oe}=eg(t,ue),[_e,ht]=a.useState(!1),yt=a.useCallback(()=>{ue&&En("desktop_open_session_mini_chat_window",{sessionId:re.id,directory:ue,apiBaseUrl:ho(),clientToken:fo()}).catch(Z=>{console.warn("[session-sidebar] failed to open mini chat window",Z)})},[re.id,ue]);a.useEffect(()=>{if(f!==re.id)return;const Z=Ve=>{const Et=Ve.target?.closest?.(`[data-session-rename-form="${CSS.escape(re.id)}"]`);Ge.current&&!Et&&q.current(Ae.current)};return document.addEventListener("mousedown",Z),()=>document.removeEventListener("mousedown",Z)},[f,re.id]),a.useLayoutEffect(()=>{if(f!==re.id){Se.current===re.id&&(Se.current=null);return}Se.current!==re.id&&(Se.current=re.id,le(x))},[f,x,re.id]);const nt=At==="needs-input",ns=nt&&kt?gu(kt.kind,kt.count):null,rs=At==="unread",Ze=rt&&ot,Ot=X&&(T||_e),lt=rt&&!H&&!Ot&&f!==re.id,wt=!!(B?.showFolderLabel&&se),vt=!!pe||fe,_s=!!(He&&He!=="default"),zs=!!We&&Le!=null,Cs=Ze&&!lt,fs=wt&&vt||zs||je>0||_s||Cs,Nt=Z=>pe?s.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",Z?"shrink":"flex-1"),children:[s.jsx(P,{name:"git-branch",className:z,style:Ie?{color:Ie}:void 0}),s.jsx("span",{className:"truncate",children:pe})]}):fe?s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[s.jsx(P,{name:"git-repository",className:z}),s.jsx("span",{children:"git"})]}):null,hs=et,St=s.jsx(P,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),os=hs?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:St}):null,is=Tt?s.jsx("button",{type:"button",onClick:Z=>{Z.stopPropagation(),b(ce)},onKeyDown:Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),Z.stopPropagation(),b(ce))},className:"inline-flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-label":Ct?"Collapse subsessions":"Expand subsessions",children:Ct?s.jsx(P,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(P,{name:"arrow-right-s",className:"h-3 w-3"})}):null,it=Z=>{if(!Z&&me.current){const{id:Ve,title:qe}=me.current;me.current=null,p(Ve),y(qe)}},Bt=Z=>{ht(Z)},Us=Z=>{Z.preventDefault(),Z.stopPropagation()},It=Z=>{Z.preventDefault(),Z.stopPropagation()},mn=Z=>{Z.preventDefault(),Z.stopPropagation(),M(null),R(re,{archivedBucket:i})},$s=Z=>{Z.preventDefault(),Z.stopPropagation(),M(null),R(re,{archivedBucket:i,hardDelete:!0,skipConfirm:!0})},Ks=Z=>{if(ne.current){ne.current=!1;return}if(Fe){if(Z?.preventDefault(),Z?.stopPropagation(),Z?.shiftKey){const qe=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(ms=>ms.getAttribute("data-session-row")).filter(ms=>typeof ms=="string"&&ms.length>0),Et=ct.getState().anchorId,pt=new Map;pt.set(re.id,yr(t)),Qe(Et,re.id,qe,oe,pt);return}bt(re.id,oe,yr(t));return}Z?.currentTarget&&qp(Z.currentTarget),g(re.id,ue)},ks=Z=>{Z.defaultPrevented||Z.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||Ks(Z)},O=Z=>{(Z.button===2||Z.button===0&&Z.ctrlKey&&!Fe)&&(ne.current=!0)},ie={session:re,sessionTitle:qt,sessionDirectory:ue,isPinnedSession:et,archivedBucket:i,isElectron:Q,renamingFolderId:F,editingIdRef:we,pendingRenameRef:me,handleCopySessionId:j,togglePinnedSession:v,handleExportSession:ge,handleOpenMiniChatWindow:yt,handleDeleteSession:R,handleRestoreSession:I},ye=s.jsx(Hp,{...ie});return s.jsxs(a.Fragment,{children:[s.jsx(Fm,{sessionId:re.id,sessionDirectory:ue??null,sessionTitle:qt,children:s.jsxs(Ca,{open:_e,onOpenChange:Bt,onOpenChangeComplete:it,children:[s.jsxs(ka,{render:s.jsx("div",{"data-session-row":re.id,"data-session-scope":oe??"","data-session-archived":i?"1":"0","data-fork-color":xt?t.forkColorId:void 0,"data-global-session":B?.globalSession?"1":void 0,"data-sidebar-tree-row":H?"":void 0,onClick:ks,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...Je?{backgroundColor:Je}:void 0},className:_("group relative flex cursor-pointer items-start px-3 transition-colors",H?Fl:"my-0.5 rounded-xl py-2",!Je&&n>0?"bg-secondary/30 hover:bg-interactive-hover":Je?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!Je&&xe&&!st&&"bg-interactive-selection",!Je&&st&&"bg-interactive-selection")}),children:[s.jsxs("div",{className:_("flex min-w-0 flex-1 items-start",lt&&"oc-session-row-working-fade"),"data-clear-on-hover":lt&&X?"true":void 0,"data-working-duration":lt&&Ze?"true":void 0,children:[s.jsxs("div",{className:_("flex min-w-0 flex-1 items-center",H?Cr:"gap-1.5"),children:[H?s.jsx("span",{"data-session-row-gutter":!0,className:"inline-flex size-4 shrink-0 items-center justify-center",children:rt?s.jsx(vs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null}):null,is,os,f===re.id?s.jsxs("form",{ref:Ge,"data-session-rename-form":re.id,className:_("flex min-w-0 flex-1 items-center gap-2",H?"min-h-5":"min-h-8"),onPointerDown:Z=>Z.stopPropagation(),onMouseDown:Z=>Z.stopPropagation(),onSubmit:Z=>{Z.preventDefault(),m(te)},children:[s.jsx("input",{value:te,onChange:Z=>le(Z.target.value),className:"min-w-0 flex-1 bg-transparent typography-ui-label text-foreground outline-none placeholder:text-muted-foreground",autoFocus:!0,placeholder:"Rename",onKeyDown:Z=>{Z.stopPropagation(),Z.key==="Escape"&&h()}}),s.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:s.jsx(P,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:h,"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:s.jsx(P,{name:"close",className:"size-4"})})]}):s.jsxs("button",{type:"button",onMouseDown:O,onClick:Z=>Ks(Z),onDoubleClick:Z=>{Z.stopPropagation(),S(re.id,qt)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-1 overflow-hidden text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 text-foreground select-none",children:[s.jsxs("div",{className:"flex w-full items-center min-w-0 flex-1 gap-1.5 overflow-hidden",children:[s.jsx("div",{className:_("block min-w-0 flex-1 truncate font-normal typography-ui-label",ss?"text-foreground":H&&!xe?"text-muted-foreground transition-colors group-hover:text-foreground":"text-foreground/90"),children:rr(qt,u)}),et?s.jsx(P,{name:"star-fill",className:"h-3 w-3 text-primary shrink-0"}):null,s.jsx("span",{"aria-hidden":"true",className:"invisible ml-1 min-w-6 shrink-0 whitespace-nowrap text-[11px]",children:rs?null:Ft})]}),!H&&(wt||vt||fs)?s.jsxs("div",{className:"flex w-full min-w-0 items-center justify-between gap-2 overflow-hidden text-xs leading-4 font-normal text-muted-foreground/80",children:[wt?s.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",fs?"max-w-[60%] shrink-0":"flex-1"),children:[s.jsx(P,{name:"folder",className:z}),s.jsx("span",{className:"truncate",children:se})]}):Nt(!1),fs?s.jsxs("span",{className:_("ml-auto flex min-w-0 items-center justify-end gap-2 overflow-hidden",wt?"flex-1":"shrink-0"),children:[wt?Nt(!0):null,zs?s.jsx(ag,{prDirectory:ve,prNumber:Le,prStatusLabel:Ye,prIconColor:Ie}):null,je>0?s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[s.jsx(P,{name:"node-tree",className:z}),s.jsx("span",{children:je})]}):null,_s?s.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:He}):null,Cs?s.jsx(Ri,{sessionId:re.id,running:rt,className:"shrink-0 text-muted-foreground/70"}):null]}):null]}):null]})]}),s.jsxs("div",{className:_("absolute right-3 flex h-5 min-w-6 items-center justify-end",H?"top-1/2 -translate-y-1/2":"top-2",f===re.id&&"hidden"),children:[s.jsx("div",{className:_("flex items-center justify-end",Ot?"opacity-0":X?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:nt&&!lt?s.jsx(ki,{label:ns??"Needs input"}):rs?s.jsx(Nf,{label:"Session complete"}):s.jsx("span",{className:"text-[11px] text-muted-foreground/75 whitespace-nowrap",children:Ft})}),X?s.jsx("div",{className:_("absolute inset-0 flex items-center justify-end",T||_e?"opacity-100":"pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 group-focus-within:pointer-events-auto group-focus-within:opacity-100"),children:s.jsx(Kp,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:Us,onMouseDown:It,onArchive:mn,onDelete:$s})}):null]})]}),lt?s.jsxs("span",{"data-session-working":!0,className:_("pointer-events-none absolute inset-y-0 right-0 flex items-center rounded-r-[inherit] pr-3 transition-opacity",X&&"group-hover:opacity-0 group-focus-within:opacity-0"),children:[s.jsx("span",{"aria-hidden":"true",className:"oc-session-row-working-aura absolute inset-y-0 right-0 w-24 rounded-r-[inherit] bg-gradient-to-l from-primary/15 to-transparent"}),s.jsxs("span",{className:"relative flex flex-col items-end gap-1",children:[s.jsxs("span",{className:"flex h-5 items-center gap-1.5",children:[nt&&ns?s.jsx(ki,{label:ns}):null,s.jsx(vs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})]}),Ze?s.jsx(Ri,{sessionId:re.id,running:rt,className:"text-[11px] leading-4"}):null]})]}):null]}),ye]})}),Tt&&Ct?t.children.map(Z=>{const Ve=De?De(Z):{subtreeContainsEditing:V,menuOpenSessionId:Ce,nodeStructureKey:""};return s.jsx(a.Fragment,{children:G(Z,n+1,ue??r,o,i,B?.globalSession?{globalSession:!0}:void 0,be,Ve)},Z.session.id)}):null,s.jsx(Wp,{open:Lt,onOpenChange:Yt,descendantCount:Be,exportIncludeSubtasks:us,setExportIncludeSubtasks:ke,onExport:Oe})]},re.id)}const cg=a.memo(lg,og),dg=({open:e,onOpenChange:t,project:n,onSave:r})=>s.jsx(es,{open:e,onOpenChange:t,children:s.jsx(ts,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:s.jsx(Is,{outerClassName:"max-h-[min(90vh,48rem)]",className:"w-full bg-background",children:s.jsx("div",{className:"w-full p-3 sm:p-6 sm:pt-8",children:e&&n?s.jsx(Oh,{project:n,onIdentitySave:r}):null})})})});function ac(e){const{showDeletionDialog:t,setShowDeletionDialog:n,onCancel:r,onConfirm:o,confirmLabel:i}=e;return s.jsxs(Ls,{className:"w-full sm:items-center sm:justify-between",children:[s.jsxs("button",{type:"button",onClick:()=>n(!t),className:"inline-flex items-center gap-1.5 typography-ui-label text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-primary/50","aria-pressed":!t,children:[t?s.jsx(P,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(P,{name:"checkbox",className:"h-4 w-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx("button",{type:"button",onClick:r,className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),s.jsx("button",{type:"button",onClick:()=>{o()},className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:i})]})]})}function ug(e){const{value:t,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,l=c=>xs(c);return s.jsx(es,{open:!!t,onOpenChange:c=>{c||n(null)},children:s.jsxs(ts,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Ss,{children:[s.jsx(ds,{children:t?.archivedBucket?"Delete session?":"Archive session?"}),s.jsx(js,{children:t&&t.descendantCount>0?t.archivedBucket?t.descendantCount===1?`"${l(t.session)}" and its ${t.descendantCount} sub-task will be permanently deleted.`:`"${l(t.session)}" and its ${t.descendantCount} sub-tasks will be permanently deleted.`:t.descendantCount===1?`"${l(t.session)}" and its ${t.descendantCount} sub-task will be archived.`:`"${l(t.session)}" and its ${t.descendantCount} sub-tasks will be archived.`:t?.archivedBucket?`"${t?.session?l(t.session):"Untitled Session"}" will be permanently deleted.`:`"${t?.session?l(t.session):"Untitled Session"}" will be archived.`})]}),s.jsx(ac,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:i,confirmLabel:t?.archivedBucket?"Delete":"Archive"})]})})}function fg(e){const{value:t,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,l=t?.archivedBucket===!0,c=t?.sessionCount??0,d=l?c===1?"Delete session?":"Delete sessions?":c===1?"Archive session?":"Archive sessions?",u=l?c===1?`${c} session will be permanently deleted.`:`${c} sessions will be permanently deleted.`:c===1?`${c} session will be archived.`:`${c} sessions will be archived.`;return s.jsx(es,{open:!!t,onOpenChange:f=>{f||n(null)},children:s.jsxs(ts,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Ss,{children:[s.jsx(ds,{children:d}),s.jsx(js,{children:u})]}),s.jsx(ac,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:i,confirmLabel:l?"Delete":"Archive"})]})})}function hg(e){const{value:t,setValue:n,onConfirm:r}=e,{git:o}=Os(),[i,l]=a.useState(null),[c,d]=a.useState(!1),[u,f]=a.useState(!1),[p,x]=a.useState(!1),y=t?.worktree.path??null;a.useEffect(()=>{let k=!1;return l(null),d(!1),f(!1),x(!1),!t||!y?()=>{k=!0}:(o.getGitStatus(y).then(C=>{if(!k){if(typeof C?.isClean!="boolean"){d(!0);return}l(C)}}).catch(()=>{k||d(!0)}),()=>{k=!0})},[o,t,y]);const m=i?.isClean===!1,h=(i?.ahead??0)>0,b=h&&!t?.worktree.branch,g=t?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",S=!!(t&&i&&!c&&!t.hasActiveSession&&(!m&&!b||u)&&!p),v=t?.worktree.branch||t?.worktree.name||t?.worktree.path||"",E=async()=>{if(S){x(!0);try{await r({force:m})}finally{x(!1)}}};return s.jsx(es,{open:!!t,onOpenChange:k=>{!k&&!p&&n(null)},children:s.jsxs(ts,{showCloseButton:!1,className:"max-w-md gap-5",children:[s.jsxs(Ss,{children:[s.jsx(ds,{children:"Close worktree?"}),s.jsx(js,{children:`Closing "${v}" removes its worktree directory. ${g}`})]}),c?s.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-3",children:[s.jsx(P,{name:"alert",className:"mt-0.5 size-4 shrink-0 text-[var(--status-error)]"}),s.jsx("p",{className:"typography-ui-label text-foreground",children:"Unable to check this worktree's status. Refresh and try again."})]}):i===null?s.jsx("p",{className:"typography-ui-label text-muted-foreground","aria-live":"polite",children:"Checking worktree status…"}):null,t?.hasActiveSession?s.jsxs("div",{role:"alert",className:"flex items-start gap-2 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[s.jsx(P,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),s.jsx("p",{className:"typography-ui-label text-foreground",children:"Stop the active session before closing this worktree."})]}):null,m?s.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(P,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),s.jsx("p",{className:"typography-ui-label text-foreground",children:"This worktree has uncommitted changes. They will be permanently removed."})]}),s.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[s.jsx(oo,{checked:u,onChange:f,ariaLabel:"Confirm removal of uncommitted changes",className:"mt-0.5"}),s.jsx("span",{children:"I understand that the uncommitted changes will be lost."})]})]}):null,h?s.jsxs("div",{className:"space-y-3",children:[s.jsx("p",{className:"typography-ui-label text-muted-foreground",children:i?.ahead===1?`This worktree has 1 unpushed commit. ${g}`:`This worktree has ${i?.ahead} unpushed commits. ${g}`}),b?s.jsxs("div",{className:"space-y-3 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] p-3",children:[s.jsxs("div",{className:"flex items-start gap-2",children:[s.jsx(P,{name:"error-warning",className:"mt-0.5 size-4 shrink-0 text-[var(--status-warning)]"}),s.jsx("p",{className:"typography-ui-label text-foreground",children:"Because this worktree is detached, its unpushed commits may be lost."})]}),s.jsxs("label",{className:"flex items-start gap-2 pl-6 typography-ui-label text-foreground",children:[s.jsx(oo,{checked:u,onChange:f,ariaLabel:"Confirm removal of unpushed detached commits",className:"mt-0.5"}),s.jsx("span",{children:"I understand that the unpushed commits may be lost."})]})]}):null]}):null,s.jsxs(Ls,{className:"sm:justify-end",children:[s.jsx(Ne,{variant:"outline",size:"sm",onClick:()=>n(null),disabled:p,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",size:"sm",onClick:()=>{E()},disabled:!S,children:p?"Closing…":"Close worktree"})]})]})})}function mg(e){const{value:t,setValue:n,onConfirm:r}=e;return s.jsx(es,{open:!!t,onOpenChange:o=>{o||n(null)},children:s.jsxs(ts,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Ss,{children:[s.jsx(ds,{children:"Delete folder?"}),s.jsx(js,{children:t&&(t.subFolderCount>0||t.sessionCount>0)?t.subFolderCount>0?t.subFolderCount===1?`"${t.folderName}" will be deleted along with ${t.subFolderCount} sub-folder. Sessions inside will not be deleted.`:`"${t.folderName}" will be deleted along with ${t.subFolderCount} sub-folders. Sessions inside will not be deleted.`:`"${t.folderName}" will be deleted. Sessions inside will not be deleted.`:`"${t?.folderName??""}" will be permanently deleted.`})]}),s.jsxs(Ls,{children:[s.jsx("button",{type:"button",onClick:()=>n(null),className:"inline-flex h-8 items-center justify-center rounded-md border border-border px-3 typography-ui-label text-foreground hover:bg-interactive-hover/50 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:"Cancel"}),s.jsx("button",{type:"button",onClick:r,className:"inline-flex h-8 items-center justify-center rounded-md bg-destructive px-3 typography-ui-label text-destructive-foreground hover:bg-destructive/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50",children:"Delete"})]})]})})}const pg=({updateDialogOpen:e,setUpdateDialogOpen:t,updateStore:n,editingProject:r,setEditingProjectDialogId:o,handleSaveProjectEdit:i,deleteSessionConfirm:l,setDeleteSessionConfirm:c,showDeletionDialog:d,setShowDeletionDialog:u,confirmDeleteSession:f,deleteFolderConfirm:p,setDeleteFolderConfirm:x,confirmDeleteFolder:y,closeWorktreeConfirm:m,setCloseWorktreeConfirm:h,confirmCloseWorktree:b,bulkDeleteConfirm:g,setBulkDeleteConfirm:S,confirmBulkDelete:v})=>s.jsxs(s.Fragment,{children:[s.jsx(vl,{open:e,onOpenChange:t,info:n.info,downloading:n.downloading,downloaded:n.downloaded,progress:n.progress,error:n.error,onDownload:n.downloadUpdate,onRestart:n.restartToUpdate,runtimeType:n.runtimeType}),s.jsx(dg,{open:!!r,onOpenChange:E=>{E||o(null)},project:r,onSave:i}),s.jsx(ug,{value:l,setValue:c,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:f}),s.jsx(mg,{value:p,setValue:x,onConfirm:y}),s.jsx(hg,{value:m,setValue:h,onConfirm:b}),s.jsx(fg,{value:g,setValue:S,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:v})]}),gg=({directories:e})=>{const t=a.useMemo(()=>{const r=new Set;return e.forEach(o=>{const i=Ee(o)?.toLowerCase();i&&r.add(i)}),r},[e]),n=Nn(r=>{let o=0,i=!1;for(const l of r.catalog.byId.values()){const c=Ee(l.directory)?.toLowerCase();!c||!t.has(c)||(Va(l.pendingInput)?o+=1:(l.lifecycle==="busy"||l.lifecycle==="retry")&&(i=!0))}return{inputCount:o,hasBusySession:i}},(r,o)=>r.inputCount===o.inputCount&&r.hasBusySession===o.hasBusySession,"catalog");if(n.inputCount>0){const r=bu(n.inputCount);return s.jsx("span",{className:"inline-flex items-center","aria-label":r,title:r,children:s.jsx("span",{className:"size-1.5 shrink-0 rounded-full bg-status-warning"})})}return n.hasBusySession?s.jsx("span",{className:"inline-flex items-center","aria-label":"Session active",title:"Session active",children:s.jsx(vs,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},bg=e=>{let t=0;for(const n of e)for(const r of n.groups)r.isArchivedBucket||(t+=r.sessions.length);return t},xg=e=>{const t=new Map;for(const n of e){let r=0;for(const o of n.groups)o.isArchivedBucket||(r+=o.sessions.length);t.set(n.project.id,r)}return t},yg=(e,t)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>t.has(r.session.id))),wg=(e,t)=>e.groups.some(n=>n.isArchivedBucket?!1:n.sessions.some(r=>t.has(r.session.id))),vg=(e,t)=>{const n=new Map;for(const r of e){const o=new Set;for(const i of r.groups){if(i.isArchivedBucket)continue;if(i.sessions.some(c=>t.has(c.session.id))&&i.directory){const c=Ee(i.directory)?.toLowerCase();c&&o.add(c)}}o.size>0&&n.set(r.project.id,o)}return n},Sg=e=>e.map(t=>t.groups.some(n=>n.isArchivedBucket)?{...t,groups:t.groups.filter(n=>!n.isArchivedBucket)}:t),jg=(e,t,n,r)=>{if(!n)return t;const o=e.find(c=>c.project.id===n);if(!o)return[];const i=Ee(r??o.project.normalizedPath),l=o.groups.find(c=>!c.isArchivedBucket&&Ee(c.directory)===i);return l?[{...o,groups:[l]}]:[]},Cg=(e,t)=>{const n=new Map,r=new Map;return e.forEach(o=>{const i=Go(o.project.label?.trim()||Fn(o.project.normalizedPath,t)||o.project.normalizedPath);o.groups.forEach(l=>{const c=l.branch&&l.branch!=="HEAD"&&l.branch!==i?l.branch:null,d={projectLabel:i,branchLabel:c},u=f=>{f.forEach(p=>{const x=o.project.normalizedPath.length,y=r.get(p.session.id)??-1;x<y||(n.set(p.session.id,{node:p,projectId:o.project.id,groupDirectory:l.directory,secondaryMeta:d}),r.set(p.session.id,x),p.children.length>0&&u(p.children))})};u(l.sessions)})}),n};function kg({projectSections:e,flatSectionsForRender:t,sectionsForRender:n,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:i,activeSessionIdSet:l,unreadSessionIdSet:c}){const d=a.useMemo(()=>Cg(e,i),[e,i]),u=a.useMemo(()=>Sg(t),[t]),f=a.useMemo(()=>jg(n,u,r,o),[n,u,r,o]),p=a.useMemo(()=>bg(e),[e]),x=a.useMemo(()=>xg(e),[e]),y=a.useCallback(b=>{const g=e.find(S=>S.project.id===b);return g?yg(g,l):!1},[l,e]),m=a.useMemo(()=>vg(e,l),[l,e]),h=a.useCallback(b=>{const g=e.find(S=>S.project.id===b);return g?wg(g,c):!1},[e,c]);return{sessionSidebarMetaById:d,sectionsForSidebarRender:u,filteredSectionsForSidebarRender:f,totalSessionCount:p,sessionCountByProject:x,hasActiveSessionByProject:y,activeDirectoriesByProject:m,hasUnseenByProject:h}}const Ag=({selectedCount:e,archivedBucket:t,onRestore:n,onDelete:r,onDone:o})=>{const i=t?"Delete":"Archive",l="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50";return s.jsxs("div",{className:"flex shrink-0 items-center gap-1 border-t border-border pl-5 pr-3.5 py-1.5",children:[s.jsx("span",{className:"typography-ui-label text-muted-foreground whitespace-nowrap",children:`${e} selected`}),s.jsxs("div",{className:"ml-auto flex items-center gap-0.5",children:[t?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:l,"aria-label":"Restore",children:s.jsx(P,{name:"inbox-unarchive",className:"h-4 w-4"})})}),s.jsx(Ke,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Restore"})})]}):null,s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:_("inline-flex h-7 w-7 items-center justify-center rounded-md text-destructive hover:bg-destructive/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-destructive/50"),"aria-label":i,children:s.jsx(P,{name:"delete-bin",className:"h-4 w-4"})})}),s.jsx(Ke,{side:"top",sideOffset:4,children:s.jsx("p",{children:i})})]}),s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:l,"aria-label":"Exit selection",children:s.jsx(P,{name:"close",className:"h-4 w-4"})})}),s.jsx(Ke,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Exit selection"})})]})]})]})},Ng=e=>{const{isInlineEditing:t,showDeletionDialog:n,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:i,removeSessionsFromFolders:l,createFolderAndStartRename:c,archiveSessions:d,unarchiveSessions:u,deleteSessions:f,setBulkDeleteConfirm:p}=e,x=ct(R=>R.enabled),y=ct(R=>R.selectedIds.size),m=y>0,h=ct(R=>R.selectedIds),b=ct(R=>R.scopeKey),g=a.useCallback(()=>{ct.getState().toggleMode()},[]),S=a.useCallback(()=>{ct.getState().disable()},[]),v=a.useMemo(()=>{if(!m||typeof document>"u")return!1;let R=!1,I=!1;for(const T of h){const W=document.querySelectorAll(`[data-session-row="${CSS.escape(T)}"]`);for(const G of W)G.getAttribute("data-session-archived")==="1"?I=!0:R=!0}return I&&!R},[m,h]),E=a.useMemo(()=>{if(b)return b;if(!m||typeof document>"u")return null;for(const R of h){const T=document.querySelector(`[data-session-row="${CSS.escape(R)}"]`)?.getAttribute("data-session-scope");if(T&&T.length>0)return T}return null},[m,h,b]),k=a.useMemo(()=>{if(!E)return[];const R=o.get(E);return R&&R.length>0?R.map(I=>I.scopeKey):[E]},[E,o]),C=a.useMemo(()=>k.flatMap(R=>r[R]??[]),[r,k]),j=a.useCallback(R=>{for(const I of k)if((r[I]??[]).some(T=>T.id===R))return I;return null},[r,k]),w=a.useMemo(()=>{if(!m)return!1;for(const R of k)for(const I of r[R]??[])for(const T of I.sessionIds)if(h.has(T))return!0;return!1},[r,k,m,h]),N=a.useCallback((R,I)=>{const T=Array.from(h);for(const W of k)W!==R&&l(W,T);i(R,I,T)},[i,l,h,k]),M=a.useCallback(R=>{if(!m)return;const I=j(R);I&&N(I,R)},[m,N,j]),F=a.useCallback(()=>{const R=k[0];if(!R||!m)return;const I=c(R);I&&N(R,I.id)},[c,m,N,k]),$=a.useCallback(()=>{if(!m)return;const R=Array.from(h);for(const I of k)l(I,R)},[l,h,k,m]),U=a.useCallback(async()=>{const R=Array.from(h);if(R.length!==0){if(v){const{deletedIds:I,failedIds:T}=await f(R);I.length>0&&ae.success(I.length===1?`Deleted ${I.length} session`:`Deleted ${I.length} sessions`),T.length>0&&ae.error(T.length===1?`Failed to delete ${T.length} session`:`Failed to delete ${T.length} sessions`)}else{const{archivedIds:I,failedIds:T}=await d(R);I.length>0&&ae.success(I.length===1?`Archived ${I.length} session`:`Archived ${I.length} sessions`),T.length>0&&ae.error(T.length===1?`Failed to archive ${T.length} session`:`Failed to archive ${T.length} sessions`)}ct.getState().clear()}},[d,v,f,h]),K=a.useCallback(()=>{if(!m)return;const R=h.size;if(!n){U();return}p({sessionCount:R,archivedBucket:v})},[v,U,h,n,p,m]),L=a.useCallback(async()=>{if(!m||!v)return;const R=Array.from(h),{restoredIds:I,failedIds:T}=await u(R);I.length>0&&ae.success(I.length===1?`Restored ${I.length} session`:`Restored ${I.length} sessions`),T.length>0&&ae.error(T.length===1?`Failed to restore ${T.length} session`:`Failed to restore ${T.length} sessions`),ct.getState().clear()},[v,m,h,u]),D=a.useCallback(async()=>{p(null),await U()},[U]);return a.useEffect(()=>{if(!x)return;const R=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),I=T=>{if(t)return;const W=T.target;if(W&&(W.tagName==="INPUT"||W.tagName==="TEXTAREA"||W.isContentEditable))return;const G=R?T.metaKey:T.ctrlKey;if(T.key==="Escape"){T.preventDefault(),ct.getState().disable();return}if(G&&T.key==="Backspace"){T.preventDefault(),K();return}if(G&&(T.key==="a"||T.key==="A")){const B=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(B.length===0)return;T.preventDefault();const V=ct.getState().scopeKey??B[0]?.getAttribute("data-session-scope")??null,Ce=H=>V?H.getAttribute("data-session-scope")===V:!0,De=B.filter(Ce).map(H=>H.getAttribute("data-session-row")).filter(H=>typeof H=="string"&&H.length>0);if(De.length===0)return;ct.getState().replaceAll(De,V||null)}};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[K,t,x]),{selectionModeEnabled:x,hasSelection:m,selectedIdsSize:y,bulkScopeIsArchived:v,derivedSelectionScope:E,bulkScopeFolders:C,bulkCanRemoveFromFolder:w,handleToggleSelectionMode:g,handleExitSelectionMode:S,handleBulkMoveToFolder:M,handleBulkCreateFolderAndMove:F,handleBulkRemoveFromFolder:$,handleBulkDelete:K,handleBulkRestore:L,confirmBulkDelete:D}},Ig=(e,t)=>{const n=e??{};return delete n.projectSortOrder,t<4&&delete n.displayMode,t<5&&delete n.sessionGroupingMode,n},ra=Bs()(dl(e=>({stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(t=>({stickyZoneHeaders:!t.stickyZoneHeaders})),showRecentSection:!0,showArchivedSessions:!1,setShowRecentSection:t=>e({showRecentSection:t}),setShowArchivedSessions:t=>e({showArchivedSessions:t}),toggleRecentSection:()=>e(t=>({showRecentSection:!t.showRecentSection})),toggleArchivedSessions:()=>e(t=>({showArchivedSessions:!t.showArchivedSessions}))}),{name:"pichamber:session-display-settings",version:6,migrate:Ig})),oa="oc.sessions.projectCollapse",ia="oc.sessions.groupOrder",aa="oc.sessions.groupCollapse",la="oc.sessions.activeSessionByProject",ca="oc.sessions.expandedParents.v3",Eg=new Set,Gr=[],Rt=e=>{const t=a.useRef(e);return t.current=e,a.useCallback((...n)=>t.current(...n),[])},Rg=({isVisible:e=!0,mobileVariant:t=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:i=!1,showOnlyMainWorkspace:l=!1})=>{uo("react.session_sidebar_render"),Kt("ui.session_sidebar.render"),Kt(`ui.session_sidebar.render.${t?"mobile":"desktop"}`),Kt(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=a.useState(!1),[u,f]=a.useState(""),p=a.useRef(null),x=a.useRef(null),[y,m]=a.useState(null),[h,b]=a.useState(""),[g,S]=a.useState(null),[v,E]=a.useState(new Set),k=a.useMemo(()=>Wn(),[]),[C,j]=a.useState(new Set),w=qs(A=>A.selectedSpaceId),N=qs(A=>A.selectedWorktreePath),[M,F]=a.useState(new Map),[$,U]=a.useState(new Map),[K,L]=a.useState(!1),[D,R]=a.useState(null),[I,T]=a.useState(null),[W,G]=a.useState(""),[B,be]=a.useState(null),[V,Ce]=a.useState(null),[De,H]=a.useState(null),[z,Q]=a.useState(null),X=Ai(A=>A.ids),ne=xu(a.useCallback(A=>e?A.rankById:$a,[e])),we=Nn(A=>e?yu(A.catalog):"",void 0,"catalog"),me=a.useMemo(()=>we?we.split("|"):Gr,[we]),q=a.useMemo(()=>new Set(me),[me]),te=Ya(ro(A=>e?Object.entries(A.index.session.unseenCount).filter(([,J])=>J>0).map(([J])=>J).sort():Gr)),le=a.useMemo(()=>new Set(te),[te]),Ae=Ai(A=>A.toggle),[Se,Ge]=a.useState(()=>{try{const A=Wn().getItem(aa);if(!A)return new Set;const J=JSON.parse(A);return new Set(Array.isArray(J)?J.filter(ee=>typeof ee=="string"):[])}catch{return new Set}}),[Y,ce]=a.useState(()=>{try{const A=Wn().getItem(ia);if(!A)return new Map;const J=JSON.parse(A),ee=new Map;return Object.entries(J).forEach(([Me,ze])=>{Array.isArray(ze)&&ee.set(Me,ze.filter(tt=>typeof tt=="string"))}),ee}catch{return new Map}}),re=a.useMemo(()=>{try{const A=Wn().getItem(la);if(!A)return new Map;const J=JSON.parse(A),ee=new Map;return Object.entries(J).forEach(([Me,ze])=>{typeof ze=="string"&&ze.length>0&&ee.set(Me,ze)}),ee}catch{return new Map}},[]),ue=a.useCallback(A=>{try{k.setItem(la,JSON.stringify(Object.fromEntries(A.entries())))}catch{}},[k]),[ve,Le]=a.useState(new Map),xe=a.useRef(0),se=on(A=>A.homeDirectory),pe=on(A=>A.currentDirectory),fe=dt(A=>A.projects),je=dt(A=>A.activeProjectId),He=dt(A=>A.removeProject),We=dt(A=>A.setActiveProjectIdOnly),Ie=dt(A=>A.updateProjectMeta),Ye=dt(A=>A.reorderProjects),oe=de(A=>A.setActiveMainTab),Fe=de(A=>A.setSettingsDialogOpen),st=de(A=>A.setSettingsPage),bt=de(A=>A.toggleHelpDialog),Qe=de(A=>A.setSessionSwitcherOpen),rt=de(A=>A.setArchivePageOpen),ot=de(A=>A.showDeletionDialog),qt=de(A=>A.setShowDeletionDialog),Tt=de(A=>A.sidebarViewMode),et=i||l||!sf(Tt)?"workspace":Tt,Ct=de(A=>A.weekStartPreference),ss=a.useMemo(()=>tm(Ct),[Ct]),kt=om(e&&et==="timeline",ss),At=ra(A=>A.stickyZoneHeaders),Ft=wu(u,120),xt=a.useMemo(()=>Ft.trim().toLowerCase(),[Ft]),Je=xt.length>0,Lt=mt(A=>A.collapsedFolderIds),Yt=mt(A=>A.foldersMap),us=mt(A=>A.getFoldersForScope),ke=mt(A=>A.createFolder),Be=mt(A=>A.renameFolder),ge=mt(A=>A.deleteFolder),Oe=mt(A=>A.addSessionToFolder),_e=mt(A=>A.addSessionsToFolder),ht=mt(A=>A.removeSessionFromFolder),yt=mt(A=>A.removeSessionsFromFolders),nt=mt(A=>A.toggleFolderCollapse),ns=mt(A=>A.getSessionFolderId);gm({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchContainerRef:p});const rs=vu(e),{git:Ze}=Os(),Ot=Nn(A=>A.connection,void 0,"chrome"),lt=Nn(A=>{for(const J of A.catalog.listStatusByDirectory.values())if(J==="ready")return!0;return!1},void 0,"catalog"),wt=ao({archived:!1}),vt=ao({archived:!0}),_s=Te(A=>A.setCurrentSession),zs=Te(A=>A.updateSessionTitle),Cs=Te(A=>A.shareSession),fs=Te(A=>A.unshareSession),Nt=lo(A=>A.projects),hs=lo(A=>A.refreshProject),St=a.useMemo(()=>Su(fe,{projects:Nt}),[fe,Nt]),os=a.useMemo(()=>{const A=new Map;for(const J of fe){const ee=Ee(J.path);if(!ee)continue;const Me=Nt.get(ee)?.error;Me&&A.set(ee,Me)}return A},[fe,Nt]);a.useEffect(()=>{if(!w)return;const A=fe.find(ee=>ee.id===w);if(!A){qs.getState().clearSpaceSelection();return}if(!N)return;(St.get(Ee(A.path)??A.path)??[]).some(ee=>Ee(ee.path)===Ee(N))||(qs.getState().clearSelectedWorktree(),ae.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[St,fe,w,N]);const is=Te(A=>A.openNewSessionDraft),it=a.useCallback(A=>{de.getState().closeMainSurfaces(),is(A),r?.()},[r,is]),Bt=tr(ro(A=>({checkForUpdates:A.checkForUpdates,available:A.available,runtimeType:A.runtimeType,info:A.info,downloading:A.downloading,downloaded:A.downloaded,progress:A.progress,error:A.error,downloadUpdate:A.downloadUpdate,restartToUpdate:A.restartToUpdate}))),Us=a.useMemo(()=>ju(fe,St,{includeWorktrees:!0}),[St,fe]),It=a.useMemo(()=>wt.filter(A=>Rm(A,Us,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:se})),[wt,se,Us]),mn=a.useMemo(()=>[...It,...vt],[vt,It]),$s=Pt(),Ks=a.useMemo(()=>`${$s}|${fe.map(A=>`${A.id}:${Ee(A.path)??""}`).join("|")}`,[fe,$s]),ks=a.useMemo(()=>{const A=new Set;let J=!0;for(const ee of fe){const Me=Ee(ee.path);if(!Me)continue;const ze=Nt.get(Me)?.status??"idle";ze==="failed"&&A.add(Me),(ze==="idle"||ze==="loading")&&(J=!1)}return{complete:J,unresolved:A}},[fe,Nt]),O=ks.complete?Ks:null,ie=!ks.complete,ye=ks.unresolved,{isTablet:Z}=dn(),Ve=t||Z,qe=pm({mobileVariant:t,isTablet:Z}),{buildGroupSearchText:Et,filterSessionNodesForSearch:pt,buildGroupedSessions:ms}=mm({homeDirectory:se,pinnedSessionIds:X,sessionOrderRanks:ne}),{scheduleCollapsedProjectsPersist:Zo}=xm({safeStorage:k,keys:{sessionExpanded:ca,projectCollapse:oa,groupOrder:ia,groupCollapse:aa},groupOrderByProject:Y,collapsedGroups:Se,setExpandedParents:E,setCollapsedProjects:j}),Ws=a.useMemo(()=>Cu(It,X,ne),[X,ne,It]),Ir=a.useMemo(()=>Ws.map(A=>A.id).join("|"),[Ws]),ei=a.useRef(null),ti=a.useMemo(()=>{const A=ei.current;if(A&&A.signature===Ir)return A.map;const J=new Map(Ws.map((ee,Me)=>[ee.id,Me]));return ei.current={signature:Ir,map:J},J},[Ws,Ir]),fc=a.useMemo(()=>{const A=new Map;Ws.forEach(ee=>{const Me=ee.parentID;if(!Me)return;const ze=A.get(Me)??[];ze.push(ee),A.set(Me,ze)});const J=_a(X,ne);return A.forEach(ee=>ee.sort(J)),A},[Ws,X,ne]),hc=a.useMemo(()=>s.jsx(Xt,{icon:"chat-new",mobileVariant:t,onClick:()=>it(),children:"New session"}),[t,it]),mc=a.useMemo(()=>fe.find(A=>A.id===g)??null,[fe,g]),pc=a.useCallback(A=>{g&&Ie(g,{label:A.label,defaultModel:A.defaultModel??null})},[g,Ie]),gc=a.useCallback(()=>{const A=tr.getState();if(A.available&&A.info){L(!0);return}Bt.checkForUpdates().then(()=>{const{available:J,error:ee}=tr.getState();if(ee){ae.error("Failed to check for updates",{description:ee});return}if(!J){ae.success("You are on the latest version");return}L(!0)})},[Bt]),Gs=ku(),si=a.useCallback(()=>{if(t&&Qe(!1),r?.(),Gs?.openSettings){Gs.openSettings();return}Fe(!0)},[Gs,t,r,Qe,Fe]),bc=Bt.available&&(Bt.runtimeType==="desktop"||Bt.runtimeType==="web"),xc=Te(A=>A.deleteSession),ni=Te(A=>A.deleteSessions),yc=Te(A=>A.archiveSession),ri=Te(A=>A.archiveSessions),wc=Te(A=>A.unarchiveSession),vc=Te(A=>A.unarchiveSessions),{copiedSessionId:Sc,handleSessionSelect:jc,handleSessionDoubleClick:Cc,handleSaveEdit:kc,handleCancelEdit:Ac,handleShareSession:Nc,handleCopyShareUrl:Ic,handleCopySessionId:Ec,handleUnshareSession:Rc,handleDeleteSession:Dc,handleRestoreSession:Pc,confirmDeleteSession:Mc}=bm({mobileVariant:t,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:f,setIsSessionSearchOpen:d,setActiveMainTab:oe,setSessionSwitcherOpen:Qe,setCurrentSession:_s,updateSessionTitle:zs,shareSession:Cs,unshareSession:fs,deleteSession:xc,deleteSessions:ni,archiveSession:yc,archiveSessions:ri,unarchiveSession:wc,childrenMap:fc,showDeletionDialog:ot,setDeleteSessionConfirm:be,deleteSessionConfirm:B,setEditingId:m,setEditTitle:b,editingId:y,editTitle:h}),Tc=a.useCallback(()=>{if(!V)return;const{scopeKey:A,folderId:J}=V;Ce(null),ge(A,J)},[V,ge]),Er=a.useCallback(()=>{Ms.requestDirectoryDialog()},[]),Fc=a.useCallback(A=>{E(J=>{const ee=If(J,A);try{k.setItem(ca,JSON.stringify(Array.from(ee)))}catch{}return ee})},[k]),oi=a.useCallback((A,J)=>{if(!A)return null;J&&Lt.has(J)&&nt(J);const ee=ke(A,"New folder",J);return T(ee.id),G(ee.name),ee},[Lt,nt,ke]),pn=Rt(jc),Lc=Rt(Cc),Oc=Rt(kc),Bc=Rt(Ac),_c=Rt(Nc),zc=Rt(Ic),Uc=Rt(Ec),$c=Rt(Rc),Kc=Rt(Dc),Wc=Rt(Pc),Rr=Rt(oi),ii=a.useCallback((A,J)=>{U(ee=>{const Me=new Map(ee);return Me.set(A,J+7),Me})},[]),Un=a.useCallback(A=>{U(J=>{if(!J.has(A))return J;const ee=new Map(J);return ee.delete(A),ee})},[]),ai=a.useCallback(A=>{U(J=>{let ee=!1;const Me=new Map(J),ze=`${A}:`;for(const tt of Me.keys())tt.startsWith(ze)&&(Me.delete(tt),ee=!0);return ee?Me:J})},[]),Dr=a.useCallback(A=>{xe.current=Date.now()+150,ai(A),j(J=>{const ee=new Set(J);ee.has(A)?ee.delete(A):ee.add(A);try{k.setItem(oa,JSON.stringify(Array.from(ee)))}catch{}return Zo(ee),ee})},[ai,k,Zo]),li=a.useRef(null);a.useEffect(()=>{const A=li.current;li.current=je,et==="folder"&&(!A||!je||A===je||C.has(je)&&Dr(je))},[je,C,et,Dr]);const ps=a.useMemo(()=>fe.map(A=>({...A,normalizedPath:Ee(A.path)})).filter(A=>!!A.normalizedPath),[fe]),Gc=a.useMemo(()=>ps.map(A=>A.normalizedPath),[ps]),ci=Au(e?Gc:Gr);Cm({enabled:e,normalizedProjects:ps,gitRepoStatus:ci,setProjectRepoStatus:F,setProjectRootBranches:Le});const di=a.useMemo(()=>Pm(It,ps,St,vt),[vt,St,ps,It]);Im({enabled:e,hasAuthoritativeGlobalSessions:lt,sessions:mn});const{getSessionsForProject:Hc,getArchivedSessionsForProject:qc}=km({ownership:di});im({enabled:e,normalizedProjects:ps,ownership:di,hasAuthoritativeGlobalSessions:lt,isWorktreeTopologyLoading:ie,unresolvedWorktreeProjectPaths:ye,foldersMap:Yt,createFolder:ke,addSessionToFolder:Oe});const ui=a.useRef(!1);je&&M.has(je)&&(ui.current=!!M.get(je));const Yc=ra(A=>A.showArchivedSessions),Pr=dt(A=>A.manualProjectOrder),fi=a.useRef(new Set),$n=Ef(fi.current,v,"project");fi.current=$n;const Mr={isVisible:e,mobileVariant:t,onSessionSelected:n,allowReselect:o,hideDirectoryControls:i,showOnlyMainWorkspace:l,isTablet:Z,catalogSessions:wt,archivedSessions:vt,projects:fe,activeProjectId:je,manualProjectOrder:Pr,currentDirectory:pe,availableWorktreesByProject:St,pinnedSessionIds:X,sessionOrderRanks:ne,foldersMap:Yt,collapsedFolderIds:Lt,gitBranches:rs,gitRepoStatus:ci,updateStore:Bt,showArchivedSessions:Yc,projectRepoStatus:M,projectRootBranches:ve,resolvedWorktreeTopologyKey:O,unresolvedWorktreeProjectPaths:ye,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:y,editTitle:h,editingProjectDialogId:g,expandedParents:v,collapsedProjects:C,visibleSessionCountByGroup:$,updateDialogOpen:K,openSidebarMenuKey:D,renamingFolderId:I,renameFolderDraft:W,deleteSessionConfirm:B,deleteFolderConfirm:V,bulkDeleteConfirm:z,collapsedGroups:Se},hi=a.useRef(null),mi=hi.current;if(mi){let A=!1;for(const J of Object.keys(Mr))Object.is(mi[J],Mr[J])||(Kt(`ui.session_sidebar.source.${J}`),A=!0);A||Kt("ui.session_sidebar.source.parent_or_context")}hi.current=Mr;const Vc=a.useMemo(()=>{const A=new Map(Pr.map((J,ee)=>[J,ee]));return[...ps].sort((J,ee)=>(A.get(J.id)??1/0)-(A.get(ee.id)??1/0))},[Pr,ps]),{projectSections:_t,groupSearchDataByGroup:pi,sectionsForRender:Qc,flatSectionsForRender:Tr,searchMatchCount:Jc}=lm({normalizedProjects:Vc,getSessionsForProject:Hc,getArchivedSessionsForProject:qc,availableWorktreesByProject:St,projectRepoStatus:M,projectRootBranches:ve,lastRepoStatus:ui.current,buildGroupedSessions:ms,hasSessionSearchQuery:Je,normalizedSessionSearchQuery:xt,filterSessionNodesForSearch:pt,buildGroupSearchText:Et,foldersMap:Yt}),gn=a.useMemo(()=>{const A=It.filter(ee=>vr(In(ee),se));if(A.length===0)return null;const J=ms(A,"~",[],null,!1).map(ee=>Je?{...ee,sessions:pt(ee.sessions,xt)}:ee).filter(ee=>ee.sessions.length>0&&!ee.isArchivedBucket);return J.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:J}},[ms,pt,Je,se,xt,It]),Xc=a.useMemo(()=>{if(!Je||!gn)return 0;const A=J=>J.reduce((ee,Me)=>ee+1+A(Me.children),0);return gn.groups.reduce((J,ee)=>J+A(ee.sessions),0)},[gn,Je]),Zc=a.useMemo(()=>s.jsxs("div",{className:"py-6 text-center text-muted-foreground",children:[s.jsx("p",{className:"typography-ui-label font-semibold",children:"No matching sessions"}),s.jsx("p",{className:"typography-meta mt-1",children:"Try a different title, branch, folder, or path."})]}),[]),{getOrderedGroups:ed}=am(Y),gi=a.useRef(!1);a.useEffect(()=>{if(gi.current||_t.length===0)return;const A=_t.flatMap(J=>J.groups.filter(ee=>ee.isArchivedBucket).map(ee=>`${J.project.id}:${ee.id}`));A.length>0&&Ge(J=>new Set([...J,...A])),gi.current=!0},[_t]);const{sectionsForSidebarRender:td,filteredSectionsForSidebarRender:sd,totalSessionCount:nd,sessionCountByProject:rd,hasActiveSessionByProject:od,activeDirectoriesByProject:bn,hasUnseenByProject:id}=kg({projectSections:_t,flatSectionsForRender:Tr,sectionsForRender:Qc,selectedSpaceId:w,selectedWorktreePath:N,homeDirectory:se,activeSessionIdSet:q,unreadSessionIdSet:le}),Fr=a.useCallback(A=>{if(qs.getState().selectSpace(A),!A)return;We(A);const J=_t.find(ze=>ze.project.id===A),ee=J?.groups.find(ze=>ze.isMain),Me=ee?.sessions[0]?.session;Me?pn(Me.id,ee?.directory??J?.project.normalizedPath??null,{keepPanelOpen:!0}):J&&it({selectedProjectId:A,directoryOverride:J.project.normalizedPath})},[it,_t,We,pn]),ad=t?"flex size-10 shrink-0 items-center justify-center rounded-full leading-none text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed":"inline-flex h-6 w-6 cursor-pointer items-center justify-center rounded-md leading-none text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:cursor-not-allowed",ld=t?"size-5":"size-4",Kn=Rt((A,J=0,ee,Me,ze=!1,tt,Vt="project",Hs)=>s.jsx(cg,{node:A,depth:J,groupDirectory:ee,projectId:Me,archivedBucket:ze,pinnedSessionIds:X,expandedParents:$n,hasSessionSearchQuery:Je,normalizedSessionSearchQuery:xt,editingId:y,setEditingId:m,editTitle:h,setEditTitle:b,handleSaveEdit:Oc,handleCancelEdit:Bc,toggleParent:Fc,handleSessionSelect:pn,handleSessionDoubleClick:Lc,togglePinnedSession:Ae,handleShareSession:_c,copiedSessionId:Sc,handleCopyShareUrl:zc,handleCopySessionId:Uc,handleUnshareSession:$c,openSidebarMenuKey:D,setOpenSidebarMenuKey:R,renamingFolderId:I,getFoldersForScope:us,getSessionFolderId:ns,removeSessionFromFolder:ht,addSessionToFolder:Oe,createFolderAndStartRename:Rr,handleDeleteSession:Kc,handleRestoreSession:Wc,mobileVariant:t,alwaysShowActions:Ve,allowQuickArchiveAction:qe,renderSessionNode:Kn,secondaryMeta:tt,renderContext:Vt,subtreeContainsEditing:Hs?.subtreeContainsEditing??Eg,menuOpenSessionId:Hs?.menuOpenSessionId??null,nodeStructureKey:Hs?.nodeStructureKey??"",childRenderExtrasFor:Hs?.childRenderExtrasFor})),cd=a.useMemo(()=>{const A=new Map;return Tr.forEach(J=>{const ee=J.groups.find(Me=>!Me.isArchivedBucket);ee?.folderScopes&&ee.folderScopes.length>0&&A.set(J.project.id,ee.folderScopes)}),A},[Tr]),dd=a.useCallback((A,J)=>{const ee=[];return J.forEach(Me=>{Me.isArchivedBucket||(ee.push(Me.directory),Me.folderScopes?.forEach(ze=>ee.push(ze.directory)))}),s.jsx(gg,{directories:ee})},[]),bi=a.useCallback(A=>{Un(A),Ge(J=>{const ee=new Set(J);return ee.has(A)?ee.delete(A):ee.add(A),ee})},[Un]),ud=a.useCallback((A,J,ee,Me,ze,tt,Vt)=>s.jsx(vp,{group:A,groupKey:J,projectId:ee,hideGroupLabel:Me,dragHandleProps:ze,compactBodyPadding:tt,hasSessionSearchQuery:Je,normalizedSessionSearchQuery:xt,groupSearchDataByGroup:pi,visibleSessionCount:$.get(J),collapsedGroups:Se,hideDirectoryControls:i,collapsedFolderIds:Lt,toggleFolderCollapse:nt,renameFolder:Be,deleteFolder:ge,showDeletionDialog:ot,setDeleteFolderConfirm:Ce,renderSessionNode:Kn,showMoreGroupSessions:ii,resetGroupSessionLimit:Un,mobileVariant:t,alwaysShowActions:Ve,activeProjectId:je,setActiveProjectIdOnly:We,setActiveMainTab:oe,setSessionSwitcherOpen:Qe,openNewSessionDraft:it,addSessionToFolder:Oe,createFolderAndStartRename:Rr,renamingFolderId:I,renameFolderDraft:W,setRenameFolderDraft:G,setRenamingFolderId:T,pinnedSessionIds:X,expandedParents:$n,sessionOrderIndex:ti,editingId:y,editTitle:h,openSidebarMenuKey:D,activeActivitySessionIds:q,unreadActivitySessionIds:le,onToggleCollapsedGroup:bi,scrollContainerRef:Vt}),[Je,xt,pi,$,Se,i,Lt,nt,Be,ge,ot,Kn,ii,Un,t,Ve,je,We,oe,Qe,it,Oe,Rr,I,W,X,$n,ti,y,h,D,q,le,bi]),xi=!!(I||y||g),{selectionModeEnabled:Lr,hasSelection:yi,selectedIdsSize:fd,bulkScopeIsArchived:hd,derivedSelectionScope:md,bulkScopeFolders:pd,bulkCanRemoveFromFolder:gd,handleToggleSelectionMode:bd,handleExitSelectionMode:xd,handleBulkMoveToFolder:yd,handleBulkCreateFolderAndMove:wd,handleBulkRemoveFromFolder:vd,handleBulkDelete:Sd,handleBulkRestore:jd,confirmBulkDelete:Cd}=Ng({isInlineEditing:xi,showDeletionDialog:ot,foldersMap:Yt,folderScopesByProject:cd,addSessionsToFolder:_e,removeSessionsFromFolders:yt,createFolderAndStartRename:oi,archiveSessions:ri,unarchiveSessions:vc,deleteSessions:ni,setBulkDeleteConfirm:Q}),wi=a.useCallback(()=>{de.getState().closeMainSurfaces(),oe("chat"),t&&Qe(!1),is(),r?.()},[t,r,is,oe,Qe]),kd=a.useCallback((A,J)=>{const ee=fe.find(tt=>tt.id===A);if(!ee)return;const Me=Ee(J.path)?.toLowerCase(),ze=!!(Me&&bn.get(A)?.has(Me));H({projectId:A,projectPath:ee.path,worktree:J,hasActiveSession:ze})},[bn,fe]),Ad=a.useCallback(async({force:A})=>{const J=De;if(!J)return;const ee=Ee(J.worktree.path)?.toLowerCase();if(!!(ee&&bn.get(J.projectId)?.has(ee))){H({...J,hasActiveSession:!0}),ae.warning("Stop the active session before closing this worktree.");return}if(!Ze.deleteGitWorktree){ae.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await Ze.deleteGitWorktree(J.projectPath,{directory:J.worktree.path,force:A}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let tt=await hs(J.projectPath,Ze,{force:!0});const Vt=Ee(J.worktree.path);tt!==null&&Vt!==null&&tt.some(Id=>Ee(Id.path)===Vt)&&(tt=await hs(J.projectPath,Ze,{force:!0}));const Hs=Vt!==null&&Ee(pe)===Vt,Nd=Vt!==null&&w===J.projectId&&Ee(N)===Vt;(Hs||Nd)&&Fr(J.projectId),H(null),tt===null?ae.warning("Worktree closed, but the sidebar could not be refreshed."):ae.success("Worktree closed.")}catch(ze){const tt=ze instanceof Error?ze.message:"Try again.";ae.error("Failed to close worktree.",{description:tt})}},[bn,De,pe,Ze,Fr,hs,w,N]);return s.jsx(Nu,{delay:400,closeDelay:150,timeout:600,children:s.jsxs("div",{ref:p,className:_("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[s.jsx(dm,{projectSections:_t,activeProjectId:je,initialActiveSessionByProject:re,persistActiveSessionByProject:ue,handleSessionSelect:pn,mobileVariant:t,openNewSessionDraft:is,setActiveMainTab:oe,setSessionSwitcherOpen:Qe}),!i&&!t?s.jsx(jp,{onNewSession:wi,showSidebarToggle:!0}):null,s.jsx(Sp,{hideDirectoryControls:i,handleOpenDirectoryDialog:Er,onOpenArchive:()=>{t&&Qe(!1),rt(!0)},onOpenSettings:t?si:void 0,onOpenInstances:t?Gs?.openInstances:void 0,instanceLabel:t?Gs?.instanceLabel:void 0,onOpenUpdate:t?Gs?.openUpdate:void 0,headerActionIconClass:ld,headerActionButtonClass:ad,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:x,sessionSearchQuery:u,setSessionSearchQuery:f,hasSessionSearchQuery:Je,searchMatchCount:Jc+(et!=="workspace"||w===null?Xc:0),selectionModeEnabled:Lr,onToggleSelectionMode:bd,mobileVariant:t}),Ot==="error"||Ot==="unavailable"?s.jsx("div",{role:"alert",className:"mx-2 mb-2 rounded border border-[var(--status-error-border)] bg-[var(--status-error-background)] p-2 text-xs text-foreground",children:"Unable to reach server"}):null,!i&&_t.length>0&&et==="workspace"?s.jsx(Ap,{projects:_t.map(A=>A.project),selectedProjectId:w,selectedWorktreePath:N,worktreesByProject:St,worktreeErrorsByProject:os,onSelectProject:Fr,onSelectWorktree:(A,J)=>{qs.getState().selectWorktree(A,J),We(A);const ze=_t.find(tt=>tt.project.id===A)?.groups.find(tt=>Ee(tt.directory)===Ee(J))?.sessions[0]?.session;ze?pn(ze.id,J,{keepPanelOpen:!0}):it({selectedProjectId:A,directoryOverride:J})},onCloseWorktree:kd,onOpenDirectoryDialog:Er,onOpenProjectEditDialog:S,onRemoveProject:He,totalSessionCount:nd,getSessionCountForProject:A=>rd.get(A)??0,hasActiveSessionByProject:od,activeDirectoriesByProject:bn,hasUnseenByProject:id,homeDirectory:se,mobileVariant:t}):null,s.jsx(Mp,{viewMode:et,timelineBoundaries:kt,onOpenDirectoryDialog:Er,stickyFolderHeaders:At,sectionsForRender:et==="workspace"?sd:td,allFoldersOnlySection:et==="workspace"?w===null?gn:null:gn,isAllFoldersView:et==="workspace"?w===null:et==="timeline",projectSections:_t,activeProjectId:je,showOnlyMainWorkspace:l,hasSessionSearchQuery:Je,emptyState:hc,searchEmptyState:Zc,pinnedSessionIds:X,renderSessionNode:Kn,renderGroupSessions:ud,homeDirectory:se,collapsedProjects:C,hideDirectoryControls:i,projectRepoStatus:M,mobileVariant:t,alwaysShowActions:Ve,toggleProject:Dr,setActiveProjectIdOnly:We,setActiveMainTab:oe,setSessionSwitcherOpen:Qe,openNewSessionDraft:it,openProjectEditDialog:S,removeProject:He,reorderProjects:Ye,getOrderedGroups:ed,setGroupOrderByProject:ce,renderProjectStatusIndicator:dd,openSidebarMenuKey:D,setOpenSidebarMenuKey:R,isInlineEditing:xi}),t&&!(Lr&&yi)?s.jsxs("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 z-10 flex flex-col gap-2 bg-gradient-to-t from-sidebar via-sidebar/85 to-transparent px-4 pb-[calc(0.75rem+var(--oc-safe-area-bottom,0px))] pt-10",children:[s.jsx(Rl,{variant:"mobile"}),s.jsx(Ne,{type:"button",variant:"default",size:"lg",className:"pointer-events-auto w-full shadow-lg",onClick:wi,"aria-label":"New session",children:s.jsx(P,{name:"chat-new",className:"size-4"})})]}):null,Lr&&yi?s.jsx(Ag,{selectedCount:fd,scopeKey:md,scopeFolders:pd,archivedBucket:hd,onMoveToFolder:yd,onCreateFolderAndMove:wd,onRemoveFromFolder:vd,canRemoveFromFolder:gd,onRestore:jd,onDelete:Sd,onDone:xd}):null,t?null:s.jsx(Np,{onOpenSettings:si,onOpenShortcuts:bt,onOpenAbout:()=>{st("about"),Fe(!0)},onOpenUpdate:gc,showRuntimeButtons:!0,showUpdateButton:bc}),s.jsx(pg,{updateDialogOpen:K,setUpdateDialogOpen:L,updateStore:Bt,editingProject:mc,setEditingProjectDialogId:S,handleSaveProjectEdit:pc,deleteSessionConfirm:B,setDeleteSessionConfirm:be,showDeletionDialog:ot,setShowDeletionDialog:qt,confirmDeleteSession:Mc,deleteFolderConfirm:V,setDeleteFolderConfirm:Ce,confirmDeleteFolder:Tc,closeWorktreeConfirm:De,setCloseWorktreeConfirm:H,confirmCloseWorktree:Ad,bulkDeleteConfirm:z,setBulkDeleteConfirm:Q,confirmBulkDelete:Cd})]})})},uy=a.memo(Rg),da=6,Dt=.18,Cn=1.2,kn=.38,ir=48,Dg=(e,t)=>e==="left"?t<0:t>0,fy=(e,t,n)=>Math.min(1,Math.max(0,e==="left"?1+t/n:1-t/n)),hy=(e,t)=>t>=.999?"none":e==="left"?`translateX(${(t-1)*100}%)`:`translateX(${(1-t)*100}%)`,ua=(e,t,n,r)=>e==="left"?t?Math.min(1,Math.max(0,1+n/r)):Math.min(1,Math.max(0,n/r)):t?Math.min(1,Math.max(0,1-n/r)):Math.min(1,Math.max(0,-n/r)),my=e=>{const{side:t,dx:n,dy:r,dt:o,progress:i,isDragging:l}=e,c=n/Math.max(1,o);if(l){const d=t==="left"?c<-Dt:c>Dt,u=t==="left"?c>Dt:c<-Dt;return d||!u&&i<kn}return Math.abs(n)>=ir&&Math.abs(r)<=Math.abs(n)*Cn&&Dg(t,n)},Pg=e=>{const{side:t,isOpenAtStart:n,dx:r,dt:o,progress:i}=e,l=r/Math.max(1,o);return t==="left"?n?l<-Dt?!1:l>Dt?!0:i>kn:l>Dt?!0:l<-Dt?!1:i>kn:n?l>Dt?!1:l<-Dt?!0:i>kn:l<-Dt?!0:l>Dt?!1:i>kn},Mg='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',Tg=(e,t,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const i=e.closest(Mg);if(i&&t.contains(i))return!0}else{const i=e.closest("[data-no-drawer-swipe]");if(i&&t.contains(i))return!0}let o=e;for(;o&&o!==t;){if(o instanceof HTMLElement&&o.scrollWidth>o.clientWidth){const i=getComputedStyle(o).overflowX;if(i==="auto"||i==="scroll")return!0}o=o.parentElement}return!1},ar=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Lo=512*1024,Fg=new TextEncoder,Lg=new TextDecoder,Hr=e=>{const t=Fg.encode(e);if(t.byteLength<=Lo)return{text:e,byteLength:t.byteLength};let n=t.byteLength-Lo;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:Lg.decode(r),byteLength:r.byteLength}},Vs=(e,t)=>`${e}\0${t}`,qr=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},Og="terminal-store";let fa=!1,ha=0;const er=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(ha+=1,`tab-${Date.now().toString(36)}-${ha.toString(36)}`),Yr=e=>typeof e=="object"&&e!==null,Bg=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null};function at(e){let t=e.trim();for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t}const _g=/^Terminal(?: (\d+))?$/,zg=e=>{let t=0;for(const n of e){const r=_g.exec(n.label);if(!r)continue;const o=r[1]?Number.parseInt(r[1],10):1;Number.isSafeInteger(o)&&(t=Math.max(t,o))}return t===0?"Terminal":`Terminal ${t+1}`},Vr=(e,t)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:t,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),Qr=e=>({tabs:[e],activeTabId:e.id}),zt=(e,t)=>e.tabs.findIndex(n=>n.id===t);let Jr=null,Xr=null;const Ug=e=>{if(Xr&&Jr?.sessions===e.sessions&&Jr.nextTabId===e.nextTabId)return Xr;const t={sessions:Array.from(e.sessions.entries()).map(([n,r])=>[n,{activeTabId:r.activeTabId,tabs:r.tabs.map(o=>({id:o.id,label:o.label,iconKey:o.iconKey,createdAt:o.createdAt}))}]),nextTabId:e.nextTabId};return Jr={sessions:e.sessions,nextTabId:e.nextTabId},Xr=t,t},$g=()=>{const e=Rf(()=>nf());if(!e)return;let t=null;return{getItem:n=>e.getItem(n),setItem:(n,r)=>{if(r.state!==t)return t=r.state,e.setItem(n,r)},removeItem:n=>(t=null,e.removeItem(n))}},he=Bs()(Sr(dl((e,t)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=at(n);r&&e(o=>{if(o.sessions.has(r))return o;const i=new Map(o.sessions),l=er(),c=Vr(l,"Terminal");return i.set(r,Qr(c)),{sessions:i,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=at(n);return t().sessions.get(r)},getActiveTab:n=>{const r=at(n),o=t().sessions.get(r);if(!o)return;const i=o.activeTabId;return i?o.tabs.find(l=>l.id===i)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>t().buffers.get(Vs(at(n),r))??ar,createTab:n=>{const r=at(n);if(!r)return"tab-invalid";const o=er();return e(i=>{const l=new Map(i.sessions),c=l.get(r),d=i.nextTabId+1,u=zg(c?.tabs??[]),f=Vr(o,u);return c?l.set(r,{...c,tabs:[...c.tabs,f]}):l.set(r,Qr(f)),{sessions:l,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=at(n);e(i=>{const l=new Map(i.sessions),c=l.get(o);return!c||c.activeTabId===r||zt(c,r)<0?i:(l.set(o,{...c,activeTabId:r}),{sessions:l})})},setTabLabel:(n,r,o)=>{const i=at(n),l=o.trim();l&&e(c=>{const d=new Map(c.sessions),u=d.get(i);if(!u)return c;const f=zt(u,r);if(f<0||u.tabs[f]?.label===l)return c;const p=[...u.tabs];return p[f]={...p[f],label:l},d.set(i,{...u,tabs:p}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const i=at(n);e(l=>{const c=new Map(l.sessions),d=c.get(i);if(!d)return l;const u=zt(d,r);if(u<0)return l;const f=o?.trim()||null;if(d.tabs[u]?.iconKey===f)return l;const p=[...d.tabs];return p[u]={...p[u],iconKey:f},c.set(i,{...d,tabs:p}),{sessions:c}})},closeTab:(n,r)=>{const o=at(n);e(i=>{const l=new Map(i.sessions),c=l.get(o);if(!c)return i;const d=zt(c,r);if(d<0)return i;const u=c.tabs.filter(h=>h.id!==r),f=Object.fromEntries(Object.entries(i.projectActionRuns).filter(([,h])=>!(h.directory===o&&h.tabId===r))),p=Object.keys(f).length!==Object.keys(i.projectActionRuns).length,x=Vs(o,r),y=i.buffers.has(x)?qr(i.buffers,h=>h===x):null;if(u.length===0){const h=er(),b=Vr(h,"Terminal");return l.set(o,Qr(b)),{sessions:l,nextTabId:i.nextTabId+1,...y?{buffers:y}:{},...p?{projectActionRuns:f}:{}}}let m=c.activeTabId;return c.activeTabId===r&&(m=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),l.set(o,{...c,tabs:u,activeTabId:m}),{sessions:l,...y?{buffers:y}:{},...p?{projectActionRuns:f}:{}}})},setTabSessionId:(n,r,o)=>{const i=at(n);e(l=>{const c=new Map(l.sessions),d=c.get(i);if(!d)return l;const u=zt(d,r);if(u<0)return l;const f=d.tabs[u],p=o!==null&&f.terminalSessionId!==o,x=o?"running":f.terminalSessionId?"exited":f.lifecycle,y={...f,terminalSessionId:o,lifecycle:x,isConnecting:!1},m=Vs(i,r),h=p&&l.buffers.has(m)?qr(l.buffers,g=>g===m):null,b=[...d.tabs];return b[u]=y,c.set(i,{...d,tabs:b}),{sessions:c,...h?{buffers:h}:{}}})},setTabLifecycle:(n,r,o)=>{const i=at(n);e(l=>{const c=new Map(l.sessions),d=c.get(i);if(!d)return l;const u=zt(d,r);if(u<0)return l;const f=[...d.tabs];return f[u]={...f[u],lifecycle:o,isConnecting:!1},c.set(i,{...d,tabs:f}),{sessions:c}})},setConnecting:(n,r,o)=>{const i=at(n);e(l=>{const c=new Map(l.sessions),d=c.get(i);if(!d)return l;const u=zt(d,r);if(u<0)return l;const f=[...d.tabs];return f[u]={...f[u],isConnecting:o},c.set(i,{...d,tabs:f}),{sessions:c}})},replaceBuffer:(n,r,o,i)=>{const l=at(n);e(c=>{const d=c.sessions.get(l);if(!d||zt(d,r)<0)return c;const u=Vs(l,r),f=c.buffers.get(u)??ar;if(f.lastSequence>i)return c;const p=Hr(o);if(f.lastSequence===i&&f.byteLength===p.byteLength&&f.chunks.map(m=>m.data).join("")===p.text)return c;const x=c.nextChunkId,y=new Map(c.buffers);return y.set(u,{chunks:p.text?[{id:x,data:p.text,byteLength:p.byteLength}]:[],byteLength:p.byteLength,lastSequence:i}),{buffers:y,nextChunkId:p.text?x+1:x}})},appendToBuffer:(n,r,o,i,l)=>{if(!o)return;const c=at(n);e(d=>{const u=d.sessions.get(c);if(!u||zt(u,r)<0)return d;const f=Vs(c,r),p=d.buffers.get(f)??ar;if(i!==void 0&&i<=p.lastSequence)return d;const x=d.nextChunkId,y=Hr(o),m=l!==void 0&&l!==o?Hr(l).text:void 0,h={id:x,data:y.text,...m!==void 0?{replayData:m}:{},byteLength:y.byteLength},b=[...p.chunks,h];let g=p.byteLength+h.byteLength;for(;g>Lo&&b.length>1;){const v=b.shift();if(!v)break;g-=v.byteLength}const S=new Map(d.buffers);return S.set(f,{chunks:b,byteLength:g,lastSequence:i??p.lastSequence}),{buffers:S,nextChunkId:x+1}})},setTabPreviewUrl:(n,r,o,i={})=>{const l=at(n);e(c=>{const d=new Map(c.sessions),u=d.get(l);if(!u)return c;const f=zt(u,r);if(f<0)return c;const p=u.tabs[f],x=i.autoOpened??p.previewAutoOpened,y=i.locked??p.previewUrlLocked;if(p.previewUrl===o&&p.previewAutoOpened===x&&p.previewUrlLocked===y)return c;const m=[...u.tabs];return m[f]={...p,previewUrl:o,previewAutoOpened:x,previewUrlLocked:y},d.set(l,{...u,tabs:m}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=at(n);e(i=>{const l=new Map(i.sessions),c=l.get(o);if(!c)return i;const d=zt(c,r);if(d<0)return i;const u=c.tabs[d];if(!u.previewUrl||u.previewAutoOpened)return i;const f=[...c.tabs];return f[d]={...u,previewAutoOpened:!0},l.set(o,{...c,tabs:f}),{sessions:l}})},setProjectActionRun:n=>{e(r=>{const o=r.projectActionRuns[n.key];return o&&o.directory===n.directory&&o.actionId===n.actionId&&o.tabId===n.tabId&&o.sessionId===n.sessionId&&o.status===n.status?r:{projectActionRuns:{...r.projectActionRuns,[n.key]:n}}})},updateProjectActionRunStatus:(n,r)=>{e(o=>{const i=o.projectActionRuns[n];return!i||i.status===r?o:{projectActionRuns:{...o.projectActionRuns,[n]:{...i,status:r}}}})},removeProjectActionRun:n=>{e(r=>{if(!r.projectActionRuns[n])return r;const o={...r.projectActionRuns};return delete o[n],{projectActionRuns:o}})},removeDirectory:n=>{const r=at(n);e(o=>{const i=new Map(o.sessions);i.delete(r);const l=Vs(r,""),c=qr(o.buffers,u=>u.startsWith(l)),d=Object.fromEntries(Object.entries(o.projectActionRuns).filter(([,u])=>u.directory!==r));return{sessions:i,...c?{buffers:c}:{},projectActionRuns:d}})},clearAll:()=>{e({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1})}}),{name:Og,storage:$g(),partialize:Ug,merge:(e,t)=>{if(!Yr(e))return t;const n=Array.isArray(e.sessions)?e.sessions:[],r=new Map;let o=0;for(const c of n){if(!Array.isArray(c)||c.length!==2)continue;const[d,u]=c;if(typeof d!="string"||!Yr(u))continue;const f=Array.isArray(u.tabs)?u.tabs:[],p=[],x=new Map;for(const b of f){if(!Yr(b))continue;const g=typeof b.id=="string"?b.id:null;if(!g)continue;const S=Bg(g);S!==null&&(o=Math.max(o,S));const v=S===null?g:er();x.set(g,v),p.push({id:v,label:typeof b.label=="string"?b.label:"Terminal",iconKey:typeof b.iconKey=="string"?b.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof b.createdAt=="number"?b.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(p.length===0)continue;const y=typeof u.activeTabId=="string"?u.activeTabId:null,m=y?x.get(y)??y:null,h=m?p.some(b=>b.id===m):!1;r.set(d,{tabs:p,activeTabId:h?m:p[0].id})}const i=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,l=Math.max(t.nextTabId,i,o+1);return{...t,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:l,hasHydrated:!0}}})));if(typeof window<"u"&&!fa){fa=!0;const e=he.persist,t=()=>{he.getState().hasHydrated||he.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}function Kg(e){const{colors:t}=e,n=t.syntax.base;return{background:t.surface.background,foreground:n.foreground,cursor:t.interactive.cursor,cursorAccent:t.surface.background,selectionBackground:t.interactive.selection,selectionForeground:t.interactive.selectionForeground,selectionInactiveBackground:t.interactive.selection+"50",black:t.surface.muted,red:t.status.error,green:t.status.success,yellow:t.status.warning,blue:n.function,magenta:n.keyword,cyan:n.type,white:n.foreground,brightBlack:n.comment,brightRed:t.status.error,brightGreen:t.status.success,brightYellow:t.status.warning,brightBlue:n.function,brightMagenta:n.keyword,brightCyan:n.type,brightWhite:t.surface.elevatedForeground}}function Zr(e,t,n){const o=`${e}, "JetBrainsMonoNL Nerd Font", "FiraCode Nerd Font", "Cascadia Code PL", "Fira Code", "JetBrains Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", "Courier New", monospace`;return{cursorBlink:!1,cursorStyle:"bar",cursorInactiveStyle:"none",fontSize:t,fontFamily:o,allowTransparency:!1,convertEol:!0,scrollback:1e4,theme:{background:n.background,foreground:n.foreground,cursor:n.cursor,cursorAccent:n.cursorAccent,selectionBackground:n.selectionBackground,selectionForeground:n.selectionForeground,selectionInactiveBackground:n.selectionInactiveBackground,black:n.black,red:n.red,green:n.green,yellow:n.yellow,blue:n.blue,magenta:n.magenta,cyan:n.cyan,white:n.white,brightBlack:n.brightBlack,brightRed:n.brightRed,brightGreen:n.brightGreen,brightYellow:n.brightYellow,brightBlue:n.brightBlue,brightMagenta:n.brightMagenta,brightCyan:n.brightCyan,brightWhite:n.brightWhite}}}const Wg=(e,t)=>{const n=`${e??""} ${t??""}`;return/mac|iphone|ipad|darwin/i.test(n)?"mac":"other"},Gg=e=>e.key.length===1?e.key.toLowerCase():e.code==="KeyC"?"c":e.code==="KeyV"?"v":e.code==="Insert"?"insert":e.key.toLowerCase(),Hg=(e,t,n)=>{if(e.altKey)return null;const r=Gg(e);return t==="mac"?!e.metaKey||e.ctrlKey?null:r==="c"&&!e.shiftKey?n?"copy":"ignore":null:e.metaKey?null:e.ctrlKey&&!e.shiftKey&&r==="insert"?n?"copy":"ignore":!e.ctrlKey||!e.shiftKey?null:r==="c"?n?"copy":"ignore":null},An=e=>typeof e=="string"&&e.trim().length>0;async function ma(e){return An(e)?(await ws(e)).ok:!1}async function qg(){if(typeof navigator>"u"||!navigator.clipboard?.readText)return null;try{return await navigator.clipboard.readText()||null}catch{return null}}const Yg=(e,t,n,r,o)=>{if(n.width<=0||n.height<=0||r<=0||o<=0)return null;const i=Math.floor((e-n.left)/n.width*r),l=Math.floor((t-n.top)/n.height*o);return{column:Math.max(0,Math.min(r-1,i)),row:Math.max(0,Math.min(o-1,l))}},Vg=(e,t)=>{const n=Math.max(0,Math.min(e.length-1,t)),r=l=>!!(l&&!/^\s+$/u.test(l));if(!r(e[n]))return{startColumn:n,endColumn:n};let o=n,i=n;for(;o>0&&r(e[o-1]);)o-=1;for(;i<e.length-1&&r(e[i+1]);)i+=1;return{startColumn:o,endColumn:i}};let Qg=null;const Jg=()=>Qg??=Promise.all([ft(()=>import("./vendor-xterm-xterm-B-qIQCd3.js"),[]),ft(()=>import("./vendor-xterm-addon-fit-DX4qG4td.js"),[])]).then(([e,t])=>({Xterm:e,Fit:t})),Xg=2e3,Zg=()=>{if(typeof window>"u")return Promise.resolve();const e=window.__pichamberEnsureNerdFonts;return typeof e!="function"?Promise.resolve():Promise.race([Promise.resolve(e()).catch(()=>{}),new Promise(t=>setTimeout(t,Xg))]).then(()=>{})},eb=(e,t,n)=>{if(typeof window>"u"||typeof document>"u")return null;const r=document.createElement("canvas").getContext("2d");if(!r||e.clientWidth<24||e.clientHeight<24)return null;r.font=`${n}px ${t}`;const o=r.measureText("M"),i=Math.ceil(o.width),l=Math.ceil((o.actualBoundingBoxAscent||n*.8)+(o.actualBoundingBoxDescent||n*.2))+2;if(i<1||l<1)return null;const c=window.getComputedStyle(e),d=(Number.parseInt(c.paddingLeft,10)||0)+(Number.parseInt(c.paddingRight,10)||0),u=(Number.parseInt(c.paddingTop,10)||0)+(Number.parseInt(c.paddingBottom,10)||0);return{cols:Math.max(2,Math.floor((e.clientWidth-d-15)/i)),rows:Math.max(1,Math.floor((e.clientHeight-u)/l))}},lc=a.forwardRef(({sessionKey:e,chunks:t,onInput:n,onResize:r,theme:o,fontFamily:i,fontSize:l,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:f=!0},p)=>{const x=a.useRef(null),y=a.useRef(null),m=a.useRef(null),h=a.useRef(n),b=a.useRef(r),g=a.useRef(o),S=a.useRef(i),v=a.useRef(l),E=a.useRef(null),k=a.useRef(null),C=a.useRef(null),j=a.useRef(""),w=a.useRef(!1),N=a.useRef(0),M=a.useRef(f),F=a.useRef(!1),[$,U]=a.useState(0),[K,L]=a.useState(0),[D,R]=a.useState(!1),[I,T]=a.useState(!1);h.current=n,b.current=r,M.current=f,g.current=o,S.current=i,v.current=l,a.useLayoutEffect(()=>{const H=x.current;if(!H)return;const z=eb(H,i,l);k.current=z,z&&b.current(z.cols,z.rows)},[i,l]);const W=a.useCallback(()=>{const H=x.current,z=y.current;if(!H||!z||!m.current||!M.current)return;const Q=H.getBoundingClientRect();if(!(Q.width<24||Q.height<24))try{m.current.fit();const X={cols:z.cols,rows:z.rows};(!E.current||E.current.cols!==X.cols||E.current.rows!==X.rows)&&(E.current=X,b.current(X.cols,X.rows)),F.current||(F.current=!0,U(ne=>ne+1))}catch{}},[]),G=a.useCallback(()=>{if(w.current||!j.current||!y.current)return;const H=y.current,z=j.current;if(j.current="",!z)return;w.current=!0;const Q=N.current;H.write(z,()=>{y.current!==H||N.current!==Q||(w.current=!1,j.current&&G())})},[]),B=a.useCallback(()=>{C.current=null,j.current="",w.current=!1,N.current+=1;const H=y.current;if(!H){L(z=>z+1);return}try{H.reset()}catch{L(z=>z+1)}},[]),be=a.useCallback(H=>{H?.preventDefault(),T(An(y.current?.getSelection())),R(!0)},[]),V=a.useCallback(H=>{H.stopPropagation();const z=y.current,Q=z?.getSelection()??"";z?.focus(),An(Q)&&ma(Q)},[]),Ce=a.useCallback(H=>{H.stopPropagation();const z=y.current;z?.focus(),qg().then(Q=>{Q&&y.current===z&&z&&z.paste(Q)})},[]),De=a.useCallback(H=>{H.stopPropagation();const z=y.current;z?.focus();try{z?.selectAll()}catch{}T(An(z?.getSelection()))},[]);return a.useEffect(()=>{const H=x.current;if(!H)return;let z=!1,Q=null,X=null,ne=null,we=null,me=[];const q=()=>{Q&&M.current&&(Q.options.cursorBlink=!0)},te=Se=>{Se.relatedTarget instanceof Node&&H.contains(Se.relatedTarget)||Q&&(Q.options.cursorBlink=!1)},le=()=>{Q&&M.current&&H.contains(document.activeElement)&&(Q.options.cursorBlink=!0)},Ae=()=>{Q&&(Q.options.cursorBlink=!1)};return H.addEventListener("focusin",q),H.addEventListener("focusout",te),window.addEventListener("focus",le),window.addEventListener("blur",Ae),Promise.all([Jg(),Zg()]).then(([{Xterm:Se,Fit:Ge}])=>{if(z)return;const Y=g.current,ce=S.current,re=v.current;Q=new Se.Terminal({...Zr(ce,re,Y),...k.current??{}});const ue=new Ge.FitAddon;Q.loadAddon(ue),Q.open(H),y.current=Q,m.current=ue;const ve=typeof navigator>"u"?"other":Wg(navigator.userAgentData?.platform??navigator.platform??"",navigator.userAgent??""),Le=Q;Q.attachCustomKeyEventHandler(xe=>{if(xe.type!=="keydown")return!0;const se=Le.getSelection(),pe=Hg({key:xe.key,code:xe.code,ctrlKey:xe.ctrlKey,shiftKey:xe.shiftKey,metaKey:xe.metaKey,altKey:xe.altKey},ve,An(se));return pe==="copy"?(ma(se),!1):pe!=="ignore"}),me=[Q.onData(xe=>h.current(xe))],X=new ResizeObserver(()=>{ne&&clearTimeout(ne),ne=setTimeout(W,80)}),X.observe(H),W(),we=requestAnimationFrame(W)}),()=>{z=!0;const Se=document.activeElement;Se instanceof HTMLElement&&H.contains(Se)&&(Se.blur(),window.Capacitor?.getPlatform?.()==="android"&&ft(async()=>{const{Keyboard:Y}=await import("./vendor-capacitor-keyboard-9BVxykO7.js");return{Keyboard:Y}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:Y})=>Y.hide()).catch(()=>{})),X?.disconnect(),ne&&clearTimeout(ne),we!==null&&cancelAnimationFrame(we),H.removeEventListener("focusin",q),H.removeEventListener("focusout",te),window.removeEventListener("focus",le),window.removeEventListener("blur",Ae),me.forEach(Ge=>Ge.dispose()),Q?.dispose(),y.current=null,m.current=null,E.current=null,C.current=null,j.current="",w.current=!1,N.current+=1,F.current=!1}},[W,K]),a.useEffect(()=>{const H=y.current;H&&(H.options.theme=Zr(i,l,o).theme,H.options.fontFamily=Zr(i,l,o).fontFamily,H.options.fontSize=l)},[i,l,o]),a.useEffect(()=>{const H=y.current,z=x.current;!H||!z||(H.options.cursorBlink=f&&document.hasFocus()&&z.contains(document.activeElement))},[f,$]),a.useEffect(()=>{if(!y.current)return;if(t.length===0){C.current!==null&&B();return}const z=C.current;let Q=-1;if(z!==null){for(let we=t.length-1;we>=0;we-=1){const me=t[we].id;if(me===z){Q=we;break}if(me<z)break}if(Q<0){B();return}}const X=Q<0,ne=Q>=0?t.slice(Q+1):t;j.current+=ne.map(we=>X?we.replayData??we.data:we.data).join(""),C.current=t.at(-1)?.id??null,G()},[t,G,$,B]),a.useEffect(()=>{if(!u||!f)return;const H=requestAnimationFrame(()=>y.current?.focus());return()=>cancelAnimationFrame(H)},[u,f,$,e]),a.useEffect(()=>{const H=x.current,z=y.current;if(!d||!H||!z)return;let Q=null,X=null,ne="idle",we=0,me=0,q=0,te=0,le=null;const Ae=Math.max(12,l+2),Se=()=>{window.Capacitor?.getPlatform?.()==="android"&&ft(async()=>{const{Keyboard:pe}=await import("./vendor-capacitor-keyboard-9BVxykO7.js");return{Keyboard:pe}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:pe})=>pe.show()).catch(()=>{})},Ge=()=>{X&&(clearTimeout(X),X=null)},Y=(se,pe)=>{const fe=H.querySelector("canvas");return fe?Yg(se,pe,fe.getBoundingClientRect(),z.cols,z.rows):null},ce=(se,pe)=>{const fe=H.querySelector("canvas");if(!fe)return;const je=fe.getBoundingClientRect(),He=je.left+(pe.column+.5)/z.cols*je.width,We=je.top+(pe.row+.5)/z.rows*je.height;fe.dispatchEvent(new MouseEvent(se,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:He,clientY:We}))},re=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},ue=se=>{se.pointerType!=="touch"||Q!==null||(Q=se.pointerId,ne="pending",we=se.clientX,me=se.clientY,q=se.clientY,te=0,le=null,H.setPointerCapture(se.pointerId),X=setTimeout(()=>{if(X=null,Q!==se.pointerId||ne!=="pending")return;const pe=Y(we,me);if(!pe)return;const fe=z.buffer.active,je=Math.max(0,fe.length-z.rows-fe.viewportY+pe.row),He=fe.getLine(je),We=Array.from({length:z.cols},(oe,Fe)=>He?.getCell(Fe)?.getChars()??""),Ie=Vg(We,pe.column),Ye={column:Ie.startColumn,row:pe.row};le={column:Ie.endColumn,row:pe.row},ne="selecting",ce("mousedown",Ye),ce("mousemove",le)},350))},ve=se=>{if(Q!==se.pointerId)return;if(ne==="selecting"){const je=Y(se.clientX,se.clientY);je&&(!le||je.column!==le.column||je.row!==le.row)&&(le=je,ce("mousemove",je)),se.cancelable&&se.preventDefault();return}if(ne==="pending"){if(Math.hypot(se.clientX-we,se.clientY-me)<8)return;Ge(),ne="scrolling"}if(ne!=="scrolling")return;const pe=q-se.clientY;q=se.clientY,te+=pe;const fe=Math.trunc(te/Ae);fe&&(z.scrollLines(fe),te-=fe*Ae),se.cancelable&&se.preventDefault()},Le=se=>{if(Q!==se.pointerId)return;const pe=ne==="pending",fe=ne==="selecting";Ge(),H.hasPointerCapture(se.pointerId)&&H.releasePointerCapture(se.pointerId),Q=null,ne="idle",fe&&re(),pe&&(z.focus(),Se())},xe=se=>{if(Q!==se.pointerId)return;const pe=ne==="selecting";Ge(),H.hasPointerCapture(se.pointerId)&&H.releasePointerCapture(se.pointerId),Q=null,ne="idle",pe&&re()};return H.addEventListener("pointerdown",ue),H.addEventListener("pointermove",ve,{passive:!1}),H.addEventListener("pointerup",Le),H.addEventListener("pointercancel",xe),()=>{Ge(),H.removeEventListener("pointerdown",ue),H.removeEventListener("pointermove",ve),H.removeEventListener("pointerup",Le),H.removeEventListener("pointercancel",xe)}},[d,l,$]),a.useImperativeHandle(p,()=>({focus:()=>y.current?.focus(),fit:W,getSelection:()=>{const H=y.current,z=H?.getSelectionPosition(),Q=H?.getSelection()??"";return!z||!Q.trim()?null:{text:Q,startLine:z.start.y+1,endLine:z.end.y+1}}}),[W]),s.jsxs(kr,{open:D,onOpenChange:R,children:[s.jsx(Ar,{render:s.jsx("div",{ref:x,"data-terminal-owner":"main",className:_("terminal-viewport-container h-full w-full overflow-hidden touch-none",c),onContextMenu:be})}),s.jsxs(Nr,{className:"min-w-[180px]",children:[s.jsxs(Ps,{disabled:!I,onClick:V,children:[s.jsx(P,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy"]}),s.jsxs(Ps,{onClick:Ce,children:[s.jsx(P,{name:"clipboard",className:"mr-2 h-4 w-4"})," ","Paste"]}),s.jsx(Jl,{}),s.jsx(Ps,{onClick:De,children:"Select All"})]})]})});lc.displayName="TerminalViewport";const tb=({directory:e,tabId:t,sessionId:n,sessionKey:r,isActive:o,isTerminalVisible:i,terminal:l,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,lastViewportSizeRef:p,onInput:x,controllerRef:y})=>{const m=he(v=>e&&t?v.getBuffer(e,t).chunks:ar.chunks),h=a.useRef(null),b=o&&i,g=a.useCallback(v=>{h.current=v,y&&(y.current=o?v:y.current),!o&&y&&y.current===v&&(y.current=null)},[y,o]);a.useEffect(()=>{if(!o||!i)return;const v=requestAnimationFrame(()=>{h.current?.fit()});return()=>cancelAnimationFrame(v)},[o,i,r,n]);const S=a.useCallback((v,E)=>{if(!o)return;const k=p.current;(!k||k.cols!==v||k.rows!==E)&&(p.current={cols:v,rows:E}),n&&l.resize({sessionId:n,cols:v,rows:E}).catch(()=>{})},[o,p,n,l]);return s.jsx("div",{className:_("h-full w-full",o?"block":"hidden"),"aria-hidden":!o,children:s.jsx(lc,{ref:g,sessionKey:r,chunks:m,onInput:x,onResize:S,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,autoFocus:b,isVisible:b},r)})},pa=({items:e,activeId:t,onSelect:n,onClose:r,onCreate:o,disabled:i=!1})=>{const l=e.find(c=>c.id===t)??e[0]??null;return s.jsxs(Wt,{modal:!1,children:[s.jsx(Gt,{asChild:!0,children:s.jsxs(Ne,{type:"button",variant:"ghost",size:"sm",disabled:i,title:l?`Switch terminal, current: ${l.label}`:"Switch terminal","aria-label":l?`Switch terminal, current: ${l.label}`:"Switch terminal",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1 normal-case",children:[l?.icon??s.jsx(P,{name:"terminal",className:"size-4 shrink-0"}),s.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:l?.label??"Terminal"}),s.jsx(P,{name:"arrow-down-s",className:"size-4 shrink-0 opacity-60"})]})}),s.jsxs(Ht,{align:"start",className:"w-64",children:[e.map(c=>{const d=c.id===(l?.id??t);return s.jsxs(ut,{title:c.title??c.label,onClick:()=>n(c.id),className:"group/tab min-w-0",children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[c.icon,s.jsx("span",{className:"min-w-0 flex-1 truncate",children:c.label})]}),d?s.jsx(P,{name:"check",className:"size-3.5 shrink-0 text-primary"}):null,s.jsx("button",{type:"button",title:c.closeLabel,"aria-label":c.closeLabel,onClick:u=>{u.preventDefault(),u.stopPropagation(),r(c.id)},className:"flex size-5 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-interactive-hover hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none group-hover/tab:opacity-100",children:s.jsx(P,{name:"close",className:"size-3"})})]},c.id)}),s.jsx(nn,{}),s.jsxs(ut,{onClick:o,children:[s.jsx(P,{name:"add",className:"size-3.5"}),"New tab"]})]})]})},sb=({leading:e,icon:t,title:n,actions:r,className:o})=>s.jsxs("header",{className:_("flex h-11 shrink-0 items-center gap-1 border-b border-border bg-background pl-3 pr-2",o),children:[e,n!=null?typeof n=="string"?s.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[typeof t=="string"?s.jsx(P,{name:t,className:"size-4 shrink-0 text-muted-foreground","aria-hidden":"true"}):t??null,s.jsx("h2",{className:"truncate typography-ui-label font-medium text-foreground",children:n})]}):s.jsx("div",{className:"min-w-0 flex-1",children:n}):null,r?s.jsx("div",{className:"flex shrink-0 items-center gap-1",children:r}):null]}),nb=({isTouchTerminal:e,activeModifier:t,disabled:n,onKeyPress:r,onModifierToggle:o})=>{const i=e?"lg":"xs",l=e?"w-10 p-0":"w-9 p-0",c=d=>{e&&d.preventDefault()};return s.jsxs(s.Fragment,{children:[s.jsx(Ne,{type:"button",size:i,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:n,children:"Esc"}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("tab"),disabled:n,children:[s.jsx(P,{name:"arrow-right",className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Tab"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"chip","aria-pressed":t==="ctrl",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("ctrl"),disabled:n,children:[s.jsx("span",{className:"text-xs font-medium",children:"Ctrl"}),s.jsx("span",{className:"sr-only",children:"Control modifier"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"chip","aria-pressed":t==="alt",className:e?"px-3":"px-2",onPointerDown:c,onClick:()=>o("alt"),disabled:n,children:[s.jsx("span",{className:"text-xs font-medium",children:"Alt"}),s.jsx("span",{className:"sr-only",children:"Alt modifier"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:n,children:[s.jsx(P,{name:"arrow-up"}),s.jsx("span",{className:"sr-only",children:"Arrow up"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:n,children:[s.jsx(P,{name:"arrow-left"}),s.jsx("span",{className:"sr-only",children:"Arrow left"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:n,children:[s.jsx(P,{name:"arrow-down"}),s.jsx("span",{className:"sr-only",children:"Arrow down"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:n,children:[s.jsx(P,{name:"arrow-right"}),s.jsx("span",{className:"sr-only",children:"Arrow right"})]}),s.jsxs(Ne,{type:"button",size:i,variant:"outline",className:l,onPointerDown:c,onClick:()=>r("enter"),disabled:n,children:[s.jsx(P,{name:"arrow-go-back"}),s.jsx("span",{className:"sr-only",children:"Enter"})]})]})},rb="\x1B",ob=new RegExp(`${rb}\\[[0-9;?]*[ -/]*[@-~]`,"g"),ib=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,ab=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,lb=/Serving HTTP on .*? port (\d{2,5})/i,cb=new Set([".",",",";",":","!","?"]),db=e=>{let t=e;for(;t.length>0;){const n=t[t.length-1];if(n===")"||n==="]"||n==="}"||n===">"){const r=n===")"?"(":n==="]"?"[":n==="}"?"{":"<",o=t.slice(0,-1),i=(o.match(new RegExp(`\\${r}`,"g"))||[]).length,l=(o.match(new RegExp(`\\${n}`,"g"))||[]).length;if(i>l)break;t=o;continue}if(cb.has(n)){t=t.slice(0,-1);continue}break}return t},ga=e=>{let t=db(e);return t=t.replace("0.0.0.0","127.0.0.1"),t=t.replace("[::1]","127.0.0.1"),t=t.replace("[::]","127.0.0.1"),t},ub=e=>{if(!e)return null;const t=e.replace(ob,""),n=t.match(lb);if(n?.[1]){const o=Number.parseInt(n[1],10);if(Number.isFinite(o)&&o>0&&o<=65535)return`http://127.0.0.1:${o}/`}const r=t.split(`
55
+ `);for(const o of r){if(!ab.test(o))continue;const i=Array.from(o.matchAll(ib));if(i.length===0)continue;const l=i.find(c=>{try{return!!new URL(ga(c[1])).port}catch{return!1}});return ga((l??i[0])[1])}return null},fb=async(e,t=1500)=>{if(!e||typeof window>"u")return!1;let n;try{n=new URL(e)}catch{return!1}if(n.protocol!=="http:"&&n.protocol!=="https:")return!1;const r=n.hostname.toLowerCase();if(r!=="localhost"&&r!=="127.0.0.1"&&r!=="0.0.0.0"&&r!=="::1"&&r!=="::")return!1;const o=new AbortController,i=window.setTimeout(()=>o.abort(),t);try{const l=await Mt("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:o.signal});return l.ok?(await l.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(i)}},hb={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},mb=(e,t)=>{if(t&&e.startsWith("arrow-")){const n=t==="ctrl"?"5":"3",r={"arrow-up":"A","arrow-down":"B","arrow-right":"C","arrow-left":"D"}[e];return`\x1B[1;${n}${r}`}return hb[e]},cc=e=>{const t=e[0]?.toUpperCase();return!t||t<"A"||t>"Z"?null:String.fromCharCode(t.charCodeAt(0)&31)},pb=(e,t)=>e&&(t==="ctrl"?cc(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),dc={cols:80,rows:24},ba={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class gb{tail="";pendingUrls=new Set;probeGeneration=0;reset(){this.tail="",this.pendingUrls.clear(),this.probeGeneration+=1}scan(t,n,r,o){if(!r)return;const i=`${this.tail}${r}`.replace(/\r\n|\r/g,`
56
+ `),l=i.split(`
57
+ `),c=i.endsWith(`
58
+ `)?l.join(`
59
+ `):l.slice(0,-1).join(`
60
+ `);if(this.tail=i.endsWith(`
61
+ `)?"":(l[l.length-1]??"").slice(-1024),!c)return;const d=ub(c);if(!d||this.pendingUrls.has(d))return;const u=this.probeGeneration;this.pendingUrls.add(d),fb(d).then(f=>{if(this.pendingUrls.delete(d),!f||this.probeGeneration!==u)return;const p=he.getState().getDirectoryState(t)?.tabs.find(x=>x.id===n);!p||p.previewUrlLocked||p.previewUrl===d||o(t,n,d,{locked:!1,autoOpened:!1})})}}const bb=(e,t)=>{if(t!=="ctrl")return null;const n=e.key,r=e.code??"",o=n.length===1&&/[a-zA-Z]/.test(n)?n.toUpperCase():r.startsWith("Key")&&r.length===4?r.slice(3).toUpperCase():null;return o&&o.length===1&&o>="A"&&o<="Z"?cc(o):null};function xb({terminal:e,effectiveDirectory:t,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:i,terminalHydrated:l,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:u,enableTabs:f,hasActiveContext:p,focusTerminalWhenWindowActive:x,tabs:y}){const m=he(z=>z.ensureDirectory),h=he(z=>z.setTabSessionId),b=he(z=>z.setTabLifecycle),g=he(z=>z.setConnecting),S=he(z=>z.appendToBuffer),v=he(z=>z.replaceBuffer),E=he(z=>z.setTabPreviewUrl),[k,C]=a.useState(null),[j,w]=a.useState(!1),[N,M]=a.useState(!1),F=a.useRef(new Map),$=a.useRef(null),U=a.useRef(n),K=a.useRef(r),L=a.useRef(t),D=a.useRef(null),R=a.useRef(new Set),I=a.useRef(new Map),T=a.useRef(y),W=a.useRef(l),G=a.useRef(i),B=a.useRef(e);T.current=y,W.current=l,G.current=i,B.current=e;const be=a.useCallback(()=>{const z=U.current;z&&I.current.get(z)?.reset()},[]);a.useEffect(()=>{K.current=r},[r]),a.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,u.current).catch(()=>{})},[u,e,r]),a.useEffect(()=>{U.current=n},[n]),a.useEffect(()=>{L.current=t},[t]);const V=a.useCallback(()=>{for(const z of F.current.values())try{z()}catch{}F.current.clear(),$.current=null,M(!1)},[]);a.useEffect(()=>()=>{V(),K.current=null},[V]);const Ce=a.useCallback((z,Q,X)=>{let ne=I.current.get(Q);ne||(ne=new gb,I.current.set(Q,ne)),ne.scan(z,Q,X,E)},[E]),De=a.useCallback((z,Q,X)=>{if(F.current.has(X)){$.current=X;return}const ne=Ii(),we=()=>Ii()===ne&&L.current===z&&he.getState().getDirectoryState(z)?.tabs.find(q=>q.id===Q)?.terminalSessionId===X,me=e.connect(X,{onEvent:q=>{if(we())switch(q.type){case"snapshot":{U.current===Q&&K.current===X?(g(z,Q,!1),C(null),w(!1),M(!1),x()):g(z,Q,!1),v(z,Q,q.data??"",q.sequence??0),Ce(z,Q,q.data??""),q.status==="exited"&&b(z,Q,"exited");break}case"reconnecting":{U.current===Q&&(C(null),w(!1),M(!0));break}case"data":{q.data&&(S(z,Q,q.data,q.sequence,q.replayData),Ce(z,Q,q.data));break}case"exit":{const te=typeof q.exitCode=="number"?q.exitCode:null,le=typeof q.signal=="number"?q.signal:null,Se=!!he.getState().getDirectoryState(z)?.tabs.find(Ge=>Ge.id===Q)?.label?.startsWith("Action:");S(z,Q,`\\r\\n[Process exited${te!==null?` with code ${te}`:""}${le!==null?` (signal ${le})`:""}]\\r\\n`),b(z,Q,"exited"),U.current===Q&&(g(z,Q,!1),C(Se?null:"Terminal session ended"),w(!1),M(!1));break}}},onError:(q,te)=>{if(!we())return;const le=U.current===Q;if(!te){le&&(C(null),w(!1));return}if(q.code==="SESSION_NOT_FOUND"&&!he.getState().getDirectoryState(z)?.tabs.find(Se=>Se.id===Q)?.label?.startsWith("Action:")){le&&(C(null),w(!1),g(z,Q,!1),M(!1)),h(z,Q,null),b(z,Q,"idle");return}le&&(M(!1),C(`Connection failed: ${q.message}`),w(!0),g(z,Q,!1),b(z,Q,"exited"),h(z,Q,null))}});F.current.set(X,()=>me.close()),$.current=X},[S,x,v,Ce,g,b,h,e]),H=a.useMemo(()=>y.map(z=>`${z.id}:${z.terminalSessionId??""}`).join(","),[y]);return a.useEffect(()=>{if(!l||!i||!t)return;const z=t,Q=new Set;for(const X of y)X.terminalSessionId&&(Q.add(X.terminalSessionId),De(z,X.id,X.terminalSessionId));for(const[X,ne]of F.current)if(!Q.has(X)){try{ne()}catch{}F.current.delete(X)}},[H,y,t,l,i,De]),a.useEffect(()=>rf(()=>{if(!W.current||!G.current)return;const z=L.current;if(!z)return;const Q=[];for(const ne of T.current){if(!ne.terminalSessionId)continue;he.getState().getDirectoryState(z)?.tabs.find(me=>me.id===ne.id)?.terminalSessionId===ne.terminalSessionId&&Q.push({id:ne.id,terminalSessionId:ne.terminalSessionId})}if(F.current.clear(),$.current=null,Q.length===0)return;M(!0),C(null),w(!1);for(const ne of Q)De(z,ne.id,ne.terminalSessionId);const X=D.current;if(X)for(const ne of Q)B.current.resize({sessionId:ne.terminalSessionId,...X}).catch(()=>{})}),[De]),a.useEffect(()=>{let z=!1;if(!l||!i)return;if(!t){C(p?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const X=t;if(!L.current||L.current!==X)return;if(!he.getState().getDirectoryState(X)){m(X);return}const we=he.getState().getDirectoryState(X);if(!we||we.tabs.length===0)return;const me=we.activeTabId??we.tabs[0]?.id??null;if(!me)return;const q=we.tabs.find(Y=>Y.id===me)??we.tabs[0],te=q?.terminalSessionId??null,le=q?.lifecycle??"idle",Ae=!!q?.label?.startsWith("Action:"),Se=he.getState().getBuffer(X,me),Ge=Se.byteLength>0||Se.chunks.length>0;if(!te){if(le==="exited"){g(X,me,!1);return}if(Ae&&Ge){g(X,me,!1);return}const Y=`${X}\0${me}`;if(R.current.has(Y))return;const ce=D.current??dc;R.current.add(Y),C(null),w(!1),M(!1),g(X,me,!0);try{const re=await e.createSession({cwd:X,sessionId:me,cols:ce.cols,rows:ce.rows,shell:c,loginShell:d,...u.current});if(!he.getState().getDirectoryState(X)?.tabs.find(Le=>Le.id===me)){try{await e.close(re.sessionId)}catch{}return}h(X,me,re.sessionId);const ve=D.current;ve&&(ve.cols!==ce.cols||ve.rows!==ce.rows)&&e.resize({sessionId:re.sessionId,...ve}).catch(()=>{});return}catch(re){const ue=he.getState().getDirectoryState(X)?.tabs.find(ve=>ve.id===me);if(!ue||ue.terminalSessionId||(g(X,me,!1),L.current!==X||U.current!==me))return;C(re instanceof Error?re.message:"Failed to start terminal session"),w(!0),M(!1);return}finally{R.current.delete(Y)}}!te||z||(K.current=te)})(),()=>{z=!0}},[p,t,r,o,n,i,f,l,m,g,b,h,e,d,c,u]),{connectionError:k,setConnectionError:C,isFatalError:j,setIsFatalError:w,isReconnectPending:N,setIsReconnectPending:M,terminalIdRef:K,lastViewportSizeRef:D,directoryRef:L,activeTabIdRef:U,disconnectStream:V,resetTerminalPreviewScan:be,startStream:De}}function yb({terminal:e,terminalIdRef:t,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:i,lastViewportSizeRef:l,terminalSessionId:c,useTouchTerminalInput:d}){const[u,f]=a.useState(null),p=a.useRef(null),x=a.useCallback(()=>{d||p.current?.focus()},[d]),y=a.useCallback(()=>{d||typeof document<"u"&&!document.hasFocus()||p.current?.focus()},[d]);a.useEffect(()=>{!o&&u!==null&&f(null)},[o,u]),a.useEffect(()=>{!c&&u!==null&&f(null)},[c,u]);const m=a.useCallback(v=>{if(!v||n)return;let E=v,k=!1;u&&v.length>0&&(E=pb(v,u),k=!0);const C=t.current;C&&(e.sendInput(C,E).catch(j=>{n||r(j instanceof Error?j.message:"Failed to send input")}),k&&(f(null),x()))},[u,x,n,r,e,t]),h=a.useCallback((v,E)=>{const k=l.current;if((!k||k.cols!==v||k.rows!==E)&&(l.current={cols:v,rows:E}),!i)return;const C=t.current;C&&e.resize({sessionId:C,cols:v,rows:E}).catch(()=>{})},[i,l,e,t]),b=a.useCallback(v=>{f(E=>E===v?null:v),x()},[x]),g=a.useCallback(v=>{const E=mb(v,u);E&&(m(E),f(null),x())},[u,x,m]),S=a.useCallback(v=>{if(v.repeat)return;const E=v.key;if(!E||E==="Control"||E==="Meta"||E==="Alt"||E==="Shift")return;const k=E.length===1?E.toLowerCase():E;if(k in ba){v.preventDefault(),v.stopPropagation(),g(ba[k]);return}const C=bb(v,u);C&&(v.preventDefault(),v.stopPropagation(),m(C),f(null),x())},[u,x,g,m]);return a.useEffect(()=>{if(!(!o||!u||!c))return window.addEventListener("keydown",S),()=>window.removeEventListener("keydown",S)},[u,S,o,c]),{activeModifier:u,setActiveModifier:f,terminalControllerRef:p,focusTerminalController:x,focusTerminalWhenWindowActive:y,handleViewportInput:m,handleViewportResize:h,handleModifierToggle:b,handleMobileKeyPress:g}}function wb({terminal:e,effectiveDirectory:t,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:i,terminalAppearanceRef:l,lastViewportSizeRef:c,directoryRef:d,activeTabIdRef:u,terminalIdRef:f,resetTerminalPreviewScan:p,startStream:x,setConnectionError:y,setIsFatalError:m,setIsReconnectPending:h}){const b=he($=>$.createTab),g=he($=>$.setActiveTab),S=he($=>$.closeTab),v=he($=>$.setTabSessionId),E=he($=>$.setTabLifecycle),[k,C]=a.useState(!1),j=a.useCallback(async()=>{if(!t||k)return;const $=he.getState().getDirectoryState(t),U=n??$?.activeTabId??$?.tabs[0]?.id??null;if(!U)return;const K=$?.tabs.find(L=>L.id===U)?.terminalSessionId??null;if(!(!K||!e.restartSession)){C(!0),y(null),m(!1),h(!1),p();try{const L=c.current??dc,D=await e.restartSession(K,{cwd:t,shell:o,loginShell:i,...L,...l.current});if(he.getState().getDirectoryState(t)?.tabs.find(I=>I.id===U)?.terminalSessionId!==K||(v(t,U,D.sessionId),E(t,U,"running"),d.current!==t||u.current!==U))return;f.current=D.sessionId,x(t,U,D.sessionId)}catch(L){if(he.getState().getDirectoryState(t)?.tabs.find(R=>R.id===U)?.terminalSessionId!==K||d.current!==t||u.current!==U)return;y(L instanceof Error?L.message:"Failed to restart terminal"),m(!1),h(!1),f.current=K,x(t,U,K)}finally{C(!1)}}},[n,u,d,t,r,k,c,p,y,m,h,E,v,x,e,l,f,i,o]),w=a.useCallback(async()=>{await j()},[j]),N=a.useCallback(()=>{if(!t)return;const $=b(t);g(t,$),y(null),m(!1),h(!1)},[b,t,g,y,m,h]),M=a.useCallback($=>{t&&(g(t,$),y(null),m(!1),h(!1))},[t,g,y,m,h]),F=a.useCallback($=>{if(!t)return;y(null),m(!1),h(!1);const U=he.getState().getDirectoryState(t)?.tabs.find(K=>K.id===$)?.terminalSessionId;(async()=>{U&&await e.close(U),S(t,$)})().catch(K=>y(K instanceof Error?K.message:"Terminal session ended"))},[S,t,y,m,h,e]);return{isRestarting:k,handleRestart:j,handleHardRestart:w,handleCreateTab:N,handleSelectTab:M,handleCloseTab:F}}const py=({visible:e,onCloseView:t,terminalHeaderSlot:n})=>{const{terminal:r,runtime:o}=Os(),{currentTheme:i}=Qa(),l=a.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});l.current={themeMode:i.metadata.variant==="light"?"light":"dark",terminalBackground:i.colors.surface.background,terminalForeground:i.colors.syntax.base.foreground};const{monoFont:c}=Iu(),d=de(oe=>oe.terminalFontSize),u=de(oe=>oe.terminalShell),f=de(oe=>oe.terminalLoginShells.includes(oe.terminalShell)),{isMobile:p,isTablet:x,hasTouchOnlyPointer:y}=dn(),m=p||x,h=(m||y)&&o.platform==="web",b=!0,g=de(oe=>oe.showTerminalQuickKeysOnDesktop),S=m||g,v=Te(oe=>oe.currentSessionId),E=Te(oe=>oe.newSessionDraft),k=v!==null||E?.open===!0,C=Eu()??null,j=he(oe=>C?oe.sessions.get(C):void 0),w=he(oe=>oe.hasHydrated),N=de(oe=>oe.openContextPreview),M=a.useMemo(()=>j?j.activeTabId??j.tabs[0]?.id??null:null,[j,b]),F=a.useMemo(()=>{if(j)return M?j.tabs.find(oe=>oe.id===M)??j.tabs[0]:j.tabs[0]},[j,M]),$=a.useMemo(()=>(j?.tabs??[]).map(oe=>({icon:(()=>{const Fe=oe.iconKey?Dn[oe.iconKey]??"terminal":"terminal";return s.jsx(P,{name:Fe,className:"h-4 w-4"})})(),id:oe.id,label:oe.label,title:oe.label,closeLabel:"Close tab"})),[j?.tabs]),U=F?.terminalSessionId??null,K=F?.lifecycle??"idle",L=a.useMemo(()=>(j?.tabs??[]).map(oe=>({id:oe.id,terminalSessionId:oe.terminalSessionId,label:oe.label})),[j?.tabs]),D=F?.isConnecting??!1,R=F?.previewUrl??null,T=de(oe=>oe.activeMainTab)==="terminal",W=e??T,[G,B]=a.useState(W);a.useEffect(()=>{W&&B(!0)},[W]);const{connectionError:be,setConnectionError:V,isFatalError:Ce,setIsFatalError:De,isReconnectPending:H,setIsReconnectPending:z,terminalIdRef:Q,lastViewportSizeRef:X,directoryRef:ne,activeTabIdRef:we,resetTerminalPreviewScan:me,startStream:q}=xb({terminal:r,effectiveDirectory:C,activeTabId:M,terminalSessionId:U,terminalLifecycle:K,hasOpenedTerminalViewport:G,terminalHydrated:w,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:l,enableTabs:b,hasActiveContext:k,tabs:L,focusTerminalWhenWindowActive:()=>{!h&&typeof document<"u"&&document.hasFocus()&&le.current?.focus()}}),{activeModifier:te,terminalControllerRef:le,focusTerminalWhenWindowActive:Ae,handleViewportInput:Se,handleModifierToggle:Ge,handleMobileKeyPress:Y}=yb({terminal:r,terminalIdRef:Q,isReconnectPending:H,setConnectionError:V,showQuickKeys:S,isTerminalVisible:W,lastViewportSizeRef:X,terminalSessionId:U,useTouchTerminalInput:h}),{isRestarting:ce,handleRestart:re,handleHardRestart:ue,handleCreateTab:ve,handleSelectTab:Le,handleCloseTab:xe}=wb({terminal:r,effectiveDirectory:C,activeTabId:M,enableTabs:b,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:l,lastViewportSizeRef:X,directoryRef:ne,activeTabIdRef:we,terminalIdRef:Q,resetTerminalPreviewScan:me,startStream:q,setConnectionError:V,setIsFatalError:De,setIsReconnectPending:z});a.useEffect(()=>{if(!W||h)return;if(typeof window>"u"){Ae();return}const oe=window.requestAnimationFrame(()=>{Ae()});return()=>{window.cancelAnimationFrame(oe)}},[M,Ae,W,h]);const se=a.useMemo(()=>{const oe=xn[Br].stack;if(typeof window>"u")return(xn[c]??xn[Br]).stack;const st=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return st&&st.trim().length>0?st.trim():(xn[c]??xn[Br]).stack??oe},[c]),pe=a.useMemo(()=>Kg(i),[i]),fe=`${C??"no-dir"}::${M??"no-tab"}`;if(a.useEffect(()=>{if(!W||h)return;const oe=le.current;if(!oe)return;const Fe=()=>{oe.fit()};if(typeof window<"u"){const st=window.requestAnimationFrame(()=>{Fe(),Ae()}),bt=[220,400].map(Qe=>window.setTimeout(Fe,Qe));return()=>{window.cancelAnimationFrame(st),bt.forEach(Qe=>window.clearTimeout(Qe))}}Fe()},[Ae,W,h,le,fe,U]),a.useEffect(()=>{if(!W||!h)return;let oe=null;const Fe=()=>{oe!==null&&window.cancelAnimationFrame(oe),oe=window.requestAnimationFrame(()=>{oe=null,le.current?.fit()})};return window.addEventListener("oc:keyboard-settled",Fe),()=>{window.removeEventListener("oc:keyboard-settled",Fe),oe!==null&&window.cancelAnimationFrame(oe)}},[W,le,fe,h]),!k)return s.jsx("div",{className:"flex h-full items-center justify-center p-4 text-center text-sm text-muted-foreground",children:"Select a session to open the terminal."});if(!C)return s.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 p-4 text-center text-sm text-muted-foreground",children:[s.jsx("p",{children:"No working directory available for this session."}),s.jsx("button",{onClick:re,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const je=!U||D||ce||H,He=G,We=j?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsx(pa,{items:$,activeId:M,onSelect:Le,onClose:xe,onCreate:ve})}),s.jsx(Ne,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 shrink-0 p-0",onClick:ve,title:"New tab","aria-label":"New tab",children:s.jsx(P,{name:"add",className:"h-4 w-4"})}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[s.jsx(Ne,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 p-0",onClick:()=>{re()},disabled:ce,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(P,{name:"restart",className:"h-4 w-4"})}),R?s.jsxs(Ne,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{C&&N(C,R)},title:"Open preview pane",children:[s.jsx(P,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,Ie=s.jsx(nb,{isTouchTerminal:m,activeModifier:te,disabled:je,onKeyPress:Y,onModifierToggle:Ge}),Ye=!n||m||S;return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[We&&n?Ud.createPortal(s.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:We}),n):null,m&&We&&!n&&j?s.jsx(sb,{leading:s.jsx("div",{className:"min-w-0 flex-1 -ml-2",children:s.jsx(pa,{items:$,activeId:M,onSelect:Le,onClose:xe,onCreate:ve})}),actions:s.jsxs(s.Fragment,{children:[s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:ve,title:"New tab","aria-label":"New tab",children:s.jsx(P,{name:"add",className:"size-4"})}),s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:()=>{re()},disabled:ce,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(P,{name:"restart",className:"size-4"})}),R?s.jsxs(Ne,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 gap-1 px-2",onClick:()=>{C&&N(C,R)},title:"Open preview pane",children:[s.jsx(P,{name:"global",className:"size-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null,t?s.jsx(Ne,{type:"button",variant:"ghost",size:"icon",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:s.jsx(P,{name:"close",className:"size-4"})}):null]})}):null,!m&&Ye?s.jsxs("div",{className:_("app-region-no-drag sticky top-0 z-20 shrink-0 bg-background text-xs","px-3 py-2"),children:[We&&!n?s.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[We,t?s.jsx(Ne,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:s.jsx(P,{name:"close",className:"h-4 w-4"})}):null]}):null,!m&&S&&b&&j?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:Ie}):null,!m&&S&&!j?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:Ie}):null]}):null,s.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:pe.background},children:[s.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:He&&C&&j?j.tabs.map(oe=>{const Fe=oe.id===M;return s.jsx(tb,{directory:C,tabId:oe.id,sessionId:oe.terminalSessionId,sessionKey:`${C}::${oe.id}`,isActive:Fe,isTerminalVisible:W,terminal:r,theme:pe,fontFamily:se,fontSize:d,enableTouchScroll:h,lastViewportSizeRef:X,onInput:Se,controllerRef:le},oe.id)}):null}),!H&&be&&s.jsxs("div",{className:"absolute inset-x-0 bottom-0 border-t border-[var(--status-error-border)] bg-[var(--status-error-background)] px-3 py-2 text-xs text-foreground flex items-center justify-between gap-2",children:[s.jsx("span",{children:be}),Ce&&m&&s.jsx(Ne,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:ue,disabled:ce,title:"Force kill and create fresh session",type:"button",children:"Hard Restart"})]})]}),m&&S?s.jsx("div",{className:"shrink-0 overflow-x-auto border-t border-border/40 bg-[var(--surface-background)] px-2 pt-1.5 pb-[max(0.375rem,calc(var(--oc-app-bottom-safe,0px)-var(--oc-keyboard-inset,0px)))] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden","data-no-drawer-swipe":"true",children:s.jsx("div",{className:"flex min-w-max items-center gap-1.5",children:Ie})}):null]})},Oo=[{id:"changes",label:"Changes",icon:"git-branch"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"pull-requests",label:"PRs",icon:"git-pull-request"},{id:"issues",label:"Issues",icon:"task"}],vb=new Set(Oo.map(e=>e.id)),Sb=e=>typeof e=="string"&&vb.has(e),gy=e=>Sb(e)?e:"changes",uc=e=>e==="pull-requests"||e==="issues",jb=e=>e?Oo:Oo.filter(t=>!uc(t.id)),by=(e,t)=>uc(e)?"changes":e,Cb=48,kb=96,gt=(e,...t)=>{try{e?.(...t)}catch{}},eo=(e,t)=>{if(typeof e=="function"){const n=e();return n>0?n:t}return typeof e=="number"&&e>0?e:t},xy=(e,t)=>{const n=a.useRef(t);n.current=t;const r=t.enabled;a.useEffect(()=>{const o=e.current;if(!o||r===!1)return;const i=o.style.touchAction;o.style.touchAction="pan-x pan-y";const c=window.Capacitor?.getPlatform?.()==="android"?kb:Cb;let d=!1,u=!1,f=!1,p=null,x=!1,y=0,m=0,h=0,b=0;const g=()=>{d=!1,u=!1,f=!1,p=null},S=()=>{const N=n.current,M=p,F=x;u&&M&&(gt(M==="left"?N.onLeftProgress:N.onRightProgress,F?1:0),gt(N.onDragEnd,M,F)),g()},v=()=>{S(),u||g()},E=N=>{const M=n.current;if(M.enabled===!1){u&&p?S():g();return}if(N.touches.length!==1){u&&p?S():g();return}const F=N.touches[0],$=o.getBoundingClientRect(),U=o.clientWidth,K=!!M.leftOpen,L=!!M.rightOpen,D=R=>Tg(R,o);if(K||L){if(D(N.target)){g();return}if(K&&L){const R=F.clientX<=$.left+c;F.clientX>=$.right-c?(p="right",x=!0):R?(p="left",x=!0):(p=K?"left":"right",x=!0)}else K?(p="left",x=!0):(p="right",x=!0);b=eo(p==="left"?M.leftWidth:M.rightWidth,U),b<10&&(b=U||window.innerWidth||320),b<10&&(b=320),d=!0}else{if(D(N.target)){g();return}p=null,x=!1,b=0,d=!0}y=F.clientX,m=F.clientY,h=Date.now(),u=!1,f=!1},k=N=>{if(!d)return;if(N.touches.length!==1){v();return}const M=N.touches[0],F=M.clientX-y,$=M.clientY-m;if(!f){if(Math.abs(F)<da&&Math.abs($)<da)return;if(Math.abs($)>Math.abs(F)*Cn){g();return}if(!p){const L=n.current;p=F>0?"left":"right",b=eo(p==="left"?L.leftWidth:L.rightWidth,o.clientWidth),b<10&&(b=window.innerWidth||320)}if(p==="left"){if(!x&&F<=0){g();return}if(x&&F>=0){g();return}}else{if(!x&&F>=0){g();return}if(x&&F<=0){g();return}}f=!0,u=!0,gt(n.current.onDragStart,p)}if(!u)return;N.cancelable&&N.preventDefault();const U=n.current,K=ua(p,x,F,b);gt(p==="left"?U.onLeftProgress:U.onRightProgress,K)},C=(N,M)=>{if(!d){g();return}const F=N-y,$=M-m;if(!p&&!x&&Math.abs(F)>=ir&&Math.abs($)<=Math.abs(F)*Cn){const I=n.current;p=F>0?"left":"right",b=eo(p==="left"?I.leftWidth:I.rightWidth,o.clientWidth),b<10&&(b=window.innerWidth||320)}if(!p){g();return}const U=Math.max(1,Date.now()-h),K=n.current;if(!u){const I=Math.abs(F),T=Math.abs($);I>=ir&&T<=I*Cn?p==="left"&&!x&&F>0?(gt(K.onLeftProgress,1),gt(K.onLeftOpen)):p==="right"&&!x&&F<0?(gt(K.onRightProgress,1),gt(K.onRightOpen)):gt(p==="left"?K.onLeftProgress:K.onRightProgress,x?1:0):gt(p==="left"?K.onLeftProgress:K.onRightProgress,x?1:0);const W=p;g(),gt(K.onDragEnd,W);return}const L=ua(p,x,F,b),D=Pg({side:p,isOpenAtStart:x,dx:F,dt:U,progress:L}),R=p;gt(R==="left"?D?K.onLeftOpen:K.onLeftClose:D?K.onRightOpen:K.onRightClose),g(),gt(K.onDragEnd,R,D)},j=N=>{const M=N.changedTouches[0];if(!M){g();return}const F=M.clientX-y,$=M.clientY-m;d&&(u||Math.abs(F)>=ir&&Math.abs($)<=Math.abs(F)*Cn)&&N.cancelable&&N.preventDefault(),C(M.clientX,M.clientY)},w=()=>{v()};return o.addEventListener("touchstart",E,{passive:!0}),o.addEventListener("touchmove",k,{passive:!1}),o.addEventListener("touchend",j,{passive:!1}),o.addEventListener("touchcancel",w,{passive:!0}),()=>{try{u&&p&&S()}catch{}o.style.touchAction=i,o.removeEventListener("touchstart",E),o.removeEventListener("touchmove",k),o.removeEventListener("touchend",j),o.removeEventListener("touchcancel",w)}},[e,r])};function yy({className:e="h-5 w-5"}){return s.jsxs("span",{"aria-hidden":"true",className:`relative inline-block overflow-hidden rounded-[2px] ${e}`,children:[s.jsx("span",{className:"absolute left-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-error)]/25"}),s.jsx("span",{className:"absolute right-[20%] top-[20%] h-[60%] w-[25%] bg-[var(--status-success)]/25"}),s.jsx(P,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function xa({size:e,className:t,style:n,...r}){return s.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 256 256",fill:"currentColor",className:t,style:{width:typeof e=="number"?`${e}px`:e,height:typeof e=="number"?`${e}px`:e,...n},...r,children:s.jsx("path",{d:"M112,148a12,12,0,0,0-12,12v19L69.17,148.2A4,4,0,0,1,68,145.37V97.94a36,36,0,1,0-24,0v47.43a27.81,27.81,0,0,0,8.2,19.8L83,196H64a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,112,148ZM56,52A12,12,0,1,1,44,64,12,12,0,0,1,56,52ZM212,158.06V110.63a27.81,27.81,0,0,0-8.2-19.8L173,60h19a12,12,0,0,0,0-24H144a12,12,0,0,0-12,12V96a12,12,0,0,0,24,0V77l30.83,30.83a4,4,0,0,1,1.17,2.83v47.43a36,36,0,1,0,24,0ZM200,204a12,12,0,1,1,12-12A12,12,0,0,1,200,204Z"})})}const Ab=({sessionDirectory:e,draftDirectory:t,isNewSessionDraftOpen:n})=>n?t:e,Nb=({activeProjectLabel:e,openDirectory:t,homeDirectory:n})=>vr(t,n)?null:e,to=()=>Es.filter(e=>po.has(e.id)).map(e=>({...rl(e)})),Ib=()=>{if(typeof window>"u")return go;const e=window.localStorage.getItem("openInAppId");return e&&mo(e)?e:go};let so=!1,Qs=!1,gs=!1,bs=0,Pn=null;const ya=()=>{Pn&&(clearTimeout(Pn),Pn=null)},As=Bs()((e,t)=>({selectedAppId:Ib(),availableApps:to(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(so||typeof window>"u")return;so=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:to(),hasLoadedApps:u});return}const f=new Set(d.map(m=>m.name)),p=new Map(d.map(m=>[m.name,m.iconDataUrl??void 0])),y=Es.filter(m=>f.has(m.appName)||po.has(m.id)).map(m=>({...rl(m),iconDataUrl:p.get(m.appName)}));e({availableApps:y,hasLoadedApps:!0})},r=async d=>{if(!rn()||!dr()||Qs||t().hasLoadedApps&&!d)return;const f=Es.map(p=>p.appName);ya(),Qs=!0,gs=!1,e({isScanning:!0});try{const{apps:p,success:x,hasCache:y,isCacheStale:m}=await Ei(f,d),h=x&&!y&&p.length===0&&bs<3;if(e({isCacheStale:y?m:!1}),n(p,x?!h:!1),x){if(h){const g=[800,1600,3200][bs]??3200;bs+=1,gs=!0,Pn=setTimeout(()=>{r()},g);return}bs=0,gs=!1;return}if(bs<3){const g=[1e3,3e3,7e3][bs]??7e3;bs+=1,gs=!0,Pn=setTimeout(()=>{r()},g)}}finally{Qs=!1,gs||e({isScanning:!1})}};r();const o=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&mo(u.openInAppId)?u.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},i=()=>{r()},l=d=>{const u=d.detail;Array.isArray(u)&&(bs=3,gs=!1,e({isScanning:!1,isCacheStale:!1}),n(u))};window.addEventListener("pichamber:settings-synced",o),window.addEventListener("pichamber:app-ready",i),window.addEventListener("pichamber:installed-apps-updated",l),window.__pichamberAppReady&&r(),window.setTimeout(()=>{t().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(so||t().initialize(),!rn()||!dr()||Qs||t().hasLoadedApps&&!n)return;const o=Es.map(i=>i.appName);ya(),n&&e({hasLoadedApps:!1}),Qs=!0,gs=!1,e({isScanning:!0});try{const{apps:i,hasCache:l,isCacheStale:c}=await Ei(o,n),d=new Set(i.map(x=>x.name)),u=new Map(i.map(x=>[x.name,x.iconDataUrl??void 0])),p=Es.filter(x=>d.has(x.appName)||po.has(x.id)).map(x=>({...x,iconDataUrl:u.get(x.appName)}));e({availableApps:p.length>0?p:to(),hasLoadedApps:p.length>0,isCacheStale:l?c:!1})}finally{Qs=!1,gs||e({isScanning:!1})}},selectApp:async n=>{mo(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await el({openInAppId:n}))}})),Eb="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAXaSURBVFgJ7VddbBRVFP5mdme6dOnu2tZawOAPjfxU+bGQYCRAsvw8qNGEQPTRJ0I0amL0wfjgA/HBR8KLD8YgDxJEUkVFxSYYTSRii6DQQCMGIQqlW7p0u+zMzo/fuTuzO9Nt0Td94CRn7pl7z5zznZ977y5wh/7jDGiz+T979qD5Ujbfd90xlll+stOF1uI40B1+4HhkjnZk9CgLQ9iXp2/BdcbgVc/h0sAgduywudJEMwLY9Of4ugtW5p3CpL7W1jTN88VmjdQYvnDKF1mczkYuNZLeCVg3X8fa9u+nqzUB2HRpdN2pSseRQknPoUL1Jo2ICTrPGcCzdwPdHENcAnicKRqcAk7cpL5J1r0JlAtPYV1XDETM/FtH3m19r+f5by+XjNX/xnmCX3/cCzydi4CKiC7lw+PArhGgoPPFq/6E0+9vwM6d5VBNpuv03cLNfeNTRh9KnJIiV2/PvSngycC5RD+dE5zb3g7s6QESzAZc2l6wuY9SnWIAxv10r81uU85Vt1FvtpEtlc/SMFUkUofeZ2IBta0DWDmXgkfbyTRz1qAYAMczOz3p1elOxYPyEllj421hdELViPO6Kudk3ia3UGe5ABDbvtnJZ52SdYmCZ3stdeexBabFdeAbYopEowtagVUZqFapBrtAGqpiVaFrGgyjZlrmTD5yEqoEJj4iFMuA62i6L3WPZkAiuHgarZ/vbWSBkTzO2rfTR4XOJVJhjfX44MBn+OTocVWbcF5MalxXPeVL6zYonoGo44YOtDI7qHC1lkL5nHnOc+tJRi3K6iygLNGMjt1A1XVV6iUzOvVtAvMlS2I/yBYlRf8MgA6szmXQ1jDfKhSgjft6DRtrkgarAiAw5nI9v2WDSn+Zxfd9DawGxIlPPQUg0A2HGABfEIYlCDU4+q0d8O+jRzHCCFYy+nu4BaeYAoksBCDrPYsXQQ6iitgiSQaS1FHHtMzFil4DpxTl4UhORSn4WOaaiGsbu4iFRkMnYQlEV0oSJQGQ4FyYgSRDjpqPZcCR6EOOWonIEsBqArAIQOMLzw0VXRRERF2VoA6Atk1+MzsASekMJYgaFEeHR4Cr85lNGntYzgKCYd/NSNIDCXr0ZJ2jwTsjSvEMzFQCCVmKHBRahn2DNb4rDRx8pnbXOOIg0JELLMHOF1AUkaRj1V8c2TookkMS83WK9QCVpRwtf5wCykQWRKDyJ44Ytc452QUV6inmN9IDIv/6y2+YLDuqTywBEHxv8rsoxQC4Fpf4cZ2pbJ4/huxXr0EvFmoRCrAIVymLQ3Eid0GJYPsPfISBLwdwi79YQnCqBNS7LQDP5qYSAKEDypOrX4WVWYLsFy+i9cwh6CUmUKIJI2Gq5cSbnLLw849D2Ld3L4olC1u3P0c1ow5Ozgixa3puWChONG1D3eLZUQOglvng+Vp5dBfseesx5/yHyI4cBTL3wsssRGs2g6/ppHijiMLoNSSMNHofy6Nn6SPsAR02nUoTtrDTSrdoi8CTni55rlOsCf1ypaDxlFMNU1epCV5XL6Y6dmOq+BeS48NIlq7Anpjg5dOFbPdDWLQyj/aubnUKSkMKi3NhkUd4kieYtbRbYS0bFAOQKI8NO363z1RJHmamtnlwhGksxV2w/gl29WRtm8kWtWUnRShLnQvXgDOXmLg2HzlvbDiyHD8Y517YP2i4FtueFPbB9FFqKcyobk4A5y7zquUFa7IXojyHoeXmAFcY755vaI6A56Xsofm/7+cmblBTpOldQ5vs3PJDVS+RVSAaus2SpJTO80t4NTNSOQfCDrtFkBevA0ME6HGvPdDpFlekzm7rf3nFQNRQEwBZTL9warObWfx21Uv1+fx1ERqVNampGoOHpF1tsdp07RnoGMxK1vT97rbK4IP6+Tc+fWXVsahaYGL6VO09d//GXHXr7jVeqmuppqU6ff4x0RO6lqRxgxHJpWKSlcw5eWfjq5rq/CdhaL5l6JWxjDc6bP7w5sn+/uMs2B36H2bgb6v9raK0+o9IAAAAAElFTkSuQmCC",Rb="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAeGVYSWZNTQAqAAAACAAEARoABQAAAAEAAAA+ARsABQAAAAEAAABGASgAAwAAAAEAAgAAh2kABAAAAAEAAABOAAAAAAAAAJAAAAABAAAAkAAAAAEAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAIKADAAQAAAABAAAAIAAAAAB+C9pSAAAACXBIWXMAABYlAAAWJQFJUiTwAAABnWlUWHRYTUw6Y29tLmFkb2JlLnhtcAAAAAAAPHg6eG1wbWV0YSB4bWxuczp4PSJhZG9iZTpuczptZXRhLyIgeDp4bXB0az0iWE1QIENvcmUgNi4wLjAiPgogICA8cmRmOlJERiB4bWxuczpyZGY9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkvMDIvMjItcmRmLXN5bnRheC1ucyMiPgogICAgICA8cmRmOkRlc2NyaXB0aW9uIHJkZjphYm91dD0iIgogICAgICAgICAgICB4bWxuczpleGlmPSJodHRwOi8vbnMuYWRvYmUuY29tL2V4aWYvMS4wLyI+CiAgICAgICAgIDxleGlmOlBpeGVsWERpbWVuc2lvbj4yNTY8L2V4aWY6UGl4ZWxYRGltZW5zaW9uPgogICAgICAgICA8ZXhpZjpQaXhlbFlEaW1lbnNpb24+MjU2PC9leGlmOlBpeGVsWURpbWVuc2lvbj4KICAgICAgPC9yZGY6RGVzY3JpcHRpb24+CiAgIDwvcmRmOlJERj4KPC94OnhtcG1ldGE+Cl6wHhsAAAQzSURBVFgJ7VZNbBNHFH67Xv9RxwnBDqlUoQglcZK6qSIEJIQWAYJQoVY9IE5RTzn20FMvqdpDesq9B24+NdwthAJCkZChJg1JSOXYQIwQKQIaBdtENbs73t2+N8miGWOcpFHUHniyd97OvJ9v3nv7ZgDe038cAeVd/jOZjC94sKdfU+Bj24G9igpexwYPyiu2bauKqqqirkOTqmrjnIOyFsoyUKDocSCj/7mU7ujoMER5l68JYOFZ4YSiwPjd9O0jjx7ch1KhAJZVAcdx0LxDv3XetYKjggr4I4bzHo8G4aYmONjZBYf6+2dUzfd9PNowJajUZmef/PX5zcWl0rmvvnbQHrra+f/M+S+dqYXs2t3Hz09Ve5UicCmZ3NPb1Zv66btv+65dSULA64WGxkbw+Xx8V9XK9d4pWowxeFUqgW6acHroC/j5l0sLD/PZY98MDf3t6mouQ+On3X1H7/2e7rtOztHpgbY2+CAUgperq+D3+7cNgtLSEA7D0+VluDF5FS7cSff2HT56DF1dd/3KhQTWJ/lclsc8jIrk9IfRURgZGQEvRqNSWa8D2t1W/liXXK8Ro0i0lF0ExaPEXec0SgAqhrm3VCzwdS9GQNd1GBsbg0AgAIlEAlpbW7EYLVF/U56AagieiGwbuhERlSQApmEE8c/XKXxU0fF4HNowFfPz81Aul7edBjLGbeHITANsZga4g42HVAM2Y74KM/kSIQ/izgcHB2FiYgJmZmZ4MZpYULRG5PF4+Bx/2cLDxuhhYUqFLwGoWCaQEBGhNjAa4+Pj/J3SQA6pHpqbm/kcNitIJpOgaZIZvlbrQbZNJvcjSZOZDKhwRKLic4l2Pjc3B8FgkE+trKxAVUN0RWuOZNtCHyJJACj/bgREIZcnA9PT029SQM63unuywSOwUWOuTQmAhfmnlluPxIjUk6u1RrbJh0jyV0Ap2OZnJhrbjOcRqEqBBMDCAtltAORDJAkAVj2mWS5CUXinPDUx+oxFkgBYjO0qANu2wKoqQgkAfgW7C4AiYMmfoQSgwpjj7GYRUh/Q66SAmdisNxql227FfP1bXrRlVExdtCNHwDRLdPkgwmi8OUREhe3y1NLJFpEfbWMNvBRtSI2o+KqYi+zbx4NQwptMCO8E1HjEHYjKm/HknG5FZIsCG4lEoLS2lhP1JAB3bt1KH//s+GJPd3dPJpvlN5kwXiYIhHukisr1eAItXsm6YzGItrTcn5+dvS3qSQBSqVQhFouNnj039CsaCC7mcqDjgbNT6op1AtrU8Wo3Ojk5KaVAOptdR8PDwxf3t7SMvXjxvJNOPP31a35Krt8CXKl3j2SUDip/IAjRaBRaP9z/cHW18GMikbhcrVUTAAm1t7d/NDAwcDIUCvVqmtqkyLe3ajtvvTtg4x3SLpbLa3+kUr9N5fP55beE3k/8HyLwDx2/HIx7q3WfAAAAAElFTkSuQmCC",no=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?Eb:e.id==="terminal"?Rb:void 0}),wa=({label:e,iconDataUrl:t,fallbackIconDataUrl:n})=>{const[r,o]=a.useState(!1),i=e.trim().slice(0,1).toUpperCase()||"?",l=t||n;return l&&!r?s.jsx("img",{src:l,alt:"",className:"h-4 w-4 rounded-sm",onError:()=>o(!0)}):s.jsx("span",{className:_("h-4 w-4 rounded-sm flex items-center justify-center","bg-[var(--surface-muted)] text-[9px] font-medium text-muted-foreground"),children:i})},Db=({directory:e,className:t})=>{const n=As(m=>m.selectedAppId),r=As(m=>m.availableApps),o=As(m=>m.isCacheStale),i=As(m=>m.isScanning),l=As(m=>m.initialize),c=As(m=>m.loadInstalledApps),d=As(m=>m.selectApp);a.useEffect(()=>{l()},[l]);const u=rn()&&dr(),f=a.useMemo(()=>{const m=r.find(h=>h.id===n)??r.find(h=>h.id===go)??r[0]??Es[0];return no(m||Es[0])},[r,n]);if(!u||!e||r.length===0)return null;const p=async m=>{await of(e,m.id,m.appName)||await sl(e,m.appName)},x=async m=>{await d(m.id),await p(m)},y=async()=>{(await ws(e)).ok&&ae.success("Path copied to clipboard")};return s.jsxs("div",{className:_("app-region-no-drag inline-flex h-7 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",t),children:[s.jsx("button",{type:"button",onClick:()=>{p(f)},className:_("inline-flex h-full items-center px-2.5 typography-ui-label font-medium","text-foreground hover:bg-interactive-hover transition-colors",i&&"animate-pulse"),"aria-label":`Open in ${f.label}`,children:s.jsx(wa,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),s.jsxs(Wt,{children:[s.jsx(Gt,{asChild:!0,children:s.jsx("button",{type:"button",className:_("inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors"),"aria-label":"Choose app to open",children:s.jsx(P,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(Ht,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{y()},children:[s.jsx(P,{name:"file-copy",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy Path"})]}),s.jsx(nn,{}),r.map(m=>{const h=no(m);return s.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{x(m)},children:[s.jsx(wa,{label:m.label,iconDataUrl:m.iconDataUrl,fallbackIconDataUrl:h.fallbackIconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:m.label}),f.id===m.id?s.jsx(P,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},m.id)}),o?s.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[s.jsx(P,{name:"refresh",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh Apps"})]}):null]})]})]})},Pb="\x1B",Mb=new RegExp(`${Pb}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Tb=/https?:\/\/[^\s<>'"`]+/gi,jt="__pichamber_auto_discover_preview__",Fb=15e3,Lb=e=>{let t="";for(let n=0;n<e.length;n+=1){const r=e.charCodeAt(n);r>=0&&r<=8||r===11||r===12||r>=14&&r<=31||r===127||(t+=e[n])}return t},Ob=e=>{const t=(e||"").trim();if(!t)return null;const n=/^https?:\/\//i.test(t)?t:`http://${t}`;try{const r=new URL(n);return r.protocol!=="http:"&&r.protocol!=="https:"?null:r.toString()}catch{return null}},Bb=e=>{const n=e.replace(Mb,"").match(Tb);if(!n||n.length===0)return null;const r=n.map(i=>i.replace(/[),.;]+$/,"")).filter(Boolean);if(r.length===0)return null;const o=[];for(const i of r)try{const l=new URL(i);l.port&&l.port.length>0&&o.push({raw:i,parsed:l})}catch{}if(o.length>0){const i=l=>{const{parsed:c}=l,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",f=c.pathname||"/",p=f.split("/").filter(Boolean).length,x=f==="/"||f==="",y=!!(c.search||c.hash);let m=0;return u&&(m+=50),x&&(m+=30),m-=Math.min(p*5,20),y&&(m-=10),m};return o.sort((l,c)=>i(c)-i(l)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},_b=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],zb=["dev","start","preview","serve"];async function Ub(e,t,n){if(!e)return null;const r=Wb(t);if(r)return{command:r.command,label:r.name||"Start Preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=Gb(n);if(o){const i=await Hb(e);return{command:`${i==="npm"?"npm run":i==="yarn"?"yarn":i==="pnpm"?"pnpm":i==="bun"?"bun run --shell=bun":"npm run"} ${o}`,label:`Start (${o})`}}}if(await $b(e)){const o=await Kb(),i=typeof o=="number"&&Number.isFinite(o)&&o>0?o:8e3;return{command:`python3 -m http.server ${i}`,label:"Static preview",previewUrlHint:`http://127.0.0.1:${i}/`}}return null}async function $b(e){const t=`${e}/index.html`,n=await wr(t,e);return typeof n=="string"&&n.trim().length>0}async function Kb(){try{const e=await Mt("/api/system/free-port",{cache:"no-store"});if(!e.ok)return null;const t=await e.json().catch(()=>null),n=typeof t?.port=="number"?t.port:null;return n&&Number.isFinite(n)?n:null}catch{return null}}function Wb(e){for(const t of e){const n=`${t.name} ${t.command}`.toLowerCase();if(zb.some(o=>n.includes(o)))return t}return null}function Gb(e){for(const{pattern:t}of _b)for(const n of Object.keys(e))if(t.test(n))return n;return null}async function Hb(e){const t=await wr(`${e}/package.json`,e);if(t)try{const r=JSON.parse(t),o=typeof r.packageManager=="string"?r.packageManager.toLowerCase():"";if(o.startsWith("bun@"))return"bun";if(o.startsWith("pnpm@"))return"pnpm";if(o.startsWith("yarn@"))return"yarn";if(o.startsWith("npm@"))return"npm"}catch{}const n=[["bun.lock","bun"],["bun.lockb","bun"],["pnpm-lock.yaml","pnpm"],["yarn.lock","yarn"],["package-lock.json","npm"]];for(const[r,o]of n){const i=await wr(`${e}/${r}`,e);if(typeof i=="string"&&i.trim().length>0)return o}return"npm"}async function wr(e,t){if(t?.trim())try{const r=new URLSearchParams({path:e,directory:t,optional:"true"}),o=await Mt(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=tl()?.files;if(n?.readFile)try{const r=await n.readFile(e,{optional:!0});return typeof r?.content=="string"?r.content:null}catch{return null}try{const r=await Mt(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function qb(e){try{const t=await wr(`${e}/package.json`,e);if(t==null)return null;const r=JSON.parse(t).scripts;return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}const Yb=(e,t,n)=>new Promise(r=>{let o=!1,i=null,l=null;const c=d=>{o||(o=!0,l&&clearTimeout(l),i?.close(),r(d))};i=e.connect(t,{onEvent:d=>{(d.type==="exit"||d.type==="snapshot"&&d.status==="exited")&&c(!0)},onError:(d,u)=>{u&&c(!0)}}),o?i.close():l=setTimeout(()=>c(!1),n)});function Vb({projectRef:e,directory:t,allowMobile:n=!1}){const{currentTheme:r}=Qa(),{terminal:o}=Os(),{isMobile:i}=dn(),l=de(Y=>Y.terminalShell),c=de(Y=>Y.terminalLoginShells.includes(Y.terminalShell)),d=de(Y=>Y.setSettingsPage),u=de(Y=>Y.setSettingsDialogOpen),f=de(Y=>Y.setSettingsProjectsSelectedId),p=de(Y=>Y.openContextPreview),x=he(Y=>Y.ensureDirectory),y=he(Y=>Y.setTabLabel),m=he(Y=>Y.setTabIconKey),h=he(Y=>Y.setActiveTab),b=he(Y=>Y.setConnecting),g=he(Y=>Y.setTabSessionId),S=he(Y=>Y.setTabPreviewUrl),v=he(Y=>Y.projectActionRuns),E=he(Y=>Y.setProjectActionRun),k=he(Y=>Y.updateProjectActionRunStatus),C=he(Y=>Y.removeProjectActionRun),[j,w]=a.useState([]),[N,M]=a.useState(null),[F,$]=a.useState(!1),U=a.useRef({}),K=a.useRef({}),L=a.useRef({}),D=a.useRef({}),R=a.useRef(new Set),I=a.useRef(0),T=e?.id??null,W=e?.path??"",G=a.useMemo(()=>T?{id:T,path:W}:null,[T,W]),B=a.useCallback(async Y=>{await La(Y)},[]),be=a.useCallback(async()=>{if(!G)return;const Y=I.current+1;I.current=Y,$(!0);try{const ce=await io(G);if(I.current!==Y)return;const re=ce.actions;w(re),M(ue=>ue===jt||ue&&re.some(ve=>ve.id===ue)?ue:null)}catch{if(I.current!==Y)return}finally{I.current===Y&&$(!1)}},[G]),V=a.useMemo(()=>Nl(t||G?.path||""),[t,G?.path]),Ce=a.useMemo(()=>N?j.find(Y=>Y.id===N)??null:null,[j,N]),De=a.useMemo(()=>({id:jt,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),H=!i,z=a.useMemo(()=>H?[De,...j]:j,[j,De,H]);a.useEffect(()=>{be()},[be]),a.useEffect(()=>{if(typeof window>"u")return;const Y=ce=>{const re=ce.detail;T&&(re?.projectId&&re.projectId!==T||be())};return window.addEventListener(So,Y),()=>{window.removeEventListener(So,Y)}},[be,T]),a.useEffect(()=>{N&&(N===jt&&H||j.some(Y=>Y.id===N)||M(null))},[j,H,N]),a.useEffect(()=>{const Y=()=>{const ce=he.getState(),re=ce.sessions,ue=ce.projectActionRuns;for(const[ve,Le]of Object.entries(ue)){const se=re.get(Le.directory)?.tabs.find(Fe=>Fe.id===Le.tabId);if(!se||se.terminalSessionId!==Le.sessionId){C(ve);continue}const pe=K.current[ve]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};K.current[ve]=pe;const fe=z.find(Fe=>Fe.id===Le.actionId),je=ce.getBuffer(Le.directory,Le.tabId).chunks;if(!fe||je.length===0)continue;const He=je.filter(Fe=>pe.lastSeenChunkId===null||Fe.id>pe.lastSeenChunkId);if(He.length===0)continue;const We=He.map(Fe=>Fe.data).join(""),Ie=`${pe.tail}${We}`,Ye=!pe.openedUrl&&fe.autoOpenUrl===!0?Bb(Ie):null,oe=He[He.length-1]?.id??pe.lastSeenChunkId;if(pe.lastSeenChunkId=oe,pe.tail=Ie.slice(-512),Ye)if(pe.openedUrl=!0,pe.openInPreview){const Fe=ue[ve];Fe&&(S(Fe.directory,Fe.tabId,Ye,{locked:!1,autoOpened:!1}),Fe.status==="waiting-for-preview"&&k(ve,"running"),window.clearTimeout(D.current[ve]),delete D.current[ve],p(Fe.directory,Ye))}else B(Ye),ae.success("Opened URL from action output");K.current[ve]=pe}for(const ve of Object.keys(K.current))ue[ve]||(delete K.current[ve],window.clearTimeout(D.current[ve]),delete D.current[ve])};return Y(),he.subscribe((ce,re)=>{(ce.sessions!==re.sessions||ce.buffers!==re.buffers)&&Y()})},[z,p,B,v,C,S,k]);const Q=a.useCallback(async(Y,ce={})=>{if(!V)throw new Error("No active directory");const re=as(V,Y.id);x(V);const ue=he.getState(),ve=ue.getDirectoryState(V);let Le=U.current[re]||null;const xe=Le?!!ve?.tabs.some(fe=>fe.id===Le):!1;(!Le||!xe)&&(Le=ue.createTab(V),U.current[re]=Le),y(V,Le,`Action: ${Y.name}`),m(V,Le,Y.icon||"play"),h(V,Le),ce.revealTerminal!==!1&&de.getState().openContextPanelTab(V,{mode:"terminal"});const pe=he.getState().getDirectoryState(V)?.tabs.find(fe=>fe.id===Le);return{key:re,tabId:Le,sessionId:pe?.terminalSessionId??null}},[x,V,h,m,y]),X=a.useCallback(async Y=>{if(!n&&i)return;if(!V){ae.error("No active directory for action");return}const ce=as(V,Y.id),re=v[ce];if(!(re&&re.status==="running")&&!R.current.has(ce)){R.current.add(ce);try{const ue=Y.id===jt?await(async()=>{const[Ie,Ye]=await Promise.all([io({id:G?.id??"",path:V}),qb(V)]),oe=await Ub(V,Ie.actions,Ye);if(!oe)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:jt,name:"Auto-discover",command:oe.command,icon:"scan-2",autoOpenUrl:!0,openUrl:oe.previewUrlHint||""}})():Y,ve=ue.autoOpenUrl===!0&&(ue.openUrl||"").trim().length>0,Le=!ve&&Y.id!==jt,{key:xe,tabId:se,sessionId:pe}=await Q(ue,{revealTerminal:Le});let fe=pe;if(!fe){b(V,se,!0);try{fe=(await o.createSession({cwd:V,sessionId:se,shell:l,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,g(V,se,fe)}finally{b(V,se,!1)}}if(!fe)throw new Error("Failed to create terminal session");L.current[xe]?.(),b(V,se,!0);const je=o.connect(fe,{onEvent:Ie=>{Ie.type==="snapshot"&&(he.getState().replaceBuffer(V,se,Ie.data??"",Ie.sequence??0),he.getState().setConnecting(V,se,!1)),Ie.type==="data"&&typeof Ie.data=="string"&&Ie.data.length>0&&he.getState().appendToBuffer(V,se,Ie.data,Ie.sequence,Ie.replayData),Ie.type==="exit"&&(he.getState().setTabLifecycle(V,se,"exited"),he.getState().setConnecting(V,se,!1),he.getState().removeProjectActionRun(xe),delete K.current[xe],L.current[xe]?.(),delete L.current[xe],window.clearTimeout(D.current[xe]),delete D.current[xe])},onError:(Ie,Ye)=>{he.getState().setConnecting(V,se,!1),Ye&&(he.getState().setTabLifecycle(V,se,"exited"),he.getState().setTabSessionId(V,se,null),he.getState().removeProjectActionRun(xe))}});L.current[xe]=je.close;const He=ue.autoOpenUrl?Ob(ue.openUrl):null;E({key:xe,directory:V,actionId:ue.id,tabId:se,sessionId:fe,status:ue.id===jt&&!He?"waiting-for-preview":"running"}),window.clearTimeout(D.current[xe]),delete D.current[xe],ue.id===jt&&!He&&(D.current[xe]=window.setTimeout(()=>{const Ie=he.getState(),Ye=Ie.projectActionRuns[xe];Ie.updateProjectActionRunStatus(xe,"running"),Ye&&(Ie.setActiveTab(Ye.directory,Ye.tabId),de.getState().openContextPanelTab(Ye.directory,{mode:"terminal"})),delete D.current[xe]},Fb)),K.current[xe]={lastSeenChunkId:null,openedUrl:!!He||ve,tail:"",openInPreview:ue.id===jt};const We=Lb(ue.command.trim().replace(/\r\n|\r/g,`
62
+ `));await o.sendInput(fe,`${We}\r`),He?(S(V,se,He,{locked:!0,autoOpened:!0}),p(V,He),ae.success("Opened action URL")):ve?(S(V,se,null,{locked:!0}),ae.error("Invalid custom URL format")):S(V,se,null,{locked:!1,autoOpened:!1})}catch(ue){C(ce),delete K.current[ce],L.current[ce]?.(),delete L.current[ce],window.clearTimeout(D.current[ce]),delete D.current[ce],ae.error(ue instanceof Error?ue.message:"Failed to run action")}finally{R.current.delete(ce)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,Q,n,i,V,c,l,p,v,C,b,E,S,g,G?.id,o]),ne=a.useCallback(async Y=>{const ce=as(V,Y.id),re=v[ce];if(!re)return;k(ce,"stopping");const ue=Yb(o,re.sessionId,1e3);try{await o.sendInput(re.sessionId,"")}catch{}const ve=await ue;if(he.getState().getDirectoryState(re.directory)?.tabs.find(se=>se.id===re.tabId)?.terminalSessionId===re.sessionId&&!ve){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:re.sessionId})}catch{}else try{await o.close(re.sessionId)}catch{}g(re.directory,re.tabId,null)}C(ce),delete K.current[ce],L.current[ce]?.(),delete L.current[ce],window.clearTimeout(D.current[ce]),delete D.current[ce]},[V,v,C,g,o,k]),we=a.useCallback(()=>{const Y=Ce??z[0];if(!Y)return;const ce=as(V,Y.id),re=v[ce];if(re?.status!=="stopping"){if(re){ne(Y);return}X(Y)}},[z,V,X,v,Ce,ne]),me=a.useCallback((Y,ce=!1)=>{if(M(Y.id),!ce){X(Y);return}const re=as(V,Y.id),ue=v[re];if(ue?.status!=="stopping"){if(ue){ne(Y);return}X(Y)}},[V,X,v,ne]),q=a.useCallback(()=>{G?.id&&(f(G.id),d("projects"),u(!0))},[u,d,f,G?.id]),te=Ce??z[0]??null,le=te?v[as(V,te.id)]:null,Ae=he(Y=>le?Y.sessions.get(le.directory)?.tabs.find(ce=>ce.id===le.tabId)?.previewUrl??null:null),Se=!!((n||!i)&&G&&V),Ge=Ce??z[0]??null;return{shouldRender:Se,isLoading:F,normalizedDirectory:V,resolvedSelected:Ge,displayActions:z,projectActionRuns:v,selectedRunPreviewUrl:Ae,handlePrimaryClick:we,handleSelectAction:me,openProjectActionsSettings:q,openContextPreview:p}}const va=({projectRef:e,directory:t,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:i,isLoading:l,normalizedDirectory:c,resolvedSelected:d,displayActions:u,projectActionRuns:f,selectedRunPreviewUrl:p,handlePrimaryClick:x,handleSelectAction:y,openProjectActionsSettings:m,openContextPreview:h}=Vb({projectRef:e,directory:t,allowMobile:o});if(!i||!d)return null;const b=d.icon||"play",g=d.id===jt?"scan-2":Dn[b]||"play",S=as(c,d.id),v=f[S],E=v?.status==="stopping",k=v?.status==="waiting-for-preview",C=!!(v&&p),j=()=>{!v||!p||h(v.directory,p)},w=d.id===jt;return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",disabled:l||E,className:_("app-region-no-drag inline-flex h-9 w-9 items-center justify-center rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] p-2","typography-ui-label font-medium text-muted-foreground hover:bg-interactive-hover hover:text-foreground transition-colors","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","disabled:cursor-not-allowed",n),onClick:x,"aria-label":v?`Stop ${d.name}`:`Run ${d.name}`,children:E||k?s.jsx(P,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):v?s.jsx(P,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-5 w-5"})})}),w?s.jsx(Ke,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),C?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-7 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Open Preview",onClick:j,children:s.jsx(P,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ke,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Wt,{children:[s.jsx(Gt,{asChild:!0,children:s.jsx("button",{type:"button",className:"app-region-no-drag -ml-1 inline-flex h-9 w-5 items-center justify-center rounded-[10px] text-muted-foreground hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary","aria-label":"Choose project action",children:s.jsx(P,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(Ht,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ut,{className:"flex items-center gap-2",onClick:m,children:[s.jsx(P,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(nn,{}),u.map(N=>{const M=N.icon||"play",F=N.id===jt?"scan-2":Dn[M]||"play",$=as(c,N.id),U=f[$],K=!!U,L=U?.status==="stopping";return s.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{y(N,!0)},children:[s.jsx(P,{name:F,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),L||U?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):K?s.jsx(P,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},N.id)})]})]})]}):s.jsxs("div",{className:_("app-region-no-drag inline-flex shrink-0 items-center self-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px]","bg-[var(--surface-elevated)] overflow-hidden","border border-border/60",r?"h-9":"h-7",n),children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:x,disabled:l||E,className:_("inline-flex h-full items-center justify-center typography-ui-label font-medium text-foreground hover:bg-interactive-hover",r?"w-9 px-0":"px-2.5","transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed"),"aria-label":v?`Stop ${d.name}`:`Run ${d.name}`,children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:E||k?s.jsx(P,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):v?s.jsx(P,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(P,{name:g,className:"h-4 w-4"})})})}),w?s.jsx(Ke,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),C?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:j,className:_(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-foreground","hover:bg-interactive-hover transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Open Preview",children:s.jsx(P,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ke,{sideOffset:6,children:"Open Preview"})]}):null,s.jsxs(Wt,{children:[s.jsx(Gt,{asChild:!0,children:s.jsx("button",{type:"button",className:_(r?"inline-flex h-full w-8 items-center justify-center":"inline-flex h-full w-7 items-center justify-center","border-l border-[var(--interactive-border)] text-muted-foreground","hover:bg-interactive-hover hover:text-foreground transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"),"aria-label":"Choose project action",children:s.jsx(P,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(Ht,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ut,{className:"flex items-center gap-2",onClick:m,children:[s.jsx(P,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(nn,{}),u.map(N=>{const M=N.icon||"play",F=N.id===jt?"scan-2":Dn[M]||"play",$=as(c,N.id),U=f[$],K=!!U,L=U?.status==="stopping";return s.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{y(N,!0)},children:[s.jsx(P,{name:F,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:N.name}),L||U?.status==="waiting-for-preview"?s.jsx(P,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):K?s.jsx(P,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},N.id)})]})]})]})},Ut={docker:"docker",windows:"windows",ubuntu:"ubuntu-fill",arch:"arch-linux",nixos:"nixos",fedora:"fedora",debian:"debian",centos:"centos-fill",linux:"terminal-box",darwin:"apple",unknown:"server"};function lr(e){return e?.deploymentKind==="docker"?{name:Ut.docker,color:"#2496ED"}:e?.serverPlatform==="win32"?{name:Ut.windows,color:"#0078D4"}:e?.serverPlatform==="linux"?e.serverDistribution==="ubuntu"?{name:Ut.ubuntu,color:"#E95420"}:e.serverDistribution==="arch"?{name:Ut.arch,color:"#1793D1"}:e.serverDistribution==="nixos"?{name:Ut.nixos,color:"#5277C3"}:e.serverDistribution==="fedora"?{name:Ut.fedora,color:"#51A2DA"}:e.serverDistribution==="debian"?{name:Ut.debian,color:"#A81D33"}:e.serverDistribution==="centos"?{name:Ut.centos,color:"#932279"}:{name:Ut.linux}:e?.serverPlatform==="darwin"?{name:Ut.darwin}:{name:Ut.unknown}}const Qb=e=>e?.deploymentKind==="docker"?"Docker":e?.serverPlatform==="win32"?"Windows":e?.serverPlatform==="darwin"?"macOS":e?.serverPlatform==="linux"?typeof e.serverDistribution=="string"&&e.serverDistribution.trim()?{ubuntu:"Ubuntu",arch:"Arch Linux",nixos:"NixOS",fedora:"Fedora",debian:"Debian",centos:"CentOS"}[e.serverDistribution]??"Linux":"Linux":"Server";function Jb({open:e,onOpenChange:t}){const[n,r]=a.useState(null),o=a.useCallback(async()=>{const u=Xe();try{const f=await Mt("/api/version");if(!f.ok)throw new Error("Version request failed");const p=await f.json().catch(()=>null);u===Xe()&&r(p)}catch{u===Xe()&&r(null)}},[]);a.useEffect(()=>(o(),Bn(()=>{o()})),[o]);const i=lr(n),l=Qb(n),c=typeof n?.pichamberVersion=="string"?n.pichamberVersion:null,d=typeof window<"u"?window.location.origin:"";return s.jsxs(Wt,{open:e,onOpenChange:u=>{t(u),u&&o()},children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx(Gt,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":"Show connected server information",className:_(un,"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5"),children:[s.jsx(P,{name:i.name,className:"h-[18px] w-[18px] shrink-0",style:i.color?{color:i.color}:void 0}),s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:"This server"})]})})}),s.jsx(Ke,{children:s.jsx("p",{children:"Connected server information"})})]}),s.jsxs(Ht,{align:"end",className:"w-80 max-w-[calc(100vw-2rem)] p-3",children:[s.jsxs("div",{className:"flex items-center justify-between gap-4",children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2.5",children:[s.jsx(P,{name:i.name,className:"size-5 shrink-0",style:i.color?{color:i.color}:void 0}),s.jsx("div",{className:"truncate typography-ui-label font-medium text-foreground",children:l})]}),c?s.jsx("div",{className:"shrink-0 typography-micro text-muted-foreground",children:`v${c}`}):null]}),s.jsx("div",{className:"mt-3 border-t border-[var(--interactive-border)] pt-3 typography-micro",children:s.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[s.jsx("span",{className:"shrink-0 text-muted-foreground",children:"Address"}),s.jsxs("button",{type:"button",className:"ml-auto flex min-w-0 items-center gap-1.5 rounded px-1 py-0.5 text-foreground hover:bg-interactive-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",title:`Copy ${d}`,"aria-label":"Copy server address",onClick:()=>{ws(d).then(u=>{u.ok?ae.success("Server address copied"):ae.error("Could not copy server address")})},children:[s.jsx("span",{className:"block max-w-[30ch] truncate font-mono",children:d}),s.jsx(P,{name:"file-copy",className:"size-3.5 shrink-0 text-muted-foreground"})]})]})})]})]})}const Xb=({isMobile:e})=>{const n=Os().github??null,r=jr(i=>i.refresh),o=Uh();return a.useEffect(()=>{!n||e||r(n)},[n,e,r]),e||!n||!o?null:s.jsxs("span",{className:_(un,"app-region-no-drag inline-flex w-auto cursor-default gap-1.5 px-2"),title:`${o} via GitHub CLI`,"aria-label":`Signed in to GitHub as ${o} via GitHub CLI`,children:[s.jsx(P,{name:"github-fill",className:"h-3.5 w-3.5 shrink-0 text-foreground"}),s.jsxs("span",{className:"max-w-28 truncate typography-micro text-muted-foreground",children:["@",o]})]})},Zb=a.memo(function({isDesktopApp:t,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,currentInstanceIcon:i,isDesktopServicesOpen:l,setIsDesktopServicesOpen:c,refreshCurrentInstanceLabel:d,shortcutLabel:u,remoteUpdateInfo:f,remoteUpdateChecking:p,remoteUpdateError:x,onOpenRemoteUpdate:y}){return s.jsxs(Wt,{open:l,onOpenChange:m=>{c(m),m&&d()},children:[s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx(Gt,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":t?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:_(un,t?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[s.jsx(P,{name:i.name,className:"h-[18px] w-[18px]",style:i.color?{color:i.color}:void 0}),t?s.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:r}):null]})})}),s.jsx(Ke,{children:s.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),s.jsx(Ht,{align:"end",className:"w-[min(27rem,calc(100vw-2rem))] max-h-[75vh] overflow-y-auto p-0",children:t?s.jsxs("div",{children:[o?null:s.jsx("div",{className:"border-b border-[var(--interactive-border)] px-4 py-2.5",children:s.jsxs("div",{className:"flex items-center justify-between gap-3",children:[s.jsxs("div",{className:"min-w-0",children:[s.jsx("div",{className:"typography-ui-label font-medium text-foreground",children:"Remote instance update"}),s.jsx("div",{className:"typography-micro text-muted-foreground",children:f?.available?`Version ${f.version||""} is available for this instance.`:p?"Looking for updates...":x||"This instance is up to date."})]}),f?.available?s.jsx("button",{type:"button",className:"shrink-0 rounded-md bg-[var(--primary-base)] px-3 py-1.5 typography-ui-label font-medium text-[var(--primary-foreground)] hover:opacity-90",onClick:y,children:"Update"}):null]})}),s.jsx(Ru,{embedded:!0,open:l,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),ex=({action:e,onClose:t,sessionTitle:n,onConfirm:r})=>s.jsx(es,{open:e!==null,onOpenChange:o=>{o||t()},children:s.jsxs(ts,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Ss,{children:[s.jsx(ds,{children:e==="delete"?"Delete session?":"Archive session?"}),s.jsx(js,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),s.jsxs(Ls,{children:[s.jsx(Ne,{variant:"outline",size:"sm",onClick:t,children:"Cancel"}),s.jsx(Ne,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),tx=e=>{const t=e.trim();if(!t)return"";const n=t.split(/\s+/).filter(Boolean);if(n.length>=2){const r=n[0],o=n[1].slice(0,3),i=`${r} ${o}`.trim();return n.length>2||i.length<t.length?`${i}...`:i}return t.length>12?`${t.slice(0,9).trimEnd()}...`:t},Sn=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},sx=a.lazy(()=>ft(()=>import("./SessionSwitcherDropdown-DtNt3qw4.js"),__vite__mapDeps([46,5,10,4,6,1,2,3,7,8,9,11,12])).then(e=>({default:e.SessionSwitcherDropdown}))),wy=({onToggleLeftDrawer:e,onToggleRightDrawer:t,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:i,tabletGitHubTabsAvailable:l=!1})=>{Kt("ui.header.render");const c=de(O=>O.setSessionSwitcherOpen),d=de(O=>O.toggleSidebar),u=de(O=>O.isSidebarOpen),f=de(O=>O.activeMainTab),p=de(O=>O.setActiveMainTab),x=de(O=>O.shortcutOverrides);de(O=>O.timeFormatPreference),Os();const y=Te(O=>!!O.newSessionDraft?.open),m=Te(O=>O.currentSessionId),h=qa(m??""),b=Du(m),g=a.useMemo(()=>{if(!b)return null;const O=b;return{title:b.title??null,directory:O.directory??null,created:b.time?.created??null,slug:O.slug??null,shareUrl:b.share?.url??null,parentId:b.parentID??null,messageCount:typeof b.messageCount=="number"?b.messageCount:null}},[b]),S=dt(ro(O=>{if(!O.activeProjectId)return null;const ie=O.projects.find(ye=>ye.id===O.activeProjectId);return ie?{id:ie.id,path:ie.path,label:ie.label}:null})),v=on(O=>O.homeDirectory),E=a.useMemo(()=>{if(!S)return null;const O=S.label?.trim();if(O)return O;const ie=S.path.split(/[\\/]/).filter(Boolean);return ie[ie.length-1]??null},[S]),{isMobile:k}=dn(),{enabled:C}=Ko(),j=!!(C&&i&&o!==void 0),w=a.useMemo(()=>[...jb(l)],[l]),[N,M]=a.useState(!1),F=a.useRef(null),[$,U]=a.useState(()=>typeof window>"u"?!1:rn()),K=a.useMemo(()=>nl(),[]),L=Pu(),[D,R]=a.useState(!1),I=a.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),T=Ja(),W=a.useMemo(()=>{if(typeof window>"u")return null;const O=window.__PICHAMBER_MACOS_MAJOR__;if(typeof O=="number"&&Number.isFinite(O)&&O>0)return O;if(typeof navigator>"u")return null;const ie=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!ie)return null;const ye=Number.parseInt(ie[1],10),Z=Number.parseInt(ie[2],10);return Number.isNaN(ye)?null:ye===10?Z:ye},[]);Re.useEffect(()=>{typeof window>"u"||U(rn())},[]);const G=de(O=>O.isSessionSwitcherOpen),[B,be]=a.useState(!1),[V,Ce]=a.useState("Local"),[De,H]=a.useState(!0),[z,Q]=a.useState(()=>lr(null)),[X,ne]=a.useState(!1),[we,me]=a.useState(null),[q,te]=a.useState(!1),[le,Ae]=a.useState(null),Se=a.useRef(0),Ge=a.useMemo(()=>tx(V),[V]),Y=a.useCallback(async()=>{if(typeof window>"u"||!$)return;const O=Xe(),ie=()=>Xe()===O;try{const ye=await Mt("/api/version");if(!ie())return;const Z=ye.ok?await ye.json().catch(()=>null):null;if(!ie())return;if(Q(lr(Z)),dr()){Ce("Local"),H(!0);return}H(!1);const Ve=await af();if(!ie())return;const qe=lf(),Et=cf([df(qe),...Ve.hosts]);if(Et.id===uf){Ce("Local"),H(!0);return}Ce(ff(Et.label.trim()||"Instance"))}catch{ie()&&(Ce("Local"),H(!0),Q(lr(null)))}},[$]);Re.useEffect(()=>(Y(),Bn(()=>{Se.current+=1,me(null),Ae(null),te(!1),ne(!1),Y()})),[Y]);const ce=a.useCallback(async()=>{const O=Se.current+1;Se.current=O;const ie=Xe(),ye=()=>Se.current===O&&Xe()===ie;if(De){me(null),Ae(null);return}te(!0),Ae(null);try{const Z=new URLSearchParams({appType:"web",instanceMode:"remote"}),Ve=await Mt(`/api/pi/update-check?${Z.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!Ve.ok)throw new Error(`Server responded with ${Ve.status}`);const qe=await Ve.json();if(!ye())return;me({available:qe.available??!1,version:qe.version,currentVersion:qe.currentVersion??"unknown",body:qe.body,nextSuggestedCheckInSec:typeof qe.nextSuggestedCheckInSec=="number"?qe.nextSuggestedCheckInSec:void 0,packageManager:qe.packageManager,updateCommand:qe.updateCommand,channel:qe.channel==="rc"?"rc":"stable"})}catch(Z){if(!ye())return;me(null),Ae(Z instanceof Error?Z.message:"Failed to check remote instance updates")}finally{ye()&&te(!1)}},[De]);a.useEffect(()=>wh(()=>{De||ce()}),[ce,De]),a.useEffect(()=>{Se.current+=1,me(null),Ae(null),te(!1),ne(!1)},[De,V]),a.useEffect(()=>{if(!$||De)return;const O=3e3,ie=3600*1e3;let ye=!1,Z=null;const Ve=qe=>{Z=window.setTimeout(()=>{if(ye||typeof document<"u"&&document.visibilityState!=="visible"){Ve(ie);return}ce().finally(()=>{ye||Ve(ie)})},qe)};return Ve(O),()=>{ye=!0,Z!==null&&window.clearTimeout(Z)}},[ce,De,V,$]);const re=a.useCallback(()=>{if(we?.available){ne(!0);return}ce()},[ce,we?.available]),ue=m?g??null:null,ve=a.useRef(null),[Le,xe]=a.useState(0);a.useEffect(()=>{if(!m){ve.current&&(ve.current=null,xe(Z=>Z+1));return}if(ue){ve.current={sessionId:m,session:ue,expiresAt:Date.now()+2e3};return}const O=ve.current;if(!O||O.sessionId!==m)return;const ie=O.expiresAt-Date.now();if(ie<=0){ve.current=null,xe(Z=>Z+1);return}const ye=window.setTimeout(()=>{ve.current?.sessionId===m&&(ve.current=null),xe(Z=>Z+1)},ie);return()=>{window.clearTimeout(ye)}},[m,ue]);const se=(()=>{if(ue)return ue;if(!m)return null;const O=ve.current;return O&&O.sessionId===m&&O.expiresAt>Date.now()?O.session:null})(),pe=a.useMemo(()=>{const O=typeof se?.directory=="string"?se.directory:"";return Sn(O||"")},[se?.directory]),fe=Te(O=>O.newSessionDraft?.open?Sn(O.newSessionDraft.directoryOverride??""):""),je=a.useMemo(()=>Ab({sessionDirectory:pe,draftDirectory:fe,isNewSessionDraftOpen:y}),[fe,y,pe]),We=Ha(je||null),Ie=a.useMemo(()=>Nb({activeProjectLabel:E,openDirectory:je,homeDirectory:v}),[E,v,je]),Ye=!!(Ie||We),oe=a.useMemo(()=>m?xs(se,"Untitled session"):Ie??"PiChamber",[se,m,Ie]),Fe=Mu(),st=Te(O=>O.updateSessionTitle),bt=Te(O=>O.archiveSessions),Qe=Te(O=>O.deleteSessions),[rt,ot]=a.useState(!1),[qt,Tt]=a.useState(!1),et=a.useRef(!1),[Ct,ss]=a.useState(""),[kt,At]=a.useState(null),Ft=a.useRef(null);a.useEffect(()=>{et.current=!1,Tt(!1),ot(!1),ss(""),At(null)},[m]);const xt=a.useCallback(()=>{m&&(ss(se?.title?.trim()||oe),ot(!0))},[se?.title,m,oe]),Je=a.useCallback(async()=>{if(!m)return;const O=Ct.trim();O&&O!==se?.title?.trim()&&await st(m,O),ot(!1)},[se?.title,m,Ct,st]);a.useEffect(()=>{if(!rt)return;const O=ie=>{const ye=ie.target;(!ye||!Ft.current?.contains(ye))&&Je()};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[rt,Je]);const Lt=a.useCallback(()=>{m&&ws(m).then(O=>{ae[O.ok?"success":"error"](O.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>ae.error("Failed to copy session ID"))},[m]),Yt=a.useCallback(async()=>{if(!m||!je){ae.error("Nothing to export");return}try{await Fe.syncSession(m)}catch{ae.error("Failed to load the complete session history");return}const O=[];if(O.length===0){ae.error("Nothing to export");return}const ie=nc(O,se?.title??null),ye=ic(se?.title??null);await oc(ie,ye)||rc(ie,ye),ae.success("Session exported")},[se?.title,m,je,Fe]);h?.type==="busy"||h?.type;const us=a.useCallback(async()=>{if(!m||!kt)return;const O=Tu(),ie=[m];for(let qe=0;qe<ie.length;qe+=1){const Et=ie[qe];for(const pt of O)pt.parentID===Et&&!ie.includes(pt.id)&&ie.push(pt.id)}const ye=kt;if(At(null),(ye==="archive"?await bt(ie):await Qe(ie)).failedIds.length>0){ae.error(ye==="archive"?"Failed to archive session":"Failed to delete session");return}ae.success(ye==="archive"?"Session archived":"Session deleted")},[bt,m,Qe,kt]),ke=de(O=>O.isArchivePageOpen),Be=a.useMemo(()=>ke?{title:"Archive",subtitle:null}:null,[ke]),ge=a.useMemo(()=>Sn(je||S?.path||""),[S?.path,je]),Oe=a.useCallback(()=>{ge&&ws(ge).then(O=>{ae[O.ok?"success":"error"](O.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>ae.error("Failed to copy working directory"))},[ge]),_e=a.useMemo(()=>S?{id:S.id,path:S.path}:null,[S]),ht=a.useRef(null);a.useEffect(()=>{!_e||!ge||(ht.current={projectRef:_e,directory:ge})},[ge,_e]);const yt=a.useMemo(()=>_e&&ge?{projectRef:_e,directory:ge}:ht.current,[ge,_e]),nt=a.useCallback(()=>{if(typeof document>"u")return;const O=document.activeElement;if(!O)return;const ie=O.tagName;(ie==="INPUT"||ie==="TEXTAREA"||ie==="SELECT"||O.isContentEditable)&&O.blur()},[]),ns=a.useCallback(()=>{if(k){nt(),c(!G);return}d()},[nt,k,G,c,d]),rs=a.useCallback(()=>{En("desktop_open_draft_mini_chat_window",{directory:Sn(je||S?.path||""),projectId:S?.id??null,apiBaseUrl:ho(),clientToken:fo()}).catch(O=>{console.warn("[header] failed to open draft mini chat window",O)})},[S?.id,S?.path,je]),Ze=a.useCallback(()=>{if(y){rs();return}m&&En("desktop_open_session_mini_chat_window",{sessionId:m,directory:Sn(je||S?.path||""),apiBaseUrl:ho(),clientToken:fo()}).catch(O=>{console.warn("[header] failed to open session mini chat window",O)})},[S?.path,m,rs,y,je]),Ot=un,lt=Vh,wt=a.useMemo(()=>n?"sessions":j?r&&o?o:null:r?"git":f,[f,j,n,r,o]),vt=a.useCallback(()=>{n&&e&&e(),r&&t&&t(),!e&&G&&c(!1)},[G,n,e,t,r,c]),_s=a.useCallback(()=>{e?.()},[e]),zs=a.useCallback(()=>{t?.()},[t]),Cs=a.useMemo(()=>$&&I&&!D?"5.5rem":L?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!$||T?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[$,D,I,L,T]);Re.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Cs)},[Cs]);const fs=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",Nt=u?"0px":$&&T?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":C?"2.75rem":"2.5rem";Re.useEffect(()=>{if(!$||!I){R(!1);return}let O=!1;const ie=async()=>{try{const Z=await En("desktop_is_window_fullscreen");O||R(Z===!0)}catch{O||R(!1)}},ye=()=>{ie()};return ie(),window.addEventListener("pichamber:window-resized",ye),()=>{O=!0,window.removeEventListener("pichamber:window-resized",ye)}},[$,I]);const hs=a.useMemo(()=>!$||!I||W===null?"":W>=26?"h-12":W<=15?"h-14":"",[$,I,W]),St=a.useMemo(()=>{if(!($&&!T))return{paddingRight:"calc(0.75rem + var(--oc-wco-right-inset, 0px))",minHeight:"max(3rem, var(--oc-wco-titlebar-height, 0px))",height:"max(3rem, var(--oc-wco-titlebar-height, 0px))"}},[$,T]),os=a.useCallback(()=>{if(typeof document>"u")return;const O=F.current?.getBoundingClientRect().height;if(O){const ie=`${O}px`,ye=document.documentElement.style;ye.getPropertyValue("--oc-header-height")!==ie&&ye.setProperty("--oc-header-height",ie)}},[]);Re.useEffect(()=>{if(typeof window>"u")return;os();const O=F.current;if(!O||typeof ResizeObserver>"u")return()=>{};let ie=0;const ye=()=>{ie||(ie=requestAnimationFrame(()=>{ie=0,os()}))},Z=new ResizeObserver(ye);return Z.observe(O),window.addEventListener("resize",ye),window.addEventListener("orientationchange",ye),()=>{ie&&cancelAnimationFrame(ie),Z.disconnect(),window.removeEventListener("resize",ye),window.removeEventListener("orientationchange",ye)}},[os]),Re.useEffect(()=>{os()},[os,k,hs]);const is=a.useCallback(async O=>{const ie=O.target;ie.closest(".app-region-no-drag")||ie.closest("button, a, input, select, textarea")||O.button===0&&$&&await Fu()},[$]),it=a.useMemo(()=>k?[{id:"chat",label:"Chat",icon:"chat-4"},{id:"diff",label:"Diff",icon:"diff"},{id:"files",label:"Files",icon:"file-text"},{id:"terminal",label:"Terminal",icon:"terminal-box"},{id:"context",label:"Context",icon:"file-list-2"},{id:"diagram",label:"Diagram",icon:"file"}]:[],[k]),Bt=a.useCallback(O=>Wo(cr(O,x)),[x]);Re.useEffect(()=>{!k&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&p("chat")},[f,k,p]),Re.useEffect(()=>{const O=ie=>{if(hf(ie)&&!ie.shiftKey&&!ie.altKey){const ye=parseInt(ie.key,10);ye>=1&&ye<=it.length&&(ie.preventDefault(),k&&(nt(),vt()),p(it[ye-1].id))}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[nt,vt,k,p,it]),Re.useEffect(()=>{const O=ie=>{const ye=cr("toggle_services_menu",x);if(mf(ie,ye)){ie.preventDefault(),B?be(!1):(be(!0),Y());return}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[x,B,Y]);const Us=O=>{const ie=f===O.id,ye=O.icon==="diff",Z=ye?null:O.icon,Ve=O.id==="chat",qe=pt=>ye?s.jsx(xa,{size:pt}):Z?s.jsx(P,{name:Z,className:`h-${pt/4} w-${pt/4}`}):null,Et=s.jsxs("button",{type:"button",onClick:()=>p(O.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",ie?"app-region-no-drag bg-interactive-selection text-interactive-selection-foreground shadow-none":"app-region-no-drag text-muted-foreground hover:bg-interactive-hover/50 hover:text-foreground","focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary",Ve&&!k&&"min-w-[100px] justify-center"),"aria-label":O.label,"aria-selected":ie,role:"tab",children:[k?qe(20):s.jsxs(s.Fragment,{children:[qe(16),s.jsx("span",{className:"header-tab-label",children:O.label})]}),O.badge!==void 0&&O.badge>0&&s.jsx("span",{className:"header-tab-badge typography-micro text-status-info font-medium",children:O.badge})]});return s.jsx(a.Fragment,{children:Et},O.id)},It=s.jsxs(s.Fragment,{children:[s.jsx(Db,{directory:ge,className:"mr-1"}),$?s.jsx(Zb,{isDesktopApp:$,currentInstanceLabel:V,compactCurrentInstanceLabel:Ge,currentInstanceIsLocal:De,currentInstanceIcon:z,isDesktopServicesOpen:B,setIsDesktopServicesOpen:be,refreshCurrentInstanceLabel:Y,shortcutLabel:Bt,remoteUpdateInfo:we,remoteUpdateChecking:q,remoteUpdateError:le,onOpenRemoteUpdate:re}):s.jsx(Jb,{open:B,onOpenChange:be}),s.jsx(Xb,{isMobile:k})]}),mn=K&&(y||!!m),$s=()=>s.jsxs("div",{onMouseDown:is,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",hs),style:St,role:"tablist","aria-label":"Main navigation",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:fs}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Nt}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Be?s.jsxs("div",{className:"mr-3 flex min-w-0 items-center gap-1.5 px-1 py-0.5 -my-0.5 text-left",children:[s.jsx("span",{className:"truncate typography-ui-label text-[14px] font-normal leading-tight text-foreground max-w-full",children:Be.title}),Be.subtitle?s.jsxs(s.Fragment,{children:[s.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),s.jsx("span",{className:"truncate typography-ui-label font-normal leading-tight text-muted-foreground/75 max-w-full",children:Be.subtitle})]}):null]}):s.jsxs("div",{className:"app-region-no-drag mr-3 flex min-w-0 max-w-full items-center gap-0.5 py-0.5 -my-0.5 text-left",children:[u?null:s.jsx(a.Suspense,{fallback:s.jsx("button",{type:"button",className:Ot,"aria-label":"Open session switcher",children:s.jsx(P,{name:"history",className:"h-[18px] w-[18px]"})}),children:s.jsx(sx,{align:"start",children:s.jsx("button",{type:"button",className:Ot,"aria-label":"Open session switcher",children:s.jsx(P,{name:"history",className:"h-[18px] w-[18px]"})})})}),s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[rt?s.jsxs("form",{ref:Ft,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:O=>{O.preventDefault(),Je()},children:[s.jsx("input",{value:Ct,onChange:O=>ss(O.target.value),autoFocus:!0,onKeyDown:O=>{O.stopPropagation(),O.key==="Escape"&&ot(!1)},placeholder:"Rename",className:"min-w-0 flex-1 bg-transparent typography-ui-label font-normal leading-tight outline-none placeholder:text-muted-foreground"}),s.jsx("button",{type:"submit","aria-label":"Save session name",title:"Save session name",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(P,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:()=>ot(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(P,{name:"close",className:"size-4"})})]}):s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:y?"New session":oe}),Ye?s.jsxs(s.Fragment,{children:[s.jsx("span",{"aria-hidden":"true",className:"h-3 w-px shrink-0 bg-border"}),s.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 truncate typography-ui-label font-normal leading-tight text-muted-foreground/75",children:[Ie?s.jsx("span",{className:"truncate",children:Ie}):null,We?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(P,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-muted-foreground/70"}),s.jsx("span",{className:"truncate",children:We})]}):null]})]}):null]}),s.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:m&&!y&&!rt?s.jsxs(Wt,{open:qt,onOpenChange:Tt,onOpenChangeComplete:O=>{!O&&et.current&&(et.current=!1,xt())},children:[s.jsx(Gt,{asChild:!0,children:s.jsx(Ne,{variant:"ghost",size:"xs",className:"h-[18px] w-6 px-0 text-muted-foreground hover:bg-transparent hover:text-foreground","aria-label":"Open session actions",children:s.jsx(P,{name:"more",className:"size-4"})})}),s.jsxs(Ht,{align:"end",className:"min-w-[190px]",children:[s.jsxs(ut,{onClick:()=>{et.current=!0},children:[s.jsx(P,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),s.jsxs(ut,{onClick:Lt,children:[s.jsx(P,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),s.jsxs(ut,{onClick:Oe,disabled:!ge,children:[s.jsx(P,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),s.jsx(nn,{}),s.jsxs(ut,{onClick:()=>{Yt()},children:[s.jsx(P,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),s.jsx(nn,{}),s.jsxs(ut,{onClick:()=>At("archive"),children:[s.jsx(P,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),s.jsxs(ut,{className:"text-destructive focus:text-destructive",onClick:()=>At("delete"),children:[s.jsx(P,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),it.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:it.map(O=>Us(O))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Rl,{}),yt?s.jsx(va,{projectRef:yt.projectRef,directory:yt.directory,className:"mr-1"}):null,s.jsx(Qh,{visible:mn,title:y?"New Mini Chat Window":"Open Session in Mini Chat",ariaLabel:y?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:Ze,className:_(Ot,"mr-1"),Icon:"picture-in-picture-2"}),It,s.jsx(Lu,{visible:T})]})]})]}),Ks=()=>s.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[C&&s.jsxs(s.Fragment,{children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:fs}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:Nt}})]}),!C&&s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?s.jsx("button",{type:"button",onClick:_s,className:_(lt,wt==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:s.jsx(P,{name:"layout-left",className:"h-5 w-5"})}):G?s.jsx("button",{type:"button",onClick:()=>c(!1),className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Back",children:s.jsx(P,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:ns,className:"app-region-no-drag h-9 w-9 p-2 text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md active:bg-interactive-active","aria-label":"Open sessions",children:s.jsx(P,{name:"play-list-add",className:"h-5 w-5"})}),!e&&G&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!G||!!e)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!j&&s.jsx("div",{className:"flex min-w-0 flex-1 overflow-x-auto overflow-y-hidden scrollbar-hidden touch-pan-x overscroll-x-contain","data-no-drawer-swipe":"true",children:s.jsx("div",{className:"flex w-max items-center gap-1 pr-1",children:s.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Main navigation",children:it.map(O=>{const ie=f===O.id,ye=O.icon==="diff",Z=ye?null:O.icon;return s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{k&&(nt(),vt()),p(O.id)},"aria-label":O.label,"aria-selected":ie,role:"tab",className:_(lt,"relative rounded-lg",wt===O.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ye?s.jsx(xa,{className:"h-5 w-5"}):Z?s.jsx(P,{name:Z,className:"h-5 w-5"}):null,O.badge!==void 0&&O.badge>0&&s.jsx("span",{className:"absolute -top-1 -right-1 text-[10px] font-semibold text-primary",children:O.badge}),O.showDot&&s.jsx("span",{className:"absolute top-1.5 right-1.5 h-2 w-2 rounded-full bg-primary","aria-label":"Changes available"})]})}),s.jsx(Ke,{children:s.jsx("p",{children:O.label})})]},O.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[j&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"flex items-center gap-0.5 rounded-lg bg-[var(--surface-muted)]/50 p-0.5",role:"tablist","aria-label":"Workspace",children:w.map(O=>{const ie=r&&o===O.id;return s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>{k&&(nt(),vt()),M(!1),i?.(O.id)},"aria-label":O.label,"aria-selected":ie,role:"tab",className:_(lt,"relative h-11 w-11 rounded-lg",ie&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(P,{name:O.icon,className:"h-5 w-5"})})}),s.jsx(Ke,{children:s.jsx("p",{children:O.label})})]},O.id)})}),s.jsx(Yh,{open:N,onOpenChange:M,currentSessionId:m,effectiveDirectory:je||null,isNewSessionDraftOpen:y})]}),yt&&s.jsx(va,{projectRef:yt.projectRef,directory:yt.directory,compact:!0,allowMobile:!0,className:"h-9"}),t&&!j?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:zs,className:_(lt,"relative",wt==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(P,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(Ke,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),ks=_("header-safe-area relative z-10 bg-background",k&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:F,className:ks,style:{"--padding-scale":"1"},children:k?Ks():$s()}),s.jsx(ex,{action:kt,onClose:()=>At(null),sessionTitle:oe,onConfirm:()=>{us()}}),s.jsx(vl,{open:X,onOpenChange:ne,info:we,downloading:!1,downloaded:!1,progress:null,error:le,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},Sa="app-region-no-drag inline-flex h-8 w-8 items-center justify-center gap-2 rounded-md typography-ui-label font-medium text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary hover:bg-interactive-hover transition-colors",nx="app-region-no-drag flex size-10 shrink-0 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-interactive-hover hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary disabled:pointer-events-none disabled:opacity-50",vy=()=>{const e=de(y=>y.isSidebarOpen),t=de(y=>y.toggleSidebar),n=de(y=>y.shortcutOverrides),r=a.useRef(null),o=a.useRef(null),i=Wo(cr("toggle_sidebar",n)),l=Ja(),{enabled:c}=Ko(),d=!e,u=l,f=d||u,p=u,x=a.useCallback(()=>{En("desktop_show_app_menu").catch(y=>{console.warn("[titlebar] failed to open app menu",y)})},[]);return a.useEffect(()=>{if(typeof document>"u")return;const y=v=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(v)}px`)},m=v=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(v)}px`)};if(!p)return;const h=o.current,b=r.current;if(!h||!b){y(0),m(0);return}const g=()=>{const v=Math.max(h.getBoundingClientRect().width,h.scrollWidth);y(v),m(b.getBoundingClientRect().width)};if(g(),typeof ResizeObserver>"u")return;const S=new ResizeObserver(g);return S.observe(h),S.observe(b),()=>{S.disconnect()}},[p]),f?s.jsx("div",{ref:r,className:"app-region-no-drag absolute left-0 z-40 flex select-none items-center pr-2",style:{top:"var(--oc-safe-area-top, 0px)",height:"calc(var(--oc-header-height, 3rem) - var(--oc-safe-area-top, 0px))",paddingLeft:"var(--oc-titlebar-left-inset, 0.75rem)"},children:s.jsxs("div",{ref:o,className:"flex items-center gap-2",children:[u?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:x,"aria-label":"Open PiChamber menu",className:_(Sa,"shrink-0"),children:s.jsx(P,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(Ke,{children:s.jsx("p",{children:"PiChamber menu"})})]}):null,d?s.jsxs(Ue,{children:[s.jsx($e,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,"aria-label":"Open sessions",className:_(c?nx:Sa,"shrink-0"),children:s.jsx(P,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),s.jsx(Ke,{children:s.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},ja=200,rx="cubic-bezier(0.22, 1, 0.36, 1)",Sy=e=>{const t=a.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=a.useState(e),[o,i]=a.useState(e);return a.useLayoutEffect(()=>{if(t){i(e),r(e);return}if(e){i(!0),r(!1);let c=0;const d=window.requestAnimationFrame(()=>{c=window.requestAnimationFrame(()=>r(!0))});return()=>{window.cancelAnimationFrame(d),window.cancelAnimationFrame(c)}}r(!1);const l=window.setTimeout(()=>i(!1),ja);return()=>window.clearTimeout(l)},[e,t]),{slidIn:n,layoutVisible:o,prefersReducedMotion:t,transition:t?"none":`transform ${ja}ms ${rx}`}},jy=()=>{ol()},Cy=e=>{Te.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),de.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),he.getState().clearAll(),ol(),on.getState().resetForRuntimeSwitch(),Ou.getState().resetForRuntimeSwitch(),Bu.getState().resetForRuntimeSwitch(),_u(),pf(),gf(),Wu(),zu.getState().resetForRuntimeSwitch(),$t.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),dt.getState().resetForRuntimeSwitch(),Uu(),$u(),Pf.getState().reset(),bf.getState().resetForRuntimeSwitch(),za.getState().resetForRuntimeSwitch(e.runtimeKey),lo.getState().resetForRuntimeSwitch(e.runtimeKey),xf(),Ts.getState().resetForRuntimeSwitch(e.runtimeKey),Ku.getState().resetForRuntimeSwitch(),Zt.getState().resetForRuntimeSwitch(),mt.getState().resetForRuntimeSwitch(e.runtimeKey),yf.getState().resetForRuntimeSwitch(e.runtimeKey),Te.getState().restoreForRuntimeSwitch(e.runtimeKey),de.getState().restoreForRuntimeSwitch(e.runtimeKey);const t=de.getState();bo({sessionId:Te.getState().currentSessionId,tab:t.activeMainTab,isSettingsOpen:t.isSettingsDialogOpen,settingsPath:t.settingsPage,diffFile:t.pendingDiffFile},{replace:!0,force:!0})};export{Zx as $,qx as A,Nr as B,Hx as C,da as D,Ps as E,kx as F,Jl as G,wy as H,$h as I,Kh as J,_i as K,yy as L,El as M,Qf as N,Sx as O,As as P,ys as Q,Zt as R,uy as S,py as T,Ql as U,_l as V,vx as W,On as X,Bl as Y,Ax as Z,kl as _,Yh as a,Zf as a$,Yx as a0,ey as a1,cy as a2,dy as a3,Uh as a4,ny as a5,ty as a6,Qx as a7,sy as a8,oy as a9,Rn as aA,Ex as aB,mh as aC,yh as aD,Ox as aE,Cl as aF,zn as aG,zx as aH,xh as aI,_n as aJ,jl as aK,Lx as aL,Nx as aM,hh as aN,Kx as aO,Ux as aP,$x as aQ,Wx as aR,_x as aS,Rx as aT,Dx as aU,Px as aV,Ph as aW,Tx as aX,Sl as aY,Xf as aZ,ph as a_,iy as aa,ay as ab,ly as ac,ry as ad,Eo as ae,Ji as af,Ns as ag,vn as ah,hn as ai,np as aj,fn as ak,Jx as al,jr as am,Xx as an,Vx as ao,bh as ap,Bx as aq,fh as ar,Ix as as,Gx as at,Fx as au,vl as av,qo as aw,Mx as ax,gh as ay,Oh as az,Cn as b,xx as b0,Dg as c,fy as d,ir as e,jb as f,hy as g,sb as h,Tg as i,gy as j,uc as k,Sy as l,xy as m,vy as n,jy as o,Cy as p,jx as q,by as r,my as s,Cx as t,Hh as u,wx as v,bx as w,yx as x,kr as y,Ar as z};