@pi-chamber/web 1.0.7 → 1.0.8-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/AgentsSurface-CcWBqAWV.js +1 -0
- package/dist/assets/ChoicesArtifact-Kk-qvrSB.js +1 -0
- package/dist/assets/DiagramView-DZUBo1uP.js +1 -0
- package/dist/assets/{DiffView-BxW6BuOC.js → DiffView-CiZy4jFA.js} +6 -6
- package/dist/assets/FileSaveConflictDialog-DZ9NDwOO.js +3 -0
- package/dist/assets/FilesView-DqiZ9kw9.js +6 -0
- package/dist/assets/GitHubDetailScaffold-DM2DH7o8.js +11 -0
- package/dist/assets/GitHubLinkPicker-ChB8NZ1h.js +1 -0
- package/dist/assets/GitHubListPrimitives-CibDiJGq.js +1 -0
- package/dist/assets/{GitView-DD33ngnM.js → GitView--EaZQrBr.js} +5 -5
- package/dist/assets/{IssuesSurface-BAY_eyX5.js → IssuesSurface-CySTpaD1.js} +3 -3
- package/dist/assets/{JsonTreeView-DpXbUrAl.js → JsonTreeView-_yMHKKQZ.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-Cn63lAmn.js → MarkdownRendererImpl-D_-2fQw0.js} +3 -3
- package/dist/assets/PatchDiff-bHObDlhD.js +1 -0
- package/dist/assets/PierreDiffViewer-UY7Cse-s.js +147 -0
- package/dist/assets/PullRequestsSurface-iXy6chwc.js +2 -0
- package/dist/assets/{SessionSwitcherContent-CscYekC1.js → SessionSwitcherContent-DJGCa_wN.js} +1 -1
- package/dist/assets/SessionSwitcherDropdown-CDOX-5Y2.js +2 -0
- package/dist/assets/SessionUnreadDot-Dwc3MdvA.js +1 -0
- package/dist/assets/SettingsView-DA-U9lsj.js +11 -0
- package/dist/assets/{SettingsWindow-gxjULdm1.js → SettingsWindow-CUg49Mfh.js} +1 -1
- package/dist/assets/{StickyHorizontalScrollbar-DNsbTLS7.js → StickyHorizontalScrollbar-CMbTn5WQ.js} +1 -1
- package/dist/assets/SubagentsArtifact-DUZX9tDe.js +1 -0
- package/dist/assets/ToolOutputDialog-BuZZaRw4.js +8 -0
- package/dist/assets/ToolPartDiffPreview-CKncG6i2.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-BrbPymTL.js → VirtualizedFileDiff-BGZiLPe_.js} +4 -4
- package/dist/assets/{Virtualizer-okhy9Aq3.js → Virtualizer-PxblpQn6.js} +1 -1
- package/dist/assets/VisualFrame-DBZkHFnG.js +22 -0
- package/dist/assets/VisualsArtifact-Bq0vMO-i.js +1 -0
- package/dist/assets/{collapsible-D6qdoq7-.js → collapsible-Bro9KrfM.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-G4csGiKs.js → computeVirtualFileMetrics-DJQqK49u.js} +2 -2
- package/dist/assets/contextFileOpenGuard-ByWK3Sru.js +1 -0
- package/dist/assets/{fileTreeStatus-Bskhj4qT.js → fileTreeStatus-CyJ3TOYD.js} +2 -2
- package/dist/assets/gitStatusPredicates-BsXrwngT.js +1 -0
- package/dist/assets/githubLink-g2bmC0qi.js +10 -0
- package/dist/assets/index-B_L9GVYw.css +1 -0
- package/dist/assets/{index-ComwtfT4.js → index-C9rUUQ_Y.js} +1 -1
- package/dist/assets/index-CKKWVoND.js +11 -0
- package/dist/assets/{main-DoiadX0a.js → main-DT-4_fhe.js} +2 -2
- package/dist/assets/main-DsLMU9CT.js +137 -0
- package/dist/assets/{markdownCore-DczkEluO.js → markdownCore-QmM_aOnZ.js} +2 -2
- package/dist/assets/{miniChat-Ck6MEZ9Q.js → miniChat-BqGslD2z.js} +2 -2
- package/dist/assets/{mobile-BucKVm1P.js → mobile-C5JOcDIC.js} +2 -2
- package/dist/assets/{nativeFileSave-Cp9i5QGd.js → nativeFileSave-DSMsJqXM.js} +1 -1
- package/dist/assets/pi-session-focus-preference-Cc_S4zi1.js +9 -0
- package/dist/assets/{renderDiffWithHighlighter-PL82AR81.js → renderDiffWithHighlighter-BXhnIAHg.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-CiSkecEE.js +2 -0
- package/dist/assets/{renderFileWithHighlighter-CYgfbA4F.js → renderFileWithHighlighter-CK29YZtC.js} +1 -1
- package/dist/assets/renderMobileApp-C4JuoxsZ.js +11 -0
- package/dist/assets/runtimeEndpointReset-Dwj-jCDS.js +66 -0
- package/dist/assets/runtimeSurface-0K7vuUpd.js +1 -0
- package/dist/assets/selection-CnYkEsu_.js +1 -0
- package/dist/assets/useAppFontEffects-CV5UyTRw.js +226 -0
- package/dist/assets/useGitHubRemoteSearch-CgP-zEBj.js +1 -0
- package/dist/assets/useSwitcherItems-C8G5F0hs.js +1 -0
- package/dist/assets/{vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js → vendor-aparajita-capacitor-secure-storage-DUoR8t1G.js} +1 -1
- package/dist/assets/{vendor-base-ui-BCqPBzDj.js → vendor-base-ui-DE6jnTiC.js} +1 -1
- package/dist/assets/{vendor-boot-3SaHYVb1.js → vendor-boot-D-KEJjsM.js} +29 -29
- package/dist/assets/{vendor-capacitor-app-NbQ-WiPS.js → vendor-capacitor-app-CO5jS31X.js} +1 -1
- package/dist/assets/{vendor-capacitor-keyboard-CgrHt8iN.js → vendor-capacitor-keyboard-335osRpd.js} +1 -1
- package/dist/assets/{vendor-capacitor-status-bar-CWt0OF5t.js → vendor-capacitor-status-bar-lB9y4H9d.js} +1 -1
- package/dist/assets/{vendor-codemirror-autocomplete-WThuuUAz.js → vendor-codemirror-autocomplete-BKvJ8PfM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-angular-BbLGCxF6.js → vendor-codemirror-lang-angular-wjCUD0bM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-cpp-Cceks-9O.js → vendor-codemirror-lang-cpp-LJzlG8sJ.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-css-D1wpUg3Z.js → vendor-codemirror-lang-css-DoEEdEpW.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-go-Cv0zXHHM.js → vendor-codemirror-lang-go-DexsLPb8.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-html-DbL8oT9H.js → vendor-codemirror-lang-html-h25V-Hp5.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-java-CNugenuC.js → vendor-codemirror-lang-java-D8xoT8cv.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-javascript-Bx_FIyZF.js → vendor-codemirror-lang-javascript-DF3GDYje.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-jinja-DDGjB3Zq.js → vendor-codemirror-lang-jinja-BboTHFdn.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-json-DIvqf9Pb.js → vendor-codemirror-lang-json-DCqvG1nE.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-less-D8r9dGG1.js → vendor-codemirror-lang-less-B8ZrSKJM.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-liquid-B24mguYi.js → vendor-codemirror-lang-liquid-DF9S5m5F.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-markdown-v3yG2sbf.js → vendor-codemirror-lang-markdown-6BNbCEPe.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-php-BcZGalqy.js → vendor-codemirror-lang-php-CQwAz1Hd.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-python-b-JqEwQy.js → vendor-codemirror-lang-python-DQym-8Tx.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-rust-B1uZxDW-.js → vendor-codemirror-lang-rust-DknzOTkO.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sass-DqPrngKp.js → vendor-codemirror-lang-sass-dB0Rm5HI.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-sql-UyCnpt-k.js → vendor-codemirror-lang-sql-CCQUnnD-.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-vue-xDwYkovV.js → vendor-codemirror-lang-vue-h1M5bF00.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-wast-CF3169p_.js → vendor-codemirror-lang-wast-DWgtlGfu.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-xml-FCtVhuOb.js → vendor-codemirror-lang-xml-DncwoCUY.js} +1 -1
- package/dist/assets/{vendor-codemirror-lang-yaml-g0sPmAnv.js → vendor-codemirror-lang-yaml-C7QkS5ER.js} +1 -1
- package/dist/assets/{vendor-codemirror-language-data-B03xgzP2.js → vendor-codemirror-language-data-BUZIlm3G.js} +2 -2
- package/dist/assets/{vendor-codemirror-search-Dw3Wpu15.js → vendor-codemirror-search-BlDCaCMK.js} +1 -1
- package/dist/assets/{vendor-lezer-cpp-Cu3E-KUI.js → vendor-lezer-cpp-B4JK1BC1.js} +1 -1
- package/dist/assets/{vendor-lezer-css-Cb8vp67u.js → vendor-lezer-css-DRxDmhcy.js} +1 -1
- package/dist/assets/{vendor-lezer-go-BTsIaOm7.js → vendor-lezer-go-DsUgfmxi.js} +1 -1
- package/dist/assets/{vendor-lezer-html-UQMsUwj-.js → vendor-lezer-html-qr9pUPmM.js} +1 -1
- package/dist/assets/{vendor-lezer-java-BIWrFrAx.js → vendor-lezer-java-6UyNiQiB.js} +1 -1
- package/dist/assets/{vendor-lezer-javascript-BH2Etgoy.js → vendor-lezer-javascript-CUdJ0VGA.js} +1 -1
- package/dist/assets/{vendor-lezer-json-CE-QUCwM.js → vendor-lezer-json-BKYAA8Hu.js} +1 -1
- package/dist/assets/{vendor-lezer-lr-HY6Yc0Vr.js → vendor-lezer-lr-DluApmOX.js} +1 -1
- package/dist/assets/{vendor-lezer-markdown-xFL3Evwf.js → vendor-lezer-markdown-B-uzYzYT.js} +1 -1
- package/dist/assets/{vendor-lezer-php-Cr_mQGrG.js → vendor-lezer-php-DI6PNjlz.js} +1 -1
- package/dist/assets/{vendor-lezer-python-BNRFWCb0.js → vendor-lezer-python-Bj232yb5.js} +1 -1
- package/dist/assets/{vendor-lezer-rust-BvfOK5cU.js → vendor-lezer-rust-DlPG_Yau.js} +1 -1
- package/dist/assets/{vendor-lezer-sass-qoxiLisk.js → vendor-lezer-sass-CBsyWB2A.js} +1 -1
- package/dist/assets/{vendor-lezer-xml--x8SSpqU.js → vendor-lezer-xml-C1FmgtmE.js} +1 -1
- package/dist/assets/{vendor-lezer-yaml-BDo1JaEr.js → vendor-lezer-yaml-DpHmjriG.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-D1Fe7FiY.js → vendor-replit-codemirror-vim-Cvk64got.js} +1 -1
- package/dist/assets/{web-components-CGDpzixf.js → web-components-BpncHjnV.js} +4 -4
- package/dist/index.html +4 -4
- package/dist/mini-chat.html +3 -3
- package/dist/mobile.html +3 -3
- package/package.json +2 -1
- package/plugins/featured.json +12 -0
- package/plugins/registry.json +7 -0
- package/plugins/subagents/LICENSE +25 -0
- package/plugins/subagents/agents/planner.md +36 -0
- package/plugins/subagents/agents/reviewer.md +34 -0
- package/plugins/subagents/agents/scout.md +49 -0
- package/plugins/subagents/agents/worker.md +23 -0
- package/plugins/subagents/extension.js +631 -0
- package/plugins/subagents/extension.test.js +295 -0
- package/plugins/subagents/package.json +41 -0
- package/plugins/visuals/choices.js +168 -0
- package/plugins/visuals/extension.js +90 -0
- package/plugins/visuals/files.js +74 -0
- package/plugins/visuals/package.json +32 -0
- package/server/index.js +103 -24
- package/server/lib/git/DOCUMENTATION.md +4 -0
- package/server/lib/git/service.js +70 -5
- package/server/lib/git/service.test.js +179 -0
- package/server/lib/github/DOCUMENTATION.md +6 -2
- package/server/lib/github/gh-cli.js +35 -9
- package/server/lib/github/gh-cli.test.js +122 -0
- package/server/lib/marketplace/DOCUMENTATION.md +95 -0
- package/server/lib/marketplace/featured.js +176 -0
- package/server/lib/marketplace/featured.test.js +207 -0
- package/server/lib/marketplace/npm-registry.js +255 -0
- package/server/lib/marketplace/npm-registry.test.js +227 -0
- package/server/lib/marketplace/routes.js +64 -0
- package/server/lib/marketplace/routes.test.js +119 -0
- package/server/lib/marketplace/service.js +225 -0
- package/server/lib/marketplace/service.test.js +174 -0
- package/server/lib/notifications/DOCUMENTATION.md +10 -4
- package/server/lib/notifications/pi-notification-watcher.js +95 -33
- package/server/lib/notifications/pi-notification-watcher.test.js +89 -0
- package/server/lib/open-url/DOCUMENTATION.md +2 -1
- package/server/lib/pi/extension-protocol.js +54 -0
- package/server/lib/pi/fixtures/pichamber-gui-demo.ts +12 -13
- package/server/lib/pi/merged-event-stream.js +316 -0
- package/server/lib/pi/merged-event-stream.test.js +95 -0
- package/server/lib/pi/routes-daemon-pool.test.js +348 -0
- package/server/lib/pi/routes-extension-events.test.js +115 -0
- package/server/lib/pi/routes-merged-events.test.js +327 -0
- package/server/lib/pi/routes-sandbox.test.js +1684 -0
- package/server/lib/pi/routes.js +790 -87
- package/server/lib/pi/routes.test.js +381 -1
- package/server/lib/pi/sandbox/DOCUMENTATION.md +68 -0
- package/server/lib/pi/sandbox/launcher.js +122 -0
- package/server/lib/pi/sandbox/launcher.test.js +91 -0
- package/server/lib/pi/sandbox/nono-launcher.js +455 -0
- package/server/lib/pi/sandbox/nono-launcher.test.js +371 -0
- package/server/lib/pi/sandbox/nono-profile-macos.json +20 -0
- package/server/lib/pi/sandbox/nono-profile-wsl2.json +21 -0
- package/server/lib/pi/sandbox/nono-profile.json +22 -0
- package/server/lib/pi/sandbox/project-sandbox-manager.js +1461 -0
- package/server/lib/pi/sandbox/project-sandbox-setting.js +166 -0
- package/server/lib/pi/sandbox/project-sandbox.js +207 -0
- package/server/lib/pi/sandbox/sandbox-routes.js +110 -0
- package/server/lib/pi/sandbox/sandboxed-folders.js +100 -0
- package/server/lib/pi/sandbox/sandboxed-folders.test.js +65 -0
- package/server/lib/pi/sandbox/trust-ask.js +135 -0
- package/server/lib/pi/sandbox/trust-ask.test.js +54 -0
- package/server/lib/pi/sandbox/worktree-ids.js +96 -0
- package/server/lib/pi/sandbox/worktree-ids.test.js +73 -0
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +47 -10
- package/server/lib/pi/session-daemon/daemon-pool.js +157 -0
- package/server/lib/pi/session-daemon/daemon-process.js +10 -1
- package/server/lib/pi/session-daemon/extension-bridge.js +89 -29
- package/server/lib/pi/session-daemon/extension-config.js +902 -0
- package/server/lib/pi/session-daemon/extension-config.test.js +798 -0
- package/server/lib/pi/session-daemon/extension-controls.js +177 -0
- package/server/lib/pi/session-daemon/extension-controls.test.js +181 -0
- package/server/lib/pi/session-daemon/extension-name.js +6 -0
- package/server/lib/pi/session-daemon/extension-name.test.js +5 -0
- package/server/lib/pi/session-daemon/extension-palette.js +146 -0
- package/server/lib/pi/session-daemon/extension-palette.test.js +107 -0
- package/server/lib/pi/session-daemon/extension-replacements.js +138 -0
- package/server/lib/pi/session-daemon/extension-replacements.test.js +116 -0
- package/server/lib/pi/session-daemon/extension-ui-mode.js +30 -0
- package/server/lib/pi/session-daemon/extension-ui-mode.test.js +34 -0
- package/server/lib/pi/session-daemon/pichamber-ui.js +44 -0
- package/server/lib/pi/session-daemon/plugin-host.js +245 -0
- package/server/lib/pi/session-daemon/plugin-host.test.js +192 -0
- package/server/lib/pi/session-daemon/session-daemon-controls.e2e.test.js +205 -0
- package/server/lib/pi/session-daemon/session-daemon-drafts.e2e.test.js +409 -0
- package/server/lib/pi/session-daemon/session-daemon-extension-config.e2e.test.js +196 -0
- package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +137 -6
- package/server/lib/pi/session-daemon/session-daemon-plugins.e2e.test.js +272 -0
- package/server/lib/pi/session-daemon/session-daemon-providers.e2e.test.js +153 -0
- package/server/lib/pi/session-daemon/session-daemon-read-persisted.test.js +167 -0
- package/server/lib/pi/session-daemon/session-daemon.js +927 -108
- package/server/lib/pi/session-daemon/session-daemon.test.js +391 -4
- package/server/lib/pi/session-daemon/session-engine-router.js +7 -0
- package/server/lib/pi/session-daemon/session-engine-router.test.js +20 -0
- package/server/lib/pi/session-daemon/session-idle-residency.test.js +98 -1
- package/server/lib/pi/session-daemon/session-jsonl.js +49 -10
- package/server/lib/pi/session-daemon/session-jsonl.test.js +11 -0
- package/server/lib/pi/session-daemon/session-lease.js +93 -15
- package/server/lib/pi/session-daemon/session-lease.test.js +107 -1
- package/server/lib/pi/session-daemon/supervisor-launcher-stop.test.js +295 -0
- package/server/lib/pi/session-daemon/supervisor-sandbox-nono.e2e.test.js +301 -0
- package/server/lib/pi/session-daemon/supervisor-sandbox.test.js +444 -0
- package/server/lib/pi/session-daemon/supervisor.js +408 -38
- package/server/lib/pi/session-daemon/supervisor.test.js +28 -0
- package/server/lib/pi/settings-store.js +14 -0
- package/server/lib/pi/settings-store.test.js +11 -0
- package/server/lib/pi/ui-settings-store.js +88 -2
- package/server/lib/pi/ui-settings-store.test.js +118 -0
- package/server/lib/plugins/DOCUMENTATION.md +198 -0
- package/server/lib/plugins/daemon-sync.js +88 -0
- package/server/lib/plugins/daemon-sync.supervisor.test.js +83 -0
- package/server/lib/plugins/daemon-sync.test.js +108 -0
- package/server/lib/plugins/impact.js +139 -0
- package/server/lib/plugins/impact.test.js +83 -0
- package/server/lib/plugins/manifest.js +220 -0
- package/server/lib/plugins/manifest.test.js +127 -0
- package/server/lib/plugins/registry.js +59 -0
- package/server/lib/plugins/routes.js +92 -0
- package/server/lib/plugins/routes.test.js +247 -0
- package/server/lib/plugins/service.js +183 -0
- package/server/lib/plugins/store.js +261 -0
- package/server/lib/plugins/store.test.js +188 -0
- package/server/lib/plugins/visuals-extension.test.js +237 -0
- package/server/lib/server/cross-process-lock.js +28 -3
- package/server/lib/server-browser/DOCUMENTATION.md +32 -7
- package/server/lib/server-browser/browser-tab.js +4 -1
- package/server/lib/server-browser/downloads.js +261 -34
- package/server/lib/server-browser/downloads.test.js +171 -0
- package/server/lib/server-browser/runtime.integration.test.js +47 -0
- package/server/lib/server-browser/runtime.js +16 -0
- package/server/lib/server-browser/server-browser.js +25 -6
- package/server/lib/tunnels/executable-search.js +5 -1
- package/server/lib/tunnels/executable-search.test.js +26 -0
- package/dist/assets/DiagramView-BB-aZobi.js +0 -1
- package/dist/assets/FileSaveConflictDialog-Bzz8FNMq.js +0 -3
- package/dist/assets/FilesView-DECxN8Z0.js +0 -6
- package/dist/assets/GitHubDetailScaffold-CWsWycRd.js +0 -11
- package/dist/assets/GitHubLinkPicker-BVYdg_e8.js +0 -1
- package/dist/assets/GitHubListPrimitives-Dlv3tC4d.js +0 -1
- package/dist/assets/PatchDiff-BklyOEHs.js +0 -1
- package/dist/assets/PierreDiffViewer-wc6cB6qw.js +0 -147
- package/dist/assets/PullRequestsSurface-BZvJkT1I.js +0 -2
- package/dist/assets/SessionSwitcherDropdown-DShvvGwC.js +0 -2
- package/dist/assets/SessionUnreadDot-CbqRq6h_.js +0 -1
- package/dist/assets/SettingsView-DcF-At5E.js +0 -6
- package/dist/assets/ToolOutputDialog-DdMIfrnK.js +0 -8
- package/dist/assets/ToolPartDiffPreview-C6Sm4eVf.js +0 -1
- package/dist/assets/contextFileOpenGuard-UU86YHgI.js +0 -1
- package/dist/assets/gitStatusPredicates-DQEO4Psc.js +0 -1
- package/dist/assets/githubLink-ByPAyFjh.js +0 -10
- package/dist/assets/index-BaLCg7tL.css +0 -1
- package/dist/assets/index-I2QYqABE.js +0 -11
- package/dist/assets/main-DyFfbllq.js +0 -137
- package/dist/assets/pi-session-focus-preference-Dx0UXPoO.js +0 -9
- package/dist/assets/renderElectronMiniChatApp-Cb7s7dWl.js +0 -2
- package/dist/assets/renderMobileApp-Bp74b_Lo.js +0 -11
- package/dist/assets/runtimeEndpointReset-7nWYnKd4.js +0 -62
- package/dist/assets/runtimeSurface-CFwnvks_.js +0 -1
- package/dist/assets/useAppFontEffects-ZTyNwFk6.js +0 -213
- package/dist/assets/useGitHubRemoteSearch-BF3ohpsh.js +0 -1
- package/dist/assets/useSwitcherItems-BJzwyDGX.js +0 -1
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-C9rUUQ_Y.js","assets/useAppFontEffects-CV5UyTRw.js","assets/index-CKKWVoND.js","assets/vendor-zustand-CXhN0IMY.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-clsx-B-dksMZM.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-B_L9GVYw.css","assets/vendor-boot-D-KEJjsM.js","assets/runtimeSurface-0K7vuUpd.js","assets/nativeFileSave-DSMsJqXM.js","assets/computeVirtualFileMetrics-DJQqK49u.js","assets/vendor-shiki-BEwTOAFg.js","assets/vendor-shikijs-core-Ck_OPM_T.js","assets/vendor-shikijs-types-CPSbSeK6.js","assets/vendor-shikijs-vscode-textmate-DPFxvYtK.js","assets/vendor-hast-util-to-html-O3stl53j.js","assets/vendor-html-void-elements-CkdplsNl.js","assets/vendor-property-information-C40bX6nM.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-DrfmQi8i.js","assets/vendor-pierre-theming-BO6EPniU.js","assets/vendor-shikijs-engine-javascript-DL394yyj.js","assets/vendor-oniguruma-to-es-DgwFOwdE.js","assets/vendor-oniguruma-parser-BrbMHgHx.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-CK29YZtC.js","assets/renderDiffWithHighlighter-BXhnIAHg.js","assets/vendor-diff-C3JhlQdm.js","assets/vendor-lru_map-BbiDqlyL.js","assets/appThemeRegistry-Ca8eGRB9.js","assets/registerCustomTheme-C-h6lsYW.js","assets/vendor-capacitor-keyboard-335osRpd.js","assets/SessionSwitcherDropdown-CDOX-5Y2.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{_ as pt}from"./vendor-vite-runtime-DD1OZmLC.js";import{j as s,aP as Eu,aQ as Du,aR as Ru,aS as Pu,aT as Tu,aU as Mu,aV as Fu,bi as Jr,bj as wn,bk as Rl,bl as Xr,bm as Di,bp as Pl,by as Lu,bz as Tl,bA as Ml,bB as Fl,bC as qo,bD as Vo,bE as Yo,aW as Ll,bF as Ol,bn as Bl,bv as _l,bs as zl,bt as Ul,bq as Ri,br as Pi,bG as Ou,bH as Bu,bI as _u,bh as Qo,b1 as zu}from"./vendor-boot-D-KEJjsM.js";import{a as Te,R as l}from"./vendor-react-Bz1tRBxM.js";import{dZ as fn,v as Uu,a as ot,x as Me,t as oe,ai as Cn,I as R,bi as tr,cA as Yn,m as ss,n as ns,p as gs,q as Ds,B as Ae,d6 as $u,d_ as ca,bS as sr,C as fs,M as Ku,o as Hs,U as An,d$ as Ws,e0 as Wu,a5 as dn,e1 as bo,e2 as da,e3 as ua,w as Qn,bV as Rr,e4 as Gu,e5 as Hu,e6 as qu,e7 as Vu,e8 as Yu,e9 as Qu,af as $l,aj as zs,ag as fa,a2 as hs,ap as Ke,aq as We,ar as Ge,dX as Kl,ea as Ju,eb as Xu,ec as Zu,ed as ef,au as tf,ee as Jo,ef as sf,D as Vt,h as Yt,i as Qt,f as nr,ak as Gt,eg as nf,am as rf,dI as of,cJ as af,eh as lf,dm as Nt,ei as cf,ej as xo,ek as ha,el as pa,dn as df,bv as uf,bw as ff,bx as hf,by as pf,bz as ma,dU as mf,u as Xo,r as gn,c4 as Ti,bR as gf,cY as bf,d0 as Wl,em as xf,en as Gl,ci as Is,eo as yf,ep as wf,eq as vf,er as Sf,e as Hl,b as rr,es as ur,j as qs,ax as ql,d4 as or,et as ga,l as Vl,eu as bt,ev as jf,ew as kf,d1 as Yl,b1 as Zo,b2 as Ql,ex as Jl,d5 as Mi,a0 as ut,ey as Cf,ez as Af,eA as Nf,eB as ir,eC as If,eD as Ef,eE as Df,eF as Rf,az as ei,bO as Pf,y as Xl,b_ as Tf,z as Mf,bU as Zl,A as Ff,E as Lf,eG as ec,F as Of,eH as Bf,G as ba,eI as _f,eJ as nn,c as zf,eK as Uf,aV as $f,d as Kf,bB as _r,bA as tc,eL as Wf,d2 as Gf,dY as Hf,eM as qf,aI as Vf,eN as yo,aY as vn,bC as Yf,$ as sc,c9 as Qf,aZ as Jf,eO as Xf,eP as Zf,b$ as eh,g as th,eQ as sh,ay as nc,aM as nh,a7 as rh,eR as oh,aA as ih,dO as ah,dP as lh,eS as ch,dh,_ as uh,eT as fh,eU as hh,eV as ph,N as mh,eW as gh}from"./useAppFontEffects-CV5UyTRw.js";import{a as xa,c as _,b5 as bh,u as ue,r as st,f as Sn,b6 as rc,b7 as oc,b8 as xh,b9 as yh,k as jn,ba as wh,T as vh,bb as Sh,bc as jh,ad as et,b as Xe,p as Wt,as as ya,s as Nn,bd as kh,P as Ch,be as Ah,Z as Nh,n as Re,bf as wa,C as Ht,at as ti,aP as va,bg as si,aj as ic,A as ps,a7 as Fi,w as zr,G as hn,bh as Ih,l as ac,bi as Eh,Y as lc,N as Dh,v as cc,q as Jn,bj as ni,I as ri,bk as Rh,bl as Ph,bm as Th,bn as Sa,bo as _n,aG as wo,bp as oi,B as Ur,bq as Us,br as ja,bs as ii,bt as dc,bu as ai,bv as Mh,am as Fh,ar as Lh,an as Oh,ao as Bh,ap as _h,aq as zh,_ as Uh,t as $h,ab as uc,bw as Kh,bx as Wh,z as Gh,by as Hh,R as qh}from"./index-CKKWVoND.js";import{saveOrShareFile as fc}from"./nativeFileSave-DSMsJqXM.js";import{d as Vh,e as hc,g as In,h as Pr,i as pc,s as Gs,b as kn,c as Yh,j as Qh,k as Jh,l as Xh,f as Zh,S as ka,a as ep,t as tp,m as sp}from"./SessionUnreadDot-Dwc3MdvA.js";import{c as bs,d as Zr,p as mc,a as np}from"./vendor-zustand-CXhN0IMY.js";/* empty css */import{usePermissionStore as rp}from"./permissionStore-zIpxq9Pq.js";const op="chat";function gc(e){const t=new URLSearchParams;if(e.sessionId&&e.sessionId.trim().length>0&&t.set(fn.SESSION,e.sessionId),e.isSettingsOpen){const n=e.settingsPath.trim().length>0?e.settingsPath:"home";return t.set(fn.SETTINGS,n),t}return e.tab!==op&&t.set(fn.TAB,e.tab),e.tab==="diff"&&e.diffFile&&e.diffFile.trim().length>0&&t.set(fn.FILE,e.diffFile),t}function ip(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 ap(e){if(typeof window>"u")return!0;try{const t=new URLSearchParams(window.location.search),n=gc(e),r=window.location.pathname.match(/^\/(?:session|s)\/([^/?#]+)/i),o=r?.[1]?decodeURIComponent(r[1].trim()):null;o&&!t.has(fn.SESSION)&&t.set(fn.SESSION,o);const i=[...t.entries()].sort((c,d)=>c[0].localeCompare(d[0])),a=[...n.entries()].sort((c,d)=>c[0].localeCompare(d[0]));if(i.length!==a.length)return!1;for(let c=0;c<i.length;c++)if(i[c][0]!==a[c][0]||i[c][1]!==a[c][1])return!1;return!0}catch{return!0}}function li(e,t={}){if(!(typeof window>"u")&&!(!t.force&&ap(e)))try{const n=gc(e),r=ip(n);t.replace?window.history.replaceState({...window.history.state,route:e},"",r):window.history.pushState({route:e},"",r)}catch{}}const lp=["typescript","javascript","tsx","jsx","json","markdown"],bc={unified:{poolSize:1,totalASTLRUCacheSize:24,lineDiffType:"none"},split:{poolSize:2,totalASTLRUCacheSize:56,lineDiffType:"word-alt"}};let Ca=null;const xc=()=>(Ca??=Promise.all([pt(()=>import("./index-C9rUUQ_Y.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])),pt(()=>import("./workerFactory-DlGfNFqf.js"),[]),pt(()=>import("./appThemeRegistry-Ca8eGRB9.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})),Ca),ar={},Aa=new Set,ci=new Set;let Tr={light:"pierre-light",dark:"pierre-dark"};const cp=()=>{for(const e of ci)e()},yc=(e,t)=>{t.setRenderOptions({theme:Tr,lineDiffType:bc[e].lineDiffType})},di=e=>{typeof window>"u"||Aa.has(e)||(Aa.add(e),xc().then(t=>{if(ar[e])return;const n=bc[e],r=new t.WorkerPoolManager({workerFactory:t.workerFactory,poolSize:n.poolSize,totalASTLRUCacheSize:n.totalASTLRUCacheSize},{theme:{light:"pierre-light",dark:"pierre-dark"},langs:lp,lineDiffType:n.lineDiffType,preferredHighlighter:"shiki-wasm"});r.initialize(),ar[e]=r,yc(e,r),cp()}))},dp=e=>(ci.add(e),()=>ci.delete(e)),up=e=>{if(!(Tr.light===e.light&&Tr.dark===e.dark)){Tr=e;for(const t of Object.keys(ar)){const n=ar[t];n&&yc(t,n)}}},Kw=({children:e})=>{const t=Uu(),n=xa(!1),r=xa(!0),o=t?.lightThemeId??n.metadata.id,i=t?.darkThemeId??r.metadata.id,a=t?.availableThemes.find(d=>d.metadata.id===o)??n,c=t?.availableThemes.find(d=>d.metadata.id===i)??r;return Te.useEffect(()=>{let d=!1;return xc().then(u=>{d||(u.ensurePierreThemeRegistered(a),u.ensurePierreThemeRegistered(c),up({light:a.metadata.id,dark:c.metadata.id}))}),()=>{d=!0}},[c,a]),Te.useEffect(()=>{if(typeof window>"u")return;const d=()=>{di("unified"),di("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})},Ww=(e="unified")=>{const t=Te.useSyncExternalStore(dp,()=>ar[e],()=>{});return Te.useEffect(()=>{di(e)},[e]),t},fp=e=>{const t=e.trim();return t&&(t.split(/[?#]/,1)[0]||t).match(/([^/:]+?)(?:\.git)?\/?$/)?.[1]?.trim()||""},hp=e=>{const t=e.trim();return t?/[/\\]/.test(t)?"A name can’t contain / or \\.":t==="."||t===".."?"Choose a different name.":null:"Enter a name for the folder."},Na=(e,t)=>e?e.endsWith("/")?`${e}${t}`:`${e}/${t}`:t,wc=l.forwardRef(({id:e,active:t,onSelect:n,onHover:r,ariaLabel:o,ariaChecked:i,className:a,quiet:c=!1,children:d},u)=>s.jsx("div",{ref:u,id:e,role:"option","aria-selected":t,"aria-checked":i,"aria-label":o,onMouseMove:t?void 0:r,onMouseDown:f=>f.preventDefault(),onClick:n,className:_("flex w-full cursor-pointer select-none items-center gap-2.5 rounded-lg px-2.5 py-1.5 text-left typography-ui-label text-foreground",t&&(c?"group-focus-within/palette:bg-interactive-hover":"group-focus-within/palette:bg-interactive-selection group-focus-within/palette:text-interactive-selection-foreground"),!t&&"hover:bg-interactive-hover/60",a),children:d}));wc.displayName="PaletteRow";const pp=e=>e==="/",Es=e=>e.replace(/\\/g,"/"),ms=e=>{if(!e||pp(e))return e;let t=e;for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t},bn=e=>e.endsWith("/"),Xn=e=>{const t=e.trim();return!t||bn(t)?t:`${t}/`},Li=e=>e.lastIndexOf("/"),mp=e=>{if(bn(e))return e;const t=Li(e);return t<0?e:e.slice(0,t+1)},gp=e=>{const t=Li(e);return e.slice(t+1)},vc=e=>{const t=ms(e.trim());if(!t||t==="~"||t==="~/"||t==="/")return null;const n=Li(t);return n<0?null:t.startsWith("~/")&&n<=1?"~/":n===0?"/":`${t.slice(0,n)}/`},bp=e=>bn(e)&&vc(e)!==null,Mr=e=>{if(!e)return null;const t=ms(Es(e.trim()));return t?t.toLowerCase():null},vo=(e,t)=>{const n=e.trim();return n==="~"?t:n.startsWith("~/")?`${t}${n.slice(1)}`:n},xp=(e,t)=>{const n=ms(Es(e.trim())),r=ms(Es(t.trim()));if(!n)return"";if(!r)return Xn(n);if(n.toLowerCase()===r.toLowerCase())return"~/";const o=`${r}/`;return n.toLowerCase().startsWith(o.toLowerCase())?`~/${n.slice(r.length+1)}/`:Xn(n)},Sc=()=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform),yp=e=>Sc()?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey,wp=()=>Sc()?"⌘":"Ctrl",vp=e=>{if(!e)return;e.focus({preventScroll:!0});const t=e.value.length;e.setSelectionRange(t,t),e.scrollLeft=e.scrollWidth},Sp=async()=>bh({fresh:!0}),xr=async(e,t)=>{try{const n=await e.json();if(typeof n.error=="string"&&n.error.trim())return n.error.trim()}catch{}return t},So=(e,t,n)=>st(e,{method:"POST",headers:{"Content-Type":"application/json"},query:n,body:JSON.stringify(t)});function jp({open:e,onClose:t,isMobile:n}){const r=ot(x=>x.addProject),o=ue(x=>x.setActiveMainTab),i=ue(x=>x.setSessionSwitcherOpen),a=Me(x=>x.openNewSessionDraft),[c,d]=l.useState(null),[u,f]=l.useState(null);l.useEffect(()=>{e&&(d(null),f(null))},[e]);const m=l.useCallback(x=>{const C=r(x);return C?(o("chat"),n&&i(!1),a({selectedProjectId:C.id,directoryOverride:C.path}),t(),!0):(f("PiChamber couldn’t add this folder. Check that the path is a folder."),!1)},[r,n,t,a,o,i]),g=l.useCallback(async(x,C)=>{if(!c){d(x),f(null);try{await C()}catch(j){f(j instanceof Error&&j.message?j.message:"Something went wrong. Try again.")}finally{d(null)}}},[c]),b=l.useCallback((x,C)=>g("add",async()=>{if(C.create){const j=await So("/api/fs/mkdir",{path:x},{directory:C.location});if(!j.ok)throw new Error(await xr(j,"Couldn’t create the folder."))}m(x)}),[m,g]),h=l.useCallback((x,C)=>g("clone",async()=>{const j=await So("/api/fs/clone",{remoteUrl:x.trim(),destinationPath:`${ms(C)}/`});if(!j.ok){const w=(await xr(j,"The clone failed.")).replace(/^Cloning into '[^']*'\.\.\.\s*/,"").replace(/^fatal:\s*/,"");throw new Error(w.charAt(0).toUpperCase()+w.slice(1))}const A=await j.json();if(typeof A.path!="string"||!A.path)throw new Error("The clone finished, but the server didn’t say where. Add the folder from Folder on this server.");m(A.path)}),[m,g]),p=l.useCallback((x,C,j)=>g("create",async()=>{const A=`${ms(x)}/${C.trim()}`,w=await So("/api/fs/mkdir",{path:A},{directory:x});if(!w.ok)throw new Error(await xr(w,"Couldn’t create the folder."));if(j){const S=await st("/api/git/init",{method:"POST",query:{directory:A}});if(!S.ok){const v=await xr(S,"git init failed.");throw new Error(`The folder was created, but git init failed: ${v}`)}}m(A)}),[m,g]),y=l.useCallback(()=>f(null),[]);return{pending:c,error:u,clearError:y,addFolder:b,cloneRepository:h,createProject:p}}const kp=()=>{const[e,t]=Te.useState(!1),[n,r]=Te.useState(!1);Te.useEffect(()=>{t(Sn()),r(rc())},[]);const o=Te.useCallback(async c=>e?await oc(c):{success:!0,path:c},[e]),i=Te.useCallback(async c=>e?await xh():{success:!0},[e]),a=Te.useCallback(async c=>e?await yh():{success:!0},[e]);return{isDesktop:e,canRequestAccess:n,requestAccess:o,startAccessing:i,stopAccessing:a}},jo=async(e,t)=>{try{const r=(await vh(t)).filter(o=>o.isDirectory).map(o=>({name:o.name,path:Es(o.path)})).sort((o,i)=>o.name.localeCompare(i.name));return{displayDir:e,absoluteDir:t,entries:r,error:null}}catch(n){return{displayDir:e,absoluteDir:t,entries:[],error:Sh(n)?n.reason:"unknown"}}},Cp=250;function Ap({open:e,addedProjectPaths:t}){const n=jn(W=>W.homeDirectory),{canRequestAccess:r,startAccessing:o}=kp(),[i,a]=l.useState(""),[c,d]=l.useState("~/"),[u,f]=l.useState(null),[m,g]=l.useState(!1),[b,h]=l.useState(!1),[p,y]=l.useState(!1),x=l.useRef(0),C=i||n;l.useEffect(()=>{if(!e)return;x.current+=1,d("~/"),f(null),h(!1),y(!1);let W=!1;return(async()=>{const ae=await Sp();W||a(ae||n||"")})(),()=>{W=!0}},[n,e]);const j=l.useMemo(()=>mp(c),[c]),A=l.useMemo(()=>bn(c)?"":gp(c),[c]),w=l.useMemo(()=>C?vo(j,C):"",[j,C]),S=!!(u&&u.displayDir===j&&u.absoluteDir===w);l.useEffect(()=>{if(!e||!w||S)return;const W=++x.current;jo(j,w).then(L=>{W===x.current&&f(L)})},[w,j,S,e]),l.useEffect(()=>{if(S||!w){g(!1);return}const W=window.setTimeout(()=>g(!0),Cp);return()=>window.clearTimeout(W)},[w,S]);const v=l.useCallback(async W=>{const L=Xn(W);if(!C)return d(L),!0;const ae=++x.current,J=await jo(L,vo(L,C));return ae!==x.current?!1:(f(J),d(L),!0)},[C]),k=l.useCallback(()=>{if(!w)return;const W=++x.current;jo(j,w).then(L=>{W===x.current&&f(L)})},[w,j]),E=l.useMemo(()=>S?A:!u||!c.startsWith(u.displayDir)?"":c.slice(u.displayDir.length).split("/")[0]??"",[A,S,u,c]),P=l.useMemo(()=>{if(!u)return[];const W=E.toLowerCase(),L=p||E.startsWith(".");return u.entries.filter(ae=>ae.name.toLowerCase().startsWith(W)&&(L||!ae.name.startsWith(".")))},[E,u,p]),z=l.useMemo(()=>{if(!u||u.error)return[];const W=[],L=bp(u.displayDir)?vc(u.displayDir):null;if(L){const ae=Mr(u.absoluteDir);W.push({type:"parent",value:"browse:up",name:"..",path:u.absoluteDir,target:L,alreadyAdded:!!(ae&&t.has(ae))})}for(const ae of P){const J=Mr(ae.path);W.push({type:"directory",value:`browse:${ae.path}`,name:ae.name,path:ae.path,target:`${Xn(u.displayDir)}${ae.name}/`,alreadyAdded:!!(J&&t.has(J))})}return W},[t,P,u]),K=S?u?.error??null:null,q=l.useMemo(()=>S&&u?u.entries:[],[S,u]),H=l.useMemo(()=>C?ms(vo(c,C)):"",[C,c]),F=Mr(H),D=!!(F&&t.has(F)),T=l.useMemo(()=>A?q.find(W=>W.name===A)??null:null,[A,q]),I=!!(S&&H&&!D&&(K===null||K==="not-found")&&(bn(c)&&K==="not-found"||!bn(c)&&A.trim().length>0&&T===null)),M=l.useCallback(async W=>{const L=await o(W);if(!L.success)return oe.error("Failed to open directory",{description:L.error||"Desktop could not grant file access."}),!1;const ae=C?xp(W,C):Xn(Es(W));return await v(ae),!0},[C,v,o]),G=l.useCallback(async()=>{if(!b){h(!0);try{if(rc()){const L=await oc(H);if(!L.success||!L.path){L.error&&L.error!=="Directory selection cancelled"&&oe.error("Failed to select directory",{description:L.error});return}await M(L.path);return}const W=await wh(H);if(W.status==="cancelled")return;if(W.status!=="picked"){oe.error("Couldn't open a folder picker",{description:W.error});return}await M(W.path)}catch(W){oe.error("Failed to select directory",{description:W instanceof Error?W.message:"Unknown error occurred."})}finally{h(!1)}}},[M,b,H]);return{query:c,setQuery:d,isSettled:S,showLoading:m,browseErrorReason:K,reload:k,isPickingLocation:b,showHidden:p,setShowHidden:y,explorerRootDirectory:C,browseDirectoryDisplayPath:j,browseDirectoryAbsolutePath:w,browseFilterQuery:A,entries:q,rows:z,targetPath:H,isAlreadyAdded:D,shouldCreateTarget:I,canRequestAccess:r,navigate:v,handleBrowseLocation:G}}const Np={folder:"source","clone-url":"source","clone-location":"clone-url","new-name":"source","new-location":"new-name"},Ut=e=>e==="folder"||e==="clone-location"||e==="new-location",Ip=[{step:"folder",icon:"folder-6",title:"Folder on this server",description:"Pick a folder that’s already here."},{step:"clone-url",icon:"download-cloud",title:"Clone a repository",description:"Copy a Git repository from a URL."},{step:"new-name",icon:"folder-add",title:"New project",description:"Start an empty folder, with Git if you want it."}],Ep={folder:"Open folder","clone-url":"Clone","clone-location":"Clone","new-name":"New project","new-location":"New project"},Dp={source:"Choose where the project comes from, type a folder path, or paste a Git URL.",folder:"Pick a folder on this server or type its path.","clone-url":"Paste the URL of the repository to clone.","clone-location":"Pick the folder the repository is cloned into.","new-name":"Name the new project.","new-location":"Pick the folder the new project goes in."},Rp={source:"Filter sources, type a folder path, or paste a Git URL",folder:"Folder path","clone-url":"Repository URL","clone-location":"Location","new-name":"Project name","new-location":"Location"},Pp={source:"Choose a source, type a path, or paste a Git URL",folder:"~/","clone-url":"https://github.com/owner/repo.git","clone-location":"~/","new-name":"Project name","new-location":"~/"},Tp=e=>/^(~|\/|[a-zA-Z]:[\\/])/.test(e),Mp=e=>/^(https?:\/\/|ssh:\/\/|git:\/\/|git@)/i.test(e)||/^[\w.-]+@[\w.-]+:/.test(e),Fp=e=>ms(Es(e)).split("/").pop()??"",Lp=({open:e,onOpenChange:t})=>{const n=ot(U=>U.projects),{isMobile:r,isTablet:o}=Cn(),i=r||o,[a,c]=l.useState("source"),[d,u]=l.useState(""),[f,m]=l.useState(""),[g,b]=l.useState(""),[h,p]=l.useState(!0),[y,x]=l.useState(null),C=l.useRef(null),j=l.useRef(new Map),A=l.useId(),w=l.useMemo(()=>new Set(n.map(U=>Mr(U.path)).filter(U=>!!U)),[n]),S=l.useCallback(()=>t(!1),[t]),v=Ap({open:e,addedProjectPaths:w}),{pending:k,error:E,clearError:P,addFolder:z,cloneRepository:K,createProject:q}=jp({open:e,onClose:S,isMobile:r});l.useEffect(()=>{e&&(c("source"),u(""),m(""),b(""),p(!0),x(null))},[e]),l.useEffect(()=>{P()},[v.query,P,g,f,a]),l.useLayoutEffect(()=>{e&&(i&&a!=="clone-url"&&a!=="new-name"||vp(C.current))},[i,e,a]);const H=l.useCallback(U=>{c(U),x(null)},[]),F=l.useCallback(()=>{k||a==="source"||H(Np[a])},[H,k,a]),{navigate:D}=v,T=l.useCallback(U=>{const ge=U.type==="parent"?`dir:${Fp(U.path)}`:null;D(U.target).then(ne=>{ne&&x(ge)})},[D]),I=l.useMemo(()=>new Set(v.entries.map(U=>U.name)),[v.entries]),M=v.browseDirectoryDisplayPath,G=v.browseErrorReason==="not-found"?"This folder doesn’t exist. Pick a location that does.":v.browseErrorReason?"PiChamber can’t read this location.":null,W=!v.isSettled||v.isPickingLocation,L=fp(f),ae=g.trim(),J=hp(ae);let le=!1,Ie="",Y="",B=null;if(a==="folder"){Y="Adding…";const U=ms(v.query.trim())||v.query.trim();if(v.isAlreadyAdded)Ie="Added",U&&(B={tone:"outcome",text:"Already added:",path:U});else{Ie=v.shouldCreateTarget?"Create and add":"Add";const ge=v.browseErrorReason&&v.browseErrorReason!=="not-found";le=!!v.targetPath&&!ge&&!W,U&&!ge&&(B={tone:"outcome",text:v.shouldCreateTarget?"Creates and adds":"Adds",path:U})}}else if(a==="clone-location"){Ie="Clone",Y="Cloning…";const U=Na(M,L);G?B={tone:"problem",text:G}:I.has(L)?B={tone:"problem",text:"Already exists:",path:U}:(B={tone:"outcome",text:"Clones into",path:U},le=!!L&&!W)}else if(a==="new-location"){Ie="Create",Y="Creating…";const U=Na(M,ae);G?B={tone:"problem",text:G}:J?B={tone:"problem",text:J,path:U}:I.has(ae)?B={tone:"problem",text:"Already exists:",path:U}:(B={tone:"outcome",text:"Creates",path:U},le=!W)}le=le&&k===null;const $=()=>{le&&(a==="folder"?z(v.targetPath,{create:v.shouldCreateTarget,location:v.browseDirectoryAbsolutePath}):a==="clone-location"?K(f,v.browseDirectoryAbsolutePath):a==="new-location"&&q(v.browseDirectoryAbsolutePath,ae,h))},X=a==="clone-url"?!!L:a==="new-name"?!!ae&&!J:!1,ee=()=>{X&&H(a==="clone-url"?"clone-location":"new-location")},ie=[];if(a==="source"){const U=d.trim().toLowerCase();for(const ge of Ip)U&&!`${ge.title} ${ge.description}`.toLowerCase().includes(U)||ie.push({key:`source:${ge.step}`,kind:"source",select:()=>H(ge.step),content:s.jsxs(s.Fragment,{children:[s.jsx(R,{name:ge.icon,className:"size-4 shrink-0 text-muted-foreground"}),s.jsxs("span",{className:"flex min-w-0 flex-1 flex-col py-0.5",children:[s.jsx("span",{className:"truncate",children:ge.title}),s.jsx("span",{className:"truncate typography-meta text-muted-foreground",children:ge.description})]})]})})}else if(Ut(a)){a==="new-location"&&ie.push({key:"toggle:git",kind:"toggle",select:()=>p(U=>!U),ariaChecked:h,ariaLabel:"Initialize a Git repository",content:s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"pointer-events-none flex size-4 shrink-0 items-center justify-center",children:s.jsx(tr,{checked:h,onChange:p})}),s.jsx("span",{className:"flex-1 truncate",children:"Initialize a Git repository"})]})});for(const U of v.rows){const ge=U.type==="parent";ie.push({key:ge?"browse:up":`dir:${U.name}`,kind:ge?"parent":"directory",select:()=>T(U),ariaLabel:ge?`Up to ${U.target}`:`${U.name}${U.alreadyAdded?", already added":""}`,content:s.jsxs(s.Fragment,{children:[s.jsx(R,{name:ge?"arrow-up-s":"folder-6",className:"size-4 shrink-0 text-muted-foreground"}),ge?s.jsxs("span",{className:"flex min-w-0 flex-1 items-baseline gap-2",children:[s.jsx("span",{className:"shrink-0",children:"Up to"}),s.jsx(Yn,{value:U.target,className:"min-w-0 font-mono typography-meta text-muted-foreground"})]}):s.jsx("span",{className:"min-w-0 flex-1 truncate",children:U.name}),!ge&&U.alreadyAdded?s.jsx("span",{className:"shrink-0 typography-micro text-muted-foreground",children:"Added"}):null]})})}}const Ce=Ut(a)?ie.findIndex(U=>U.kind==="directory"):ie.length>0?0:-1,pe=y?ie.findIndex(U=>U.key===y):-1,je=pe>=0?pe:Ce,be=je>=0?ie[je]:void 0,ze=be?.key,me=U=>`${A}-option-${U}`;l.useLayoutEffect(()=>{ze&&j.current.get(ze)?.scrollIntoView({block:"nearest"})},[ze]);const Pe=U=>{if(ie.length===0)return;const ge=je>=0?je:U>0?-1:ie.length,ne=Math.min(ie.length-1,Math.max(0,ge+U));x(ie[ne]?.key??null)},V=a==="source"?d:a==="clone-url"?f:a==="new-name"?g:v.query,fe=U=>{if(x(null),a==="source"){const ge=U.trimStart();if(Mp(ge)){u(""),m(ge),H("clone-url");return}if(Tp(ge)){u(""),v.setQuery(ge==="~"?"~/":Es(ge)),H("folder");return}u(U);return}if(a==="clone-url"){m(U);return}if(a==="new-name"){b(U);return}v.setQuery(Es(U).replace(/\/{2,}/g,"/"))},xe=U=>{if(!U.nativeEvent.isComposing){if(U.key==="ArrowDown"||U.key==="ArrowUp"){if(ie.length===0)return;U.preventDefault(),Pe(U.key==="ArrowDown"?1:-1);return}if(U.key==="Enter"){if(U.preventDefault(),k)return;if(Ut(a)&&yp(U)){$();return}if(a==="clone-url"||a==="new-name"){ee();return}be?be.select():Ut(a)&&$();return}if(U.key==="Tab"&&!U.shiftKey&&be?.kind==="directory"){U.preventDefault(),be.select();return}U.key==="Backspace"&&V===""&&a!=="source"&&(U.preventDefault(),F())}},te=wp(),re=[];ie.length>1&&re.push({keys:["↑","↓"],label:"Navigate"}),a==="source"?be&&re.push({keys:["↵"],label:"Select"}):a==="clone-url"||a==="new-name"?re.push({keys:["↵"],label:"Continue"}):be?re.push({keys:["↵"],label:be.kind==="toggle"?"Toggle":"Open"}):re.push({keys:["↵"],label:Ie}),a!=="source"&&V===""&&re.push({keys:["⌫"],label:"Back"}),re.push({keys:["Esc"],label:"Close",onSelect:()=>t(!1)});const Be=Ut(a)&&be?[te,"↵"]:["↵"];let ke=null;Ut(a)?ke=s.jsxs(Ae,{variant:"solid",size:"sm",className:"shrink-0 gap-1.5",disabled:!le,onMouseDown:U=>U.preventDefault(),onClick:$,children:[k?Y:Ie,!r&&!k&&le?s.jsx("span",{className:"flex items-center gap-0.5",children:Be.map(U=>s.jsx(ca,{className:"border-current/30 bg-transparent text-current",children:U},U))}):null]}):(a==="clone-url"||a==="new-name")&&(ke=s.jsxs(Ae,{variant:"solid",size:"sm",className:"shrink-0 gap-1.5",disabled:!X,onMouseDown:U=>U.preventDefault(),onClick:ee,children:["Continue",!r&&X?s.jsx(ca,{className:"border-current/30 bg-transparent text-current",children:"↵"}):null]}));let Q=null;const ve=ie.filter(U=>U.kind==="directory").length;a==="source"&&ie.length===0?Q={tone:"quiet",text:"Nothing matches. Type a folder path, or paste a Git URL."}:a==="clone-url"?f.trim()?L?Q={tone:"quiet",text:s.jsxs(s.Fragment,{children:["Clones as ",s.jsx("span",{className:"font-mono text-foreground",children:L}),". Press Enter to choose where it goes."]})}:Q={tone:"problem",text:"This URL doesn’t name a repository."}:Q={tone:"quiet",text:"Paste the repository’s HTTPS or SSH URL, then press Enter to choose where it goes."}:a==="new-name"?ae?J?Q={tone:"problem",text:J}:Q={tone:"quiet",text:s.jsxs(s.Fragment,{children:["Press Enter to choose where ",s.jsx("span",{className:"font-mono text-foreground",children:ae})," goes."]})}:Q={tone:"quiet",text:"Name the project, then press Enter to choose where it goes."}:Ut(a)&&(v.browseErrorReason==="not-found"?Q=a==="folder"?{tone:"quiet",text:"This folder doesn’t exist yet. Adding it creates it."}:{tone:"problem",text:"This folder doesn’t exist. Pick a location that does."}:v.browseErrorReason?Q={tone:"problem",text:v.browseErrorReason==="os-permission"?"PiChamber needs access to this folder.":"Couldn’t read this folder.",actions:s.jsxs(s.Fragment,{children:[v.browseErrorReason==="os-permission"&&v.canRequestAccess?s.jsx(Ae,{size:"xs",onClick:()=>{v.handleBrowseLocation()},disabled:v.isPickingLocation,children:"Grant access"}):null,s.jsx(Ae,{variant:"outline",size:"xs",onClick:v.reload,children:"Try again"})]})}:v.showLoading&&ve===0?Q={tone:"quiet",text:"Loading folders…"}:v.isSettled&&ve===0&&(Q={tone:"quiet",text:v.browseFilterQuery?a==="folder"?s.jsxs(s.Fragment,{children:["No folder named ",s.jsx("span",{className:"font-mono text-foreground",children:v.browseFilterQuery})," here. Adding it creates it."]}):"No folders match.":"No folders in here."}));const he=E?s.jsx("p",{role:"alert",className:"border-b border-border/60 px-4 py-2 typography-meta text-[var(--status-error)] text-pretty",children:E}):null,Se=(U,ge)=>s.jsx("button",{type:"button",onClick:F,disabled:k!==null,"aria-label":ge,className:"ml-auto shrink-0 rounded px-1 typography-ui-label text-muted-foreground underline-offset-2 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50 disabled:pointer-events-none disabled:opacity-50",children:U}),qe=B?s.jsxs("div",{className:"flex flex-col gap-1 border-b border-border/60 px-4 py-2",children:[a==="new-location"?s.jsxs("div",{className:"flex min-w-0 items-center gap-2 typography-ui-label",children:[s.jsx("label",{htmlFor:"new-project-name",className:"shrink-0 text-muted-foreground",children:"Name"}),s.jsx("input",{value:g,onChange:U=>b(U.target.value),onKeyDown:U=>{U.nativeEvent.isComposing||U.key==="Enter"&&(U.preventDefault(),$())},id:"new-project-name",spellCheck:!1,autoComplete:"off",disabled:k!==null,className:"h-7 min-w-0 flex-1 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-1.5 font-mono text-foreground outline-none focus-visible:border-[var(--interactive-focus)] focus-visible:ring-2 focus-visible:ring-primary/30"})]}):null,s.jsxs("p",{className:_("flex min-w-0 items-baseline gap-1.5 typography-ui-label",B.tone==="problem"?"text-[var(--status-error)]":"text-muted-foreground"),children:[s.jsx("span",{className:"shrink-0",children:B.text}),B.path?s.jsx(Yn,{value:B.path,className:"min-w-0 font-mono text-foreground"}):null]}),a==="clone-location"?s.jsxs("p",{className:"flex min-w-0 items-baseline gap-1.5 typography-ui-label text-muted-foreground",children:[s.jsx("span",{className:"shrink-0",children:"From"}),s.jsx(Yn,{value:f.trim(),className:"min-w-0 font-mono text-foreground"}),Se("Change","Change the repository URL")]}):null]}):null,Ue=a!=="source"&&a!=="new-name";return s.jsx(ss,{open:e,onOpenChange:t,children:s.jsxs(ns,{showCloseButton:!1,initialFocus:i?!1:C,className:_("group/palette w-full max-w-xl gap-0 self-start overflow-hidden rounded-2xl p-0","mt-[max(env(safe-area-inset-top),0.25rem)] max-h-[calc(100%-0.5rem)] sm:mt-[10vh] sm:max-h-[80vh]"),children:[s.jsx(gs,{className:"sr-only",children:"Add folder"}),s.jsx(Ds,{className:"sr-only",children:Dp[a]}),s.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-2 border-b border-border/60 pl-2.5 pr-2",children:[a==="source"?s.jsx("span",{className:"flex size-7 shrink-0 items-center justify-center text-muted-foreground",children:s.jsx(R,{name:"folder-add",className:"size-4"})}):s.jsx(Ae,{variant:"ghost",size:"icon",className:"size-7 shrink-0",onMouseDown:U=>U.preventDefault(),onClick:F,disabled:k!==null,"aria-label":"Back",title:"Back",children:s.jsx(R,{name:"arrow-left-s",className:"size-4"})}),a!=="source"?s.jsxs("span",{className:"flex shrink-0 items-center gap-2 typography-ui-label font-medium text-foreground","aria-hidden":"true",children:[Ep[a],s.jsx("span",{className:"h-4 w-px bg-border"})]}):null,s.jsx("input",{ref:C,value:V,onChange:U=>fe(U.target.value),onKeyDown:xe,readOnly:k!==null,"aria-busy":k!==null||void 0,"aria-label":Rp[a],placeholder:Pp[a],role:"combobox","aria-expanded":ie.length>0,"aria-controls":A,"aria-autocomplete":"list","aria-activedescendant":je>=0?me(je):void 0,"aria-invalid":Q?.tone==="problem"&&!Ut(a)?!0:void 0,spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",className:_("min-w-0 flex-1 text-foreground outline-none placeholder:text-muted-foreground",a==="source"?"h-full bg-transparent":"h-8 rounded-md border border-[var(--interactive-border)] bg-[var(--surface-muted)] px-2","typography-markdown md:typography-ui-label",Ue&&"font-mono")}),ke]}),qe,he,s.jsxs("div",{className:"min-h-0 overflow-y-auto overscroll-contain sm:max-h-[min(24rem,52vh)]",children:[ie.length>0?s.jsx("div",{id:A,role:"listbox","aria-label":a==="source"?"Sources":"Folders",className:"flex flex-col gap-px p-1.5",children:ie.map((U,ge)=>s.jsxs(l.Fragment,{children:[ge>0&&ie[ge-1]?.kind==="toggle"?s.jsx("div",{role:"presentation",className:"mx-2.5 my-1 h-px bg-border/60"}):null,s.jsx(wc,{ref:ne=>{ne?j.current.set(U.key,ne):j.current.delete(U.key)},id:me(ge),active:ge===je,onSelect:U.select,onHover:()=>x(U.key),ariaLabel:U.ariaLabel,ariaChecked:U.ariaChecked,className:U.kind==="source"?"py-2":void 0,quiet:Ut(a),children:U.content})]},U.key))}):null,Q?s.jsxs("div",{className:_("flex flex-col items-center gap-3 px-6 text-center",ie.length>0?"pb-6 pt-3":"py-8"),children:[s.jsx("p",{className:_("typography-meta text-balance",Q.tone==="problem"?"text-[var(--status-error)]":"text-muted-foreground"),children:Q.text}),Q.actions?s.jsx("div",{className:"flex items-center gap-2",children:Q.actions}):null]}):null]}),!r||Ut(a)?s.jsxs("div",{className:"flex min-h-10 shrink-0 items-center justify-between gap-3 border-t border-border/60 bg-[var(--surface-muted)]/40 px-3 py-2 typography-micro text-muted-foreground",children:[r?s.jsx("span",{}):s.jsx($u,{hints:re}),Ut(a)?s.jsxs("span",{className:"flex shrink-0 items-center gap-3",children:[s.jsxs("label",{className:"flex cursor-pointer items-center gap-1.5",children:[s.jsx(tr,{checked:v.showHidden,onChange:v.setShowHidden,ariaLabel:"Show hidden folders"}),"Hidden"]}),s.jsx(Ae,{variant:"ghost",size:"xs",disabled:k!==null||v.isPickingLocation,onMouseDown:U=>U.preventDefault(),onClick:()=>{v.handleBrowseLocation()},title:"Pick a folder with the system dialog",children:v.isPickingLocation?"Opening…":"Browse…"})]}):null]}):null]})})},yr=e=>e?s.jsx("span",{className:"text-foreground/80 dark:text-foreground/70",children:e}):void 0,Gw=()=>{const[e,t]=l.useState(!1),[n,r]=l.useState(null),[o,i]=l.useState(!1),a=Me(S=>S.deleteSession),c=Me(S=>S.deleteSessions),d=ue(S=>S.showDeletionDialog),u=ue(S=>S.setShowDeletionDialog),{isMobile:f,isTablet:m,hasTouchInput:g}=Cn(),b=f||m||g;l.useEffect(()=>jh(()=>{t(!1)}),[]);const h=l.useCallback(S=>{r({sessions:S.sessions,dateLabel:S.dateLabel})},[]),p=l.useCallback(()=>{r(null),i(!1)},[]),y=l.useCallback(async S=>{if(S.sessions.length===0)return;if(S.sessions.length===1){const P=S.sessions[0];await a(P.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const v=S.sessions.map(P=>P.id),{deletedIds:k,failedIds:E}=await c(v);if(k.length>0){const P=E.length>0?E.length===1?`${E.length} session could not be deleted.`:`${E.length} sessions could not be deleted.`:S.dateLabel?`Removed all sessions from ${S.dateLabel}.`:void 0;oe.success(k.length===1?"Deleted {count} session":`Deleted ${k.length} sessions`,{description:yr(P)})}E.length>0&&oe.error(E.length===1?`Failed to delete ${E.length} session`:`Failed to delete ${E.length} sessions`,{description:yr("Please try again in a moment.")})},[a,c]);l.useEffect(()=>sr.onDeleteRequest(S=>{if(!d){y(S);return}h(S)}),[h,d,y]),l.useEffect(()=>sr.onDirectoryRequest(()=>{t(!0)}),[]);const x=l.useCallback(async()=>{if(n){i(!0);try{if(n.sessions.length===1){const S=n.sessions[0];if(!await a(S.id)){oe.error("Failed to delete session"),i(!1);return}oe.success("Session deleted",{action:{label:"OK",onClick:()=>{}}})}else{const S=n.sessions.map(P=>P.id),v=await c(S),k=v.deletedIds,E=v.failedIds;if(k.length>0){const P=E.length>0?E.length===1?`${E.length} session could not be deleted.`:`${E.length} sessions could not be deleted.`:n.dateLabel?`Removed all sessions from ${n.dateLabel}.`:void 0;oe.success(k.length===1?"Deleted {count} session":`Deleted ${k.length} sessions`,{description:yr(P),action:{label:"OK",onClick:()=>{}}})}if(E.length>0&&(oe.error(E.length===1?`Failed to delete ${E.length} session`:`Failed to delete ${E.length} sessions`,{description:yr("Please try again in a moment.")}),k.length===0)){i(!1);return}}p()}finally{i(!1)}}},[n,a,c,p]),C=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.`:"",j=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(S=>s.jsx("li",{className:"typography-micro text-subtle-foreground",children:s.jsx("span",{className:"truncate",children:fs(S)})},S.id)),n.sessions.length>5&&s.jsx("li",{className:"typography-micro text-subtle-foreground",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-subtle-foreground",children:"Worktree directories stay intact. Subsessions linked to the selected sessions will also be removed."})})]}):null,A=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(R,{name:"checkbox-blank",className:"size-4"}):s.jsx(R,{name:"checkbox",className:"size-4 text-primary"}),"Never ask"]}),s.jsxs("div",{className:"flex items-center gap-2",children:[s.jsx(Ae,{variant:"ghost",onClick:p,disabled:o,children:"Cancel"}),s.jsx(Ae,{variant:"destructive",onClick:x,disabled:o,children:o?"Deleting…":n?.sessions.length===1?"Delete session":"Delete sessions"})]})]}),w=n?.sessions.length===1?"Delete session":"Delete sessions";return s.jsxs(s.Fragment,{children:[b?s.jsx(Ku,{open:!!n,onClose:()=>{o||p()},title:w,footer:s.jsx("div",{className:"flex justify-end gap-2",children:A}),children:s.jsxs("div",{className:"space-y-2 pb-2",children:[C&&s.jsx("p",{className:"typography-meta text-subtle-foreground",children:C}),j]})}):s.jsx(ss,{open:!!n,onOpenChange:S=>{if(!S){if(o)return;p()}},children:s.jsxs(ns,{className:"max-w-[min(520px,100vw-2rem)] space-y-2 pb-2",children:[s.jsxs(Hs,{children:[s.jsx(gs,{children:w}),C&&s.jsx(Ds,{children:C})]}),s.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto space-y-2",children:j}),s.jsx(An,{className:"mt-2 gap-2 pt-1 pb-1",children:A})]})}),s.jsx(Lp,{open:e,onOpenChange:t})]})},Hw=()=>{const e=Ws(t=>t.entries);return l.useEffect(()=>{for(const t of e.values())!Wu(t)||!t.receipt||(Ws.getState().markNotificationSent(t.key),oe.success("Worktree ready",{id:`worktree-ready:${t.key}`,description:t.receipt.branch||t.receipt.path}))},[e]),null},Op=[{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:"plugins",title:"Extensions & Plugins",group:"agent",kind:"single",description:"PiChamber plugins, and the extensions and packages Pi loads.",keywords:["plugin","plugins","extension","extensions","package","packages","pi config","pi list","pi remove","add-ons","visuals","html","render","chart","diagram","tools","sub-agents","subagents","composer","toggles"]},{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"]}],Bp={sessions:"sessions",skills:"skills.installed",providers:"providers","git-identities":"git",settings:"home"};function _p(e){const t=e.trim().toLowerCase();return Op.find(n=>n.slug===t)??null}function zp(e){const t=(e??"").trim().toLowerCase();if(!t)return"home";if(t==="remote-instances")return"remote-access";const n=Bp[t];if(n)return n;const r=_p(t);return r?r.slug:"home"}function qw(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"plugins":return"plug";case"git":return"git-repository";case"tunnel":return"global";case"about":return"pichamber";case"home":return null;default:return"robot-2"}}function Vw(){const e=l.useRef(!1),t=l.useRef(!1),n=Me(f=>f.setCurrentSession),r=ue(f=>f.setActiveMainTab),o=ue(f=>f.setSettingsDialogOpen),i=ue(f=>f.setSettingsPage),a=ue(f=>f.navigateToDiff),c=l.useCallback(async f=>{if(!t.current){t.current=!0;try{if(f.sessionId){const m=Me.getState().currentSessionId,g=dn().getState().selectedSessionId;if(f.sessionId!==m||f.sessionId!==g){const b=Me.getState().getDirectoryForSession(f.sessionId);n(f.sessionId,b)}}if(f.settingsPath){i(zp(f.settingsPath)),o(!0);return}ue.getState().isSettingsDialogOpen&&o(!1),f.tab&&r(f.tab),f.diffFile&&(f.tab==="diff"||!f.tab)&&a(f.diffFile)}finally{t.current=!1}}},[n,r,o,i,a]),d=l.useCallback(()=>{const f=Me.getState(),m=dn().getState(),g=ue.getState();return{sessionId:bo({currentSessionId:f.currentSessionId,piSelectedSessionId:m.selectedSessionId,draft:f.newSessionDraft}),tab:g.activeMainTab,isSettingsOpen:g.isSettingsDialogOpen,settingsPath:g.settingsPage,diffFile:g.pendingDiffFile}},[]),u=l.useCallback((f={})=>{if(t.current)return;const m=d();li(m,f)},[d]);l.useEffect(()=>{if(e.current||(e.current=!0,!da()))return;const f=ua();(async()=>(await c(f),li({...d(),sessionId:f.sessionId??bo({currentSessionId:Me.getState().currentSessionId,piSelectedSessionId:dn().getState().selectedSessionId,draft:Me.getState().newSessionDraft}),tab:f.tab??ue.getState().activeMainTab,settingsPath:f.settingsPath??ue.getState().settingsPage,diffFile:f.diffFile??ue.getState().pendingDiffFile},{replace:!0,force:!0})))()},[c,d]),l.useEffect(()=>{const f=()=>{const y=Me.getState(),x=dn().getState();return bo({currentSessionId:y.currentSessionId,piSelectedSessionId:x.selectedSessionId,draft:y.newSessionDraft})};let m=f(),g=Me.getState().newSessionDraft?.open===!0;const b=()=>{const y=Me.getState(),x=f(),C=y.newSessionDraft?.open===!0;x===m&&C===g||t.current||(m=x,g=C,u({replace:!0}))},h=Me.subscribe(()=>{b()}),p=dn().subscribe(()=>{b()});return()=>{h(),p()}},[u]),l.useEffect(()=>{let f=ue.getState().activeMainTab,m=ue.getState().isSettingsDialogOpen,g=ue.getState().settingsPage,b=ue.getState().pendingDiffFile;return ue.subscribe(p=>{if(t.current)return;const y=p.activeMainTab!==f,x=p.isSettingsDialogOpen!==m,C=p.settingsPage!==g,j=p.pendingDiffFile!==b&&p.activeMainTab==="diff";f=p.activeMainTab,m=p.isSettingsDialogOpen,g=p.settingsPage,b=p.pendingDiffFile,(y||x||C||j)&&u()})},[u]),l.useEffect(()=>{if(typeof window>"u")return;const f=()=>{const m=ua();if(da())c(m);else{const g=ue.getState();g.isSettingsDialogOpen&&o(!1),g.activeMainTab!=="chat"&&r("chat")}};return window.addEventListener("popstate",f),()=>{window.removeEventListener("popstate",f)}},[c,r,o])}function Up(e=!0){const t=Rr(r=>r.checkForUpdates),n=l.useRef(t);l.useEffect(()=>{n.current=t},[t]),l.useEffect(()=>{if(!e)return;const r=3e3,o=3600*1e3,i=300*1e3,a=1440*60*1e3;let c=!1,d=null;const u=m=>{const g=Math.round(m*1e3);return Math.max(i,Math.min(a,g))},f=m=>{c||(d=window.setTimeout(async()=>{const g=await n.current(),b=typeof g=="number"&&Number.isFinite(g)?u(g):o;f(b)},m))};return f(r),()=>{c=!0,d!==null&&window.clearTimeout(d)}},[e])}function Yw(){const e=Qn(t=>t.connection==="ready",void 0,"chrome");return Up(e),null}const $p=200,Kp=15e3,Wp=e=>{const{id:t,url:n}=e.payload,r=Hu(e.payload);if(!r.showNotice)return;const o=`open-request:${t}`,i=qu(Vu(n),r.target,{isMobile:ue.getState().isMobile});if(!i.canOpen){oe.info(i.title,{id:o,description:i.description,duration:Kp});return}oe.info(i.title,{id:o,description:i.description,duration:1/0,action:{label:"Open",onClick:()=>{Yu(r.target,n,Qu()||e.directory)}},cancel:{label:"Dismiss",onClick:()=>{oe.dismiss(o)}}})},Qw=()=>(l.useEffect(()=>{const e=new Set;return Gu(t=>{if(!e.has(t.payload.id)){if(e.add(t.payload.id),e.size>$p){const n=e.values().next().value;n!==void 0&&e.delete(n)}Wp(t)}})},[]),null),Ia=12,Gp=[{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"}],Hp=({isActive:e,burstKey:t=0,className:n,durationMs:r=900,bursts:o=Gp,onComplete:i})=>{const a=Te.useRef(!1);Te.useEffect(()=>{!e&&a.current&&i?.(),e&&(a.current=!0)},[e,i]);const c=Te.useMemo(()=>Array.from({length:Ia},(d,u)=>{const f=Math.PI*2*u/Ia;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,m)=>{const g=f.x*d.radius,b=f.y*d.radius,h={"--translate-x":`${g}px`,"--translate-y":`${b}px`,"--particle-delay":`${f.delay}ms`,color:`var(${d.colorVar})`};return s.jsx("span",{className:"firework-particle",style:h},`${d.id}-${m}-${t}`)})},`${d.id}-${t}`)})}):null},qp=({durationMs:e=3400}={})=>{const[t,n]=Te.useState({isActive:!1,cycle:0}),r=Te.useRef(null),o=Te.useCallback(()=>{r.current&&(window.clearTimeout(r.current),r.current=null)},[]),i=Te.useCallback(()=>{o(),n(c=>c.isActive?{...c,isActive:!1}:c)},[o]),a=Te.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 Te.useEffect(()=>()=>o(),[o]),{isActive:t.isActive,burstKey:t.cycle,triggerFireworks:a,dismissFireworks:i}},jc=l.createContext(void 0),Jw=({children:e})=>{const{isActive:t,burstKey:n,triggerFireworks:r,dismissFireworks:o}=qp(),i=l.useMemo(()=>({triggerFireworks:r,dismissFireworks:o}),[r,o]);return s.jsxs(jc.Provider,{value:i,children:[e,s.jsx(Hp,{isActive:t,burstKey:n})]})},Vp={triggerFireworks:()=>{},dismissFireworks:()=>{}},Xw=()=>l.useContext(jc)??Vp,$r=2e3,kc=600*1e3;async function Yp(){try{const e=await st("/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 Qp(e,t=Math.ceil(kc/$r),n=$r,r=et()){for(let o=0;o<t;o++){if(et()!==r)return{applied:!1,stale:!0};try{const i=await st("/api/pi/update-check",{method:"GET",headers:{Accept:"application/json"}});if(et()!==r)return{applied:!1,stale:!0};if(i.ok){const a=await i.json().catch(()=>null);if(et()!==r)return{applied:!1,stale:!0};if(typeof a?.error=="string"&&a.error.length>0)return{applied:!1,error:a.error};if(a&&a.available===!1)return{applied:!0};if(a&&typeof a.currentVersion=="string"&&typeof e=="string"&&a.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(et()!==r)return{applied:!1,stale:!0}}await new Promise(i=>setTimeout(i,n))}return{applied:!1}}async function Jp(e,t,n=Math.ceil(kc/$r),r=$r,o=et()){for(let i=0;i<n;i++){if(et()!==o)return{applied:!1,stale:!0};try{const a=await st(`/api/pi/update-install/${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"}});if(et()!==o)return{applied:!1,stale:!0};if(a.ok){const c=await a.json().catch(()=>null);if(et()!==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(a.status===401||a.status===403)return{applied:!1,error:"Authentication was lost while following the update. Reauthenticate to check its status."};if(a.status===404)return{applied:!1,error:"The server lost the update status. Check the installed version or run: pichamber update"};if(a.status===503){const c=await a.json().catch(()=>null);if(et()!==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(et()!==o)return{applied:!1,stale:!0};t("reconnecting")}await new Promise(a=>setTimeout(a,r))}return{applied:!1}}const Ea="https://github.com/RyderAsKing/PiChamber/releases";function Xp(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 Zp(e){return e.replace(/^## \[[^\]]+\] - \d{4}-\d{2}-\d{2}\s*\n?/,"").trim()}function Da(e){return e.replace(/(^|[^a-zA-Z0-9])@([a-zA-Z0-9-]+)/g,"$1[@$2](https://github.com/$2)")}function em(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,a]=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,m=Number.isFinite(d[u])?d[u]:0;if(f!==m)return m-f}return!o||!a?(o?1:0)-(a?1:0):a.localeCompare(o,void 0,{numeric:!0})}function tm(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 a=n[i+1]?.start??e.length,c=e.slice(o.start,a).trim();return{version:o.version,date:o.date,start:o.start,end:a,raw:c}})}const Cc=({open:e,onOpenChange:t,info:n,downloading:r,downloaded:o,progress:i,error:a,onDownload:c,onRestart:d,runtimeType:u="desktop"})=>{const[f,m]=Te.useState(null),[g,b]=Te.useState("idle"),[h,p]=Te.useState(null),[y,x]=Te.useState(null),[C,j]=Te.useState({}),A=n?.version?n.releaseUrl||`${Ea}/tag/v${n.version}`:Ea,w=n?.downloadUrl||A,S=i?.total?Math.round(i.downloaded/i.total*100):0,v=u==="web",k=u==="mobile",E=n?.updateCommand||"pichamber update",P=C.version||n?.version,z=C.channel||n?.channel;Te.useEffect(()=>{e||(b("idle"),p(null),x(null),j({}))},[e]);const K=async(I=E)=>{(await hs(I)).ok&&(m(I),setTimeout(()=>m(null),2e3))},q=Te.useCallback(async I=>{await $l(I)},[]),H=Te.useCallback(async()=>{const I=et();b("updating"),p(null),x(null),j({});const M=await Yp();if(et()!==I)return;if(!M.success){b("error"),p(M.error||"Update failed"),x(M.commands??null);return}if(j({version:M.targetVersion,channel:M.channel}),M.jobId){const W=await Jp(M.jobId,L=>{et()===I&&b(L)},void 0,void 0,I);if(W.stale||et()!==I)return;if(W.applied){window.location.reload();return}b("error"),p(W.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update");return}b(M.autoRestart?"restarting":"reconnecting");const G=await Qp(n?.currentVersion,void 0,void 0,I);if(!(G.stale||et()!==I)){if(G.applied){window.location.reload();return}b("error"),p(G.error||"Update is taking longer than expected. Wait a bit and refresh, or run: pichamber update")}},[n?.currentVersion]),F=Te.useCallback(()=>{q(w)},[q,w]),D=g!=="idle"&&g!=="error",T=Te.useMemo(()=>{if(!n?.body)return null;const I=n.body.trim();if(!I)return null;const M=tm(I);return M.length===0?{kind:"raw",title:"What's new",content:Da(I)}:{kind:"sections",title:"What's new",sections:[...M].sort((W,L)=>em(W.version,L.version)).map(W=>({version:W.version,dateLabel:Xp(W.date),content:Da(Zp(W.raw)||I)}))}},[n?.body]);return s.jsx(ss,{open:e,onOpenChange:D?void 0:t,children:s.jsxs(ns,{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(gs,{className:"flex items-center gap-2.5",children:[s.jsx(R,{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:g==="restarting"||g==="reconnecting"?"Updating PiChamber...":"Update available"})]}),(n?.currentVersion||P||v&&z)&&s.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 pl-[1.875rem]",children:[(n?.currentVersion||P)&&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&&P&&s.jsx("span",{className:"text-subtle-foreground","aria-hidden":"true",children:"→"}),P&&s.jsx("span",{className:"text-[var(--primary-base)] font-medium",children:P})]}),v&&z&&s.jsx("span",{className:"whitespace-nowrap typography-meta text-muted-foreground",children:z==="rc"?"RC channel":"Stable channel"})]})]}),s.jsxs("div",{className:"space-y-2",children:[v&&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(R,{name:"loader",className:"h-5 w-5 animate-spin text-[var(--primary-base)]"}),s.jsxs("div",{className:"typography-ui-label text-foreground",children:[g==="updating"&&"Installing update...",g==="restarting"&&"Server restarting...",g==="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."})]}),T&&!D&&s.jsx("div",{className:"rounded-lg border border-[var(--surface-subtle)] bg-[var(--surface-elevated)]/20 overflow-hidden",children:s.jsx(zs,{className:"max-h-[min(400px,50dvh)] p-0",fillContainer:!1,children:T.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 G=I.target.closest("a");G&&G.href&&(I.preventDefault(),I.stopPropagation(),q(G.href))},children:s.jsx(fa,{content:T.content,disableLinkSafety:!0,enableFileReferences:!1})}):s.jsx("div",{className:"divide-y divide-[var(--surface-subtle)]",children:T.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:M=>{const W=M.target.closest("a");W&&W.href&&(M.preventDefault(),M.stopPropagation(),q(W.href))},children:s.jsx(fa,{content:I.content,disableLinkSafety:!0,enableFileReferences:!1})})]},I.version))})})}),(a||h)&&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:a||h})}),v&&g==="error"&&(y??[E]).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(R,{name:"terminal",className:"h-4 w-4"}),s.jsx("span",{children:y?"Run these commands:":"Or update via terminal:"})]}),(y??[E]).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(Ae,{variant:"ghost",size:"icon",onClick:()=>{K(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(R,{name:"check",className:"h-4 w-4"}):s.jsx(R,{name:"clipboard",className:"h-4 w-4"})})]},I))]}),!v&&!k&&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:[S,"%"]})]}),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:`${S}%`}})})]})]}),s.jsxs("div",{className:"mt-4 flex flex-wrap items-center justify-between gap-x-4 gap-y-2",children:[s.jsxs("a",{href:A,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(R,{name:"external-link",className:"h-4 w-4"}),"GitHub"]}),s.jsxs("div",{className:"flex-1 flex justify-end",children:[!v&&!k&&!o&&!r&&s.jsxs(Ae,{onClick:c,children:[s.jsx(R,{name:"download",className:"h-4 w-4"}),"Download update"]}),!v&&!k&&r&&s.jsxs(Ae,{disabled:!0,children:[s.jsx(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Downloading..."]}),!v&&!k&&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(R,{name:"restart",className:"h-4 w-4"}),"Restart to update"]}),k&&s.jsxs(Ae,{onClick:F,size:"default",children:[s.jsx(R,{name:"external-link",className:"h-4 w-4"}),"Open update"]}),v&&!D&&s.jsxs(Ae,{onClick:H,children:[s.jsx(R,{name:"download",className:"h-4 w-4"}),"Update now"]}),v&&D&&s.jsxs(Ae,{disabled:!0,children:[s.jsx(R,{name:"loader",className:"h-4 w-4 animate-spin"}),"Updating..."]})]})]})]})})},fr=({children:e,className:t,contentClassName:n})=>{const[r,o]=l.useState(!1),i=l.useRef(null);return l.useEffect(()=>{if(!r)return;const a=c=>{const d=i.current;d&&c.target instanceof Node&&d.contains(c.target)||o(!1)};return document.addEventListener("pointerdown",a,!0),()=>document.removeEventListener("pointerdown",a,!0)},[r]),s.jsxs(Ke,{open:r,onOpenChange:o,children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{ref:i,type:"button","aria-label":"More information","aria-expanded":r,onClick:a=>{a.preventDefault(),a.stopPropagation(),o(c=>!c)},className:_("inline-flex h-5 w-5 shrink-0 cursor-help items-center justify-center rounded text-subtle-foreground hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",t),children:s.jsx(R,{name:"information",className:"h-3.5 w-3.5"})})}),s.jsx(Ge,{sideOffset:8,className:_("max-w-sm",n),children:e})]})},Zw="w-full min-w-40 max-w-48",sm="settings",nm="w-full min-w-40 max-w-48",rm="h-8 w-8 px-0 text-muted-foreground hover:text-foreground",om="w-full max-w-[24rem]",ev="min-w-0 flex-1",tv="flex w-full min-w-0 items-center gap-2",sv="typography-meta shrink-0 text-muted-foreground tabular-nums",Oi="space-y-3.5",im="space-y-1.5",nv="typography-settings-page-title text-foreground",am="typography-settings-section-title text-foreground",Ac="typography-settings-group-title text-foreground",Bi="typography-settings-field-label text-foreground",lm="typography-settings-description text-muted-foreground",Cs="typography-meta text-muted-foreground",cm="typography-meta font-medium text-foreground",dm=({title:e,description:t,titleAccessory:n,info:r,headerAction:o,children:i,divider:a=!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",a?"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:am,children:e}):e,n,r!=null?s.jsx(fr,{children:r}):null]}):null,t!=null?s.jsx("div",{className:lm,children:t}):null]}),o?s.jsx("div",{className:"shrink-0",children:o}):null]}):null,s.jsx("div",{className:_(d),children:i})]})},rv=({children:e,className:t})=>s.jsx("div",{className:_("grid grid-cols-1 gap-6 @3xl:grid-cols-2 @3xl:gap-10",t),children:e}),um=({children:e,className:t,as:n="h3"})=>s.jsx(n,{className:_(Ac,t),children:e}),ov=({title:e,description:t,info:n,children:r,className:o,contentClassName:i,settingsItem:a})=>s.jsxs("div",{"data-settings-item":a,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(um,{children:e}),n!=null?s.jsx(fr,{children:n}):null]}):null,t!=null?s.jsx("p",{className:Cs,children:t}):null]}):null,s.jsx("div",{className:_(i),children:r})]}),As=({label:e,description:t,info:n,descriptionPlacement:r="before",children:o,settingsItem:i,className:a,controlClassName:c})=>{const d=t!=null?s.jsx("p",{className:Cs,children:t}):null;return s.jsxs("div",{"data-settings-item":i,className:_("space-y-2",a),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:Bi,children:e}),n!=null?s.jsx(fr,{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]})},iv=({label:e,description:t,info:n,children:r,settingsItem:o,className:i,labelClassName:a,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",a),children:[s.jsxs("div",{className:"flex items-center gap-1.5",children:[s.jsx("div",{className:Bi,children:e}),n!=null?s.jsx(fr,{children:n}):null]}),t!=null?s.jsx("p",{className:_(Cs,"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})]}),fm="typography-meta text-muted-foreground",av=({children:e,className:t,"aria-label":n})=>s.jsx("ul",{"aria-label":n,className:_("divide-y divide-border/60 overflow-hidden rounded-xl border border-border/60 bg-[var(--surface-elevated)]",t),children:e}),lv=({title:e,titleAccessory:t,leading:n,detail:r,trailing:o,mono:i=!1,dimmed:a=!1,wrap:c=!1,heading:d=!1,interactive:u=!1,stackTrailing:f=!1,className:m,settingsItem:g})=>{const b=r!=null&&r!==!1,h=o!=null&&o!==!1;return s.jsxs("li",{"data-settings-item":g,className:_("relative flex min-w-0 items-center gap-x-3 px-3.5 py-2.5",d&&"bg-muted/50",u&&"transition-colors hover:bg-interactive-hover/60",m),children:[n,s.jsxs("div",{className:_("grid min-w-0 flex-1 items-center gap-x-3 gap-y-0.5",h&&!f?"grid-cols-[minmax(0,1fr)_auto]":"grid-cols-1",h&&f&&"@xl:grid-cols-[minmax(0,1fr)_auto]"),children:[s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[typeof e=="string"||typeof e=="number"?s.jsx("span",{className:_("min-w-0",c?"text-pretty":"truncate",i?"font-mono typography-code":"typography-ui-label",d&&"font-medium",a?"text-muted-foreground":"text-foreground"),children:e}):e,t]}),h?s.jsx("div",{className:_("flex min-w-0 items-center gap-2",f?"order-last mt-1 @xl:order-none @xl:mt-0 @xl:justify-self-end":"justify-self-end",b&&"@xl:row-span-2"),children:o}):null,b?s.jsx("div",{className:_("min-w-0 space-y-0.5",h&&!f&&"col-span-2 @xl:col-span-1"),children:typeof r=="string"||typeof r=="number"?s.jsx("p",{className:_(fm,"line-clamp-2 text-pretty"),children:r}):r}):null]})]})},cv=({title:e,children:t,action:n,className:r})=>s.jsxs("div",{role:"status",className:_("flex flex-col gap-x-4 gap-y-2.5 rounded-lg border border-[var(--status-warning-border)] bg-[var(--status-warning-background)] px-3.5 py-3","@xl:flex-row @xl:items-center @xl:justify-between",r),children:[s.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e!=null?s.jsx("p",{className:cm,children:e}):null,t!=null?s.jsx("p",{className:"typography-meta text-pretty text-foreground",children:t}):null]}),n!=null?s.jsx("div",{className:"shrink-0",children:n}):null]}),dv=({children:e,className:t,settingsItem:n})=>s.jsx("div",{"data-settings-item":n,className:_("pt-4",t),children:e}),uv=({label:e,children:t,divider:n=!0,className:r,contentClassName:o,defaultOpen:i=!1})=>{const[a]=l.useState(i);return s.jsxs("details",{open:a||void 0,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(R,{name:"arrow-right-s",className:"size-4 transition-transform group-open/disclosure:rotate-90"}),e]}),s.jsx("div",{className:_("pt-4",o),children:t})]})},hm=({checked:e,onChange:t,label:n,description:r,disabled:o=!1,ariaLabel:i,settingsItem:a,className:c,labelAccessory:d,info:u})=>{const f=()=>{o||t(!e)},m=r!=null;return s.jsxs("div",{"data-settings-item":a,className:_("group flex cursor-pointer gap-2 py-0.5",m?"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:g=>{(g.key===" "||g.key==="Enter")&&(g.preventDefault(),f())},children:[s.jsx(tr,{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:Bi,children:n}),d,u!=null?s.jsx(fr,{children:u}):null]}),m?s.jsx("span",{className:Cs,children:r}):null]})]})},fv=({selected:e,onSelect:t,label:n,description:r,ariaLabel:o,disabled:i=!1,className:a})=>s.jsxs("div",{className:_("flex cursor-pointer gap-2 py-0.5",r!=null?"items-start":"items-center",i&&"cursor-not-allowed opacity-60",a),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(Kl,{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","text-foreground"),children:n}),r!=null?s.jsx("span",{className:Cs,children:r}):null]})]}),hv=({selected:e,onSelect:t,label:n,preview:r,description:o,ariaLabel:i,disabled:a=!1,className:c})=>{const d=l.useId();return s.jsxs("div",{className:_("group/preview flex min-w-0 cursor-pointer flex-col gap-2",a&&"cursor-not-allowed opacity-60",c),role:"radio",tabIndex:a?-1:0,"aria-checked":e,"aria-label":i,"aria-describedby":o?d:void 0,"aria-disabled":a||void 0,onClick:()=>{a||t()},onKeyDown:u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),a||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-[var(--interactive-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(Kl,{checked:e,onChange:t,disabled:a,decorative:!0}),s.jsx("span",{className:_("min-w-0 truncate typography-settings-field-label font-normal","text-foreground"),children:n})]}),o?s.jsx("p",{id:d,className:"-mt-1 pl-[20px] typography-meta text-muted-foreground text-pretty",children:o}):null]})},pv=({"aria-label":e,children:t,className:n})=>s.jsx("div",{role:"radiogroup","aria-label":e,className:_(im,n),children:t});function pm({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(Ae,{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 ui="pichamber:server-update-channel-changed",mv=()=>{typeof window<"u"&&window.dispatchEvent(new Event(ui))},mm=e=>typeof window>"u"?()=>{}:(window.addEventListener(ui,e),()=>window.removeEventListener(ui,e));class gm extends l.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(Ju,{className:"w-full max-w-md",children:[s.jsx(Xu,{className:"text-center",children:s.jsxs(Zu,{className:"flex items-center justify-center gap-2 text-destructive",children:[s.jsx(R,{name:"chat-3",className:"h-5 w-5"}),this.props.texts.title]})}),s.jsxs(ef,{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(Ae,{onClick:this.handleReset,variant:"outline",className:"flex-1",children:[s.jsx(R,{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 bm(e){return s.jsx(gm,{...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 gv=({active:e=!0})=>{const t=Me(n=>n.currentSessionId);return s.jsx(bm,{sessionId:t||void 0,children:s.jsx(tf,{active:e},t??"no-session")})};function xm({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 _i=Te.forwardRef(({className:e,outerClassName:t,scrollbarClassName:n,fillContainer:r=!1,useScrollShadow:o=!1,scrollShadowSize:i,hasError:a,resizedHeight:c,onResizeHeightChange:d,disabled:u,simple:f,endSlot:m,...g},b)=>{const h=Te.useRef(null),p=Te.useRef(null),[y,x]=Te.useState(null),C=c??y,j=Te.useCallback(w=>{const S=h.current;if(!S)return;p.current={startY:w.clientY,startHeight:S.getBoundingClientRect().height};const v=w.currentTarget;v.setPointerCapture(w.pointerId);const k=P=>{const z=p.current;if(!z)return;const K=z.startHeight+(P.clientY-z.startY),q=Math.max(82,K);d?d(q):x(q)},E=()=>{p.current=null,v.removeEventListener("pointermove",k),v.removeEventListener("pointerup",E),v.removeEventListener("pointercancel",E)};v.addEventListener("pointermove",k),v.addEventListener("pointerup",E),v.addEventListener("pointercancel",E),w.preventDefault()},[d]),A=Te.useCallback(w=>{if(w.target.closest('textarea, button, [role="separator"]'))return;const v=h.current?.querySelector("textarea");v&&document.activeElement!==v&&(w.preventDefault(),v.focus())},[]);return f?s.jsx(zs,{as:"textarea",ref:b,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,...g}):s.jsx("div",{ref:h,onPointerDown:A,style:C!==null?{height:`${C}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",!a&&["hover:[&:not(:focus-within)]:ring-transparent","focus-within:ring-2 focus-within:ring-[var(--interactive-focus-ring)]"],a&&["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:b,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-subtle-foreground placeholder:text-subtle-foreground",e),spellCheck:!1,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",disabled:u,...g}),s.jsxs("div",{className:"flex items-center justify-end gap-1.5 pl-3 pr-2.5",children:[m,s.jsx(xm,{onResizeStart:j,ariaLabel:"Resize textarea"})]})]})})});_i.displayName="Textarea";const ym=e=>`install:${e}`,wm=5e3,rn=e=>e?.trim()??"",vm=e=>e instanceof Error&&e.message?e.message:"Could not reach the server.";let Ss=0,ko=0;const zn=new Map,on=new Map,Ra=e=>{if(e.deferred===void 0)return e;const t={...e};return delete t.deferred,t},Sm=(e,t)=>e.project.available===!!t,Pa=(e,t,n)=>{if(!e?.config)return e;let r=!1;const o=e.config.extensions.map(i=>{if(i.id!==t)return i;const a=n(i);return a!==i&&(r=!0),a});return r?{...e,config:{...e.config,extensions:o}}:e},jm=bs()((e,t)=>{const n=(d,u)=>d===Ss&&Xe()===u,r=(d,u,f)=>{const m=Sm(f,d)&&on.get(d)===u;e(g=>{const b={};for(const[h,p]of Object.entries(g.entries))b[h]=h===d?p:{...p,loadedAt:0};return m&&(b[d]={config:Ra(f),status:"ready",error:null,loadedAt:Date.now()}),{entries:b}}),!m&&on.get(d)===u&&o(d)},o=async d=>{const u=zn.get(d);u&&await u,await t().load(d||null,{force:!0})},i=d=>{e(u=>{if(!u.pending[d])return u;const f={...u.pending};return delete f[d],{pending:f}})},a=async(d,u,f,m)=>{if(t().pending[d])return{ok:!1,error:new Error("A change to this extension is still saving.")};const g=Xe(),b=Ss,h=++ko;on.set(u,h);let p;e(y=>{const x=Pa(y.entries[u],d,C=>(p=C,f(C)));return{pending:{...y.pending,[d]:!0},entries:x?{...y.entries,[u]:x}:y.entries}});try{const y=await m(g);return n(b,g)?(r(u,h,y),i(d),{ok:!0,deferred:y.deferred===!0}):{ok:!0,deferred:y.deferred===!0}}catch(y){return n(b,g)?(e(x=>{const C=p,j=C?Pa(x.entries[u],d,()=>C):x.entries[u];return j?{entries:{...x.entries,[u]:j}}:x}),i(d),o(u),{ok:!1,error:y}):{ok:!1,error:y}}},c=async(d,u,f,m)=>{if(t().pending[d])return{ok:!1,error:new Error(f)};const g=Xe(),b=Ss,h=++ko;on.set(u,h),e(p=>({pending:{...p.pending,[d]:!0}}));try{const p=await m(u,g);return n(b,g)?(r(u,h,p),i(d),{ok:!0,deferred:p.deferred===!0}):{ok:!0,deferred:p.deferred===!0}}catch(p){return n(b,g)?(i(d),o(u),{ok:!1,error:p}):{ok:!1,error:p}}};return{entries:{},pending:{},load:async(d,u)=>{const f=rn(d),m=t().entries[f];if(!u?.force&&m?.status==="ready"&&Date.now()-m.loadedAt<wm)return;const g=zn.get(f);if(g)return g;const b=Xe(),h=Ss,p=ko;e(x=>({entries:{...x.entries,[f]:{config:x.entries[f]?.config??null,status:"loading",error:null,loadedAt:x.entries[f]?.loadedAt??0}}}));const y=(async()=>{try{const x=await Wt.getExtensionConfig(f||void 0,{runtimeKey:b});if(h!==Ss||Xe()!==b)return;e(C=>{const j=C.entries[f],A=(on.get(f)??0)>p&&!!j?.config;return{entries:{...C.entries,[f]:A&&j?{...j,status:"ready",error:null}:{config:Ra(x),status:"ready",error:null,loadedAt:Date.now()}}}})}catch(x){if(h!==Ss||Xe()!==b)return;e(C=>({entries:{...C.entries,[f]:{config:C.entries[f]?.config??null,status:"error",error:vm(x),loadedAt:C.entries[f]?.loadedAt??0}}}))}finally{h===Ss&&zn.delete(f)}})();return zn.set(f,y),y},setGlobal:(d,u)=>a(d,"",f=>f.global===u?f:{...f,global:u},f=>Wt.setExtensionConfig(d,{scope:"global",enabled:u},{runtimeKey:f})),setProjectEnabled:(d,u,f)=>{const m=rn(f);return m?a(d,m,g=>{if(!g.project||g.project.enabled===u)return g;const b=u===g.project.inherited?"inherit":u?"load":"unload";return{...g,project:{...g.project,state:b,enabled:u}}},g=>Wt.setExtensionConfig(d,{scope:"project",enabled:u,directory:m},{runtimeKey:g})):Promise.resolve({ok:!1,error:new Error("A project setting needs a project.")})},setProjectState:(d,u,f)=>{const m=rn(f);return m?a(d,m,g=>{if(!g.project||g.project.state===u)return g;const b=u==="inherit"?g.project.inherited:u==="load";return{...g,project:{...g.project,state:u,enabled:b}}},g=>Wt.setExtensionConfig(d,{scope:"project",state:u,directory:m},{runtimeKey:g})):Promise.resolve({ok:!1,error:new Error("A project setting needs a project.")})},removePackage:(d,u)=>c(d,rn(u),"This package is already being removed.",(f,m)=>Wt.removeExtensionPackage(d,f||void 0,{runtimeKey:m})),installPackage:(d,u)=>c(ym(d),rn(u),"This package is already being installed.",(f,m)=>Wt.installExtensionPackage({name:d,scope:f?"project":"user",...f?{directory:f}:{}},{runtimeKey:m})),updatePackage:(d,u)=>c(d,rn(u),"This package is already being updated.",(f,m)=>Wt.updateExtensionPackage(d,f||void 0,{runtimeKey:m})),invalidate:()=>{e(d=>{const u={};for(const[f,m]of Object.entries(d.entries))u[f]={...m,loadedAt:0};return{entries:u}})},resetForRuntimeSwitch:()=>{Ss+=1,zn.clear(),on.clear(),e({entries:{},pending:{}})}}}),Co=300*1e3,km=(e,t)=>`${t?"1":"0"}
|
|
3
|
+
${e.trim().replace(/\s+/g," ").toLowerCase()}`,wr=()=>({data:null,status:"loading",loadedAt:0});let Os=0;const vr=new Map,Sr=new Set,Ao=(e,t)=>{let n=e;for(const r of t)!r.version||e[r.name]===r.version||(n===e&&(n={...e}),n[r.name]=r.version);return n},Cm=bs()((e,t)=>{const n=(r,o)=>{const i=vr.get(r);if(i)return i;const a=Os,c=Xe(),u=o(()=>a===Os&&Xe()===c).finally(()=>{a===Os&&vr.delete(r)});return vr.set(r,u),u};return{featured:wr(),searches:{},details:{},latest:{},loadFeatured:r=>{const o=t().featured;return!r?.force&&o.status==="ready"&&Date.now()-o.loadedAt<Co?Promise.resolve():n("featured",async i=>{e(a=>({featured:{...a.featured,status:"loading"}}));try{const a=await Wt.getMarketplaceFeatured({runtimeKey:Xe()});if(!i())return;e(c=>({featured:{data:a,status:"ready",loadedAt:Date.now()},latest:Ao(c.latest,a.packages)}))}catch{if(!i())return;e(a=>({featured:{...a.featured,status:"error"}}))}})},search:(r,o,i)=>{const a=km(r,o),c=t().searches[a],d=i?.more===!0;if(d){if(!c||c.status!=="ready"||c.nextFrom===null||c.loadingMore)return Promise.resolve()}else if(!i?.force&&c?.status==="ready"&&Date.now()-c.loadedAt<Co)return Promise.resolve();const u=d&&c?c.nextFrom??0:0;return n(`search
|
|
4
|
+
${a}
|
|
5
|
+
${u}`,async f=>{e(m=>{const g=m.searches[a];return{searches:{...m.searches,[a]:d&&g?{...g,loadingMore:!0,moreFailed:!1}:{packages:g?.packages??[],...g?.total!==void 0?{total:g.total}:{},nextFrom:g?.nextFrom??null,status:"loading",loadingMore:!1,moreFailed:!1,loadedAt:g?.loadedAt??0}}}});try{const m=await Wt.searchMarketplace({query:r.trim(),from:u,pichamberOnly:o},{runtimeKey:Xe()});if(!f())return;e(g=>{const b=g.searches[a],h=new Set(d&&b?b.packages.map(y=>y.name):[]),p=d&&b?[...b.packages,...m.packages.filter(y=>!h.has(y.name))]:m.packages;return{searches:{...g.searches,[a]:{packages:p,...m.total!==void 0?{total:m.total}:{},nextFrom:m.nextFrom,status:"ready",loadingMore:!1,moreFailed:!1,loadedAt:d&&b?b.loadedAt:Date.now()}},latest:Ao(g.latest,m.packages)}})}catch{if(!f())return;e(m=>{const g=m.searches[a];return g?{searches:{...m.searches,[a]:d?{...g,loadingMore:!1,moreFailed:!0}:{...g,status:"error"}}}:m})}})},loadDetail:(r,o)=>{const i=t().details[r];return!o?.force&&i?.status==="ready"&&Date.now()-i.loadedAt<Co?Promise.resolve():n(`detail
|
|
6
|
+
${r}`,async a=>{e(c=>({details:{...c.details,[r]:{...c.details[r]??wr(),status:"loading"}}}));try{const c=await Wt.getMarketplacePackage(r,{runtimeKey:Xe()});if(!a())return;e(d=>({details:{...d.details,[r]:{data:c,status:"ready",loadedAt:Date.now()}},latest:Ao(d.latest,[c])}))}catch{if(!a())return;e(c=>({details:{...c.details,[r]:{...c.details[r]??wr(),status:"error"}}}))}})},loadVersions:async r=>{const o=[...new Set(r)].filter(c=>!Sr.has(c));if(o.length===0)return;for(const c of o)Sr.add(c);const i=Os,a=Xe();try{for(let c=0;c<o.length;c+=50){const{versions:d}=await Wt.getMarketplaceVersions(o.slice(c,c+50),{runtimeKey:a});if(i!==Os||Xe()!==a)return;e(u=>({latest:{...u.latest,...d}}))}}catch{if(i===Os)for(const c of o)Sr.delete(c)}},resetForRuntimeSwitch:()=>{Os+=1,vr.clear(),Sr.clear(),e({featured:wr(),searches:{},details:{},latest:{}})}}}),Nc=[{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"}],Zn=Object.fromEntries(Nc.map(e=>[e.key,e.Icon])),fi="pichamber:project-actions-updated",Ic=e=>{const t=(e||"").trim().replace(/\\/g,"/");return t?t==="/"?"/":t.length>1?t.replace(/\/+$/,""):t:""},ds=(e,t)=>`${Ic(e)}::${t}`,pn=({title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,children:a,className:c,contentClassName:d,divider:u=!0})=>s.jsx(dm,{title:e,description:t,info:n,settingsItem:r,titleAccessory:o,headerAction:i,divider:u,className:c,contentClassName:d,children:a}),hi=e=>e.name.trim().length>0&&e.command.trim().length>0,Am=e=>e.name.trim().length===0&&e.command.trim().length===0,Nm=e=>!hi(e)&&!Am(e),Im=(e,t)=>e.some(r=>t.has(r.id)&&!hi(r))?{canPersist:!1,actions:e}:{canPersist:!0,actions:e.filter(hi)},Em=450,Dm=()=>typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`action_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,Rm=()=>({id:Dm(),name:"",command:"",icon:"play"}),Pm=({projectRef:e})=>{const[t,n]=l.useState([]),[r,o]=l.useState(!1),[i,a]=l.useState(null),[c,d]=l.useState(new Set),u=l.useRef(!1);l.useEffect(()=>{let x=!1;return o(!0),(async()=>{try{const C=await Jo(e);if(x)return;n(C.actions),a(JSON.stringify({actions:C.actions})),d(new Set(C.actions.map(j=>j.id)))}catch{if(x)return;n([]),a(JSON.stringify({actions:[]})),d(new Set)}finally{x||o(!1)}})(),()=>{x=!0}},[e]);const f=l.useMemo(()=>Im(t,c),[t,c]),m=l.useMemo(()=>JSON.stringify({actions:f.actions}),[f.actions]),g=i!==null&&f.canPersist&&m!==i,b=l.useCallback(async x=>await sf(e,{actions:x,primaryActionId:null})?(a(JSON.stringify({actions:x})),d(new Set(x.map(j=>j.id))),typeof window<"u"&&window.dispatchEvent(new CustomEvent(fi,{detail:{projectId:e.id}})),!0):(oe.error("Failed to save actions"),!1),[e]);l.useEffect(()=>{if(!g||r||u.current)return;const x=window.setTimeout(()=>{u.current||(u.current=!0,(async()=>{try{await b(f.actions)}finally{u.current=!1}})())},Em);return()=>{window.clearTimeout(x)}},[g,r,b,f.actions]);const h=l.useCallback(()=>{const x=Rm();n(C=>[...C,x])},[]),p=l.useCallback(x=>{n(C=>C.filter(j=>j.id!==x))},[]),y=l.useCallback((x,C)=>{n(j=>j.map(A=>A.id===x?C(A):A))},[]);return s.jsx(pn,{title:"Actions",info:"Per-project commands shown in the header next to the project name.",settingsItem:"projects.actions",headerAction:s.jsxs(Ae,{type:"button",variant:"outline",size:"xs",className:"!font-normal",onClick:h,children:[s.jsx(R,{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",om),children:t.map((x,C)=>{const j=x.icon||"play",A=Zn[j]||"play",w=x.name.trim()||`Action ${C+1}`,S=Nm(x);return s.jsxs("div",{className:Oi,children:[s.jsxs("div",{className:"flex items-center justify-between gap-2",children:[s.jsx("h3",{className:Ac,children:w}),s.jsx(Ae,{type:"button",variant:"ghost",size:"xs",className:"h-8 w-8 px-0 text-muted-foreground hover:text-[var(--status-error)]",onClick:()=>p(x.id),"aria-label":`Delete ${w}`,children:s.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]}),s.jsxs(As,{label:"Name",controlClassName:"w-full max-w-none",children:[s.jsxs(Vt,{children:[s.jsx(Yt,{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(R,{name:A,className:"h-4 w-4"})})}),s.jsx(Qt,{align:"start",className:"w-56 p-2",children:s.jsx("div",{className:"grid grid-cols-6 gap-1",children:Nc.map(v=>{const k=v.Icon,E=(x.icon||"play")===v.key;return s.jsx("button",{type:"button",onClick:()=>y(x.id,P=>({...P,icon:v.key})),className:_("inline-flex h-8 w-8 items-center justify-center rounded-md border border-transparent text-foreground hover:bg-[var(--interactive-hover)]",E&&"border-[var(--primary-base)] bg-[var(--primary-base)]/10 text-[var(--primary-base)]"),"aria-label":`Icon ${v.label}`,children:s.jsx(R,{name:k,className:"h-4 w-4"})},v.key)})})})]}),s.jsx(nr,{value:x.name,onChange:v=>y(x.id,k=>({...k,name:v.target.value})),placeholder:"Action name",className:"h-8 min-w-0 flex-1 rounded-md px-3"})]}),s.jsx(As,{label:"Command",controlClassName:"w-full max-w-none",children:s.jsx(_i,{value:x.command,onChange:v=>y(x.id,k=>({...k,command:v.target.value})),placeholder:"e.g. bun run lint",className:"min-h-[88px] w-full font-mono text-xs"})}),S?s.jsx("p",{className:"typography-meta text-muted-foreground",children:"Enter a name and command to save this action."}):null,s.jsx(hm,{checked:x.autoOpenUrl===!0,onChange:v=>y(x.id,k=>({...k,...v?{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 ${w}`}),x.autoOpenUrl===!0?s.jsx(s.Fragment,{children:s.jsx(As,{label:"Custom URL",info:"Leave empty to use the best URL from command output.",controlClassName:"w-full max-w-none",children:s.jsx(nr,{value:x.openUrl||"",onChange:v=>y(x.id,k=>({...k,openUrl:v.target.value})),placeholder:"https://localhost:3000",className:"h-8 w-full rounded-md px-3"})})}):null]},x.id)})})})},Tm={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)"},Mm=({value:e,noneLabel:t,ariaLabel:n,disabled:r=!1,className:o,isModelAllowed:i,onChange:a})=>{const c=Gt(k=>k.providers),d=Gt(k=>k.modelsMetadata),u=ue(k=>k.hiddenModels),f=ue(k=>k.isFavoriteModel),m=ue(k=>k.toggleFavoriteModel),g=ue(k=>k.reorderFavoriteModel),{favoriteModelsList:b,recentModelsList:h}=nf(),[p,y]=l.useState(!1),[x,C]=l.useState("");l.useEffect(()=>{p?Gt.getState().ensureModelMetadata():C("")},[p]);const j=e?c.find(k=>k.id===e.providerId):void 0,A=e&&j?(Array.isArray(j.models)?j.models:[]).find(k=>k.id===e.modelId):void 0,w=e?rf(A,e.modelId):t,S=l.useMemo(()=>e?u.filter(k=>!(k.providerID===e.providerId&&k.modelID===e.modelId)):u,[u,e]),v=l.useCallback(k=>{a({providerId:k.providerID,modelId:k.modelID}),y(!1)},[a]);return s.jsxs(Vt,{modal:!1,open:p,onOpenChange:k=>{r||y(k)},children:[s.jsx(Yt,{asChild:!0,disabled:r,children:s.jsxs("button",{type:"button","aria-label":n,disabled:r,className:_(af({size:"default"}),nm,"min-w-0",o),children:[s.jsxs("span",{className:"flex min-w-0 flex-1 items-center gap-2",children:[e?.providerId?s.jsx(of,{providerId:e.providerId,className:"size-4 shrink-0"}):null,s.jsx("span",{className:_("truncate",e?"text-foreground":"text-muted-foreground"),children:w})]}),s.jsx(R,{name:"arrow-down-s",className:"size-4 shrink-0"})]})}),s.jsx(Qt,{align:"start",portalToBody:!0,positionerClassName:"z-[80]",className:"w-[min(380px,calc(100vw-2rem))] p-0 flex flex-col",children:s.jsx(lf,{providers:c,favoriteModels:b,recentModels:h,modelsMetadata:d,searchQuery:x,onSearchQueryChange:C,onSelect:v,labels:{...Tm,notSelected:t},selectedModel:e?{providerID:e.providerId,modelID:e.modelId}:null,hiddenModels:S,isModelAllowed:i,includeNotSelected:!0,onSelectNone:()=>{a(null),y(!1)},disabled:r,autoFocus:!0,onEscape:()=>y(!1),isFavorite:k=>f(k.providerID,k.modelID),onToggleFavorite:k=>m(k.providerID,k.modelID),onReorderFavorite:(k,E)=>g(k.providerID,k.modelID,E.providerID,E.modelID),reorderFavoriteAriaLabel:"Reorder favorite",reorderFavoriteTitle:"Drag to reorder favorite"})})]})},No="w-full max-w-[24rem]",Fm=({form:e})=>{const{name:t,setName:n,parsedDefaultModel:r,handleDefaultModelChange:o,project:i}=e,a=Gt(c=>c.loadProviders);return l.useEffect(()=>{a({source:"projectSettings"})},[a]),i?s.jsx(pn,{title:"Project",divider:!1,children:s.jsxs("div",{className:Oi,children:[s.jsx(As,{label:"Name",settingsItem:"projects.name",controlClassName:No,children:s.jsx(nr,{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(As,{label:"Default model",info:"Used when starting a new chat in this project. Unset keeps the global session default.",settingsItem:"projects.default-model",controlClassName:No,children:s.jsx(Mm,{value:r,noneLabel:"Use global default",ariaLabel:"Default model for new chats",className:No,onChange:c=>{if(!c){o("","");return}o(c.providerId,c.modelId)}})})]})}):null},Io={read:"Read only",readWrite:"Read and write"},Ta={nono:"On",off:"Off"},Ma="w-full max-w-[24rem]",Lm=({projectId:e})=>{const t=Nt(h=>h.projects[e]),n=Nt(h=>h.projectsStatus),r=Nt(h=>!!h.saving[e]),o=Nt(h=>h.saveErrors[e]),i=Nt(h=>h.loadProjects),a=Nt(h=>h.saveProject),c=Nt(h=>h.defaults),d=Nt(h=>h.loadDefaults),[u,f]=l.useState(!1),m=l.useRef(null),g=l.useCallback(async()=>{f(!1),await i();const h=Nt.getState();h.projectsStatus==="ready"&&!h.projects[e]&&f(!0)},[i,e]);l.useEffect(()=>{m.current=e,g(),d()},[e,g,d]),l.useEffect(()=>{if(t){m.current=null;return}(n==="ready"||n==="failed")&&m.current!==e&&(m.current=e,g())},[t,n,e,g]);const b=l.useCallback(async h=>{if(!cf(h,Nt.getState().projects[e]))return;ya("saving");const p=await a(e,h);ya(p?"saved":"error")},[e,a]);return s.jsx(Om,{projectId:e,state:t,defaults:c,loadFailed:n==="failed",unavailable:u,saving:r,saveError:o,onReload:()=>{g()},onSave:b})},Om=({projectId:e,state:t,defaults:n,loadFailed:r,unavailable:o=!1,saving:i,saveError:a,onReload:c,onSave:d})=>{const[u,f]=l.useState(()=>xo(t)),[m,g]=l.useState(null),b=t?JSON.stringify(xo(t)):"";l.useEffect(()=>{f(xo(t)),g(null)},[e,b]);const h=l.useCallback(async(w,S=!0)=>{const{setting:v,error:k}=ha(w,t);S&&g(k),v&&await d(v)},[d,t]),p=l.useRef({draft:u,save:h});l.useEffect(()=>()=>{p.current.save(p.current.draft,!1)},[e]),l.useEffect(()=>{p.current={draft:u,save:h}});const y=(w,S)=>{const v={...u,...w};f(v),S&&h(v)};if(r&&!t)return s.jsx(pn,{title:"Sandbox",settingsItem:"projects.sandbox",children:s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:Cs,children:"The sandbox setting could not be loaded."}),s.jsx(Ae,{variant:"outline",size:"xs",onClick:c,children:"Try again"})]})});if(!t&&o)return s.jsx(pn,{title:"Sandbox",settingsItem:"projects.sandbox",children:s.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[s.jsx("p",{className:Cs,children:"The sandbox setting is unavailable for this project."}),s.jsx(Ae,{variant:"outline",size:"xs",onClick:c,children:"Try again"})]})});if(!t)return s.jsx(pn,{title:"Sandbox",settingsItem:"projects.sandbox",children:s.jsx("p",{className:Cs,children:"Loading…"})});const x=t.mode!=="off"&&t.availability.state==="unavailable",C=pa(u.mode,n,t),j=n?`Default (${pa("default",n,t)?"on":"off"})`:"Default",A=C?n?.allowHosts??[]:[];return s.jsx(pn,{title:"Sandbox",settingsItem:"projects.sandbox",info:"Runs every session in this project inside nono, so agents reach only this project's folders, its worktrees, the extra folders below and allowed hosts. Default follows Sandbox projects by default in Settings, Projects. Idle sessions switch right away; a session in the middle of a turn switches when the turn ends. Turning the sandbox off resets this project's trust, so Pi asks again before it loads the project's extensions. The setting stays on this server machine.",children:s.jsxs("div",{className:Oi,children:[s.jsx(pm,{"aria-label":"Sandbox for this project",value:u.mode,options:[{value:"default",label:j,disabled:i},{value:"nono",label:Ta.nono,disabled:i},{value:"off",label:Ta.off,disabled:i}],onChange:w=>{const{setting:S,error:v}=ha({...u,mode:w},t);if(!S){g(v);return}y({mode:w},!0)}}),x?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"status",children:`Sessions in this project will not run until the sandbox is available. ${df(t.availability.reason)}`}):null,a?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:a}):null,m?s.jsx("p",{className:"typography-meta text-[var(--status-error)]",role:"alert",children:m}):null,C?s.jsxs(s.Fragment,{children:[s.jsx(As,{label:"Allowed hosts",info:"Hosts this project's agent may reach on top of the hosts for all projects, one per line. The model providers you are signed in to are always allowed. If the agent runs Git fetch or push itself, add the Git host, such as github.com; the agent can use HTTPS remotes only. The Git panel runs outside the sandbox.",description:A.length>0?`Also allowed for all projects: ${A.join(", ")}.`:void 0,descriptionPlacement:"after",controlClassName:Ma,children:s.jsx(_i,{value:u.hostsText,onChange:w=>y({hostsText:w.target.value},!1),onBlur:()=>{h(u)},placeholder:"api.example.com","aria-label":"Allowed hosts, one per line",rows:3,className:"min-h-0 font-mono",readOnly:i})}),s.jsx(As,{label:"Local ports",info:"Ports the agent may connect to on any host, not only the server machine, such as 8080 for a local llama.cpp server. Separate them with commas. Ports 80 and 443 are refused because they would reach any host; add the host above instead.",controlClassName:Ma,children:s.jsx(nr,{value:u.portsText,onChange:w=>y({portsText:w.target.value},!1),onBlur:()=>{h(u)},placeholder:"8080","aria-label":"Local ports",inputMode:"numeric",className:"h-8 w-full rounded-md px-3",readOnly:i})}),s.jsx(As,{label:"Extra folders",info:"Folders outside the project the agent may use, such as a shared docs folder. Use full paths on the server machine.",controlClassName:"w-full max-w-[32rem]",children:s.jsxs("div",{className:"w-full min-w-0 space-y-2",children:[u.folders.map((w,S)=>s.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[s.jsx(nr,{value:w.path,onChange:v=>{const k=u.folders.map((E,P)=>P===S?{...E,path:v.target.value}:E);y({folders:k},!1)},onBlur:()=>{h(u)},placeholder:"/home/me/docs","aria-label":`Extra folder ${S+1} path`,className:"h-8 min-w-0 flex-1 rounded-md px-3 font-mono",readOnly:i}),s.jsxs(uf,{value:w.access,disabled:i,onValueChange:v=>{const k=v,E=u.folders.map((P,z)=>z===S?{...P,access:k}:P);y({folders:E},!0)},children:[s.jsx(ff,{size:sm,className:"w-36 shrink-0","aria-label":`Extra folder ${S+1} access`,children:s.jsx(hf,{children:v=>Io[v]??""})}),s.jsxs(pf,{children:[s.jsx(ma,{value:"read",children:Io.read}),s.jsx(ma,{value:"readWrite",children:Io.readWrite})]})]}),s.jsx(Ae,{variant:"ghost",size:"icon",className:rm,"aria-label":`Remove extra folder ${S+1}`,title:"Remove folder",disabled:i,onClick:()=>y({folders:u.folders.filter((v,k)=>k!==S)},!0),children:s.jsx(R,{name:"close",className:"size-4"})})]},S)),s.jsx(Ae,{variant:"outline",size:"xs",disabled:i,onClick:()=>y({folders:[...u.folders,{path:"",access:"read"}]},!1),children:"Add folder"})]})})]}):null]})})},Bm=e=>{const[t,n]=l.useState(""),[r,o]=l.useState(void 0);l.useEffect(()=>{if(!e){n(""),o(void 0);return}n(e.label??""),o(e.defaultModel)},[e]);const i=l.useMemo(()=>mf(r),[r]),a=!!e&&(t.trim()!==(e?.label??"").trim()||(r??void 0)!==(e?.defaultModel??void 0)),c=l.useCallback((u,f)=>{o(u&&f?`${u}/${f}`:void 0)},[]),d=l.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:a,prepareSaveData:d,project:e}},_m=450,zm=(e,t)=>{const{hasChanges:n,name:r,defaultModel:o,prepareSaveData:i}=e,a=l.useRef(!1);l.useEffect(()=>{if(!n||!r.trim()||a.current)return;const c=window.setTimeout(()=>{a.current||(a.current=!0,(async()=>{try{const d=await i();if(d)try{await t(d)}catch{oe.error("Failed to save project settings")}}finally{a.current=!1}})())},_m);return()=>{window.clearTimeout(c)}},[o,n,r,t,i])},Um=({project:e,onIdentitySave:t})=>{const n=Bm(e),r=l.useMemo(()=>e?{id:e.id,path:e.path}:null,[e]),o=l.useCallback(async i=>{await t(i)},[t]);return zm(n,o),!e||!r?null:s.jsxs("div",{className:"space-y-0",children:[s.jsx(Fm,{form:n}),s.jsx(Pm,{projectRef:r}),s.jsx(Lm,{projectId:e.id})]})},$m=6e4,Km=3e4,Un=new Map;let Fa=0,La=!1;const Wm=()=>{if(La||typeof window>"u")return;La=!0;const e=()=>{const t=Date.now();t-Fa<Km||typeof document<"u"&&document.hidden||(Fa=t,pt(async()=>{const{getRegisteredRuntimeAPIs:n}=await import("./index-CKKWVoND.js").then(r=>r.cK);return{getRegisteredRuntimeAPIs:n}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:n})=>{const r=n()?.github;r&&eo.getState().refresh(r)}).catch(()=>{}))};window.addEventListener("focus",e),typeof document<"u"&&document.addEventListener("visibilitychange",()=>{document.hidden||e()})},eo=bs()(Zr((e,t)=>({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:Xe(),resetForRuntimeSwitch:n=>{const r=n??Xe();Un.clear(),e({status:null,fetchedAt:null,isLoading:!1,error:null,runtimeKey:r})},refresh:async(n,r)=>{Wm();const o=Xe();t().runtimeKey!==o&&t().resetForRuntimeSwitch(o);const i=t(),a=Date.now();if(!r?.force&&i.status&&i.fetchedAt&&a-i.fetchedAt<$m)return i.status;const c=Un.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 Xe()!==o?null:(e({status:f,fetchedAt:Date.now(),isLoading:!1,error:null,runtimeKey:o}),f)}catch(f){return Xe()!==o?null:(e({isLoading:!1,error:f instanceof Error?f.message:"GitHub status check failed"}),t().status)}})();Un.set(o,u);try{return await u}finally{Un.get(o)===u&&Un.delete(o)}}}),{name:"github-status-store"}));typeof window<"u"&&Nn(e=>{eo.getState().resetForRuntimeSwitch(e.runtimeKey)});const Gm=()=>eo(e=>(e.status?.hosts??[]).find(n=>n.authenticated)?.login??null),bv=e=>{if(e.byteLength<4)return null;const t=new DataView(e).getUint32(0);if(t<=0||4+t>e.byteLength)return null;try{const n=JSON.parse(new TextDecoder().decode(new Uint8Array(e,4,t)));return!Number.isFinite(n?.width)||!Number.isFinite(n?.height)?null:{header:n,jpeg:new Uint8Array(e,4+t)}}catch{return null}},xv=e=>{try{const t=JSON.parse(e);return t&&typeof t=="object"&&typeof t.type=="string"?t:null}catch{return null}},yv=e=>e===4003?"unavailable":e===4004?"stop":e===4005?"closed":"reconnect",wv=50*1024*1024-1,vv=[250,1e3,2e3,4e3,8e3],Hm=(e,t)=>{const n=r=>{let o=r>>>0;for(const i of`${e}\0${t}`)o^=i.codePointAt(0)??0,o=Math.imul(o,16777619)>>>0;return o.toString(36).padStart(7,"0")};return`tab-${n(2166136261)}${n(16777619)}`},Sv=e=>({alt:e.altKey,ctrl:e.ctrlKey,meta:e.metaKey,shift:e.shiftKey}),jv=(e,t,n,r)=>{if(n.width<=0||n.height<=0)return null;const o=(e-n.left)/n.width*r.width,i=(t-n.top)/n.height*r.height;return{x:Math.round(Math.max(0,Math.min(r.width-1,o))*100)/100,y:Math.round(Math.max(0,Math.min(r.height-1,i))*100)/100}},kv=(e,t)=>e.key.toLowerCase()!=="v"||e.altKey?!1:t?e.metaKey:e.ctrlKey,Cv=(e,t)=>{const n=Math.min(1,t.width/e.width,t.height/e.height),r=Number.isFinite(n)&&n>0?n:1;return{width:Math.round(e.width*r),height:Math.round(e.height*r),scale:r}},Vs=async(e,t)=>{const n=await e.json().catch(()=>null);return new Error(typeof n?.error=="string"?n.error:t)},Av=async()=>{const e=await st("/api/server-browser/status");if(!e.ok)throw await Vs(e,"Could not check the server browser");return await e.json()},Nv=async e=>{const t=await st("/api/server-browser/settings",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw await Vs(t,"Could not save the server browser settings");return await t.json()},Iv=async(e,t)=>{const n=await st("/api/server-browser/dev-servers",{query:e?{directory:e}:void 0,signal:t});if(!n.ok)throw await Vs(n,"Could not find dev servers");const r=await n.json();return Array.isArray(r.servers)?r.servers:[]},Ev=async(e,t,n)=>{const r=await st("/api/server-browser/frame-policy",{query:{url:e,origin:t},signal:n});if(!r.ok)return{framing:"unknown"};const o=await r.json().catch(()=>null);return o?.framing==="refused"||o?.framing==="allowed"?{framing:o.framing,reason:o.reason==="frame-ancestors"?"frame-ancestors":"x-frame-options"}:{framing:"unknown"}},Dv=async()=>{const e=await st("/api/server-browser/clear-data",{method:"POST"});if(!e.ok)throw await Vs(e,"Could not clear browsing data")},Rv=(e,t)=>{const n=Hm(e,t);st(`/api/server-browser/tabs/${encodeURIComponent(n)}`,{method:"DELETE"}).catch(()=>{})},Pv=async e=>{const t=new URLSearchParams({name:e.name,type:e.type,lastModified:String(e.lastModified)}),n=await st(`/api/server-browser/uploads?${t}`,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:e});if(!n.ok)throw await Vs(n,`Could not upload ${e.name}`);const r=await n.json();if(typeof r.id!="string")throw new Error(`Could not upload ${e.name}`);return r.id},Tv=async(e,t,{onProgress:n,signal:r}={})=>{const o=await st(`/api/server-browser/downloads/${encodeURIComponent(e)}`,{signal:r??new AbortController().signal});if(!o.ok)throw await Vs(o,`Could not download ${t}`);const i=Number(o.headers.get("content-length"))||0,a=o.headers.get("content-type")||"application/octet-stream";let c;if(o.body&&n){const d=o.body.getReader(),u=[];let f=0;for(n(0,i);;){const{done:m,value:g}=await d.read();if(m)break;u.push(g),f+=g.byteLength,n(f,i)}c=new Blob(u,{type:a})}else c=await o.blob();return c},Mv=(e,t)=>fc({filename:t,mimeType:e.type||void 0,data:e}),Fv=e=>e instanceof Error&&(e.name==="NotAllowedError"||e.message.includes("NotAllowedError")),Lv=async e=>{const t=await st(`/api/server-browser/downloads/${encodeURIComponent(e)}/save-to-server`,{method:"POST"});if(!t.ok)throw await Vs(t,"Could not save the download on the server");const n=await t.json();if(typeof n.path!="string")throw new Error("Could not save the download on the server");return n.path},Ov=async(e,t,n)=>{const r=await Ch();return{socket:Ah(Nh().websocket("/api/server-browser/ws",{tab:e,url:t,popup:n},r)),urlAuthToken:r}},Bv=e=>{kh(e)},jr=100;function _v(){const e=ue(k=>k.isArchivePageOpen),t=ue(k=>k.setArchivePageOpen),n=ue(k=>k.setActiveMainTab),r=Me(k=>k.setCurrentSession),o=Me(k=>k.unarchiveSession),i=jn(k=>k.homeDirectory),a=Xo({archived:!0}),[c,d]=l.useState(""),[u,f]=l.useState(null),[m,g]=l.useState(jr),b=c.trim().toLowerCase(),h=l.useMemo(()=>e?[...a].sort((k,E)=>(E.time?.archived??0)-(k.time?.archived??0)):[],[a,e]),p=l.useMemo(()=>{const k=new Map;for(const E of h){const P=Re(gn(E))??"",z=k.get(P);if(z){z.sessions.push(E);continue}k.set(P,{directory:P,label:P?wa(P,i)||P:"other projects",sessions:[E]})}return[...k.values()].sort((E,P)=>P.sessions.length-E.sessions.length)},[i,h]),y=l.useMemo(()=>b?h.filter(k=>(k.title??"").toLowerCase().includes(b)):u===null?h:p.find(k=>k.directory===u)?.sessions??[],[p,b,u,h]),x=y.slice(0,m),C=y.length-x.length,j=a.length,A=l.useCallback(k=>{f(k),g(jr)},[]),w=l.useCallback(k=>{const E=Re(gn(k));r(k.id,E??void 0),n("chat"),t(!1)},[n,r,t]),S=l.useCallback(k=>{o(k.id).then(E=>{E?oe.success("Session restored"):oe.error("Failed to restore session")})},[o]);if(!e)return null;const v=(k,E,P,z,K,q,H)=>s.jsxs("div",{className:"group/dir relative",children:[s.jsxs("button",{type:"button",onClick:K,title:q,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",H?"group-hover/dir:pr-8 group-focus-within/dir:pr-8":"",z?"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:E}),s.jsx("span",{className:"flex-shrink-0 typography-micro text-subtle-foreground",children:P})]}),H?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>sr.requestDelete({sessions:H,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 ${E}`,children:s.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:"Delete all archived sessions in this project"})]}):null]},k);return s.jsx(Eu,{open:e,onOpenChange:t,children:s.jsxs(Du,{children:[s.jsx(Ru,{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(Pu,{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(Tu,{className:"sr-only",children:"Archived sessions"}),s.jsx(Mu,{className:"sr-only",children:"Browse and restore archived sessions."}),s.jsx(Fu,{"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(R,{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:[v("__all__","All directories",j,u===null,()=>A(null)),p.map(k=>v(k.directory||"__none__",k.label,k.sessions.length,u===k.directory,()=>A(k.directory),k.directory||void 0,k.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(R,{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:k=>{d(k.target.value),g(jr)},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:y.length===1?`${y.length} archived session`:`${y.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:[x.length===0?s.jsx("div",{className:"py-10 text-center text-muted-foreground",children:s.jsx("p",{className:"typography-ui-label font-semibold",children:b?"No matching archived sessions":"No archived sessions"})}):x.map(k=>{const E=Re(gn(k))??"",P=E?wa(E,i)||E: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:()=>w(k),role:"button",tabIndex:0,onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),w(k))},children:[s.jsx("span",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:fs(k)}),b&&P?s.jsx("span",{className:"max-w-40 flex-shrink-0 truncate typography-micro text-subtle-foreground",title:E,children:P}):null,s.jsx("span",{className:"flex-shrink-0 typography-micro text-subtle-foreground",children:Vh(k.time?.archived??k.time?.updated??k.time?.created??Date.now())}),s.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),S(k)},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 ${fs(k)}`,children:s.jsx(R,{name:"inbox-unarchive",className:"h-3.5 w-3.5"})}),s.jsx("button",{type:"button",onClick:z=>{z.stopPropagation(),sr.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 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 ${fs(k)}`,children:s.jsx(R,{name:"delete-bin",className:"h-3.5 w-3.5"})})]},k.id)}),C>0?s.jsx("button",{type:"button",onClick:()=>g(k=>k+jr),className:"mt-1 flex items-center justify-start rounded-md px-2 py-1 text-left text-xs text-subtle-foreground leading-tight hover:text-foreground hover:underline",children:"Show more sessions"}):null]})})]})]})]})})]})})}const qm=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}},Vm=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},es=e=>typeof e=="number"&&Number.isFinite(e)&&e>=0?e:0,Ym=e=>{if(!e||typeof e!="object")return null;const t=es(e.input),n=es(e.output),r=es(e.cacheRead),o=es(e.cacheWrite);return{input:t,output:n,reasoning:null,cacheRead:r,cacheWrite:o,total:t+n+r+o}},Oa=e=>{const t=Ym(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:es(r)};if(!r||typeof r!="object")return{input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0};const o=r,i=es(o.input),a=es(o.output),c=es(o.reasoning),d=es(o.cache?.read),u=es(o.cache?.write);return{input:i,output:a,reasoning:c,cacheRead:d,cacheWrite:u,total:i+a+c+d+u}},Ec=380,Eo=8,Qm=140;function Jm({open:e,onClose:t,anchorRef:n,closeOnWheel:r=!1}){const o=l.useRef(null),i=l.useRef(null),[a,c]=l.useState(e),[d,u]=l.useState(!1),[f,m]=l.useState(null),{enabled:g}=Ti();return l.useLayoutEffect(()=>{if(!e||!g||!a)return;const b=()=>{const y=n.current?.getBoundingClientRect(),x=i.current?.getBoundingClientRect();if(!y||!x){m(null);return}const C=y.left-x.left;m(Math.min(Math.max(C,Eo),Math.max(Eo,x.width-Ec-Eo)))};b();const h=i.current;if(typeof ResizeObserver>"u"||!h)return;const p=new ResizeObserver(b);return p.observe(h),()=>p.disconnect()},[n,g,e,a]),l.useEffect(()=>{if(e){c(!0),u(!1);return}if(!a)return;u(!0);const b=window.setTimeout(()=>{c(!1),u(!1)},Qm);return()=>window.clearTimeout(b)},[e,a]),l.useEffect(()=>{if(!e)return;const b=h=>{h.key==="Escape"&&t()};return document.addEventListener("keydown",b),()=>document.removeEventListener("keydown",b)},[t,e]),l.useEffect(()=>{if(!e)return;const b=h=>{const p=h.target;if(!(p instanceof Node)){t();return}o.current?.contains(p)||n.current?.contains(p)||t()};return document.addEventListener("pointerdown",b,!0),r&&document.addEventListener("wheel",b,!0),()=>{document.removeEventListener("pointerdown",b,!0),r&&document.removeEventListener("wheel",b,!0)}},[n,r,t,e]),{panelRef:o,wrapperRef:i,shouldRender:a,isExiting:d,anchorLeft:f,isPopover:g&&f!==null}}const Ba=(e,t)=>{if(!e||typeof e!="object")return;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:void 0},Kr=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:String(e),kr=({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(R,{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})]}),Xm=({open:e,onClose:t,anchorRef:n,contextDisplay:r})=>{const{panelRef:o,wrapperRef:i,shouldRender:a,isExiting:c,anchorLeft:d,isPopover:u}=Jm({open:e,onClose:t,anchorRef:n,closeOnWheel:!0});return a?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(${Ec}px, calc(100% - 16px))`}:null},children:s.jsx("div",{className:"space-y-1",children:r?s.jsxs(s.Fragment,{children:[s.jsx(kr,{iconNode:s.jsx(Wl,{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(kr,{icon:"stack",label:"Cache read",children:s.jsx("span",{className:"tabular-nums",children:Kr(r.cacheRead)})}),s.jsx(kr,{icon:"edit",label:"Cache write",children:s.jsx("span",{className:"tabular-nums",children:Kr(r.cacheWrite)})})]}):null,r.cacheHitPercent!==null?s.jsx(kr,{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:`
|
|
7
|
+
@keyframes session-metadata-in {
|
|
8
|
+
from { opacity: 0; transform: translateY(-8px) scale(0.985); }
|
|
9
|
+
to { opacity: 1; transform: translateY(0) scale(1); }
|
|
10
|
+
}
|
|
11
|
+
@keyframes session-metadata-out {
|
|
12
|
+
from { opacity: 1; transform: translateY(0) scale(1); }
|
|
13
|
+
to { opacity: 0; transform: translateY(-6px) scale(0.985); }
|
|
14
|
+
}
|
|
15
|
+
`})]}):null},Zm=l.memo(function({open:t,onOpenChange:n,currentSessionId:r,effectiveDirectory:o,isNewSessionDraftOpen:i}){const a=l.useRef(null),c=gf(r??""),d=Gt(D=>D.providers),u=Gt(D=>D.currentProviderId),f=Gt(D=>D.currentModelId),m=Gt(D=>D.getCurrentModel()),g=Gt(D=>D.getModelMetadata);Gt(D=>D.modelsMetadata.size);const b=bf(l.useCallback(D=>r?D.sessionModelSelections.get(r)??null:null,[r])),h=l.useMemo(()=>{for(let D=c.length-1;D>=0;D-=1){const T=c[D]?.info;if(T.role!=="user")continue;const I=T.model,M=I?.providerID??I?.providerId,G=I?.modelID??I?.modelId,W=typeof M=="string"&&M.trim().length>0?M:void 0,L=typeof G=="string"&&G.trim().length>0?G:void 0;if(W&&L)return{providerID:W,modelID:L}}return null},[c]),p=l.useMemo(()=>{for(let D=c.length-1;D>=0;D-=1){const T=c[D];if(T?.info.role==="assistant"&&Oa(T).total>0)return T}return null},[c]),y=h??(()=>{const D=p?.info.model,T=D?.providerID??D?.providerId,I=D?.modelID??D?.modelId;return T&&I?{providerID:T,modelID:I}:null})()??(b?{providerID:b.providerId,modelID:b.modelId}:null)??(u&&f?{providerID:u,modelID:f}:null),C=(y?d.find(D=>D.id===y.providerID):void 0)?.models.find(D=>D.id===y?.modelID),j=y?g(y.providerID,y.modelID):void 0,A=Ba(C?.limit,"context")??j?.limit?.context??Ba(m?.limit,"context")??0,w=p?Oa(p):null,S=p?.info?.usage,v=S?Vm(S):w?.total??0,k=!i&&v>0&&A>0?Math.min(v/A*100,999):null,E=k!==null?`${Kr(v)}/${Kr(A)}`:null,P=k===null?"":k>=90?"text-[var(--status-error)]":k>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",z=w?.cacheRead??null,K=w?.cacheWrite??null,q=w?qm({input:w.input,cache:{read:w.cacheRead,write:w.cacheWrite}}):{percent:0,hasInput:!1},H=q.hasInput?q.percent:null,F=k!==null&&E?{percentage:k,tokens:E,colorClass:P,cacheRead:z,cacheWrite:K,cacheHitPercent:H}:null;return s.jsxs(s.Fragment,{children:[s.jsx("button",{ref:a,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:F?s.jsx(Wl,{percentage:F.percentage,size:20,className:"size-5 -rotate-90"}):s.jsx(R,{name:"pie-chart",className:"size-5"})}),s.jsx(Xm,{open:t,onClose:()=>n(!1),anchorRef:a,contextDisplay:F})]})}),Dc=({sessionId:e,className:t})=>{const n=xf(e);return n?s.jsx("span",{role:"img","aria-label":n.text,title:n.text,className:_("inline-flex shrink-0 items-center",t),children:s.jsx(R,{name:n.icon,className:"size-3.5 text-subtle-foreground"})}):null},En="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",eg="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",tg=l.memo(function({visible:t=!0,title:n,ariaLabel:r,onClick:o,className:i,Icon:a,iconClassName:c,pressed:d=!1}){return t?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,"aria-label":r,"aria-pressed":d,className:_(i??En,d&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(R,{name:a,className:c??"h-[18px] w-[18px]"})})}),s.jsx(Ge,{children:s.jsx("p",{children:n})})]}):null}),sg=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)},Rc=({variant:e="desktop"})=>{const t=Ws(f=>f.entries),[n,r]=l.useState(!1),o=l.useRef(null),i=l.useMemo(()=>[...t.values()].sort((f,m)=>m.startedAt-f.startedAt),[t]),a=i.filter(f=>f.state&&f.state.phase!=="failed"||Gl(f)).length,c=l.useCallback(()=>{o.current&&(clearTimeout(o.current),o.current=null)},[]),d=l.useCallback(()=>{c(),o.current=setTimeout(()=>r(!1),150)},[c]);if(l.useEffect(()=>()=>c(),[c]),i.length===0)return null;const u=f=>{if(!Sf(f))return;const m=f.receipt;if(!m)return;const g=Me.getState();g.newSessionDraft.open?g.setNewSessionDraftTarget({directoryOverride:m.path,worktreeIntent:null}):g.openNewSessionDraft({directoryOverride:m.path}),Ws.getState().clearEntry(f.key),ue.getState().setActiveMainTab("chat"),r(!1)};return s.jsxs(Vt,{open:n,onOpenChange:r,children:[s.jsx(Yt,{asChild:!0,children:s.jsxs("button",{type:"button",className:_(e==="desktop"?En:"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:[a>0?s.jsx(Is,{variant:"inline",text:null,animationType:"spinner"}):s.jsx(R,{name:"task",className:"size-[18px]"}),s.jsx("span",{children:"Background tasks"})]})}),s.jsxs(Qt,{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:a===1?"1 worktree is being created":`${a} worktrees are being created`})]}),s.jsx("div",{className:"divide-y divide-border",children:i.map(f=>s.jsx(ng,{entry:f,onOpen:()=>u(f)},f.key))})]})]})},ng=({entry:e,onOpen:t})=>{const n=e.state?.phase==="failed",r=!!(e.state&&!n),o=Gl(e),i=yf(e),a=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(Is,{variant:"inline",text:null,animationType:"spinner"}):n?s.jsx(R,{name:"alert",className:"size-4 text-[var(--status-error)]"}):s.jsx(R,{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:a}),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(Ae,{type:"button",size:"xs","aria-label":`Restore draft for ${e.intent.sourceDirectory} from ${e.intent.startRef} (task ${sg(e.key)})`,onClick:()=>{const c=wf(e.key),d=vf(c,"background-task");d&&oe.error(d.title,{description:d.description})},children:"Restore draft"}):null,s.jsx(Ae,{type:"button",variant:"ghost",size:"xs",onClick:()=>Ws.getState().dismissFailed(e.key),children:"Dismiss"})]}):null,i?s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Ae,{type:"button",size:"xs",onClick:t,children:"Open"}),s.jsx(Ae,{type:"button",variant:"ghost",size:"icon",className:"size-6",onClick:()=>Ws.getState().clearEntry(e.key),"aria-label":"Dismiss completed task",children:s.jsx(R,{name:"close",className:"size-3.5"})})]}):null]})},rg=["pinned","today","yesterday","thisWeek","lastWeek","older"],og={pinned:"Pinned",today:"Today",yesterday:"Yesterday",thisWeek:"This week",lastWeek:"Last week",older:"Older"},ig=(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},pi=(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 m=f.getTime();return{startOfToday:r,startOfYesterday:i,startOfThisWeek:u,startOfLastWeek:m}},ag=(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",lg=(e,t)=>{const n={pinned:[],today:[],yesterday:[],thisWeek:[],lastWeek:[],older:[]},{getTimestamp:r,isPinned:o,boundaries:i}=t,a=e.length;for(let d=0;d<a;d++){const u=e[d];if(o(u))n.pinned.push(u);else{const f=r(u),m=ag(f,i);n[m].push(u)}}const c=[];for(const d of rg){const u=n[d];u.length>0&&c.push({id:d,items:u})}return c},cg=e=>{const t=new Date(e);return t.setDate(t.getDate()+1),t.setHours(0,0,0,0),t.getTime()},dg=(e,t)=>{const[n,r]=l.useState(0),o=l.useMemo(()=>e?pi(Date.now(),t):null,[e,t,n]),i=o?.startOfToday??null;return l.useEffect(()=>{if(i===null||typeof window>"u"||typeof document>"u")return;const a=Date.now(),c=window.setTimeout(()=>{r(u=>u+1)},Math.max(50,cg(a)-a+50)),d=()=>{document.visibilityState==="visible"&&pi(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},ug=e=>({getOrderedGroups:l.useCallback((n,r)=>{const o=e.get(n);if(!o||o.length===0)return r;const i=new Map(r.map(d=>[d.id,d])),a=[];o.forEach(d=>{const u=i.get(d);u&&(a.push(u),i.delete(d))});const c=[];return r.forEach(d=>{i.has(d.id)&&c.push(d)}),[...c,...a]},[e])}),fg=[],hg=e=>{const{normalizedProjects:t,getSessionsForProject:n,getArchivedSessionsForProject:r,availableWorktreesByProject:o,projectRepoStatus:i,projectRootBranches:a,lastRepoStatus:c,buildGroupedSessions:d,hasSessionSearchQuery:u,normalizedSessionSearchQuery:f,filterSessionNodesForSearch:m,buildGroupSearchText:g,foldersMap:b,alwaysIncludeArchived:h=!1}=e,p=l.useRef(new Map),y=u||h,x=l.useMemo(()=>{const E=p.current,P=new Map;let z=0,K=0;const q=(F,D)=>F.length===D.length&&F.every((T,I)=>T===D[I]),H=t.map(F=>{const D=n(F.id),T=y?r(F.id):fg,I=i.has(F.id)?!!i.get(F.id):c,M=a.get(F.id)??null,G=o.get(F.normalizedPath)??[],W=E.get(F.id);if(W&&W.project===F&&q(W.activeSessions,D)&&q(W.archivedSessions,T)&&W.rootBranch===M&&W.isRepo===I&&W.worktrees===G&&W.buildGroupedSessions===d)return z+=1,P.set(F.id,W),W.section;K+=1;const L=hc([...D,...T]),ae=d(L,F.normalizedPath,G,M,I),J={project:F,groups:ae};return P.set(F.id,{project:F,activeSessions:D,archivedSessions:T,rootBranch:M,isRepo:I,worktrees:G,buildGroupedSessions:d,section:J}),J});return p.current=P,z>0&&Ht("ui.sidebar.project_section.reused",z),K>0&&Ht("ui.sidebar.project_section.rebuilt",K),H},[t,n,r,y,o,i,c,d,a]),C=l.useMemo(()=>x,[x]),j=l.useMemo(()=>{const E=new WeakMap;if(!u)return E;const P=z=>z.reduce((K,q)=>K+1+P(q.children),0);return C.forEach(z=>{z.groups.forEach(K=>{const q=m(K.sessions,f),H=P(q),F=g(K).includes(f),D=Re(K.directory??null),I=(D?b[D]??[]:[]).filter(M=>M.name.toLowerCase().includes(f)).length;E.set(K,{filteredNodes:q,matchedSessionCount:H,folderNameMatchCount:I,groupMatches:F,hasMatch:F||H>0||I>0})})}),E},[u,C,m,f,g,b]),A=l.useMemo(()=>u?C.map(E=>({...E,groups:E.groups.filter(P=>j.get(P)?.hasMatch===!0)})).filter(E=>E.groups.length>0):C,[u,C,j]),w=u?A:C,S=l.useRef(new WeakMap),v=l.useMemo(()=>{const E=S.current;return w.map(P=>{const z=E.get(P);if(z&&z.query===f)return z.section;const K=P.groups,q=K.flatMap(I=>u?j.get(I)?.filteredNodes??[]:I.sessions),H=K.map(I=>({scopeKey:I.folderScopeKey??Re(I.directory??null),directory:I.directory??null})).filter(I=>!!I.scopeKey),F=K.find(I=>I.isMain)??null,D={id:"flat",label:F?.label??"",branch:F?.branch??null,description:F?.description??null,isMain:!0,directory:F?.directory??P.project.normalizedPath,folderScopeKey:F?.folderScopeKey??P.project.normalizedPath,folderScopes:H,sessions:q};if(u){const I=K.map(M=>j.get(M)).filter(M=>!!M);j.set(D,{filteredNodes:q,matchedSessionCount:I.reduce((M,G)=>M+G.matchedSessionCount,0),folderNameMatchCount:I.reduce((M,G)=>M+G.folderNameMatchCount,0),groupMatches:I.some(M=>M.groupMatches),hasMatch:I.some(M=>M.hasMatch)})}const T={project:P.project,groups:[D]};return E.set(P,{query:f,section:T}),T})},[j,u,f,w]),k=l.useMemo(()=>u?w.reduce((E,P)=>E+P.groups.reduce((z,K)=>{const q=j.get(K);if(!q)return z;const H=q.folderNameMatchCount+(q.groupMatches?1:0);return z+q.matchedSessionCount+H},0),0):0,[u,w,j]);return{projectSections:x,visibleProjectSections:C,groupSearchDataByGroup:j,searchableProjectSections:A,sectionsForRender:w,flatSectionsForRender:v,searchMatchCount:k}},to=e=>!!e.session.time?.archived,Pc=e=>{let t=0;for(const n of e)to(n)||(t+=1);return t},pg=e=>{let t=0;for(const n of e)for(const r of n.groups)t+=Pc(r.sessions);return t},mg=e=>{const t=new Map;for(const n of e){let r=0;for(const o of n.groups)r+=Pc(o.sessions);t.set(n.project.id,r)}return t},gg=(e,t)=>e.groups.some(n=>n.sessions.some(r=>!to(r)&&t.has(r.session.id))),bg=(e,t)=>e.groups.some(n=>n.sessions.some(r=>!to(r)&&t.has(r.session.id))),xg=(e,t)=>{const n=new Map;for(const r of e){const o=new Set;for(const i of r.groups)if(i.sessions.some(c=>!to(c)&&t.has(c.session.id))&&i.directory){const c=Re(i.directory)?.toLowerCase();c&&o.add(c)}o.size>0&&n.set(r.project.id,o)}return n},Tc=(e,t,n,r)=>{if(!n)return t;const o=e.find(c=>c.project.id===n);if(!o)return[];const i=Re(r??o.project.normalizedPath),a=o.groups.find(c=>Re(c.directory)===i);return a?[{...o,groups:[a]}]:[]},yg=(e,t)=>{const n=new Map,r=new Map;return e.forEach(o=>{const i=In(o.project,t);o.groups.forEach(a=>{const c=a.branch&&a.branch!=="HEAD"&&a.branch!==i?a.branch:null,d={projectLabel:i,branchLabel:c},u=f=>{f.forEach(m=>{const g=o.project.normalizedPath.length,b=r.get(m.session.id)??-1;g<b||(n.set(m.session.id,{node:m,projectId:o.project.id,groupDirectory:a.directory,secondaryMeta:d}),r.set(m.session.id,g),m.children.length>0&&u(m.children))})};u(a.sessions)})}),n};function wg({projectSections:e,flatSectionsForRender:t,sectionsForRender:n,selectedSpaceId:r,selectedWorktreePath:o,homeDirectory:i,activeSessionIdSet:a,unreadSessionIdSet:c}){const d=l.useMemo(()=>yg(e,i),[e,i]),u=t,f=l.useMemo(()=>Tc(n,u,r,o),[n,u,r,o]),m=l.useMemo(()=>pg(e),[e]),g=l.useMemo(()=>mg(e),[e]),b=l.useCallback(y=>{const x=e.find(C=>C.project.id===y);return x?gg(x,a):!1},[a,e]),h=l.useMemo(()=>xg(e,a),[a,e]),p=l.useCallback(y=>{const x=e.find(C=>C.project.id===y);return x?bg(x,c):!1},[e,c]);return{sessionSidebarMetaById:d,sectionsForSidebarRender:u,filteredSectionsForSidebarRender:f,totalSessionCount:m,sessionCountByProject:g,hasActiveSessionByProject:b,activeDirectoriesByProject:h,hasUnseenByProject:p}}const _a=[],vg={id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},Sg=(e,t,n)=>{const r=[],o=new Set,i=(a,c)=>{const d=In(a.project,n);for(const u of a.groups)for(const f of u.sessions){if(o.has(f.session.id))continue;o.add(f.session.id);const m=f.session.time;r.push({node:f,project:a.project,projectLabel:d,isPinned:!1,timestamp:m?.archived||m?.updated||m?.created||0,globalSession:c})}};t&&i(t,!0);for(const a of e)i(a,!1);return r.sort((a,c)=>c.timestamp-a.timestamp)},jg=({viewMode:e,enabled:t,projects:n,archivedSessions:r,getArchivedSessionsForProject:o,isGlobalSession:i,buildGroupedSessions:a,availableWorktreesByProject:c,projectRepoStatus:d,projectRootBranches:u,lastRepoStatus:f,selectedSpaceId:m,selectedWorktreePath:g,homeDirectory:b})=>{const p=t&&(e==="threads"||e==="folder"||e==="workspace"),y=e==="workspace"?m:null,x=l.useMemo(()=>{if(!p)return[];const j=[];for(const A of n){if(y!==null&&A.id!==y)continue;const w=o(A.id);if(w.length===0)continue;const S=d.has(A.id)?!!d.get(A.id):f;j.push({project:A,groups:a(w,A.normalizedPath,c.get(A.normalizedPath)??[],u.get(A.id)??null,S)})}return j},[p,c,a,o,f,d,u,n,y]),C=l.useMemo(()=>{if(!p||y!==null)return null;const j=r.filter(i);return j.length===0?null:{project:vg,groups:a(j,"~",[],null,!1)}},[p,r,a,i,y]);return l.useMemo(()=>{if(!p)return _a;const j=y!==null?Tc(x,x,y,g):x,A=Sg(j,C,b);return A.length>0?A:_a},[p,b,C,x,y,g])},kg=e=>{const{projectSections:t,activeProjectId:n,activeSessionByProject:r,setActiveSessionByProject:o,currentSessionId:i,handleSessionSelect:a,newSessionDraftOpen:c,mobileVariant:d,openNewSessionDraft:u,setActiveMainTab:f,setSessionSwitcherOpen:m}=e,g=l.useMemo(()=>{const h=new Map,p=new Map,y=(x,C,j,A)=>{h.has(x)||h.set(x,new Map);const w=h.get(x);A.forEach(S=>{const v=Re(S.session.directory??j??C);w.set(S.session.id,{directory:v}),p.has(x)||p.set(x,{id:S.session.id,directory:v}),S.children.length>0&&y(x,C,v,S.children)})};return t.forEach(x=>{x.groups.forEach(C=>{y(x.project.id,x.project.normalizedPath,C.directory,C.sessions)})}),{metaByProject:h,firstSessionByProject:p}},[t]),b=l.useRef(null);l.useLayoutEffect(()=>{if(!n)return;if(c){b.current=n;return}if(b.current===n)return;const h=t.find(S=>S.project.id===n);if(!h)return;b.current=n;const p=g.metaByProject.get(n);if(i&&p&&p.has(i)){o(S=>{if(S.get(n)===i)return S;const v=new Map(S);return v.set(n,i),v});return}const y=i?Array.from(g.metaByProject.entries()).some(([S,v])=>S!==n&&v.has(i)):!1;if(i&&p&&!y)return;if(!p||p.size===0){f("chat"),d&&m(!1),u({selectedProjectId:h.project.id,directoryOverride:h.project.normalizedPath});return}const x=r.get(n),C=x&&p.has(x)?x:null,j=g.firstSessionByProject.get(n)?.id??null,A=C??j;if(!A||A===i)return;const w=p.get(A)?.directory??null;a(A,w,{keepPanelOpen:!0})},[n,r,i,a,c,d,u,t,g,f,m,o]),l.useEffect(()=>{if(!n||!i)return;const h=g.metaByProject.get(n);!h||!h.has(i)||o(p=>{if(p.get(n)===i)return p;const y=new Map(p);return y.set(n,i),y})},[n,i,g,o])},Cg=({initialActiveSessionByProject:e,persistActiveSessionByProject:t,...n})=>{const r=Me(c=>c.currentSessionId),o=Me(c=>!!c.newSessionDraft?.open),[i,a]=l.useState(()=>new Map(e));return kg({...n,activeSessionByProject:i,setActiveSessionByProject:a,currentSessionId:r,newSessionDraftOpen:o}),l.useEffect(()=>{t(i)},[i,t]),null},za=["var(--chart-1)","var(--chart-2)","var(--chart-3)","var(--chart-4)","var(--chart-5)"],Ag=e=>{let t=5381;for(let n=0;n<e.length;n+=1)t=t*33^e.charCodeAt(n);return t>>>0},Ng=(e,t,n)=>(n.get(e)??0)>0?e:t.get(e)??null,Mc=e=>{if(!e||typeof e!="string"||e.trim().length===0)return null;const t=Ag(e.trim())%za.length;return za[t]},Ig=(e,t)=>{const n=Mc(e);return n?t?.active?`color-mix(in srgb, ${n} 30%, var(--interactive-selection))`:`color-mix(in srgb, ${n} 18%, transparent)`:null},Ua=e=>!!e.time?.archived,Eg=e=>{const t=l.useCallback(i=>[i.label,i.branch??"",i.description??"",i.directory??""].join(" ").toLowerCase(),[]),n=l.useCallback(i=>{const a=Re(i.directory??null)??"";return`${fs(i)} ${a}`.toLowerCase()},[]),r=l.useCallback((i,a)=>a?i.flatMap(c=>{if(n(c.session).includes(a))return[c];const u=r(c.children,a);return u.length===0?[]:[{...c,children:u}]}):i,[n]),o=l.useCallback((i,a,c=[],d,u)=>{const f=Re(a??null),m=hc(i).sort(Hl(e.pinnedSessionIds,e.sessionOrderRanks)),g=new Map(m.map(S=>[S.id,S])),b=new Map,h=new Map;m.forEach(S=>{const v=S.parentID??null,k=v?g.get(v):null,E=k&&Ua(k)===Ua(S)?v:null;b.set(S.id,E),E&&h.set(E,(h.get(E)??0)+1)});const p=c.map(S=>({worktree:S,directory:Re(S.path)})).filter(S=>!!S.directory&&!S.worktree.isPrimary).sort((S,v)=>v.directory.length-S.directory.length),y=(S,v)=>v===S||v.startsWith(`${S}/`),x=S=>{const v=Re(S.directory??null);return v?p.find(k=>y(k.directory,v))?.worktree??null:null},C=(S,v)=>{const k=Ng(S.id,b,h);return{session:S,children:[],worktree:v,forkColorId:k}},j=[],A=new Map;for(const S of p)A.set(S.directory,[]);m.forEach(S=>{const v=x(S),k=C(S,v);v?A.get(Re(v.path)??"")?.push(k):j.push(k)});const w=[{id:"root",label:u&&d&&d!=="HEAD"?`project root: ${d}`:"project root",branch:d??null,description:f?ti(f,e.homeDirectory):null,isMain:!0,worktree:null,directory:f,folderScopeKey:f,sessions:j}];for(const{worktree:S,directory:v}of p)w.push({id:`worktree:${v}`,label:S.branch||(S.detached?"Detached HEAD":S.name),branch:S.branch,description:ti(v,e.homeDirectory),isMain:!1,worktree:S,directory:v,folderScopeKey:v,sessions:A.get(v)??[]});return w},[e.homeDirectory,e.pinnedSessionIds,e.sessionOrderRanks]);return{buildGroupSearchText:t,buildSessionSearchText:n,filterSessionNodesForSearch:r,buildGroupedSessions:o}},Dg=({mobileVariant:e,isTablet:t})=>!e&&!t,Rg=({enabled:e=!0,isSessionSearchOpen:t,setIsSessionSearchOpen:n,sessionSearchInputRef:r,sessionSearchContainerRef:o})=>{l.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]),l.useEffect(()=>{if(!e||!t||typeof document>"u")return;const i=a=>{o.current&&(o.current.contains(a.target)||n(!1))};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[e,t,n,o])},Do=(e,t)=>t===1?`Could not ${e} the session`:`Could not ${e} the sessions`,$a=(e,t)=>{if(!e.directory)return;const n=rr.getState();ur(n.ids,e.directory,e.sessionId)!==t&&n.toggle({directory:e.directory,sessionId:e.sessionId})},Fc=async(e,t={})=>{if(e.length===0)return;const n=rr.getState(),r=new Set(e.filter(b=>ur(n.ids,b.directory,b.sessionId)).map(b=>b.sessionId));for(const b of e)r.has(b.sessionId)&&$a(b,!1);const o=b=>{for(const h of b)r.has(h.sessionId)&&$a(h,!0)},i=[...new Set(e.flatMap(b=>[b.sessionId,...b.forkIds]))];let a;try{a=await Me.getState().archiveSessions(i)}catch(b){console.warn("[session-archive] archive failed",b),a={archivedIds:[],failedIds:i}}const c=new Set(a.archivedIds),d=e.filter(b=>c.has(b.sessionId));if(o(e.filter(b=>!c.has(b.sessionId))),d.length===0){c.size>0&&Me.getState().unarchiveSessions([...c]),oe.error(Do("archive",e.length));return}const f=e.length===1&&t.title?`Archived “${t.title}”`:`Archived ${va(d.length)}`,m=a.archivedIds;oe.success(f,{action:{label:"Undo",onClick:()=>{o(d),Me.getState().unarchiveSessions(m).then(({failedIds:b})=>{b.length>0&&oe.error(Do("unarchive",m.length))}).catch(b=>{console.warn("[session-archive] undo failed",b),oe.error(Do("unarchive",m.length))})}}});const g=i.length-c.size;g>0&&oe.error(`Could not archive ${va(g)}`)},Pg=e=>{const[t,n]=l.useState(null),r=l.useRef(null);l.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]);const o=l.useCallback((j,A,w)=>{si("navigation.session_select"),ue.getState().closeMainSurfaces();const S=()=>{!e.isSessionSearchOpen&&e.sessionSearchQuery.length===0||(e.setSessionSearchQuery(""),e.setIsSessionSearchOpen(!1))},v=w?.keepPanelOpen!==!0;if(e.mobileVariant&&(e.setActiveMainTab("chat"),e.setSessionSwitcherOpen(!1)),j===Me.getState().currentSessionId){e.allowReselect&&v&&e.onSessionSelected?.(j),S();return}si("navigation.session_state_set"),e.setCurrentSession(j,A??null),v&&e.onSessionSelected?.(j),S()},[e]),i=l.useCallback((j,A)=>{e.setEditingId(j),e.setEditTitle(A)},[e]),a=l.useCallback(async j=>{if(!e.editingId)return;const A=(j??e.editTitle).trim();A&&await e.updateSessionTitle(e.editingId,A),e.setEditingId(null),e.setEditTitle("")},[e]),c=l.useCallback(()=>{e.setEditingId(null),e.setEditTitle("")},[e]),d=l.useCallback(async(j,A)=>{try{return(await hs(j)).ok?(n(A),r.current&&clearTimeout(r.current),r.current=window.setTimeout(()=>{n(null),r.current=null},2e3),!0):!1}catch{return!1}},[]),u=l.useCallback(async j=>{const A=await e.shareSession(j.id);if(!A?.share?.url){oe.error("Unable to share session");return}const w=await d(A.share.url,j.id);oe[w?"success":"warning"]("Session shared",{description:w?"Share link copied to clipboard.":"Failed to copy URL"})},[e,d]),f=l.useCallback((j,A)=>{d(j,A).then(w=>{w||oe.error("Failed to copy URL")})},[d]),m=l.useCallback(j=>{hs(j).then(A=>{if(A.ok){oe.success("Session ID copied");return}oe.error("Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[]),g=l.useCallback(async j=>{await e.unshareSession(j)?oe.success("Session unshared"):oe.error("Unable to unshare session")},[e]),b=l.useCallback(j=>{const A=[],w=S=>{(e.childrenMap.get(S)??[]).forEach(k=>{A.push(k),w(k.id)})};return w(j),A},[e.childrenMap]),h=l.useCallback((j,A)=>A?j:j.filter(w=>!w.time?.archived),[]),p=l.useCallback(async(j,A)=>{const w=A?.descendantIds??h(b(j.id),!0).map(k=>k.id);if(w.length===0){await e.deleteSession(j.id)?oe.success("Session deleted"):oe.error("Failed to delete session");return}const{deletedIds:S,failedIds:v}=await e.deleteSessions([j.id,...w]);if(v.length===0){const k=S.length;oe.success(k===1?`Deleted ${k} session`:`Deleted ${k} sessions`)}else oe.error("Failed to delete session")},[e,b,h]),y=l.useCallback((j,A)=>{const w=A?.archivedBucket===!0||A?.hardDelete===!0,S=h(b(j.id),w).map(v=>v.id);if(!w){Fc([{sessionId:j.id,directory:j.directory??null,forkIds:S}],{title:fs(j,"Untitled session")});return}if(!e.showDeletionDialog||A?.skipConfirm===!0){p(j,{descendantIds:S});return}e.setDeleteSessionConfirm({session:j,descendantCount:S.length,descendantIds:S})},[e,b,p,h]),x=l.useCallback(async()=>{if(!e.deleteSessionConfirm)return;const{session:j,descendantIds:A}=e.deleteSessionConfirm;e.setDeleteSessionConfirm(null),await p(j,{descendantIds:A})},[e,p]),C=l.useCallback(async j=>{await e.unarchiveSession(j.id)?oe.success("Session unarchived"):oe.error("Could not unarchive the session")},[e]);return{copiedSessionId:t,handleSessionSelect:o,handleSessionDoubleClick:i,handleSaveEdit:a,handleCancelEdit:c,handleShareSession:u,handleCopyShareUrl:f,handleCopySessionId:m,handleUnshareSession:g,handleDeleteSession:y,handleRestoreSession:C,confirmDeleteSession:x}},Tg=e=>{const{safeStorage:t,keys:n,groupOrderByProject:r,collapsedGroups:o,setExpandedParents:i,setCollapsedProjects:a}=e,c=l.useRef(null),d=l.useRef(null),u=l.useCallback(()=>{const m=d.current;if(d.current=null,c.current=null,!m)return;const{projects:g}=ot.getState(),b=g.map(h=>({...h,sidebarCollapsed:m.has(h.id)}));ic({projects:b}).catch(()=>{})},[]),f=l.useCallback(m=>{typeof window>"u"||(d.current=m,c.current!==null&&window.clearTimeout(c.current),c.current=window.setTimeout(()=>{u()},700))},[u]);return l.useEffect(()=>()=>{typeof window<"u"&&c.current!==null&&window.clearTimeout(c.current),c.current=null,d.current=null},[]),l.useEffect(()=>{try{const m=t.getItem(n.sessionExpanded);if(m){const b=JSON.parse(m);Array.isArray(b)&&i(new Set(b.filter(h=>typeof h=="string")))}const g=t.getItem(n.projectCollapse);if(g){const b=JSON.parse(g);Array.isArray(b)&&a(new Set(b.filter(h=>typeof h=="string")))}}catch{}},[n.projectCollapse,n.sessionExpanded,t,a,i]),l.useEffect(()=>{try{const m=Object.fromEntries(r.entries());t.setItem(n.groupOrder,JSON.stringify(m))}catch{}},[r,n.groupOrder,t]),l.useEffect(()=>{try{t.setItem(n.groupCollapse,JSON.stringify(Array.from(o)))}catch{}},[o,n.groupCollapse,t]),{scheduleCollapsedProjectsPersist:f}},Mg=3;let Wr=0;const Lc=[],Fg=()=>Wr<Mg?(Wr+=1,Promise.resolve()):new Promise(e=>{Lc.push(e)}),Lg=()=>{const e=Lc.shift();if(e){e();return}Wr=Math.max(0,Wr-1)},Og=async e=>{await Fg();try{return await e()}finally{Lg()}},Bg=5*6e4,_g=e=>{const{normalizedProjects:t,enabled:n=!0,gitRepoStatus:r,setProjectRepoStatus:o,setProjectRootBranches:i}=e,{git:a}=qs(),c=ql(h=>h.ensureStatus),d=l.useMemo(()=>t.map(h=>h.normalizedPath).slice().sort().join("\0"),[t]),u=l.useRef(null);l.useEffect(()=>{if(!n||!a||t.length===0){u.current=null,o(new Map);return}const h=`${Xe()}\0${d}`;u.current!==h&&(u.current=h,t.forEach(p=>{Og(()=>c(p.normalizedPath,a))}))},[n,t,d,a,c,o]);const f=l.useRef(null);l.useEffect(()=>{if(!n){f.current=null;return}const h=new Map;t.forEach(y=>{h.set(y.id,r.get(y.normalizedPath)?.isGitRepo??null)});const p=t.map(y=>`${y.id}:${String(h.get(y.id))}`).join("|");f.current!==p&&(f.current=p,o(h))},[n,t,d,r,o]);const m=l.useMemo(()=>t.map(h=>{const p=r.get(h.normalizedPath)?.branch??"";return`${h.id}:${p}`}).join("|"),[t,r]),g=l.useRef(new Map),b=l.useRef(new Map);l.useEffect(()=>{if(!n)return;let h=!1;const p=setTimeout(()=>{(async()=>{const x=new Set(t.map(S=>S.id));for(const S of g.current.keys())x.has(S)||(g.current.delete(S),b.current.delete(S));const C=Date.now();if(t.filter(S=>{const v=r.get(S.normalizedPath);if(v?.isGitRepo===!1)return g.current.delete(S.id),b.current.delete(S.id),!1;if(v?.isGitRepo!==!0||v.branch===null)return!1;const k=v.branch.trim(),E=`${S.normalizedPath}\0${k}`,P=g.current.get(S.id);if(P===E){const z=b.current.get(S.id);return z&&(z.at=C),!1}return!(P!==void 0&&C-(b.current.get(S.id)?.at??0)<Bg)}).length===0)return;const A=[];if(t.forEach(S=>{const v=r.get(S.normalizedPath)?.branch?.trim()??"",k=`${S.normalizedPath}\0${v}`;v&&A.push({id:S.id,inputKey:k,branch:v})}),h||A.length===0)return;const w=Date.now();i(S=>{const v=new Map(S);return A.forEach(({id:k,branch:E})=>{E&&v.set(k,E)}),v}),A.forEach(({id:S,inputKey:v,branch:k})=>{g.current.set(S,v),k&&b.current.set(S,{branch:k,at:w})})})()},150);return()=>{h=!0,clearTimeout(p)}},[n,t,m,r,i])},zg=e=>{const{ownership:t}=e,n=l.useCallback(o=>t.sessionsByProject.get(o)??[],[t]),r=l.useCallback(o=>t.archivedSessionsByProject.get(o)??[],[t]);return{getSessionsForProject:n,getArchivedSessionsForProject:r}},Ug=e=>{const t=new Map;for(const n of e){const r=gn(n);r&&t.set(n.id,{directory:r,sessionId:n.id})}return t},$g=(e,t)=>{if(!e)return[];const n=[];return e.forEach((r,o)=>{t.has(o)||n.push(r)}),n},Kg=e=>{const{enabled:t=!0,hasAuthoritativeGlobalSessions:n,sessions:r}=e,o=l.useRef(null);l.useEffect(()=>{if(!t||!n)return;const i=Xe(),a=Ug(r),c=o.current?.runtimeKey===i?o.current.identities:null;for(const d of $g(c,a))dn().commitMissedDeletion(d.sessionId,d.directory);o.current={runtimeKey:i,identities:a}},[t,n,r])},Wg=(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,Ka=(e,t,n)=>{Wg(e.get(t),n)&&e.set(t,n)},Oc=e=>{const t=e;return Re(t.directory)??Re(t.project?.worktree)},Gg=(e,t,n)=>{if(e.time?.archived)return!0;const r=Oc(e);if(!r)return n?.allowUnknownDirectory??!0;if(or(r,n?.homeDirectory))return!0;if(t.size===0)return n?.allowEmptyDirectorySet??!0;const o=r.toLowerCase();for(const i of t)if(Re(i)?.toLowerCase()===o)return!0;return!1},Hg=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)},qg=(e,t,n,r=[])=>{const o=new Map,i=new Map;for(const b of t){const h=Re(b.normalizedPath);if(!h)continue;const p=i.get(h);(!p||b.id.localeCompare(p.id)<0)&&i.set(h,b),Ka(o,h,{projectId:b.id,projectRoot:h,scopeDirectory:h,kind:"project"})}if(n)for(const[b,h]of n){const p=Re(b),y=p?i.get(p):void 0;if(!(!y||!p))for(const x of h||[]){const C=Re(x?.path);C&&Ka(o,C,{projectId:y.id,projectRoot:p,scopeDirectory:C,kind:"worktree"})}}const a=new Map,c=new Map,d=new Map,u=new Map,f=new Map,m=b=>{if(!b)return null;if(a.has(b))return a.get(b)??null;const h=[];let p=b,y=null;for(;p;){if(a.has(p)){y=a.get(p)??null;break}if(h.push(p),y=o.get(p)??null,y)break;p=Hg(p)}for(const x of h)a.set(x,y);return y},g=(b,h,p)=>{for(const y of b){const x=Oc(y);if(or(x))continue;const C=m(x);if(!C)continue;c.set(y.id,C);const j=h.get(C.projectId);if(j?j.push(y):h.set(C.projectId,[y]),!p)continue;const A=p.get(C.scopeDirectory);A?A.add(y.id):p.set(C.scopeDirectory,new Set([y.id]))}};return g(e,d,f),g(r,u),{bySessionId:c,sessionsByProject:d,archivedSessionsByProject:u,sessionsByScope:f,directoryResolutions:a.size}};function Bc({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(Is,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})})}const Vg=({folder:e,displayName:t,sessions:n,subFolderItems:r,isCollapsed:o,collapsedActivityState:i=null,onToggle:a,onRename:c,onDelete:d,renderSessionNode:u,getRenderExtras:f,groupDirectory:m,projectId:g,mobileVariant:b=!1,alwaysShowActions:h=b,isRenaming:p=!1,renameDraft:y="",onRenameDraftChange:x,onRenameSave:C,onRenameCancel:j,droppableRef:A,isDropTarget:w=!1,onNewSession:S,depth:v=0,hideActions:k=!1,archivedBucket:E=!1})=>{const[P,z]=l.useState(!1),[K,q]=l.useState(""),H=l.useRef(null),F=p||P,D=p?y:K,T=l.useCallback(()=>{q(e.name),z(!0)},[e.name]),I=l.useCallback(()=>{const L=D.trim();L&&L!==e.name&&c(L),p&&C&&C(),z(!1),q("")},[D,e.name,p,c,C]),M=l.useCallback(()=>{p&&j&&j(),z(!1),q("")},[p,j]),G=l.useCallback(L=>{p&&x?x(L):q(L)},[p,x]);l.useEffect(()=>{if(!p)return;const L=()=>{const le=H.current;le&&(le.focus(),le.select())},ae=requestAnimationFrame(L),J=window.setTimeout(L,0);return()=>{cancelAnimationFrame(ae),window.clearTimeout(J)}},[p]);const W=o?"folder":"folder-open";return s.jsxs("div",{className:"oc-folder",children:[s.jsxs("div",{ref:A,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",w&&"bg-primary/10 ring-1 ring-inset ring-primary/30"),onClick:F?void 0:L=>{L.currentTarget.blur(),a()},role:F?void 0:"button",tabIndex:F?void 0:0,onKeyDown:F?void 0:L=>{(L.key==="Enter"||L.key===" ")&&(L.preventDefault(),a())},"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]",E?h?"pr-7":"group-hover/folder:pr-7 group-focus-within/folder:pr-7":h?"pr-20":"group-hover/folder:pr-20 group-focus-within/folder:pr-20"),children:[s.jsx(R,{name:W,className:_(Pr,w?"text-primary":"text-muted-foreground")}),F?s.jsxs("form",{className:"flex min-w-0 flex-1 items-center gap-1",onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),onSubmit:L=>{L.preventDefault(),I()},children:[s.jsx("input",{ref:H,value:D,onChange:L=>G(L.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:L=>L.stopPropagation(),onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),onKeyDown:L=>{if(L.key==="Escape"){L.stopPropagation(),M();return}(L.key===" "||L.key==="Enter")&&L.stopPropagation()}}),s.jsx("button",{type:"submit",className:"shrink-0 text-muted-foreground hover:text-foreground",onClick:L=>L.stopPropagation(),onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),children:s.jsx(R,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),M()},onPointerDown:L=>L.stopPropagation(),onMouseDown:L=>L.stopPropagation(),className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(R,{name:"close",className:"size-4"})})]}):s.jsxs("div",{className:"min-w-0 flex items-center gap-1.5 flex-1",children:[s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("span",{className:_(pc,w?"text-primary":"text-muted-foreground"),children:t??e.name})}),s.jsx(Ge,{side:"right",sideOffset:8,className:"max-w-xs",children:t??e.name})]}),s.jsxs("span",{className:"typography-micro text-subtle-foreground flex-shrink-0",children:["• ",n.length]}),i?s.jsx(Bc,{state:i,activeLabel:"Session active",unreadLabel:"Unread updates"}):null,o?s.jsx(R,{name:"arrow-right-s",className:_(Pr,"text-muted-foreground")}):s.jsx(R,{name:"arrow-down-s",className:_(Pr,"text-muted-foreground")})]})]}),!F&&(!k||E)?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",h?"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:[!E&&S?s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),S()},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(R,{name:"add",className:"size-4"})}):null,E?null:s.jsx("button",{type:"button",onClick:L=>{L.stopPropagation(),T()},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(R,{name:"pencil-ai",className:"size-4"})}),s.jsx("button",{type:"button",onClick:L=>{L.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":E?`Delete archived sessions in folder ${e.name}`:`Delete folder ${e.name}`,children:s.jsx(R,{name:"delete-bin",className:"size-4"})})]})}):null]}),o?null:s.jsxs("div",{className:"pb-1",children:[r,n.length>0?n.map(L=>s.jsx(l.Fragment,{children:u(L,0,m??null,g??null,E,void 0,"project",f?.(L))},L.session.id)):r?null:s.jsx("div",{className:"py-1 px-3 text-left typography-micro text-subtle-foreground",children:"Empty folder"})]})]})},Yg=l.memo(Vg),so=l.createContext(null),Qg=({sessionId:e,sessionDirectory:t,sessionTitle:n,children:r})=>{const{attributes:o,listeners:i,setNodeRef:a,isDragging:c}=Lu({id:`session-drag:${e}`,data:{type:"session",sessionId:e,sessionDirectory:t,sessionTitle:n}}),d=l.useCallback(u=>{u.stopPropagation(),i?.onPointerDown&&i.onPointerDown(u)},[i]);return s.jsx("div",{ref:a,...o,onPointerDown:d,className:c?"opacity-30":void 0,children:r})},Jg=({folderId:e,children:t})=>{const{setNodeRef:n,isOver:r}=Tl({id:`folder-drop:${e}`,data:{type:"folder",folderId:e}});return s.jsx(s.Fragment,{children:t(n,r)})},Xg=({scopeKey:e,hasFolders:t,onSessionDroppedOnFolder:n,children:r})=>{const o=Jr(wn(Rl,{activationConstraint:{distance:8}})),[i,a]=l.useState(null),[c,d]=l.useState("Session"),[u,f]=l.useState(null),[m,g]=l.useState(null);if(!e)return s.jsx(s.Fragment,{children:r});const b=h=>{a(null),f(null),g(null);const{active:p,over:y}=h;if(!y)return;const x=p.data.current,C=y.data.current;x?.type==="session"&&x.sessionId&&C?.type==="folder"&&C.folderId&&n(x.sessionId,C.folderId)};return s.jsxs(Xr,{sensors:o,collisionDetection:Di,onDragStart:h=>{const p=h.active.data.current;if(p?.type==="session"&&p.sessionId){a(p.sessionId),d(p.sessionTitle??"Session");const y=h.active.rect.current.initial?.width,x=h.active.rect.current.initial?.height;f(typeof y=="number"?y:null),g(typeof x=="number"?x:null)}},onDragCancel:()=>{a(null),f(null),g(null)},onDragEnd:b,children:[r,s.jsx(Pl,{children:i&&t?s.jsxs("div",{style:{width:u?`${u}px`:"auto",height:m?`${m}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(R,{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})]})},no="gap-2",_c="my-0.5 rounded-lg py-1.5",lr=l.createContext("card"),qt=({icon:e,children:t,onClick:n,className:r,mobileVariant:o=!1})=>{const i=l.useContext(lr)==="tree";return s.jsxs("button",{type:"button",onClick:n,"data-sidebar-tree-row":i?"":void 0,className:_(o?Yh:Qh,i&&no,i&&_c,r),children:[s.jsx(R,{name:e,className:_(Gs(o),"text-muted-foreground")}),s.jsx("span",{className:_(kn(o),"flex-1 text-muted-foreground"),children:t})]})},Zg="select-none px-3 pb-0.5 typography-ui-label font-medium text-muted-foreground",xn=({label:e,first:t=!1,count:n,expanded:r,onToggle:o})=>{const i=t?"pt-1":"pt-3",a=typeof n=="number"?s.jsx("span",{className:"font-normal tabular-nums text-subtle-foreground",children:n}):null;return o?s.jsx("div",{role:"heading","aria-level":3,className:i,children:s.jsxs("button",{type:"button","aria-expanded":r,onClick:o,className:"group/heading flex h-7 w-full select-none items-center gap-1.5 rounded-md px-3 text-left typography-ui-label font-medium text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",children:[e,a,s.jsx(R,{name:r?"arrow-down-s":"arrow-right-s",className:"ml-auto size-4 shrink-0 text-muted-foreground group-hover/heading:text-foreground"})]})}):s.jsxs("div",{role:"heading","aria-level":3,className:_(Zg,i,"flex items-center gap-1.5"),children:[e,a]})},Wa=(e,t,n)=>{if(!t)return;const r=o=>{let i=o.session.id===t;for(const a of o.children)i=r(a)||i;return i&&n.add(o.session.id),i};for(const o of e)r(o)},us=(e,t)=>{if(!t)return!1;if(e.session.id===t)return!0;for(const n of e.children)if(us(n,t))return!0;return!1},eb=(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})},Ga=new WeakMap;let Ha=1;const tb=e=>{const t=Ga.get(e);if(t!==void 0)return t;const n=Ha;return Ha+=1,Ga.set(e,n),n},mi=e=>e.children.length===0?"":e.children.map(n=>{const r=tb(n.session);return n.children.length===0?`${n.session.id}@${r}`:`${n.session.id}@${r}:${mi(n)}`}).join("|"),zc=(e,t,n,r,o,i)=>{const a=Xe(),c=(d,u)=>{if(d.session.id!==u.session.id||d.children.length!==u.children.length)return!0;const f=d.session.directory??o,m=u.session.directory??i,g=ga(a,f??"",d.session.id),b=ga(a,m??"",u.session.id);return(g?n.has(g):!1)!==(b?r.has(b):!1)?!0:d.children.some((h,p)=>c(h,u.children[p]))};return c(e,t)},cr=(e,t)=>`${e}:${t.time?.archived?"archived":"active"}:${t.id}`,Gr=(e,t,n)=>{if(!t)return null;let r=null;const o=i=>{if(cr(n,i.session)===t)return r=i.session.id,!0;for(const c of i.children)if(o(c))return!0;return!1};return e.forEach(i=>o(i)),r},sb=5*6e4,nb=6e4,qa=5*6e4,Va=100,$n=new Map,un=new Map,$s=new Map,yn=new Map,dr=(e,t)=>{const n=ps((e??"").trim()),r=(t??"").trim();return!n||!r?"":`${Xe()}
|
|
16
|
+
${n}
|
|
17
|
+
${r}`},Ya=()=>({pr:null,checks:null,fetchedAt:null,isLoading:!1,stale:!1,error:null}),rb=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"PR status check failed"}},ob=e=>{const t=Object.keys(e);if(t.length<=Va)return e;const n=t.sort((o,i)=>(yn.get(o)??0)-(yn.get(i)??0)),r={...e};for(let o=0;o<n.length-Va;o+=1){const i=n[o];delete r[i],yn.delete(i),un.delete(i);const a=$s.get(i);a!==void 0&&(clearTimeout(a),$s.delete(i))}return r},Uc=e=>e.pr?e.pr.state!=="open"?qa:e.checks?.state==="pending"?nb:qa:sb,gi=(e,t,n,r)=>{if(typeof window>"u"||$s.has(e))return;const o=ts.getState().results[e];if(!o)return;const i=Uc(o),a=setTimeout(()=>{if($s.delete(e),!!ts.getState().results[e]){if(typeof document<"u"&&document.hidden){gi(e,t,n,r);return}ts.getState().refresh(t,n,r)}},i);typeof a=="object"&&a!==null&&typeof a.unref=="function"&&a.unref(),$s.set(e,a)},ts=bs()(Zr((e,t)=>({results:{},refresh:async(n,r,o,i)=>{const a=ps((n||"").trim()),c=(r||"").trim();if(!a||!c)return null;const d=dr(a,c);if(!d)return null;const u=$n.get(d);if(u&&!i?.force)return u;const f=o??null;if(!f)return t().results[d]??null;const m=(un.get(d)??0)+1;un.set(d,m);const g=t().results[d]??Ya();e(h=>({results:{...h.results,[d]:{...g,isLoading:!0}}}));const b=(async()=>{try{const h=await f.prStatus(a,c);if(un.get(d)!==m||Xe()!==d.split(`
|
|
18
|
+
`)[0])return t().results[d]??null;const p={pr:h.pr??null,checks:h.checks??null,checksStale:h.checksStale,defaultBranch:h.defaultBranch??null,skippedDefaultBranch:h.skippedDefaultBranch,fetchedAt:h.fetchedAt??Date.now(),isLoading:!1,stale:!1,error:null};return yn.set(d,Date.now()),e(y=>({results:ob({...y.results,[d]:p})})),gi(d,a,c,f),p}catch(h){if(un.get(d)!==m)return t().results[d]??null;const p=rb(h),y=g.pr||g.fetchedAt?{...g,isLoading:!1,stale:!0,error:p}:{...Ya(),error:p};return e(x=>({results:{...x.results,[d]:y}})),gi(d,a,c,f),y}})();$n.set(d,b);try{return await b}finally{$n.get(d)===b&&$n.delete(d)}},load:async(n,r,o)=>{const i=ps((n||"").trim()),a=(r||"").trim();if(!i||!a)return null;const c=dr(i,a);yn.set(c,Date.now());const d=t().results[c];return d&&(d.pr||d.fetchedAt)?(t().refresh(i,a,o),d):t().refresh(i,a,o)},resetForRuntimeSwitch:()=>{$n.clear(),un.clear(),yn.clear(),Gn=null;for(const n of $s.values())clearTimeout(n);$s.clear(),e({results:{}})}}),{name:"github-pr-status-store"}));typeof window<"u"&&(Nn(()=>{ts.getState().resetForRuntimeSwitch()}),document.addEventListener("visibilitychange",()=>{document.hidden||(async()=>{const e=await pt(async()=>{const{getRegisteredRuntimeAPIs:r}=await import("./index-CKKWVoND.js").then(o=>o.cK);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(ts.getState().results).filter(([,r])=>r.fetchedAt&&t-r.fetchedAt>=Uc(r)).map(([r])=>r);for(const r of n){const[,o,i]=r.split(`
|
|
19
|
+
`);if(!(!o||!i)){if(typeof document<"u"&&document.hidden)return;await ts.getState().refresh(o,i,e).catch(()=>null)}}})()}));let Gn=null;const zv=e=>{if(Gn&&Gn.results===e)return Gn.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 Gn={results:e,index:t},t},ib=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}},$c=e=>{const t=ts(n=>e?n.results[e]??null:null);return l.useMemo(()=>ib(t),[t])},Kc=(e,t,n)=>{const r=l.useMemo(()=>dr(e,t),[e,t]),o=n??null;l.useEffect(()=>{if(!r||!e?.trim()||!t?.trim())return;let i=!1;return pt(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-CKKWVoND.js").then(c=>c.cK);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:a})=>{if(i)return;const c=o??a()?.github??null;c&&ts.getState().load(e,t,c)}).catch(()=>{}),()=>{i=!0}},[r,e,t,o])},Wc=new Set,zi=(e,t)=>e==="input"||t==="input"?"input":e==="active"||t==="active"?"active":e==="unread"||t==="unread"?"unread":null,bi=(e,t,n,r=Wc)=>{if(r.has(e.session.id))return"input";if(t.has(e.session.id)){for(const i of e.children)if(bi(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=zi(o,bi(i,t,n,r)),o==="input")return o;return o},Gc=(e,t,n,r=Wc)=>{let o=null;for(const i of e)if(o=zi(o,bi(i,t,n,r)),o==="input")return o;return o},xi=(e,t)=>{if(!t)return e;const n=e.toLowerCase(),r=t.toLowerCase(),o=r.length;if(o===0)return e;const i=[];let a=0,c=n.indexOf(r,a);for(;c!==-1;){c>a&&i.push(e.slice(a,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}`)),a=c+o,c=n.indexOf(r,a)}return a<e.length&&i.push(e.slice(a)),i.length>0?i:e},Dn=e=>[Xe(),...e.map(t=>(t??"").toString())].join(`
|
|
20
|
+
`),Cr=e=>{const t=e?.body;return t&&typeof t.kind=="string"?t:{kind:"failed",message:e instanceof Error?e.message:"GitHub request failed"}},ab=200,mn=(e={})=>{const t=e.maxEntries??ab,n=new Map,r=new Map,o=new Map;let i=0;const a=new Map,c=new Map,d=p=>{const y=n.get(p)??null;return y&&a.set(p,i+=1),y},u=p=>{const y=c.get(p);if(y)for(const x of[...y])try{x()}catch{}},f=()=>{if(n.size<=t)return;const p=[...n.keys()].filter(x=>!r.has(x)&&(c.get(x)?.size??0)===0).sort((x,C)=>(a.get(x)??0)-(a.get(C)??0)),y=n.size-t;for(let x=0;x<y&&x<p.length;x+=1){const C=p[x];n.delete(C),a.delete(C),o.set(C,(o.get(C)??0)+1)}};let m=!1;const g=()=>{if(m||n.size<=t)return;m=!0;const p=()=>{m=!1,f()};typeof queueMicrotask=="function"?queueMicrotask(p):setTimeout(p,0)},b=(p,y)=>{const C={...n.get(p)??{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:null,generation:o.get(p)??0},...y};return n.set(p,C),a.set(p,i+=1),g(),u(p),C},h=async(p,y)=>{const x=r.get(p);if(x)return x;const C=(o.get(p)??0)+1;o.set(p,C);const j=n.get(p);b(p,{isLoading:!0,generation:C});const A=(async()=>{try{const w=await y();return o.get(p)!==C?n.get(p)??{data:w,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:C}:b(p,{data:w,fetchedAt:Date.now(),isLoading:!1,stale:!1,error:null,generation:C})}catch(w){return o.get(p)!==C?n.get(p)??{data:j?.data??null,fetchedAt:j?.fetchedAt??null,isLoading:!1,stale:!0,error:Cr(w),generation:C}:j?.data!=null?b(p,{isLoading:!1,stale:!0,error:Cr(w),generation:C}):b(p,{data:null,fetchedAt:null,isLoading:!1,stale:!1,error:Cr(w),generation:C})}})();r.set(p,A);try{return await A}finally{r.get(p)===A&&r.delete(p),e.onSettle?.(p)}};return{getEntry:d,snapshot:()=>Object.fromEntries(n),subscribe:(p,y)=>{let x=c.get(p);return x||(x=new Set,c.set(p,x)),x.add(y),()=>{const C=c.get(p);C&&(C.delete(y),C.size===0&&c.delete(p))}},ensure:(p,y,x)=>!x?.force&&r.has(p)?r.get(p):!x?.force&&n.get(p)?.data!=null&&n.get(p)?.isLoading?r.get(p)??Promise.resolve(n.get(p)):!x?.force&&n.get(p)?.data!=null?(h(p,y),Promise.resolve(n.get(p))):h(p,y),refresh:(p,y)=>h(p,y),invalidate:async(p,y,x)=>{if(x?.exact??!0)return o.set(p,(o.get(p)??0)+1),n.delete(p),a.delete(p),r.has(p)&&r.delete(p),u(p),y?h(p,y):null;for(const j of[...n.keys()])(j===p||j.startsWith(p))&&(o.set(j,(o.get(j)??0)+1),n.delete(j),a.delete(j),r.delete(j),u(j));return null},markStale:p=>{const y=n.get(p);y?.data&&(y.stale||b(p,{stale:!0}))},setError:(p,y)=>{const x=n.get(p);return x?.data?b(p,{isLoading:!1,stale:!0,error:Cr(y)}):x??null},remove:p=>{o.set(p,(o.get(p)??0)+1),n.delete(p),a.delete(p),r.delete(p),u(p)},reset:()=>{const p=[...n.keys()];n.clear(),r.clear(),o.clear(),a.clear();for(const y of p)u(y)}}},Rn=(e,t)=>Te.useSyncExternalStore(n=>t?e.subscribe(t,n):()=>{},()=>t?e.getEntry(t):null,()=>t?e.getEntry(t):null),Uv=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},Hc=(e,t)=>!e||!t?!1:e.toLowerCase()===t.toLowerCase(),yi=e=>{if(!e)return[];const t=[];for(const n of e)n?.login&&t.push(n.login.toLowerCase());return t},qc=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}},Ui=e=>{if(!e)return[];const t=[];for(const n of e)n?.name&&t.push(n.name.toLowerCase());return t},Vc=(e,t,n)=>{const r=Ui(e??null),o=t.split(",").map(i=>i.trim().toLowerCase()).filter(Boolean);for(const i of[...o,...n])if(!r.some(a=>a===i||a.includes(i)))return!1;return!0},lb=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??"",e.head.toLowerCase(),e.base.toLowerCase()];for(const n of Ui(e.labels))t.push(n);return t},cb=e=>{const t=[e.title.toLowerCase(),`#${e.number}`,`${e.number}`,e.author?.login?.toLowerCase()??""];for(const n of Ui(e.labels))t.push(n);return t},Yc=(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},Qa=e=>e.state==="merged"||!!e.mergedAt,db=(e,t)=>t==="all"?e:t==="open"?e.filter(n=>n.state==="open"):t==="merged"?e.filter(n=>Qa(n)):e.filter(n=>n.state==="closed"&&!Qa(n)),ub=(e,t)=>t==="all"?e:e.filter(n=>n.state===t),fb=(e,t,n)=>t==="all"||!n?!0:t==="mine"?Hc(e.author?.login,n):t==="review"?yi(e.requestedReviewers).includes(n.toLowerCase()):yi(e.assignees).includes(n.toLowerCase()),hb=(e,t,n)=>t==="all"||!n||t==="mentioned"?!0:t==="mine"?Hc(e.author?.login,n):yi(e.assignees).includes(n.toLowerCase()),an=e=>{if(!e)return 0;const t=Date.parse(e);return Number.isFinite(t)?t:0},Qc=(e,t)=>{const n=[...e];return t==="newest"?(n.sort((r,o)=>an(o.createdAt)-an(r.createdAt)||o.number-r.number),n):t==="oldest"?(n.sort((r,o)=>an(r.createdAt)-an(o.createdAt)||r.number-o.number),n):(n.sort((r,o)=>an(o.updatedAt)-an(r.updatedAt)||o.number-r.number),n)},$v=(e,t)=>{const{tokens:n,labelTokens:r}=qc(t.search),o=[];for(const i of db(e,t.state))fb(i,t.involvement,t.viewerLogin)&&Vc(i.labels,"",r)&&Yc(lb(i),n)&&o.push(i);return Qc(o,t.sort)},Kv=(e,t)=>{const{tokens:n,labelTokens:r}=qc(t.search),o=[];for(const i of ub(e,t.state))hb(i,t.involvement,t.viewerLogin)&&Vc(i.labels,t.labels,r)&&Yc(cb(i),n)&&o.push(i);return Qc(o,t.sort)},Ar=(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},Wv=(e,t)=>e.filter(n=>!t.has(n.number)),pb=(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},Ja=Object.freeze({repo:null,number:null}),Ro=e=>e.split(`
|
|
21
|
+
`)[1]??"",wi=(e,t)=>`${ps(e)}
|
|
22
|
+
${t}`,Kn=(e,t)=>`${e}#${t}`,mb=(e,t)=>{const n=e?.body;return n&&typeof n.kind=="string"?n:{kind:"failed",message:e instanceof Error?e.message:t}},_s=async(e,t)=>{if(e)try{await e.invalidate(t)}catch{}},Xa=(e,t)=>!e?.data||!e.fetchedAt?!1:Date.now()-e.fetchedAt<t,Za=10,gb=(e,t)=>{const n=mn(),r=mn({maxEntries:60}),o=mn(),i=mn(),a=new Map,c=new Map,d=async(F,D)=>{const T=c.get(F);if(T)return await T.catch(()=>null),{ran:!1,result:null};const I=D();c.set(F,I);try{return{ran:!0,result:await I}}finally{c.get(F)===I&&c.delete(F)}},u=(F,D)=>{if(D.length===0)return;const T=e.collectionKeyFor(F,e.openCollection);let I=a.get(T);I||(I=new Map,a.set(T,I));for(const M of D)I.set(M.number,M)},f=F=>{const D=Object.keys(r.snapshot()).filter(I=>Ro(I)===F&&!r.getEntry(I)?.isLoading);if(D.length<=Za)return;const T=D.map(I=>({key:I,fetchedAt:r.getEntry(I)?.data?.fetchedAt??0})).sort((I,M)=>I.fetchedAt-M.fetchedAt);for(let I=0;I<T.length-Za;I+=1)r.remove(T[I].key)},m=F=>{const D=n.getEntry(e.collectionKeyFor(F,e.openCollection))?.data?.items??[],T=n.getEntry(e.collectionKeyFor(F,e.closedCollection))?.data?.items??[],I=Ar(D,T),M=a.get(e.collectionKeyFor(F,e.openCollection));return!M||M.size===0?I:Ar(I,[...M.values()])},g=(F,D,T)=>{const I=wi(F,D),M=t.get().filtersByScope[I]??e.defaultFilters;t.set(G=>({filtersByScope:{...G.filtersByScope,[I]:{...M,...T}}}))},b=(F,D)=>{const T=wi(F,D);t.set(I=>({filtersByScope:{...I.filtersByScope,[T]:{...e.defaultFilters}}}))},h=(F,D,T)=>{const I=ps(F);I&&t.set(M=>({selectionByDirectory:{...M.selectionByDirectory,[I]:{repo:D,number:T}}}))},p=(F,D,T,I)=>{const M=e.collectionKeyFor(D,T);return n.ensure(M,async()=>{const G=await e.fetchList(I,F,D,e.buildCollectionQuery(T));return{items:G.items,nextCursor:G.nextCursor,fetchedAt:G.fetchedAt}})},y=(F,D,T)=>{const I=e.collectionKeyFor(D,e.closedCollection);n.getEntry(I)?.data||n.getEntry(I)?.isLoading||p(F,D,e.closedCollection,T).catch(()=>null)},x=async(F,D,T,I)=>{const M=T==="open"||T==="both",G=T==="closed"||T==="both",W=[],L=n.getEntry(e.collectionKeyFor(D,e.openCollection)),ae=n.getEntry(e.collectionKeyFor(D,e.closedCollection));M&&(!Xa(L,e.freshWindowMs)||L?.stale)&&W.push(p(F,D,e.openCollection,I)),G&&(!Xa(ae,e.freshWindowMs)||ae?.stale)&&W.push(p(F,D,e.closedCollection,I)),await Promise.all(W.map(J=>J.catch(()=>null))),M&&!n.getEntry(e.collectionKeyFor(D,e.closedCollection))?.data&&y(F,D,I)},C=async(F,D,T,I)=>{const M=e.collectionKeyFor(D,T),G=n.getEntry(M),W=G?.data?.nextCursor??null;if(!W||G?.isLoading)return G;try{const L=await d(`${M}:more`,async()=>{const ae=await e.fetchList(I,F,D,{...e.buildCollectionQuery(T),cursor:W}),J=n.getEntry(M)?.data,le={items:Ar(J?.items??[],ae.items),nextCursor:ae.nextCursor,fetchedAt:ae.fetchedAt};return n.refresh(M,async()=>le)});return L.ran?L.result??n.getEntry(M):n.getEntry(M)}catch(L){return n.setError(M,L)??n.getEntry(M)}},j=async(F,D,T,I)=>{const M=T==="both"?[e.openCollection,e.closedCollection]:[T];await Promise.all(M.map(G=>{const W=e.collectionKeyFor(D,G);return n.refresh(W,async()=>{const L=await e.fetchList(I,F,D,e.buildCollectionQuery(G));return{items:L.items,nextCursor:L.nextCursor,fetchedAt:L.fetchedAt}}).catch(()=>null)}))},A=async(F,D,T,I)=>{const M=e.remoteKeyFor(D,T),G=await r.refresh(M,async()=>{const W=await e.fetchList(I,F,D,e.buildRemoteQuery(T));return{items:W.items,nextCursor:W.nextCursor,fetchedAt:W.fetchedAt}});return G.data&&(u(D,G.data.items),f(D)),G},w=async(F,D,T,I)=>{const M=e.remoteKeyFor(D,T),G=r.getEntry(M),W=G?.data?.nextCursor??null;if(!W||G?.isLoading)return G;try{const L=await e.fetchList(I,F,D,e.buildRemoteQuery(T,W)),ae=r.getEntry(M)?.data,J={items:Ar(ae?.items??[],L.items),nextCursor:L.nextCursor,fetchedAt:L.fetchedAt},le=await r.refresh(M,async()=>J);return le.data&&(u(D,le.data.items),f(D)),le}catch(L){return r.setError(M,L)??r.getEntry(M)}},S=F=>{for(const D of Object.keys(r.snapshot()))Ro(D)===F&&r.remove(D);for(const D of[...a.keys()])Ro(D)===F&&a.delete(D)},v=(F,D,T,I)=>{const M=e.detailKeyFor(D,T);return o.refresh(M,async()=>({detail:await e.fetchDetail(I,F,D,T)}))};return{initialState:{filtersByScope:{},selectionByDirectory:{}},resources:{collections:n,remote:r,details:o,comments:i},setFilters:g,resetFilters:b,select:h,ensureCollection:p,ensureCollectionsFresh:x,prefetchClosedCollection:y,loadMoreCollection:C,refreshCollections:j,searchRemote:A,loadMoreRemote:w,dropRemoteForRepo:S,refreshAllForScope:async(F,D,T)=>{await _s(T,{directory:F,repo:D,kind:e.serverKind}),S(D),await j(F,D,"both",T).catch(()=>null);const I=t.get().selectionByDirectory[ps(F)];I?.repo===D&&typeof I.number=="number"&&await v(F,D,I.number,T).catch(()=>null)},ensureDetail:(F,D,T,I)=>{const M=e.detailKeyFor(D,T);return o.ensure(M,async()=>({detail:await e.fetchDetail(I,F,D,T)}))},refreshDetail:v,ensureComments:(F,D,T,I)=>{const M=e.commentsKeyFor(D,T);return i.ensure(M,async()=>{const G=await e.fetchComments(I,F,D,T);return{comments:G.comments,nextCursor:G.nextCursor,fetchedAt:G.fetchedAt}})},loadMoreComments:async(F,D,T,I)=>{const M=e.commentsKeyFor(D,T),G=i.getEntry(M),W=G?.data?.nextCursor??null;if(!W||G?.isLoading)return G;try{const L=await e.fetchComments(I,F,D,T,W),ae=i.getEntry(M)?.data,J={comments:pb(ae?.comments??[],L.comments),nextCursor:L.nextCursor,fetchedAt:L.fetchedAt};return await i.refresh(M,async()=>J)}catch(L){return i.setError(M,L)??i.getEntry(M)}},refreshComments:(F,D,T,I)=>{const M=e.commentsKeyFor(D,T);return i.refresh(M,async()=>{const G=await e.fetchComments(I,F,D,T);return{comments:G.comments,nextCursor:G.nextCursor,fetchedAt:G.fetchedAt}})},markCollectionsStale:F=>{n.markStale(e.collectionKeyFor(F,e.openCollection)),n.markStale(e.collectionKeyFor(F,e.closedCollection))},getLocalIndex:m,withSingleFlight:d,resetCore:()=>{n.reset(),r.reset(),a.clear(),o.reset(),i.reset(),c.clear(),t.set({filtersByScope:{},selectionByDirectory:{}})},toStoreError:F=>mb(F,e.errorFallback)}},vi={state:"open",involvement:"all",search:"",sort:"updated"},bb=3e4,xb=100,yb=50,Jc=(e,t)=>Dn([e,"pulls-collection",t]),Xc=(e,t)=>Dn([e,"pulls-remote",t.state,t.involvement,t.q.trim()]),Hr=(e,t)=>Dn([e,"pull-detail",t]),$i=(e,t)=>Dn([e,"pull-comments",t]),Si=(e,t)=>Dn([e,"pull-files",t]),ji=(e,t)=>Dn([e,"pull-checks",t]),wb=e=>({state:e,perPage:xb}),vb=(e,t)=>({state:e.state,filter:e.involvement,q:e.q.trim()?e.q.trim():void 0,perPage:yb,...t?{cursor:t}:{}}),qr=e=>`pichamber:pr-merge-method:${e}`,Zc=new Map,Sb=e=>{try{if(typeof localStorage<"u")return localStorage.getItem(e)}catch{}return null},jb=(e,t)=>{try{if(typeof localStorage<"u"){localStorage.setItem(e,t);return}}catch{}},Gv=e=>{if(!e)return null;const t=Sb(qr(e));return t==="merge"||t==="squash"||t==="rebase"?t:Zc.get(qr(e))??null},kb=(e,t)=>{if(e){Zc.set(qr(e),t);try{jb(qr(e),t)}catch{}}},Cb={set:e=>{typeof e=="function"?Ns.setState(t=>{const n={filtersByScope:t.filtersByScope,selectionByDirectory:t.selectionByDirectory};return e(n)}):Ns.setState(e)},get:()=>{const e=Ns.getState();return{filtersByScope:e.filtersByScope,selectionByDirectory:e.selectionByDirectory}}},Fe=gb({openCollection:"open",closedCollection:"closed",defaultFilters:vi,freshWindowMs:bb,serverKind:"pulls",errorFallback:"Pull request request failed",collectionKeyFor:Jc,remoteKeyFor:Xc,detailKeyFor:Hr,commentsKeyFor:$i,buildCollectionQuery:e=>({...wb(e)}),buildRemoteQuery:(e,t)=>({...vb(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}}},Cb),Zt=mn(),Fr=mn(),Ns=bs()(Zr((e,t)=>({...Fe.initialState,actionErrorByDetail:{},actingActions:{},setFilters:Fe.setFilters,resetFilters:Fe.resetFilters,selectPullRequest:Fe.select,ensureCollection:Fe.ensureCollection,ensureCollectionsFresh:Fe.ensureCollectionsFresh,prefetchClosedCollection:Fe.prefetchClosedCollection,loadMoreCollection:Fe.loadMoreCollection,refreshCollections:Fe.refreshCollections,searchRemote:Fe.searchRemote,loadMoreRemote:Fe.loadMoreRemote,dropRemoteForRepo:Fe.dropRemoteForRepo,refreshAllForScope:Fe.refreshAllForScope,ensureDetail:Fe.ensureDetail,refreshDetail:Fe.refreshDetail,ensureComments:Fe.ensureComments,loadMoreComments:Fe.loadMoreComments,refreshComments:Fe.refreshComments,ensureFiles:(n,r,o,i)=>{const a=Si(r,o);return Zt.ensure(a,async()=>i.pullFiles(n,r,o))},loadMoreFiles:async(n,r,o,i)=>{const a=Si(r,o),c=Zt.getEntry(a),d=c?.data?.nextCursor??null;if(!d||c?.isLoading)return c;try{const u=await Fe.withSingleFlight(`${a}:more`,async()=>{const f=await i.pullFiles(n,r,o,d),m=Zt.getEntry(a)?.data,g=new Set((m?.files??[]).map(h=>h.filename)),b={repo:f.repo,number:f.number,files:[...m?.files??[],...f.files.filter(h=>!g.has(h.filename))],nextCursor:f.nextCursor,fetchedAt:f.fetchedAt};return Zt.refresh(a,async()=>b)});return u.ran?u.result??Zt.getEntry(a):Zt.getEntry(a)}catch(u){return Zt.setError(a,u)??Zt.getEntry(a)}},ensureChecks:(n,r,o,i)=>{const a=ji(r,o);return Fr.ensure(a,async()=>i.pullChecks(n,r,o,!0))},refreshChecks:(n,r,o,i)=>{const a=ji(r,o);return Fr.refresh(a,async()=>i.pullChecks(n,r,o,!0))},performAction:async(n,r,o,i,a)=>{const c=Kn(r,o),d=Hr(r,o);if(t().actingActions[c])return{ok:!1,error:{kind:"failed",message:"Action already in progress"}};e(g=>({actingActions:{...g.actingActions,[c]:!0},actionErrorByDetail:{...g.actionErrorByDetail,[c]:null}}));const u=Fe.resources.details.getEntry(d)?.data?.detail??null,f=u?.pr??null,m=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;m&&u&&await Fe.resources.details.refresh(d,async()=>({detail:{...u,pr:m}})).catch(()=>null);try{return await a.pullAction(n,r,o,i),(i==="merge"||i==="squash"||i==="rebase")&&t().setMergeMethod(r,i),await _s(a,{directory:n,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(n,r,"both",a).catch(()=>null),await t().refreshDetail(n,r,o,a).catch(()=>null),await t().refreshChecks(n,r,o,a).catch(()=>null),e(g=>({actingActions:{...g.actingActions,[c]:!1}})),{ok:!0}}catch(g){const b=Fe.toStoreError(g);return u&&await Fe.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(h=>({actingActions:{...h.actingActions,[c]:!1},actionErrorByDetail:{...h.actionErrorByDetail,[c]:b}})),{ok:!1,error:b}}},updateTitleBody:async(n,r,o,i,a)=>{const c=Kn(r,o),d=Hr(r,o),u=Fe.resources.details.getEntry(d)?.data?.detail??null,f=u?.pr??null,m=f&&(i.title!==void 0||i.body!==void 0)?{...f,title:i.title??f.title,body:i.body??f.body}:null;m&&u&&await Fe.resources.details.refresh(d,async()=>({detail:{...u,pr:m}})).catch(()=>null);try{return await a.pullUpdate(n,r,o,i),await _s(a,{directory:n,repo:r,kind:"pulls",number:o}),t().dropRemoteForRepo(r),await t().refreshCollections(n,r,"both",a).catch(()=>null),await t().refreshDetail(n,r,o,a).catch(()=>null),{ok:!0}}catch(g){const b=Fe.toStoreError(g);return u&&await Fe.resources.details.refresh(d,async()=>({detail:u})).catch(()=>null),e(h=>({actionErrorByDetail:{...h.actionErrorByDetail,[c]:b}})),{ok:!1,error:b}}},addComment:async(n,r,o,i,a)=>{const c=Kn(r,o),d=$i(r,o),u=i.trim(),f={id:-Date.now(),url:"",body:u,author:null,createdAt:new Date().toISOString(),updatedAt:null},m=Fe.resources.comments.getEntry(d)?.data??null;if(m){const g={comments:[...m.comments,f],nextCursor:m.nextCursor,fetchedAt:m.fetchedAt};await Fe.resources.comments.refresh(d,async()=>g).catch(()=>null)}try{return await a.pullComment(n,r,o,u),await _s(a,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshComments(n,r,o,a).catch(()=>null),await t().refreshDetail(n,r,o,a).catch(()=>null),{ok:!0}}catch(g){const b=Fe.toStoreError(g);return m?await Fe.resources.comments.refresh(d,async()=>m).catch(()=>null):Fe.resources.comments.remove(d),e(h=>({actionErrorByDetail:{...h.actionErrorByDetail,[c]:b}})),{ok:!1,error:b}}},submitReview:async(n,r,o,i,a)=>{const c=Kn(r,o);try{return await a.pullReview(n,r,o,{event:i.event,body:i.body,comments:i.comments}),await _s(a,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,a).catch(()=>null),{ok:!0}}catch(d){const u=Fe.toStoreError(d);return e(f=>({actionErrorByDetail:{...f.actionErrorByDetail,[c]:u}})),{ok:!1,error:u}}},threadAction:async(n,r,o,i,a,c)=>{const d=Kn(r,o);try{return await c.pullThread(n,r,o,i,a),await _s(c,{directory:n,repo:r,kind:"pulls",number:o}),await t().refreshDetail(n,r,o,c).catch(()=>null),{ok:!0}}catch(u){const f=Fe.toStoreError(u);return e(m=>({actionErrorByDetail:{...m.actionErrorByDetail,[d]:f}})),{ok:!1,error:f}}},checkout:async(n,r,o,i,a)=>{try{const c=await a.pullCheckout(n,r,o,i);return{ok:!0,path:c.path,branch:c.branch}}catch(c){return{ok:!1,error:Fe.toStoreError(c)}}},createPullRequest:async(n,r)=>{try{const o=await r.pullCreate(n);return await _s(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:Fe.toStoreError(o)}}},rerunFailedChecks:async(n,r,o,i)=>{try{return await i.checksRerun(n,r,o),{ok:!0}}catch(a){return{ok:!1,error:Fe.toStoreError(a)}}},setMergeMethod:(n,r)=>{kb(n,r)},notifyAgentTurnComplete:n=>{const r=ps((n||"").trim());if(!r)return;const o=ts.getState();for(const a of Object.keys(o.results)){const[,c]=a.split(`
|
|
23
|
+
`);if(c!==r)continue;const[,,d]=a.split(`
|
|
24
|
+
`);d&&pt(async()=>{const{getRegisteredRuntimeAPIs:u}=await import("./index-CKKWVoND.js").then(f=>f.cK);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"&&(Fe.markCollectionsStale(i.repo),pt(async()=>{const{getRegisteredRuntimeAPIs:a}=await import("./index-CKKWVoND.js").then(c=>c.cK);return{getRegisteredRuntimeAPIs:a}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({getRegisteredRuntimeAPIs:a})=>{const c=a()?.github??null;if(c)return t().refreshDetail(r,i.repo,i.number,c)}).catch(()=>{}))},resetForRuntimeSwitch:()=>{Fe.resetCore(),Zt.reset(),Fr.reset(),e({actionErrorByDetail:{},actingActions:{}})}}),{name:"github-pull-requests-store"}));typeof window<"u"&&(Nn(()=>{Ns.getState().resetForRuntimeSwitch()}),window.addEventListener("focus",()=>{typeof document<"u"&&document.hidden}));const Hv=e=>{if(typeof window>"u")return()=>{};let t=new Set,n=!1,r=!1,o=null;return pt(async()=>{const{useNotificationStore:i}=await import("./useAppFontEffects-CV5UyTRw.js").then(a=>a.eY);return{useNotificationStore:i}},__vite__mapDeps([1,2,3,4,5,6,7,8,9,10,11,12])).then(({useNotificationStore:i})=>{if(r)return;const a=()=>{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&&(Ns.getState().notifyAgentTurnComplete(u.directory),e?.(u.directory)))}};a(),o=i.subscribe(a)}).catch(()=>{}),()=>{r=!0,o?.(),o=null}},qv=e=>Fe.getLocalIndex(e),Vv=(e,t)=>Fe.getLocalIndex(e).find(n=>n.number===t)??null,Yv=(e,t)=>Rn(Fe.resources.collections,e?Jc(e,t):null),Qv=(e,t)=>Rn(Fe.resources.remote,e?Xc(e,t):null),Jv=(e,t)=>Rn(Fe.resources.details,e!=null&&t!=null?Hr(e,t):null),Xv=(e,t)=>Rn(Fe.resources.comments,e!=null&&t!=null?$i(e,t):null),Zv=(e,t)=>Rn(Zt,e!=null&&t!=null?Si(e,t):null),eS=(e,t)=>Rn(Fr,e!=null&&t!=null?ji(e,t):null),tS=(e,t)=>Ns(n=>!e||!t?vi:n.filtersByScope[wi(e,t)]??vi),sS=e=>Ns(t=>e?t.selectionByDirectory[ps(e)]??Ja:Ja),ed=(e,t,n)=>{Ns.getState().selectPullRequest(e,t,n);const r=ps(e);pt(async()=>{const{useUIStore:o}=await import("./index-CKKWVoND.js").then(i=>i.cN);return{useUIStore:o}},__vite__mapDeps([2,3,4,5,6,7,8,9])).then(({useUIStore:o})=>{o.getState().openContextSurface(r,"pull-requests")}).catch(()=>{}),pt(async()=>{const{useGitHubScopeStore:o}=await import("./useAppFontEffects-CV5UyTRw.js").then(i=>i.e_);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(()=>{})},Ab=({directory:e,number:t,color:n})=>{const r=Vl(e);return!e||!r?s.jsxs("span",{className:"ml-auto flex-shrink-0 typography-micro font-medium leading-none",style:n?{color:n}:void 0,children:["#",t]}):s.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),ed(e,r,t)},className:"ml-auto flex-shrink-0 rounded typography-micro 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 Nb({group:e,groupKey:t,isCollapsed:n,onToggleCollapsedGroup:r,normalizedSessionSearchQuery:o,alwaysShowActions:i,groupHeaderRightPadding:a,dragHandleProps:c,groupPrColor:d,groupPrSummary:u,groupActivityIndicator:f,showBranchSubtitle:m,statusLine:g,projectId:b,activeProjectId:h,setActiveProjectIdOnly:p,setActiveMainTab:y,mobileVariant:x,setSessionSwitcherOpen:C,openNewSessionDraft:j}){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:A=>{(A.key==="Enter"||A.key===" ")&&(A.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]",a),...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",children:!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(R,{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(R,{name:"arrow-right-s",className:"size-4"}):s.jsx(R,{name:"arrow-down-s",className:"size-4"})})]}),s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal text-muted-foreground",children:xi(e.label,o)}),f,u?s.jsx(Ab,{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:xi(e.label,o)}),f]})}),m&&g?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 leading-tight",children:[s.jsx(R,{name:"git-branch",className:"size-4 flex-shrink-0 text-muted-foreground"}),s.jsx("span",{className:"min-w-0 truncate typography-micro font-medium text-subtle-foreground",children:g.label})]}):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(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:A=>{A.stopPropagation(),b&&b!==h&&p(b),y("chat"),x&&C(!1),j({selectedProjectId:b,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(R,{name:"add",className:"h-4 w-4"})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New draft session"})})]})}):null]})}const Nr=(e,t)=>t?e.sessions.some(n=>us(n,t)):!1,Ib=(e,t,n)=>e.sessions.some(r=>zc(r,r,t,n,e.directory,e.directory)),Eb=(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)},el=(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)},Db=(e,t,n)=>{const r=o=>{const i=cr("project",o.session);return t.has(i)!==n.has(i)?!0:o.children.some(r)};return e.sessions.some(r)},Rb=(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&&Ib(t.group,e.pinnedSessionIds,t.pinnedSessionIds)||e.expandedParents!==t.expandedParents&&Db(t.group,e.expandedParents,t.expandedParents)||e.sessionOrderIndex!==t.sessionOrderIndex&&Eb(t.group,e.sessionOrderIndex,t.sessionOrderIndex)||e.editingId!==t.editingId&&(Nr(e.group,e.editingId)||Nr(t.group,t.editingId))||e.editTitle!==t.editTitle&&(Nr(e.group,e.editingId)||Nr(t.group,t.editingId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=Gr(e.group.sessions,e.openSidebarMenuKey,"project"),r=Gr(t.group.sessions,t.openSidebarMenuKey,"project");if(n||r)return!1}return e.activeActivitySessionIds!==t.activeActivitySessionIds&&el(t.group,e.activeActivitySessionIds,t.activeActivitySessionIds)||e.unreadActivitySessionIds!==t.unreadActivitySessionIds&&el(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};function Pb({group:e,sourceGroupNodes:t,hasSessionSearchQuery:n,normalizedSessionSearchQuery:r,compareSessionNodes:o,activeActivitySessionIds:i,unreadActivitySessionIds:a,inputActivitySessionIds:c}){const d=bt(A=>A.foldersMap),u=e.folderScopeKey??Re(e.directory??null),f=l.useMemo(()=>e.folderScopes&&e.folderScopes.length>0?e.folderScopes:u?[{scopeKey:u,directory:e.directory??null}]:[],[u,e.directory,e.folderScopes]),m=l.useMemo(()=>f.flatMap(({scopeKey:A,directory:w})=>(d[A]??[]).map(S=>({folder:S,scopeKey:A,scopeDirectory:w}))),[f,d]),g=l.useMemo(()=>{const A=new Map,w=S=>{S.forEach(v=>{A.set(v.session.id,v),v.children.length>0&&w(v.children)})};return w(t),A},[t]),b=l.useMemo(()=>m.map(({folder:A,scopeKey:w,scopeDirectory:S})=>{const v=eb(A.sessionIds,g).sort(o);return{folder:A,scopeKey:w,scopeDirectory:S,nodes:v}}),[m,g,o]),h=l.useMemo(()=>{const A=new Map(b.map(k=>[k.folder.id,k])),w=new Map;for(const{folder:k}of b){if(!k.parentId)continue;const E=w.get(k.parentId);E?E.push(k.id):w.set(k.parentId,[k.id])}const S=new Map,v=k=>{const E=S.get(k);if(E!==void 0)return E;const P=A.get(k);if(!P)return S.set(k,!1),!1;const z=w.get(k)??[];if(!n||P.folder.name.toLowerCase().includes(r)||P.nodes.length>0)return S.set(k,!0),!0;const q=z.some(H=>v(H));return S.set(k,q),q};return b.filter(({folder:k})=>v(k.id))},[b,n,r]),p=l.useMemo(()=>new Set(h.flatMap(A=>A.folder.sessionIds)),[h]),y=l.useMemo(()=>t.filter(A=>!p.has(A.session.id)),[t,p]),x=l.useMemo(()=>h.filter(({folder:A})=>!A.parentId),[h]),C=l.useMemo(()=>{const A=new Map;return h.forEach(w=>{if(!w.folder.parentId)return;const S=A.get(w.folder.parentId)??[];S.push(w),A.set(w.folder.parentId,S)}),A},[h]),j=l.useMemo(()=>{const A=new Map(h.map(v=>[v.folder.id,v])),w=new Map,S=(v,k)=>{const E=w.get(v);if(E!==void 0)return E;if(k.has(v))return null;k.add(v);const P=A.get(v);let z=P?Gc(P.nodes,i,a,c):null;for(const K of C.get(v)??[])if(z=zi(z,S(K.folder.id,k)),z==="input")break;return w.set(v,z),z};return h.forEach(({folder:v})=>S(v.id,new Set)),w},[i,h,C,c,a]);return{folderScopeKey:u,folderScopes:f,allFoldersForGroup:h,rootFolders:x,ungroupedSessions:y,folderActivityStateById:j}}function Tb(e){const{group:t,groupKey:n,projectId:r,hideGroupLabel:o,hasSessionSearchQuery:i,normalizedSessionSearchQuery:a,groupSearchDataByGroup:c,visibleSessionCount:d,collapsedGroups:u,hideDirectoryControls:f,collapsedFolderIds:m,toggleFolderCollapse:g,renameFolder:b,deleteFolder:h,showDeletionDialog:p,setDeleteFolderConfirm:y,renderSessionNode:x,showMoreGroupSessions:C,resetGroupSessionLimit:j,mobileVariant:A,alwaysShowActions:w,activeProjectId:S,setActiveProjectIdOnly:v,setActiveMainTab:k,setSessionSwitcherOpen:E,openNewSessionDraft:P,addSessionToFolder:z,createFolderAndStartRename:K,renamingFolderId:q,renameFolderDraft:H,setRenameFolderDraft:F,setRenamingFolderId:D,pinnedSessionIds:T,sessionOrderIndex:I,editingId:M,openSidebarMenuKey:G,activeActivitySessionIds:W,unreadActivitySessionIds:L,onToggleCollapsedGroup:ae,dragHandleProps:J,compactBodyPadding:le=!1}=e,Ie=l.useCallback((Ee,Ye)=>{const Ne=I.get(Ee.session.id),De=I.get(Ye.session.id);if(Ne!==void 0||De!==void 0){if(Ne===void 0)return 1;if(De===void 0)return-1;if(Ne!==De)return Ne-De}return jf(Ee.session,Ye.session,T,Yl)},[T,I]),Y=i?c.get(t):null,B=i?!1:u.has(n),$=!t.isMain&&!o?Re(t.directory??null):null,X=!t.isMain&&!o&&t.branch?.trim()||null,ee=l.useMemo(()=>$&&X?dr($,X):null,[$,X]),ie=$c(ee);Kc($,X);const Ce=ie?`var(--pr-${ie.visualState})`:void 0,pe=l.useContext(so)!==null,je=f?10:5,be=Math.max(je,d??je),ze=i?Y?.groupMatches===!0:!1,me=i,Pe=l.useMemo(()=>[...me?Y?.filteredNodes??[]:t.sessions].sort(Ie),[Ie,t.sessions,Y?.filteredNodes,me]),V=kf(),fe=l.useMemo(()=>new Set(V.map(Ee=>Ee.sessionId)),[V]),{folderScopeKey:xe,folderScopes:te,allFoldersForGroup:re,rootFolders:Be,ungroupedSessions:ke,folderActivityStateById:Q}=Pb({group:t,sourceGroupNodes:Pe,hasSessionSearchQuery:i,normalizedSessionSearchQuery:a,compareSessionNodes:Ie,activeActivitySessionIds:W,unreadActivitySessionIds:L,inputActivitySessionIds:fe}),ve="project",he=l.useMemo(()=>{const Ee=new Set;return Wa(Pe,M,Ee),re.forEach(({nodes:Ye})=>{Wa(Ye,M,Ee)}),Ee},[Pe,re,M]),Se=l.useMemo(()=>{if(!G)return null;const Ee=Gr(Pe,G,ve);if(Ee)return Ee;for(const{nodes:Ye}of re){const Ne=Gr(Ye,G,ve);if(Ne)return Ne}return null},[G,Pe,re]),qe=l.useCallback(Ee=>{const Ye=new WeakMap,Ne=De=>{Ye.set(De,mi(De));for(const He of De.children)Ne(He)};return Ee.forEach(Ne),Ye},[]),Ue=l.useMemo(()=>qe(Pe),[qe,Pe]),U=l.useMemo(()=>{const Ee=new WeakMap;return re.forEach(({nodes:Ye})=>{Ye.forEach(Ne=>Ee.set(Ne,mi(Ne)))}),Ee},[re]),ge=l.useCallback(Ee=>Ue.get(Ee)??U.get(Ee)??"",[Ue,U]),ne=l.useCallback(Ee=>({subtreeContainsEditing:he,menuOpenSessionId:Se,nodeStructureKey:ge(Ee)}),[he,Se,ge]),_e=ke.length,rt=pe||i?ke:ke.slice(0,be),mt=_e-rt.length,Ze=!pe&&!i&&_e>je&&mt===0;if(i&&!ze&&Be.length===0&&ke.length===0)return null;const Jt=!t.isMain&&!!t.branch,gt=t.branch&&Jh(t.branch,t.label)?{label:t.branch,color:null}:null,Et=B?Gc(Pe,W,L,fe):null,rs=Et?s.jsx(Bc,{state:Et,activeLabel:"Session active",unreadLabel:"Unread updates",inputLabel:"Needs input"}):null,Qe=(Ee,Ye)=>{const{folder:Ne,scopeKey:De,scopeDirectory:He,nodes:ft}=Ee,os=i?!1:m.has(Ne.id);return s.jsx(Jg,{folderId:Ne.id,children:(Ot,Bt)=>s.jsx(Yg,{folder:Ne,displayName:Ye,sessions:ft,isCollapsed:os,collapsedActivityState:os?Q.get(Ne.id)??null:null,onToggle:()=>g(Ne.id),onRename:Ve=>{b(De,Ne.id,Ve)},onDelete:()=>{if(!p){h(De,Ne.id);return}const Ve=re.filter(({folder:Rs})=>Rs.parentId===Ne.id).length,is=ft.length;y({scopeKey:De,folderId:Ne.id,folderName:Ne.name,subFolderCount:Ve,sessionCount:is})},renderSessionNode:x,getRenderExtras:ge?Ve=>({subtreeContainsEditing:he,menuOpenSessionId:Se,nodeStructureKey:ge(Ve),childRenderExtrasFor:ne}):void 0,groupDirectory:He??t.directory,projectId:r,mobileVariant:A,alwaysShowActions:w,isRenaming:q===Ne.id,renameDraft:q===Ne.id?H:void 0,onRenameDraftChange:Ve=>F(Ve),onRenameSave:()=>{const Ve=H.trim();Ve&&b(De,Ne.id,Ve),D(null),F("")},onRenameCancel:()=>{D(null),F("")},droppableRef:Ot,isDropTarget:Bt,depth:0,onNewSession:()=>{r&&r!==S&&v(r),k("chat"),A&&E(!1),P({selectedProjectId:r,directoryOverride:He??t.directory,targetFolderId:Ne.id})},hideActions:!1})},Ne.id)},Ft=()=>{const Ee=new Map;for(const De of re){const He=De.folder.parentId;if(!He)continue;const ft=Ee.get(He);ft?ft.push(De):Ee.set(He,[De])}const Ye=[],Ne=(De,He)=>{const ft=He?`${He} / ${De.folder.name}`:De.folder.name;Ye.push(Qe(De,ft)),!(!i&&m.has(De.folder.id))&&(Ee.get(De.folder.id)??[]).forEach(Ot=>Ne(Ot,ft))};return Be.forEach(De=>Ne(De,"")),Ye},Lt=w?"pr-7":"pr-2 group-hover/gh:pr-7 group-focus-within/gh:pr-7",kt=s.jsxs(Xg,{scopeKey:te[0]?.scopeKey??xe,hasFolders:re.length>0,onSessionDroppedOnFolder:(Ee,Ye)=>{const Ne=re.find(({folder:He})=>He.id===Ye);if(!Ne)return;const De=bt.getState();for(const{scopeKey:He}of te)He!==Ne.scopeKey&&De.getSessionFolderId(He,Ee)&&De.removeSessionFromFolder(He,Ee);z(Ne.scopeKey,Ye,Ee)},children:[Ft(),rt.map(Ee=>s.jsx(l.Fragment,{children:x(Ee,0,t.directory,r,!1,void 0,"project",{subtreeContainsEditing:he,menuOpenSessionId:Se,nodeStructureKey:ge(Ee),childRenderExtrasFor:ne})},Ee.session.id)),_e===0&&re.length===0&&!pe?s.jsx(qt,{icon:"chat-new",onClick:()=>{P({selectedProjectId:r,directoryOverride:t.directory})},children:"New session"}):null,mt>0?s.jsx(qt,{icon:"arrow-down-s",onClick:()=>C(n,rt.length),children:mt===1?"Show 1 more session":`Show ${mt} more sessions`}):null,Ze?s.jsx(qt,{icon:"arrow-up-s",onClick:()=>j(n),children:"Show fewer sessions"}):null]});return o?s.jsx("div",{className:"oc-group",children:s.jsx("div",{className:"oc-group-body",children:kt})}):s.jsxs("div",{className:"oc-group",children:[s.jsx(Nb,{group:t,groupKey:n,isCollapsed:B,onToggleCollapsedGroup:ae,normalizedSessionSearchQuery:a,alwaysShowActions:w,groupHeaderRightPadding:Lt,dragHandleProps:J,groupPrColor:Ce,groupPrSummary:ie,groupActivityIndicator:rs,showBranchSubtitle:Jt,statusLine:gt,projectId:r,activeProjectId:S,setActiveProjectIdOnly:v,setActiveMainTab:k,mobileVariant:A,setSessionSwitcherOpen:E,openNewSessionDraft:P}),B?null:s.jsx("div",{className:"oc-group-body",children:kt})]})}const Mb=l.memo(Tb,Rb);function Fb(e){const{hideDirectoryControls:t,handleOpenDirectoryDialog:n,onOpenArchive:r,onOpenSettings:o,onOpenInstances:i,instanceLabel:a,onOpenUpdate:c,headerActionIconClass:d,headerActionButtonClass:u,isSessionSearchOpen:f,setIsSessionSearchOpen:m,sessionSearchInputRef:g,sessionSearchQuery:b,setSessionSearchQuery:h,hasSessionSearchQuery:p,searchMatchCount:y,selectionModeEnabled:x,onToggleSelectionMode:C,mobileVariant:j=!1,onClose:A}=e;if(t)return null;const w=_(u,"text-muted-foreground hover:text-foreground",!j&&"hover:bg-transparent"),S=o?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:w,"aria-label":"Settings",children:s.jsx(R,{name:"settings-3",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}):null,v=c?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:c,className:w,"aria-label":"Update",children:s.jsx(R,{name:"download",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Update"})})]}):null;return s.jsx("div",{className:_("select-none flex-shrink-0",j?"px-2":"px-2 py-1"),children:s.jsxs("div",{className:_("flex flex-col",j?"gap-0":"h-auto min-h-8 gap-1"),children:[s.jsxs("div",{className:_("flex items-center justify-between",j?"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",j?"gap-1 overflow-x-auto":"gap-1.5"),"data-no-drawer-swipe":j?"true":void 0,children:[j?s.jsx("h2",{className:"truncate pl-2 typography-ui-header font-semibold text-foreground",children:"Sessions"}):s.jsxs(s.Fragment,{children:[S,v]}),!j&&i?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:i,className:w,"aria-label":a?`Servers: ${a}`:"Servers",children:s.jsx(R,{name:"server",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:a||"Servers"})})]}):null,j?null:s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:w,"aria-label":"Add folder",children:s.jsx(R,{name:"folder-add",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Add folder"})})]}),j?null:s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:w,"aria-label":"Archive",children:s.jsx(R,{name:"archive",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Archive"})})]})]}),s.jsxs("div",{className:_("flex shrink-0 items-center",j?"gap-1":"gap-1.5"),children:[j?s.jsxs(s.Fragment,{children:[S,v]}):null,s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>m(k=>!k),className:w,"aria-label":"Search sessions","aria-expanded":f,children:s.jsx(R,{name:"search",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"Search sessions"})})]}),s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:C,className:_(w,x&&"bg-interactive-hover text-primary"),"aria-label":x?"Exit selection":"Select sessions","aria-pressed":x,children:s.jsx(R,{name:"checkbox-multiple",className:d})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:x?"Exit selection":"Select sessions"})})]}),j&&A?s.jsx("button",{type:"button",onClick:A,className:w,"aria-label":"Close sessions",children:s.jsx(R,{name:"close",className:d})}):null]})]}),f?s.jsxs("div",{className:_(j?"pb-2":"pb-1"),children:[s.jsx("div",{className:"mb-1 flex items-center justify-between px-0.5 typography-micro text-subtle-foreground",children:p?s.jsx("span",{children:y===1?`${y} match`:`${y} matches`}):s.jsx("span",{})}),s.jsxs("div",{className:"relative",children:[s.jsx(R,{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:g,value:b,onChange:k=>h(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(),p?h(""):m(!1))}}),b.length>0?s.jsx("button",{type:"button",onClick:()=>h(""),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(R,{name:"close",className:"h-3.5 w-3.5"})}):null]})]}):null]})})}const Po="0.75rem";function Lb(e){const t=ue(o=>o.toggleSidebar),n=ue(o=>o.shortcutOverrides),r=Fi(zr("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, ${Po})`}}),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, ${Po})))`}}),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(${Xh} - max(var(--oc-titlebar-left-inset, ${Po}), var(--oc-titlebar-overlay-width, 0px))))`},children:[s.jsx(R,{name:"chat-new",className:_(Pr,"text-current")}),s.jsx("span",{className:pc,children:"New session"})]}),e.showSidebarToggle?s.jsxs(Ke,{children:[s.jsx(We,{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(R,{name:"layout-left",className:"size-4"})})}),s.jsx(Ge,{children:s.jsx("p",{children:`Hide sessions (${r})`})})]}):null]})]})}function ro({...e}){return s.jsx(Ml,{...e})}function oo({...e}){return s.jsx(Fl,{...e})}function io({className:e,positionerClassName:t,children:n,style:r,...o}){return s.jsx(qo,{children:s.jsx(Vo,{className:_("app-region-no-drag z-50",t),children:s.jsx(Yo,{"data-slot":"dropdown-menu-content",style:{color:"var(--surface-elevated-foreground)",...r},className:_(Zo,e),...o,children:n})})})}function Ks({className:e,...t}){return s.jsx(Ll,{className:_(Ql,e),...t})}function td({className:e,...t}){return s.jsx(Ol,{className:_(Jl,e),...t})}const sd=500,Ob=({projectId:e,worktree:t,isSelected:n,hasActive:r,onSelect:o,onClose:i,mobileVariant:a=!1})=>{const[c,d]=l.useState(!1),u=l.useRef(null),f=t.branch||(t.detached?"Detached HEAD":t.name),m=l.useCallback(()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null)},[]);l.useEffect(()=>()=>m(),[m]);const g=l.useCallback(()=>{m(),u.current=window.setTimeout(()=>{u.current=null,d(!0)},sd)},[m]);return s.jsxs(ro,{open:c,onOpenChange:d,children:[s.jsxs(oo,{render:s.jsx("button",{type:"button",onClick:()=>{c||o()},onTouchStart:g,onTouchMove:m,onTouchEnd:m,onTouchCancel:m,style:{touchAction:"manipulation"},className:_(Vr(a,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(R,{name:"git-branch",className:_(Gs(a),"text-muted-foreground")}),t.branch?s.jsx(Yn,{value:f,showTitle:!1,className:"typography-ui-label font-normal"}):s.jsx("span",{className:kn(a),children:f})]}),s.jsx("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:r?s.jsx(Is,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null})]}),s.jsx(io,{className:"min-w-[160px]",children:s.jsxs(Ks,{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(R,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close worktree"})]})})]})},Vr=(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"),Bb=({project:e,label:t,isSelected:n,hasActive:r,hasWorktrees:o,worktreeError:i,isExpanded:a,canDrag:c,onSelect:d,onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:m=!1})=>{const{listeners:g,setNodeRef:b,transform:h,transition:p,isDragging:y}=Ri({id:e.id,disabled:!c}),[x,C]=l.useState(!1),j=l.useRef(null),A=l.useCallback(()=>{j.current!==null&&(window.clearTimeout(j.current),j.current=null)},[]);l.useEffect(()=>()=>A(),[A]);const w=l.useCallback(()=>{A(),j.current=window.setTimeout(()=>{j.current=null,C(!0)},sd)},[A]);return s.jsx("div",{ref:b,style:{transform:Pi.Translate.toString(h),transition:p},className:_(y&&"opacity-60"),children:s.jsxs(ro,{open:x,onOpenChange:C,children:[s.jsxs(oo,{render:s.jsx("button",{type:"button",onClick:()=>{x||d()},onTouchStart:w,onTouchMove:A,onTouchEnd:A,onTouchCancel:A,style:{touchAction:"manipulation"},className:Vr(m,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?g:{},children:s.jsx(Mi,{directory:e.normalizedPath,label:t,className:Gs(m)})}),s.jsx("span",{className:kn(m),children:t})]}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0 ml-1",children:[r?s.jsx(Is,{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(R,{name:"error-warning",className:"size-4 text-[var(--status-warning)]"})}):null,o?s.jsx(R,{name:a?"arrow-down-s":"arrow-right-s",className:"size-4 text-muted-foreground"}):null]})]}),s.jsxs(io,{className:"min-w-[160px]",children:[s.jsxs(Ks,{onClick:()=>u(e.id),children:[s.jsx(R,{name:"edit",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Edit folder"})]}),s.jsx(td,{}),s.jsxs(Ks,{onClick:()=>f(e.id),className:"text-destructive focus:text-destructive",children:[s.jsx(R,{name:"close",className:"mr-2 h-3.5 w-3.5"}),s.jsx("span",{children:"Close folder"})]})]})]})})},_b=({projects:e,selectedProjectId:t,selectedWorktreePath:n=null,worktreesByProject:r=new Map,worktreeErrorsByProject:o=new Map,onSelectProject:i,onSelectWorktree:a,onCloseWorktree:c,onOpenDirectoryDialog:d,onOpenProjectEditDialog:u,onRemoveProject:f,hasActiveSessionByProject:m,activeDirectoriesByProject:g,homeDirectory:b,className:h,mobileVariant:p=!1})=>{const y=t===null,x=ot(w=>w.reorderProjects),C=e.length>1,j=Jr(wn(Ul,{activationConstraint:{distance:8}}),wn(zl,{activationConstraint:{delay:200,tolerance:6}})),A=l.useCallback(w=>{const{active:S,over:v}=w;if(!v||S.id===v.id)return;const k=ot.getState().projects,E=k.findIndex(z=>z.id===S.id),P=k.findIndex(z=>z.id===v.id);E<0||P<0||x(E,P)},[x]);return s.jsxs("div",{className:_("select-none px-2 pt-1 pb-2 border-b border-border/40 space-y-0.5",h),children:[s.jsx("button",{type:"button",onClick:()=>i(null),className:Vr(p,y),"aria-pressed":y,children:s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5",children:[s.jsx(R,{name:"chat-history",className:Gs(p)}),s.jsx("span",{className:kn(p),children:"All sessions"})]})}),s.jsx(Xr,{sensors:j,collisionDetection:Di,onDragEnd:A,children:s.jsx(Bl,{items:e.map(w=>w.id),strategy:_l,children:e.map(w=>{const S=t===w.id,v=S&&!n,k=r.get(w.normalizedPath)??[],E=In(w,b),P=g?.get(w.id),z=Re(w.normalizedPath)?.toLowerCase()??"",K=z?P?.has(z)??!1:!1,q=(P?.size??0)>0,H=m?.(w.id)??!1,F=g?S?K:q:H;return s.jsxs(l.Fragment,{children:[s.jsx(Bb,{project:w,label:E,isSelected:v,hasActive:F,hasWorktrees:k.length>0,worktreeError:o.get(w.normalizedPath),isExpanded:S,canDrag:C,onSelect:()=>i(w.id),onOpenProjectEditDialog:u,onRemoveProject:f,mobileVariant:p}),S?k.map(D=>{const T=n===D.path,I=Re(D.path)?.toLowerCase()??"",M=I?P?.has(I)??!1:!1,G=g?M:!1;return s.jsx(Ob,{projectId:w.id,worktree:D,isSelected:T,hasActive:G,onSelect:()=>a?.(w.id,D.path),onClose:c,mobileVariant:p},D.path)}):null]},w.id)})})}),s.jsxs("button",{type:"button",onClick:d,className:Vr(p,!1),children:[s.jsx(R,{name:"add",className:Gs(p)}),s.jsx("span",{className:kn(p),children:"Add folder"})]})]})},To="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 zb({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(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:e,className:To,"aria-label":"Settings",children:s.jsx(R,{name:"settings-3",className:"size-4"})})}),s.jsx(Ge,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Settings"})})]}),s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,className:To,"aria-label":"Shortcuts",children:s.jsx(R,{name:"command",className:"size-4"})})}),s.jsx(Ge,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Shortcuts"})})]}),s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:To,"aria-label":"About PiChamber",children:s.jsx(R,{name:"information",className:"size-4"})})}),s.jsx(Ge,{side:"top",sideOffset:4,children:s.jsx("p",{children:"About PiChamber"})})]})]}):null,i?s.jsx(Ae,{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 tl="inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-[opacity,background-color,color] hover:bg-interactive-active hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",sl="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",nd=({projectLabel:e,projectPath:t=null,mobileVariant:n=!1})=>{const r=Gs(n),o=kn(n);return s.jsxs(s.Fragment,{children:[s.jsx("span",{className:_("inline-flex shrink-0 items-center justify-center",r),children:t?s.jsx(Mi,{directory:t,label:e,className:r}):s.jsx(R,{name:"folder",className:_(r,"text-subtle-foreground")})}),s.jsx("span",{className:_(o,"font-medium text-foreground"),children:e})]})},rd=({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(R,{name:e?"arrow-right-s":"arrow-down-s",className:Gs(t)})}),Ub=({id:e,disabled:t=!1,projectLabel:n,projectPath:r=null,projectDescription:o,isCollapsed:i,hideDirectoryControls:a,mobileVariant:c,alwaysShowActions:d,stickyHeader:u=!1,onToggle:f,onNewSession:m,onRenameStart:g,onClose:b,children:h,showCreateButtons:p=!0,hideHeader:y=!1,openSidebarMenuKey:x,setOpenSidebarMenuKey:C,statusIndicator:j=null,sessionCount:A=null,isEmpty:w=!1})=>{const{listeners:S,setNodeRef:v,transform:k,transition:E,isDragging:P}=Ri({id:e,disabled:t}),z=l.useRef(!1),K=`project:${e}`,q=x===K,[H,F]=l.useState(!1),D=u&&!i,T=!a&&!d,I=l.useCallback(le=>{le&&F(!1),C(le?K:null)},[K,C]),M=le=>s.jsxs(s.Fragment,{children:[p&&!a&&m&&s.jsxs(le,{onClick:m,children:[s.jsx(R,{name:"add",className:"mr-1.5 h-4 w-4"}),"New session"]}),s.jsxs(le,{onClick:g,children:[s.jsx(R,{name:"pencil-ai",className:"mr-1.5 h-4 w-4"}),"Edit folder"]}),s.jsxs(le,{onClick:b,className:"text-destructive focus:text-destructive",children:[s.jsx(R,{name:"close",className:"mr-1.5 h-4 w-4"}),"Close folder"]})]}),G=l.useCallback(le=>{le.stopPropagation()},[]),W=l.useCallback(le=>{le.stopPropagation()},[]),L=l.useCallback(le=>{le.stopPropagation()},[]),ae=l.useCallback(le=>{(le.button===2||le.button===0&&le.ctrlKey)&&(z.current=!0)},[]),J=l.useCallback(le=>{if(le.currentTarget.blur(),z.current){z.current=!1;return}f()},[f]);return s.jsxs("div",{ref:v,style:{transform:Pi.Translate.toString(k),transition:E},className:_("relative",P&&"opacity-60"),children:[y?null:s.jsxs(ro,{open:H,onOpenChange:F,children:[s.jsxs(oo,{render:s.jsx("div",{className:_("text-left group/project select-none",D&&"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":D?"true":void 0,onContextMenu:le=>{a||P||(le.preventDefault(),F(!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(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsxs("button",{type:"button","aria-expanded":!i,style:{touchAction:"manipulation"},onMouseDown:ae,onClick:J,...S,className:_(no,"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(nd,{id:e,projectLabel:n,projectPath:r,mobileVariant:c}),A?s.jsx("span",{className:"shrink-0 typography-micro text-subtle-foreground tabular-nums","aria-label":A===1?"1 session":`${A} sessions`,children:A}):null,j?s.jsx("span",{className:"ml-1 inline-flex flex-shrink-0 items-center",children:j}):null,s.jsx(rd,{isCollapsed:i,mobileVariant:c,className:_("transition-[padding]",w&&"invisible",T&&"group-hover/project:pl-14 group-focus-within/project:pl-14","pl-2")})]})}),d?null:s.jsx(Ge,{side:"right",sideOffset:8,children:o})]}),T?s.jsxs("div",{className:_("absolute top-1/2 z-10 flex -translate-y-1/2 items-center gap-0.5",w?"right-2":"right-7"),children:[p&&m?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:le=>{le.stopPropagation(),m()},className:_(tl,sl),"aria-label":"New session",children:s.jsx(R,{name:"add",className:"size-4"})})}),s.jsx(Ge,{side:"bottom",sideOffset:4,children:s.jsx("p",{children:"New session"})})]}):null,s.jsxs(Vt,{open:q,onOpenChange:I,children:[s.jsx(Yt,{asChild:!0,children:s.jsx("button",{type:"button",className:_(tl,q?"opacity-100 pointer-events-auto bg-interactive-active text-foreground":sl),"aria-label":"Folder menu",onPointerDown:W,onMouseDown:L,onClick:G,children:s.jsx(R,{name:"more-fill",className:"size-4"})})}),s.jsx(Qt,{align:"end",className:"min-w-[180px]",children:M(ut)})]})]}):null]}),D?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(io,{className:"min-w-[180px]",children:M(Ks)})]}),h]})},$b=({id:e,disabled:t=!1,children:n})=>{const{listeners:r,setNodeRef:o,setActivatorNodeRef:i,transform:a,transition:c,isDragging:d}=Ri({id:e,disabled:t}),u=l.useMemo(()=>({listeners:r,setActivatorNodeRef:i}),[r,i]);return s.jsx("div",{ref:o,style:{transform:Pi.Transform.toString(a),transition:c},className:_("space-y-0.5 rounded-md",d&&"opacity-50"),children:typeof n=="function"?n(u):n})};l.memo($b);const Kb=e=>e.session.time?.updated||e.session.time?.created||0,Wb=(e,t)=>{const n={pinned:[],active:[],working:[],snoozed:[]},r=new Map,o=new Set;for(const a of e){const c=a.node.session.id,d=t.entries[c],u={entry:d,pinned:a.isPinned,working:t.working.has(c),needsInput:t.needsInput.has(c),updatedAt:Kb(a.node),now:t.now,workingShelf:t.workingShelf},f=Cf(u);r.set(c,f),f!=="snoozed"&&Af(d,t.now)&&o.add(c);const m=f==="snoozed"?-(d?.snoozedUntil??0):Nf(u);n[f].push({item:a,key:m})}const i=a=>n[a].sort((c,d)=>d.key-c.key).map(({item:c})=>c);return{pinned:i("pinned"),active:i("active"),working:i("working"),snoozed:i("snoozed"),sectionById:r,wokeIds:o}},Gb=(e,t)=>{const n=(r,o)=>r.length===o.length&&r.every((i,a)=>i===o[a]);if(e.wokeIds.size!==t.wokeIds.size)return!1;for(const r of e.wokeIds)if(!t.wokeIds.has(r))return!1;return n(e.pinned,t.pinned)&&n(e.active,t.active)&&n(e.working,t.working)&&n(e.snoozed,t.snoozed)},Hb=6e4,qb=1500,Vb=(e,t)=>{const[n,r]=l.useState(()=>Date.now());return l.useEffect(()=>{if(!e||typeof document>"u")return;let o=null;const i=()=>{r(Date.now()),o===null&&(o=window.setInterval(()=>r(Date.now()),Hb))},a=()=>{o!==null&&window.clearInterval(o),o=null},c=()=>document.visibilityState==="visible"?i():a();return c(),document.addEventListener("visibilitychange",c),()=>{a(),document.removeEventListener("visibilitychange",c)}},[e]),l.useEffect(()=>{if(!e||t===null)return;const o=Math.min(Math.max(0,t-Date.now())+50,2**31-1),i=window.setTimeout(()=>r(Date.now()),o);return()=>window.clearTimeout(i)},[e,t]),n},Yb=(e,t)=>{const n=ir(o=>o.load);l.useEffect(()=>{if(!e)return;n();const o=()=>{document.visibilityState==="visible"&&n()};document.addEventListener("visibilitychange",o);const i=Nn(()=>{n()});return()=>{document.removeEventListener("visibilitychange",o),i()}},[e,n]);const r=l.useRef(t);l.useEffect(()=>{const o=r.current;if(r.current=t,!e)return;let i=!1;for(const c of t)if(!o.has(c)){i=!0;break}if(!i)return;const a=window.setTimeout(()=>{n()},qb);return()=>window.clearTimeout(a)},[e,t,n])},Qb=(e,{enabled:t,workingShelf:n})=>{const r=ir(g=>t?g.entries:Jb),{working:o,needsInput:i}=If(t),a=l.useMemo(()=>Ef(r,Date.now()),[r]),c=Vb(t,a);Yb(t,o);const d=l.useRef(null),u=l.useMemo(()=>{if(!t)return null;const g=Wb(e,{entries:r,working:o,needsInput:i,now:c,workingShelf:n});return d.current&&Gb(d.current,g)&&d.current.sectionById.size===g.sectionById.size&&[...g.sectionById].every(([h,p])=>d.current.sectionById.get(h)===p)?d.current:g},[t,e,r,o,i,c,n]);d.current=u;const f=Me(g=>g.currentSessionId),m=!!(t&&f&&u?.wokeIds.has(f));return l.useEffect(()=>{!m||!f||ir.getState().update(f,{snoozedUntil:null}).catch(g=>console.warn("[session-shelf] could not clear a finished snooze",g))},[m,f]),u},Jb=Object.freeze({}),ki=(e,t,n,r)=>{ir.getState().update(e,t,n??void 0).catch(o=>{console.warn("[session-shelf] update failed",o),oe.error(r)})},nl={snoozed:"Snoozed",archived:"Archived"},Xb=e=>e==="snoozed"||e==="archived",rl=10,ol=20,od="oc.sidebar.shelves.expanded",Zb=()=>{try{const e=hn().getItem(od),t=e?JSON.parse(e):[];return Array.isArray(t)?new Set(t.filter(Xb)):new Set}catch{return new Set}},ex=()=>{const[e,t]=l.useState(Zb),n=l.useCallback(r=>{t(o=>{const i=new Set(o);i.has(r)?i.delete(r):i.add(r);try{hn().setItem(od,JSON.stringify([...i]))}catch{}return i})},[]);return{expanded:e,toggle:n}},il=({target:e,dragging:t,className:n,children:r})=>{const{setNodeRef:o,isOver:i}=Tl({id:`shelf-drop:${e}`,data:{type:"shelf",target:e}});return s.jsx("div",{ref:o,"data-shelf-drop":e,className:_("rounded-xl transition-colors",t&&"outline outline-1 -outline-offset-1 outline-transparent",t&&i&&"bg-interactive-hover outline-[var(--interactive-border)]",n),children:r})},tx=["snoozed","archived"],Ki=({shelfIds:e,shelves:t,renderItem:n,hasSessionSearchQuery:r,mobileVariant:o=!1,className:i})=>{const{expanded:a,toggle:c}=ex(),d=Me(h=>h.currentSessionId),[u,f]=l.useState(rl),m=h=>r||a.has(h),g=e.filter(h=>(t[h]?.length??0)>0);if(g.length===0)return null;const b=(h,p)=>{if(h!=="archived"||r||p.length<=u)return p;const y=p.slice(0,u),x=p.find(C=>C.node.session.id===d);return x&&!y.includes(x)?[...y,x]:y};return s.jsx("div",{className:i,children:g.map(h=>{const p=t[h]??[],y=m(h),x=y?b(h,p):[],C=h==="archived"&&y&&!r?p.length-Math.min(u,p.length):0;return s.jsxs("section",{"aria-label":nl[h],"data-session-shelf":h,children:[s.jsx(xn,{label:nl[h],count:p.length,expanded:y,onToggle:()=>{h==="archived"&&f(rl),c(h)}}),x.map(n),C>0?s.jsx(qt,{icon:"arrow-down-s",mobileVariant:o,onClick:()=>f(j=>j+ol),children:`Show ${Math.min(ol,C)} more`}):null]},h)})})},sx=({items:e,shelves:t,archived:n,renderSessionNode:r,hasSessionSearchQuery:o,mobileVariant:i,emptyState:a,searchEmptyState:c})=>{const[d,u]=l.useState(null),f=Jr(wn(Rl,{activationConstraint:{distance:8}})),m=l.useMemo(()=>({sectionById:t.sectionById,wokeIds:t.wokeIds}),[t.sectionById,t.wokeIds]),g=A=>s.jsx(l.Fragment,{children:r(A.node,0,A.node.session.directory??A.project.normalizedPath,A.project.id,!1,{projectLabel:A.projectLabel,showFolderLabel:!0,globalSession:A.globalSession},"project")},A.node.session.id),b=A=>{const w=A.active.data.current;if(w?.type!=="session"||!w.sessionId)return;const S=A.active.rect.current.initial?.width;u({sessionId:w.sessionId,title:w.sessionTitle??"Session",width:typeof S=="number"?S:null})},h=A=>{u(null);const w=A.active.data.current,S=A.over?.data.current;if(w?.type!=="session"||!w.sessionId||S?.type!=="shelf"||!S.target)return;const v=w.sessionId,k=w.sessionDirectory??null,E=t.sectionById.get(v);E&&nx(v,k,E,S.target)};if(e.length===0&&n.length===0)return s.jsx(s.Fragment,{children:o?c:a});const p=!!d,y=t.pinned.length>0||p,x=t.working.length>0,C=y||x||t.snoozed.length>0||n.length>0,j=s.jsxs("div",{className:"flex min-h-full flex-1 flex-col","data-sidebar-threads":"",children:[y?s.jsxs(il,{target:"pinned",dragging:p,children:[s.jsx(xn,{label:"Pinned",first:!0}),t.pinned.map(g),p&&t.pinned.length===0?s.jsx("div",{className:"px-3 py-2 typography-micro text-subtle-foreground",children:"Drop here to pin"}):null]}):null,x?s.jsxs("section",{"aria-label":"Working","data-session-shelf":"working",children:[s.jsx(xn,{label:"Working",first:!y}),t.working.map(g)]}):null,s.jsxs(il,{target:"active",dragging:p,children:[C?s.jsx(xn,{label:"Recent",first:!y&&!x}):null,t.active.map(g),t.active.length===0&&!o?s.jsx("div",{className:"px-3 py-1.5 typography-micro text-subtle-foreground",children:p?"Drop here to keep it in the list":t.snoozed.length>0?"Nothing recent. Snoozed sessions are below.":n.length>0?"Nothing recent. Archived sessions are below.":"Nothing recent."}):null]}),s.jsx(Ki,{shelfIds:tx,shelves:{snoozed:t.snoozed,archived:n},renderItem:g,hasSessionSearchQuery:o,mobileVariant:i,className:"mt-auto border-t border-border pt-1"})]});return s.jsx(so.Provider,{value:m,children:i?j:s.jsxs(Xr,{sensors:f,collisionDetection:Ou,onDragStart:b,onDragCancel:()=>u(null),onDragEnd:h,children:[j,s.jsx(Pl,{children:d?s.jsx("div",{style:{width:d.width?`${d.width}px`:"auto"},className:"pointer-events-none flex items-center rounded-xl border border-[var(--interactive-border)] bg-[var(--surface-elevated)] px-3 py-2",children:s.jsx("div",{className:"min-w-0 flex-1 truncate typography-ui-label text-foreground",children:d.title})}):null})]})})},nx=(e,t,n,r)=>{const o=rr.getState(),i=ur(o.ids,t,e),a=c=>{!t||i===c||o.toggle({directory:t,sessionId:e})};n==="snoozed"&&ki(e,{snoozedUntil:null},t,"Could not wake the session"),a(r==="pinned")},rx=l.memo(sx),ox=[],ix=["snoozed","archived"],al=(e,t)=>{let n=!1;const r=e.groups.map(o=>{const i=o.sessions.filter(a=>!t.has(a.session.id));return i.length===o.sessions.length?o:(n=!0,{...o,sessions:i})});return n?{...e,groups:r}:e},ll=e=>e.groups.reduce((t,n)=>t+n.sessions.length,0),cl="pt-0.5 pb-1",ax=({shelves:e=null,archived:t=ox,sections:n,homeSection:r,homeDirectory:o,collapsedProjects:i,toggleProject:a,hasSessionSearchQuery:c,activeProjectId:d,hideDirectoryControls:u,mobileVariant:f,alwaysShowActions:m,isInlineEditing:g,stickyFolderHeaders:b,renderGroupSessions:h,renderSessionNode:p,getOrderedGroups:y,renderProjectStatusIndicator:x,setActiveProjectIdOnly:C,setActiveMainTab:j,setSessionSwitcherOpen:A,openNewSessionDraft:w,openProjectEditDialog:S,removeProject:v,reorderProjects:k,openSidebarMenuKey:E,setOpenSidebarMenuKey:P,onOpenDirectoryDialog:z,emptyState:K,searchEmptyState:q})=>{const H=c?null:e,F=l.useMemo(()=>{if(!H)return null;const $=new Set;for(const X of[...H.pinned,...H.snoozed])$.add(X.node.session.id);return $},[H]),D=l.useMemo(()=>F?n.map($=>al($,F)):n,[n,F]),T=l.useMemo(()=>F&&r?al(r,F):r,[r,F]),I=l.useMemo(()=>e?{sectionById:e.sectionById,wokeIds:e.wokeIds}:null,[e]),M=$=>s.jsx(l.Fragment,{children:p?.($.node,0,$.node.session.directory??$.project.normalizedPath,$.project.id,!1,{projectLabel:$.projectLabel,showFolderLabel:!0,globalSession:$.globalSession},"project")},$.node.session.id),G=Jr(wn(Ul,{activationConstraint:{distance:8}}),wn(zl,{activationConstraint:{delay:200,tolerance:6}})),W=D.length>1&&!c&&!g,L=l.useCallback($=>{if(g||c)return;const{active:X,over:ee}=$;if(!ee||X.id===ee.id)return;const ie=ot.getState().projects,Ce=ie.findIndex(je=>je.id===X.id),pe=ie.findIndex(je=>je.id===ee.id);Ce<0||pe<0||Ce===pe||k(Ce,pe)},[g,c,k]),[ae,J]=l.useState(5);l.useEffect(()=>{J(5)},[c]);const le=l.useMemo(()=>T?T.groups.flatMap($=>$.sessions):[],[T]),Ie=c||H?le:le.slice(0,ae),Y=le.length-Ie.length,B=c?!1:i.has("__home__");return D.length===0&&!T&&!(H&&t.length>0)?c?q:K:s.jsx(so.Provider,{value:I,children:s.jsxs("div",{className:H?"flex min-h-full flex-1 flex-col gap-1":"space-y-1",children:[H&&H.pinned.length>0?s.jsx(lr.Provider,{value:"card",children:s.jsxs("section",{"aria-label":"Pinned","data-session-shelf":"pinned",children:[s.jsx(xn,{label:"Pinned",first:!0}),H.pinned.map(M)]})}):null,s.jsx(Xr,{sensors:G,collisionDetection:Di,onDragEnd:L,children:s.jsx(Bl,{items:D.map($=>$.project.id),strategy:_l,children:D.map($=>{const X=$.project,ee=X.id,ie=In(X,o),Ce=ti(X.normalizedPath,o),pe=c?!1:i.has(ee),je=pe?[]:y(ee,$.groups),be=pe?null:je.find(me=>me.isMain)??null,ze=pe?[]:be?je.filter(me=>me.id!==be.id):je;return s.jsx(Ub,{id:ee,disabled:!W,projectLabel:ie,projectPath:X.normalizedPath,projectDescription:Ce,isCollapsed:pe,hideDirectoryControls:u,mobileVariant:f,alwaysShowActions:m,stickyHeader:b,statusIndicator:pe?x?.(ee,$.groups):null,sessionCount:pe?ll($):null,isEmpty:!!H&&ll($)===0,onToggle:()=>a(ee),onNewSession:()=>{ee!==d&&C(ee),j("chat"),f&&A(!1),w({selectedProjectId:ee,directoryOverride:X.normalizedPath})},onRenameStart:()=>S(ee),onClose:()=>v(ee),openSidebarMenuKey:E,setOpenSidebarMenuKey:P,children:pe?null:s.jsxs("div",{className:cl,children:[be?h(be,`${ee}:${be.id}`,ee,!0,null):null,ze.map(me=>{const Pe=`${ee}:${me.id}`,V=je.length===1;return s.jsx(l.Fragment,{children:h(me,Pe,ee,V,null)},me.id)})]})},ee)})})}),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":!B,style:{touchAction:"manipulation"},onClick:()=>a("__home__"),className:`${no} 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(nd,{id:"__home__",projectLabel:"No folder",mobileVariant:f}),s.jsx(rd,{isCollapsed:B,mobileVariant:f})]})}),B?null:s.jsxs("div",{className:cl,children:[Ie.map($=>s.jsx(l.Fragment,{children:p?.($,0,$.session.directory??"~","__home__",!1,{globalSession:!0},"project")},$.session.id)),!c&&Y>0?s.jsx(qt,{icon:"arrow-down-s",mobileVariant:f,onClick:()=>J($=>$+7),children:Y===1?"Show 1 more session":`Show ${Y} more sessions`}):null,!c&&ae>5&&le.length>5?s.jsx(qt,{icon:"arrow-up-s",mobileVariant:f,onClick:()=>J(5),children:"Show fewer sessions"}):null]})]}):null,!u&&z?s.jsx(qt,{icon:"add",mobileVariant:f,onClick:z,children:"Add folder"}):null,H?s.jsx(lr.Provider,{value:"card",children:s.jsx(Ki,{shelfIds:ix,shelves:{snoozed:H.snoozed,archived:t},renderItem:M,hasSessionSearchQuery:c,mobileVariant:f,className:"mt-auto border-t border-border pt-1"})}):null]})})},lx=l.memo(ax),cx=[],dx=["archived"];function ux(e){Ht("ui.sidebar_projects_list.render");const t=e.viewMode??"workspace",n=t==="timeline",r=l.useRef(new Map),o=l.useRef(e.getOrderedGroups);o.current!==e.getOrderedGroups&&(o.current=e.getOrderedGroups,r.current.clear());const i=(w,S)=>{const v=r.current,k=v.get(w);if(k&&k.groups===S)return k.ordered;const E=e.getOrderedGroups(w,S);if(v.set(w,{groups:S,ordered:E}),v.size>256){const P=v.keys().next().value;P!==void 0&&v.delete(P)}return E},a=t==="threads",c=t==="folder",d=e.archivedShelfItems??cx,u=t==="workspace"&&d.length>0&&!e.hasSessionSearchQuery&&!e.showOnlyMainWorkspace,f=!!(e.isAllFoldersView||n||a||c),m=l.useMemo(()=>{if(!f)return[];const w=[],S=e.allFoldersOnlySection?[e.allFoldersOnlySection,...e.sectionsForRender]:e.sectionsForRender;for(const v of S){const k=In(v.project,e.homeDirectory);for(const E of v.groups)for(const P of E.sessions){const z=e.pinnedSessionIds?ur(e.pinnedSessionIds,P.session.directory??v.project.normalizedPath,P.session.id):!1,K=P.session.time?.updated||P.session.time?.created||0;w.push({node:P,project:v.project,projectLabel:k,isPinned:z,timestamp:K,globalSession:v===e.allFoldersOnlySection})}}return w.sort((v,k)=>v.isPinned!==k.isPinned?v.isPinned?-1:1:k.timestamp-v.timestamp),w},[e.allFoldersOnlySection,f,e.sectionsForRender,e.homeDirectory,e.pinnedSessionIds]),g=Qb(m,{enabled:a||c,workingShelf:a}),[b,h]=l.useState(30);l.useEffect(()=>{h(30)},[e.hasSessionSearchQuery]);const p=l.useMemo(()=>m.slice(0,b),[m,b]),y=l.useMemo(()=>e.timelineBoundaries??pi(Date.now(),1),[e.timelineBoundaries]),x=l.useMemo(()=>n?lg(p,{getTimestamp:w=>w.timestamp,isPinned:w=>w.isPinned,boundaries:y}):[],[n,p,y]);if(e.sharedSessionsOnly)return s.jsx(zs,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.hasSharedSessions?null:e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState]})});const C=(e.isAllFoldersView||n||a||c)&&!!e.allFoldersOnlySection,j=d.length>0&&!e.hasSessionSearchQuery&&!e.showOnlyMainWorkspace;if(e.projectSections.length===0&&!C&&!j)return s.jsx(zs,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:s.jsxs("div",{className:"space-y-1 px-2",children:[e.topContent,e.emptyState]})});if(e.sectionsForRender.length===0&&!C&&!j)return s.jsx(zs,{useScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"pt-2 pb-1",children:s.jsx("div",{className:"space-y-1 px-2",children:e.searchEmptyState})});const A=()=>{const w=m.length-p.length;return s.jsxs(s.Fragment,{children:[w>0?s.jsx(qt,{icon:"arrow-down-s",onClick:()=>h(S=>S+30),children:w===1?"Show 1 more session":`Show ${w} more sessions`}):null,b>30&&m.length>30?s.jsx(qt,{icon:"arrow-up-s",onClick:()=>h(30),children:"Show fewer sessions"}):null]})};return s.jsx("div",{className:"relative flex min-h-0 flex-1",children:s.jsx(zs,{useScrollShadow:!0,hideTopScrollShadow:!0,scrollShadowSize:e.mobileVariant?12:20,outerClassName:"flex-1 min-h-0",className:"oc-sidebar-scroller pt-2 pb-1 [overflow-anchor:none]",children:s.jsxs("div",{className:_((a||c&&g&&!e.hasSessionSearchQuery||u)&&!e.showOnlyMainWorkspace?"flex min-h-full flex-col gap-1 px-2":"space-y-1 px-2"),children:[e.topContent,e.showOnlyMainWorkspace?s.jsx("div",{className:"space-y-[0.6rem]",children:(()=>{const w=e.sectionsForRender.find(k=>k.project.id===e.activeProjectId)??e.sectionsForRender[0];if(!w)return e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState;const S=w.groups.find(k=>k.isMain&&k.sessions.length>0)??w.groups.find(k=>k.sessions.length>0)??w.groups.find(k=>k.isMain)??w.groups[0];if(!S)return s.jsx(qt,{icon:"chat-new",onClick:()=>e.openNewSessionDraft({selectedProjectId:w.project.id,directoryOverride:w.project.normalizedPath}),children:"New session"});const v=`${w.project.id}:${S.id}`;return s.jsx(l.Fragment,{children:e.renderGroupSessions(S,v,w.project.id,!0,null,!0)},v)})()}):a&&g&&e.renderSessionNode?s.jsx(rx,{items:m,shelves:g,archived:d,renderSessionNode:e.renderSessionNode,hasSessionSearchQuery:e.hasSessionSearchQuery,mobileVariant:e.mobileVariant,emptyState:e.emptyState,searchEmptyState:e.searchEmptyState}):t==="folder"?s.jsx(lr.Provider,{value:"tree",children:s.jsx(lx,{shelves:g,archived:d,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,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:m.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[x.map((w,S)=>{const v=og[w.id];return s.jsxs("section",{"aria-label":v,"data-timeline-bucket":w.id,children:[s.jsx(xn,{label:v,first:S===0}),w.items.map(({node:k,project:E,projectLabel:P,globalSession:z})=>{const K=k.session.directory??E.normalizedPath;return s.jsx(l.Fragment,{children:e.renderSessionNode(k,0,K,E.id,!1,{projectLabel:P,showFolderLabel:!0,globalSession:z},"project")},k.session.id)})]},w.id)}),A()]})}):e.isAllFoldersView&&e.renderSessionNode?s.jsx("div",{children:m.length===0?e.hasSessionSearchQuery?e.searchEmptyState:e.emptyState:s.jsxs(s.Fragment,{children:[p.map(({node:w,project:S,projectLabel:v,globalSession:k})=>{const E=w.session.directory??S.normalizedPath;return s.jsx(l.Fragment,{children:e.renderSessionNode(w,0,E,S.id,!1,{projectLabel:v,showFolderLabel:!0,globalSession:k},"project")},w.session.id)}),A()]})}):s.jsx("div",{children:e.sectionsForRender.map(w=>{const S=w.project.id,v=i(S,w.groups),k=v.find(P=>P.isMain)??null,E=k?v.filter(P=>P.id!==k.id):v;return s.jsxs("div",{children:[k?e.renderGroupSessions(k,`${S}:${k.id}`,S,!0,null):null,E.map(P=>{const z=`${S}:${P.id}`,K=v.length===1;return s.jsx(l.Fragment,{children:e.renderGroupSessions(P,z,S,K,null)},P.id)})]},S)})}),u&&e.renderSessionNode?s.jsx(Ki,{shelfIds:dx,shelves:{archived:d},renderItem:w=>s.jsx(l.Fragment,{children:e.renderSessionNode(w.node,0,w.node.session.directory??w.project.normalizedPath,w.project.id,!0,{projectLabel:w.projectLabel,showFolderLabel:!!e.isAllFoldersView,globalSession:w.globalSession},"project")},w.node.session.id),hasSessionSearchQuery:!1,mobileVariant:e.mobileVariant,className:"mt-auto border-t border-border pt-1"}):null]})})})}const fx=l.memo(ux);let Ci=!1;const Ai=new Set;let dl=!1;function hx(){for(const e of Ai)e()}function Wi(e){Ci!==e&&(Ci=e,hx())}function px(e){e.key==="Shift"&&Wi(!0)}function mx(e){e.key==="Shift"&&Wi(!1)}function gx(){Wi(!1)}function bx(){dl||typeof window>"u"||(dl=!0,window.addEventListener("keydown",px),window.addEventListener("keyup",mx),window.addEventListener("blur",gx))}function xx(e){return bx(),Ai.add(e),()=>{Ai.delete(e)}}function yx(){return Ci}function wx(){return!1}function vx(){return Te.useSyncExternalStore(xx,yx,wx)}const Sx=l.memo(function({archiveLabel:t,deleteLabel:n,buttonSizeClass:r,iconSizeClass:o,onPointerDown:i,onMouseDown:a,onArchive:c,onDelete:d}){const u=vx(),f=u?n:t,m=g=>{if(u||g.shiftKey){d(g);return}c(g)};return s.jsxs(Ke,{children:[s.jsx(We,{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:a,onClick:m,onKeyDown:g=>g.stopPropagation(),children:s.jsx(R,{name:u?"delete-bin":"archive",className:o})})}),s.jsx(Ge,{side:"left",sideOffset:8,children:f})]})}),jx=l.memo(function({open:t,onOpenChange:n,descendantCount:r,exportIncludeSubtasks:o,setExportIncludeSubtasks:i,onExport:a}){return s.jsx(ss,{open:t,onOpenChange:n,children:s.jsxs(ns,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Hs,{children:[s.jsx(gs,{children:"Export Markdown"}),s.jsx(Ds,{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(An,{children:[s.jsx(Ae,{type:"button",onClick:()=>n(!1),variant:"outline",size:"sm",children:"Cancel"}),s.jsx(Ae,{type:"button",onClick:()=>{n(!1),a(o)},size:"sm",children:"Export"})]})]})})});function kx(e,t){const{session:n,sessionTitle:r,sessionDirectory:o,isPinnedSession:i,archivedBucket:a,isElectron:c,pendingRenameRef:d,handleCopySessionId:u,togglePinnedSession:f,handleExportSession:m,handleOpenMiniChatWindow:g,handleDeleteSession:b,handleRestoreSession:h,shelfActions:p}=e,{Item:y,Separator:x,Sub:C,SubTrigger:j,SubContent:A}=t;return s.jsxs(s.Fragment,{children:[s.jsxs(y,{onClick:()=>{d.current={id:n.id,title:r}},className:"[&>svg]:mr-1",children:[s.jsx(R,{name:"pencil-ai",className:"mr-1 h-4 w-4"}),"Rename"]}),s.jsxs(y,{onClick:()=>u(n.id),className:"[&>svg]:mr-1",children:[s.jsx(R,{name:"file-copy",className:"mr-1 h-4 w-4"}),"Copy session ID"]}),s.jsxs(y,{onClick:()=>o&&f({directory:o,sessionId:n.id}),className:"[&>svg]:mr-1",children:[i?s.jsx(R,{name:"unpin",className:"mr-1 h-4 w-4"}):s.jsx(R,{name:"pushpin",className:"mr-1 h-4 w-4"}),i?"Unpin session":"Pin session"]}),p&&!a?s.jsx(s.Fragment,{children:p.section==="snoozed"?s.jsxs(y,{onClick:p.onWake,className:"[&>svg]:mr-1",children:[s.jsx(R,{name:"alarm",className:"mr-1 h-4 w-4"}),"Wake session"]}):s.jsxs(C,{children:[s.jsxs(j,{className:"[&>svg:first-child]:mr-1",children:[s.jsx(R,{name:"alarm",className:"mr-1 h-4 w-4"}),"Snooze"]}),s.jsx(A,{className:"min-w-[200px]",children:Df(new Date).map(w=>s.jsxs(y,{onClick:()=>p.onSnooze(w.snoozedUntil),children:[s.jsx("span",{className:"flex-1",children:w.label}),s.jsx("span",{className:"ml-4 typography-micro text-muted-foreground tabular-nums",children:w.whenLabel})]},w.id))})]})}):null,s.jsxs(y,{onClick:()=>{m()},className:"[&>svg]:mr-1",children:[s.jsx(R,{name:"download",className:"mr-1 h-4 w-4"}),"Export Markdown"]}),c?s.jsxs(y,{disabled:!o,onClick:g,className:"[&>svg]:mr-1",children:[s.jsx(R,{name:"window",className:"mr-1 h-4 w-4"}),s.jsx("span",{className:"truncate",children:"Open in Mini Chat window"})]}):null,s.jsx(x,{}),a?null:s.jsxs(y,{className:"[&>svg]:mr-1",onClick:()=>b(n,{archivedBucket:a}),children:[s.jsx(R,{name:"inbox-archive",className:"mr-1 h-4 w-4"}),"Archive"]}),a?s.jsxs(y,{className:"[&>svg]:mr-1",onClick:()=>h(n),children:[s.jsx(R,{name:"inbox-unarchive",className:"mr-1 h-4 w-4"}),"Unarchive"]}):null,s.jsxs(y,{className:"text-destructive focus:text-destructive [&>svg]:mr-1",onClick:()=>b(n,{archivedBucket:a,hardDelete:!0}),children:[s.jsx(R,{name:"delete-bin",className:"mr-1 h-4 w-4"}),"Delete"]})]})}function Cx(e){const{renamingFolderId:t,editingIdRef:n}=e;return s.jsx(qo,{children:s.jsx(Vo,{className:"app-region-no-drag z-50",children:s.jsx(Yo,{"data-slot":"dropdown-menu-content",finalFocus:()=>!(t||n.current),style:{color:"var(--surface-elevated-foreground)"},className:_(Zo,"min-w-[180px]"),children:kx(e,{Item:({className:r,...o})=>s.jsx(Ll,{className:_(Ql,r),...o}),Separator:({className:r,...o})=>s.jsx(Ol,{className:_(Jl,r),...o}),Sub:Bu,SubTrigger:({className:r,children:o,...i})=>s.jsxs(_u,{className:_(Rf,r),...i,children:[o,s.jsx(R,{name:"arrow-right-s",className:"ml-auto size-3.5"})]}),SubContent:({className:r,children:o,...i})=>s.jsx(qo,{children:s.jsx(Vo,{className:"app-region-no-drag z-50",children:s.jsx(Yo,{"data-slot":"dropdown-menu-sub-content",style:{backgroundColor:"var(--surface-elevated)",color:"var(--surface-elevated-foreground)"},className:_(Zo,r),...i,children:o})})})})})})})}const Mo=new WeakMap,Ax=e=>{if(typeof window>"u")return;const t=e.closest("[data-session-row]"),n=t?.closest(".overlay-scrollbar-container");if(!t||!n)return;Mo.get(n)?.();const r=t.getBoundingClientRect().top;let o=3,i=!1,a=null;const c=()=>{i=!0,a!==null&&window.cancelAnimationFrame(a),a=null,Mo.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,Ht("ui.sidebar.selection_scroll_anchor_adjustment")),o-=1,o<=0){c();return}a=window.requestAnimationFrame(d)};n.addEventListener("wheel",c,{passive:!0}),n.addEventListener("touchstart",c,{passive:!0}),Mo.set(n,c),a=window.requestAnimationFrame(d)};function Nx(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"),a=String(t.getMinutes()).padStart(2,"0");return`${n} ${r}, ${o}, ${i}:${a}`}function Ix(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 Ex(e){const t=e.info.role==="user"?"User":"Assistant",n=Nx(e.info.time?.created),r=Ix(e),o=n&&r?`${n} (${r})`:n||r;return o?`**${t}**
|
|
25
|
+
|
|
26
|
+
*${o}*`:`**${t}**`}function Dx(e){return e.filter(t=>t.type==="text"&&typeof t.text=="string").map(t=>t.text).join("")}function id(e){const t=Ex(e),n=Dx(e.parts).trim();return n?`${t}
|
|
27
|
+
|
|
28
|
+
${n}`:""}function ad(e,t){const n="#".repeat(Math.min(t+1,6)),r=e.agent?` — ${e.agent}`:"",o=`${n} Sub-agent: ${e.title}${r}
|
|
29
|
+
|
|
30
|
+
---
|
|
31
|
+
|
|
32
|
+
`,i=e.records.map(id).filter(Boolean).join(`
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
`),a=[o+i];for(const c of e.children)a.push(ad(c,t+1));return a.join(`
|
|
37
|
+
|
|
38
|
+
---
|
|
39
|
+
|
|
40
|
+
`)}function ld(e,t,n){const r=t?.trim()||"Session",o=new Date().toISOString().split("T")[0],i=`# ${r}
|
|
41
|
+
|
|
42
|
+
*Exported on ${o}*
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
`,a=e.map(id).filter(Boolean).join(`
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
`);let c=i+a;if(n&&n.length>0){const d=n.map(u=>ad(u,1)).join(`
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
`);c+=`
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
`+d}return c}function cd(e,t){fc({filename:t,mimeType:"text/markdown;charset=utf-8",data:e}).catch(n=>console.warn("[export] Markdown save failed",n))}async function dd(e,t){const n=await Ih(t,e);return n||null}async function Rx(e){const t=ac()?.files;if(t?.revealPath)try{return!!(await t.revealPath(e))?.success}catch{return!1}return await Eh(e)?!0:lc(e)}function Px(){return Dh()}function ud(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 Tx(e,t){const[n,r]=l.useState(!1),[o,i]=l.useState(!0),a=e.session,c=l.useMemo(()=>Yr(e).length,[e]),d=l.useCallback(async g=>{const b=[];let h=0;for(const p of g)try{if(!t)throw new Error("Session directory is required for export");const y=[],x=p.session.title||"Untitled Sub-agent",C=typeof p.session.agent=="string"?p.session.agent:void 0,j=await d(p.children);h+=j.skipped,b.push({title:x,agent:C,records:y,children:j.children})}catch{h+=Yr(p).length+1}return{children:b,skipped:h}},[t]),u=l.useCallback(g=>{g<=0||oe.warning(g===1?`Exported session, but skipped ${g} sub-agent task that could not be loaded.`:`Exported session, but skipped ${g} sub-agent tasks that could not be loaded.`)},[]),f=l.useCallback(async g=>{if(!t){oe.error("Nothing to export");return}const b=[];if(b.length===0){oe.error("Nothing to export");return}let h,p=0;if(g&&e.children.length>0){const j=await d(e.children);h=j.children,p=j.skipped}const y=ld(b,a.title??null,h),x=ud(a.title??null),C=await dd(y,x);if(C){oe.success("Session exported",{action:{label:Px(),onClick:()=>{Rx(C).then(j=>{j||oe.error("Failed to reveal path")})}}}),u(p);return}cd(y,x),oe.success("Session exported"),u(p)},[d,e.children,a.title,t,u]),m=l.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:m,doExportSession:f}}const Mx=(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 a of i)r.has(a)||(r.add(a),n.push(a))}return n},dt=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(),a=new Set(i.selectedIds);let c=i.scopeKey,d=i.anchorId;r!==null&&i.scopeKey!==null&&r!==i.scopeKey?(a.clear(),c=r,d=null):c===null&&r!==null&&(c=r);const f=o&&o.length>0?[n,...o]:[n];if(a.has(n)){for(const g of f)a.delete(g);d===n&&(d=null)}else{for(const g of f)a.add(g);d=n}a.size===0?e({selectedIds:a,scopeKey:null,anchorId:null}):e({selectedIds:a,scopeKey:c,anchorId:d})},setRange:(n,r,o,i,a)=>{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[m,g]=u<=f?[u,f]:[f,u],b=o.slice(m,g+1),h=Mx(b,a),y=i!==null&&c.scopeKey!==null&&i!==c.scopeKey?new Set:new Set(c.selectedIds);for(const x of h)y.add(x);e({selectedIds:y,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}))}})),ul=e=>Re(e.session.directory??null),Fx=(e,t)=>(e?.projectLabel??null)===(t?.projectLabel??null)&&(e?.branchLabel??null)===(t?.branchLabel??null)&&(e?.showFolderLabel??!1)===(t?.showFolderLabel??!1),Lx=e=>{if(!e.openSidebarMenuKey)return null;const t=e.renderContext??"project",[n,,...r]=e.openSidebarMenuKey.split(":");return n===t&&r.length>0?r.join(":"):null},Ir=e=>e.menuOpenSessionId??Lx(e),Er=(e,t,n)=>t?n.has(e.node.session.id)?!0:us(e.node,t):!1,Ni=(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 a=0;a<e.children.length;a+=1)if(Ni(e.children[a],t.children[a],n,r,o))return!0;return!1},Ox=(e,t)=>e.hasSessionSearchQuery||t.hasSessionSearchQuery?!1:Ni(e.node,t.node,e.expandedParents,t.expandedParents,n=>cr(e.renderContext??"project",n.session))||Ni(e.node,t.node,e.expandedParents,t.expandedParents,n=>cr(t.renderContext??"project",n.session)),Bx=(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||ul(e.node)!==ul(t.node)||!Fx(e.secondaryMeta,t.secondaryMeta)||e.pinnedSessionIds!==t.pinnedSessionIds&&zc(e.node,t.node,e.pinnedSessionIds,t.pinnedSessionIds,e.groupDirectory,t.groupDirectory)||e.expandedParents!==t.expandedParents&&Ox(e,t)||e.editingId!==t.editingId&&(Er(e,e.editingId,e.subtreeContainsEditing)||Er(t,t.editingId,t.subtreeContainsEditing))||e.editTitle!==t.editTitle&&(Er(e,e.editingId,e.subtreeContainsEditing)||Er(t,t.editingId,t.subtreeContainsEditing))||e.copiedSessionId!==t.copiedSessionId&&(us(e.node,e.copiedSessionId)||us(t.node,t.copiedSessionId)))return!1;if(e.openSidebarMenuKey!==t.openSidebarMenuKey){const n=Ir(e),r=Ir(t);if(us(e.node,n)||us(t.node,r))return!1}if(e.renamingFolderId!==t.renamingFolderId){const n=Ir(e),r=Ir(t);if(us(e.node,n)||us(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 _x({node:e,groupDirectory:t,projectId:n,secondaryMeta:r,pinnedSessionIds:o,expandedParents:i,expansionKey:a,hasSessionSearchQuery:c}){const d=e.session,u=Re(d.directory??null)??Re(t??null),f=Me(me=>me.currentSessionId===d.id),m=ei(u),g=Pf(u),b=ot(l.useCallback(me=>{if(r?.projectLabel||!n)return null;const Pe=me.projects.find(V=>V.id===n);return Pe?In({label:Pe.label,normalizedPath:Re(Pe.path)??Pe.path},null):null},[n,r?.projectLabel])),h=r?.projectLabel??b,p=ot(l.useCallback(me=>n?me.projects.find(Pe=>Pe.id===n)?.path??null:null,[n])),y=e.worktree,x=r?.branchLabel??y?.branch??(m&&m!=="HEAD"?m:null),C=Re(p),j=ei(C),w=!!C&&u===C||!!x&&x===j,S=w?null:x,v=!w&&(g===!0||!!(x||y)),k=e.children.length,E=d.agent,P=y?.branch?.trim()||x?.trim()||null,z=Re(y?.path??u),K=l.useMemo(()=>P&&z?dr(z,P):null,[P,z]),q=$c(K);Kc(z,P);const H=q?`var(--pr-${q.visualState})`:void 0,F=l.useMemo(()=>{if(!q)return null;switch(q.visualState){case"merged":return"Merged";case"open":return q.canMerge===!0||q.mergeableState==="clean"||q.checks?.state==="success"?"Ready to merge":"PR open";case"blocked":return q.mergeableState==="dirty"?"Merge conflicts":"Merge blocked";case"draft":return"Draft PR";case"closed":return"Closed";default:return null}},[q]),D=n??u??null,T=dt(me=>me.enabled),I=dt(l.useCallback(me=>me.selectedIds.has(d.id),[d.id])),M=dt(me=>me.toggleSelected),G=dt(me=>me.setRange),L=Xl(d.id)?.type??"idle",ae=L==="busy"||L==="retry",J=Tf(d.id,ae),le=fs(d,"Untitled session"),Ie=e.children.length>0,Y=ur(o,u,d.id),B=c?!0:i.has(a),$=Mf(d.id);Zl(l.useCallback(me=>me.index.session.unseenHasError[d.id]??!1,[d.id]));const X=Ff(d.id),ee=Lf({pendingInput:X,isStreaming:ae,unseenCount:$,isActive:f}),ie=$>0||ec(X),Ce=d.time?.updated||d.time?.created||Date.now(),pe=Zh(Ce),je=l.useMemo(()=>Mc(e.forkColorId),[e.forkColorId]),ze=l.useMemo(()=>Ig(e.forkColorId,{active:f||I}),[e.forkColorId,f,I]);return{session:d,sessionDirectory:u,prDirectory:z,prBranch:P,prNumber:q?.number??null,isActive:f,tooltipProjectLabel:h,projectPath:p,tooltipBranchLabel:S,isGitRepo:v,subtaskCount:k,agentName:E,prSummary:q,prIconColor:H,prStatusLabel:F,selectionScopeKey:D,selectionModeEnabled:T,isRowSelected:I,toggleRowSelected:M,setRowRange:G,isStreaming:ae,hasActivityDuration:J,sessionTitle:le,hasChildren:Ie,isPinnedSession:Y,isExpanded:B,needsAttention:ie,pendingInput:X,attention:ee,sessionCompactUpdatedLabel:pe,forkSolid:je,rowBackground:ze}}const zx=({prDirectory:e,prNumber:t,prStatusLabel:n,prIconColor:r})=>{const o=Vl(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(R,{name:"git-pull-request",className:"size-3.5 shrink-0"}),s.jsxs("span",{children:["#",t]})]});const i=a=>{a.stopPropagation(),a.preventDefault(),ed(e,o,t)};return s.jsxs("span",{role:"button",tabIndex:0,onClick:i,onDoubleClick:a=>{a.stopPropagation(),a.preventDefault()},onKeyDown:a=>{if(!(a.key!=="Enter"&&a.key!==" ")){if(a.repeat){a.stopPropagation(),a.preventDefault();return}i(a)}},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(R,{name:"git-pull-request",className:"size-3.5 shrink-0"}),s.jsxs("span",{children:["#",t]})]})};function Ux(e){Ht("ui.sidebar_session_node.render");const{node:t,depth:n=0,groupDirectory:r,projectId:o,archivedBucket:i=!1,pinnedSessionIds:a,expandedParents:c,hasSessionSearchQuery:d,normalizedSessionSearchQuery:u,editingId:f,setEditingId:m,editTitle:g,setEditTitle:b,handleSaveEdit:h,handleCancelEdit:p,toggleParent:y,handleSessionSelect:x,handleSessionDoubleClick:C,togglePinnedSession:j,handleShareSession:A,copiedSessionId:w,handleCopyShareUrl:S,handleCopySessionId:v,handleUnshareSession:k,openSidebarMenuKey:E,setOpenSidebarMenuKey:P,renamingFolderId:z,getFoldersForScope:K,getSessionFolderId:q,removeSessionFromFolder:H,addSessionToFolder:F,createFolderAndStartRename:D,handleDeleteSession:T,handleRestoreSession:I,alwaysShowActions:M,allowQuickArchiveAction:G,renderSessionNode:W,secondaryMeta:L,renderContext:ae="project",subtreeContainsEditing:J,menuOpenSessionId:le,childRenderExtrasFor:Ie}=e,Y=i||!!t.session.time?.archived,B=l.useContext(lr)==="tree",$="size-3 shrink-0",X=l.useMemo(()=>cc(),[]),ee=!Y&&G,ie=l.useRef(!1),Ce=l.useRef(f);Ce.current=f;const pe=l.useRef(null),je=l.useRef(h);je.current=h;const[be,ze]=l.useState(g),me=l.useRef(be);me.current=be;const Pe=l.useRef(null),V=l.useRef(null),xe=cr(ae,t.session),{session:te,sessionDirectory:re,prDirectory:Be,prNumber:ke,isActive:Q,tooltipProjectLabel:ve,projectPath:he,tooltipBranchLabel:Se,isGitRepo:qe,subtaskCount:Ue,agentName:U,prSummary:ge,prIconColor:ne,prStatusLabel:_e,selectionScopeKey:rt,selectionModeEnabled:mt,isRowSelected:Ze,toggleRowSelected:Jt,setRowRange:gt,isStreaming:Et,hasActivityDuration:rs,sessionTitle:Qe,hasChildren:Ft,isPinnedSession:Lt,isExpanded:kt,pendingInput:Ee,attention:Ye,sessionCompactUpdatedLabel:Ne,forkSolid:De,rowBackground:He}=_x({node:t,groupDirectory:r,projectId:o,secondaryMeta:L,pinnedSessionIds:a,expandedParents:c,expansionKey:xe,hasSessionSearchQuery:d}),{exportDialogOpen:ft,setExportDialogOpen:os,exportIncludeSubtasks:Ot,setExportIncludeSubtasks:Bt,descendantCount:Ve,handleExportSession:is,doExportSession:Rs}=Tx(t,re),[Dt,Ys]=l.useState(!1),xt=l.useContext(so),it=n===0&&!Y?xt?.sectionById.get(te.id)??null:null,Xt=ir(l.useCallback(de=>it==="snoozed"?de.entries[te.id]?.snoozedUntil??null:null,[it,te.id])),_t=it==="snoozed"||Y,xs=it!==null&&it!=="snoozed"&&!!xt?.wokeIds.has(te.id),as=l.useMemo(()=>{if(!it)return null;const de=re??null;return{section:it,onSnooze:zt=>ki(te.id,{snoozedUntil:zt},de,"Could not snooze the session"),onWake:()=>ki(te.id,{snoozedUntil:null},de,"Could not wake the session")}},[it,te.id,re]),yt=as?.section==="snoozed"?{label:"Wake",hint:"Wake now: back to the list",icon:"alarm",run:as.onWake}:null,wt=l.useCallback(()=>{re&&Jn("desktop_open_session_mini_chat_window",{sessionId:te.id,directory:re,apiBaseUrl:ri(),clientToken:ni()}).catch(de=>{console.warn("[session-sidebar] failed to open mini chat window",de)})},[te.id,re]);l.useEffect(()=>{if(f!==te.id)return;const de=zt=>{const Fn=zt.target?.closest?.(`[data-session-rename-form="${CSS.escape(te.id)}"]`);V.current&&!Fn&&je.current(me.current)};return document.addEventListener("mousedown",de),()=>document.removeEventListener("mousedown",de)},[f,te.id]),l.useLayoutEffect(()=>{if(f!==te.id){Pe.current===te.id&&(Pe.current=null);return}Pe.current!==te.id&&(Pe.current=te.id,ze(g))},[f,g,te.id]);const Rt=Ye==="needs-input",Qs=Rt&&Ee?Of(Ee.kind,Ee.count):null,Ps=Ye==="unread",Ts=Xt!==null?Bf(Xt,Date.now()):xs?"Woke":Ne,Ct=Et&&rs,ls=ee&&(M||Dt),nt=Et&&!B&&!ls&&f!==te.id,cs=!!(L?.showFolderLabel&&ve),vt=!!Se||qe,At=!!(U&&U!=="default"),at=!!ge&&ke!=null,Ms=Ct&&!nt,lt=cs&&vt||at||Ue>0||At||Ms,Js=de=>Se?s.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",de?"shrink":"flex-1"),children:[s.jsx(R,{name:"git-branch",className:$,style:ne?{color:ne}:void 0}),s.jsx(Yn,{value:Se})]}):qe?s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[s.jsx(R,{name:"git-repository",className:$}),s.jsx("span",{children:"git"})]}):null,Xs=Lt,Pn=s.jsx(R,{name:"pushpin",className:"h-3 w-3 flex-shrink-0 text-primary","aria-label":"Pinned session"}),Fs=Xs?s.jsx("span",{className:"inline-flex h-3.5 w-3.5 shrink-0 items-center justify-center",children:Pn}):null,Tn=Ft?s.jsx("button",{type:"button",onClick:de=>{de.stopPropagation(),y(xe)},onKeyDown:de=>{(de.key==="Enter"||de.key===" ")&&(de.preventDefault(),de.stopPropagation(),y(xe))},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":kt?"Collapse subsessions":"Expand subsessions",children:kt?s.jsx(R,{name:"arrow-down-s",className:"h-3 w-3"}):s.jsx(R,{name:"arrow-right-s",className:"h-3 w-3"})}):null,O=de=>{if(!de&&pe.current){const{id:zt,title:Zs}=pe.current;pe.current=null,m(zt),b(Zs)}},ce=de=>{Ys(de)},ye=de=>{de.preventDefault(),de.stopPropagation()},$e=de=>{de.preventDefault(),de.stopPropagation()},ht=de=>{de.preventDefault(),de.stopPropagation(),P(null),T(te,{archivedBucket:Y})},Je=de=>{de.preventDefault(),de.stopPropagation(),P(null),T(te,{archivedBucket:Y,hardDelete:!0,skipConfirm:!0})},St=de=>{if(ie.current){ie.current=!1;return}if(mt){if(de?.preventDefault(),de?.stopPropagation(),de?.shiftKey){const Zs=(typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[]).map(en=>en.getAttribute("data-session-row")).filter(en=>typeof en=="string"&&en.length>0),Fn=dt.getState().anchorId,pr=new Map;pr.set(te.id,Yr(t)),gt(Fn,te.id,Zs,rt,pr);return}Jt(te.id,rt,Yr(t));return}de?.currentTarget&&Ax(de.currentTarget),x(te.id,re)},Pt=de=>{de.defaultPrevented||de.target?.closest('button, a, input, [role="menuitem"], [role="menu"]')||St(de)},ys=de=>{(de.button===2||de.button===0&&de.ctrlKey&&!mt)&&(ie.current=!0)},Mn={session:te,sessionTitle:Qe,sessionDirectory:re,isPinnedSession:Lt,archivedBucket:Y,isElectron:X,renamingFolderId:z,editingIdRef:Ce,pendingRenameRef:pe,handleCopySessionId:v,togglePinnedSession:j,handleExportSession:is,handleOpenMiniChatWindow:wt,handleDeleteSession:T,handleRestoreSession:I,shelfActions:as},hr=s.jsx(Cx,{...Mn});return s.jsxs(l.Fragment,{children:[s.jsx(Qg,{sessionId:te.id,sessionDirectory:re??null,sessionTitle:Qe,children:s.jsxs(Ml,{open:Dt,onOpenChange:ce,onOpenChangeComplete:O,children:[s.jsxs(Fl,{render:s.jsx("div",{"data-session-row":te.id,"data-session-scope":rt??"","data-session-archived":Y?"1":"0","data-fork-color":De?t.forkColorId:void 0,"data-global-session":L?.globalSession?"1":void 0,"data-sidebar-tree-row":B?"":void 0,onClick:Pt,style:{...n>0?{marginLeft:`${n*14}px`}:void 0,...He?{backgroundColor:He}:void 0},className:_("group relative flex cursor-pointer items-start px-3 transition-colors",B?_c:"my-1 rounded-xl py-2.5",!He&&n>0?"bg-secondary/30 hover:bg-interactive-hover":He?"hover:brightness-[1.07] dark:hover:brightness-[1.18]":"hover:bg-interactive-hover",!He&&Q&&!Ze&&"bg-interactive-selection",!He&&Ze&&"bg-interactive-selection")}),children:[s.jsxs("div",{className:_("flex min-w-0 flex-1 items-start",nt&&"oc-session-row-working-fade"),"data-clear-on-hover":nt&&ee?"true":void 0,"data-working-duration":nt&&Ct?"true":void 0,children:[s.jsxs("div",{className:_("flex min-w-0 flex-1 items-center",B?no:"gap-1.5"),children:[B?s.jsx("span",{"data-session-row-gutter":!0,className:"inline-flex size-4 shrink-0 items-center justify-center",children:Et&&!Rt?s.jsx(Is,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"}):null}):null,Tn,Fs,f===te.id?s.jsxs("form",{ref:V,"data-session-rename-form":te.id,className:_("flex min-w-0 flex-1 items-center gap-2",B?"min-h-5":"min-h-8"),onPointerDown:de=>de.stopPropagation(),onMouseDown:de=>de.stopPropagation(),onSubmit:de=>{de.preventDefault(),h(be)},children:[s.jsx("input",{value:be,onChange:de=>ze(de.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:de=>{de.stopPropagation(),de.key==="Escape"&&p()}}),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(R,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:p,"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(R,{name:"close",className:"size-4"})})]}):s.jsxs("button",{type:"button",onMouseDown:ys,onClick:de=>St(de),onDoubleClick:de=>{de.stopPropagation(),C(te.id,Qe)},className:"flex min-w-0 flex-1 cursor-pointer flex-col gap-1.5 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 min-w-0 flex-1 gap-1.5 overflow-hidden",B?"items-center":"items-start"),children:[s.jsx("div",{className:_("block min-w-0 flex-1 truncate typography-ui-label",Q?"font-medium text-foreground":"font-normal",!Q&&(_t?"text-muted-foreground group-hover:text-foreground":"text-foreground")),children:xi(Qe,u)}),s.jsx(Dc,{sessionId:te.id,className:_(!B&&"mt-0.5")}),Lt?s.jsx(R,{name:"star-fill",className:_("h-3 w-3 text-primary shrink-0",!B&&"mt-1")}):null,s.jsx("span",{"aria-hidden":"true",className:_("invisible ml-1 min-w-6 shrink-0 whitespace-nowrap typography-micro",(Xt!==null||xs)&&!Ps&&"pl-4"),children:Ps?null:Ts})]}),!B&&(cs||vt||lt)?s.jsxs("div",{className:_("flex w-full min-w-0 items-center justify-between gap-2 overflow-hidden typography-micro leading-4 font-normal",_t?"text-subtle-foreground":"text-muted-foreground"),children:[cs?s.jsxs("span",{className:_("inline-flex min-w-0 items-center gap-1",lt?"max-w-[60%] shrink-0":"flex-1"),children:[he?s.jsx(Mi,{directory:he,label:ve??"",className:$}):s.jsx(R,{name:"folder",className:$}),s.jsx("span",{className:"truncate",children:ve})]}):Js(!1),lt?s.jsxs("span",{className:_("ml-auto flex min-w-0 items-center justify-end gap-2 overflow-hidden",cs?"flex-1":"shrink-0"),children:[cs?Js(!0):null,at?s.jsx(zx,{prDirectory:Be,prNumber:ke,prStatusLabel:_e,prIconColor:ne}):null,Ue>0?s.jsxs("span",{className:"inline-flex shrink-0 items-center gap-1",children:[s.jsx(R,{name:"node-tree",className:$}),s.jsx("span",{children:Ue})]}):null,At?s.jsx("span",{className:"min-w-0 max-w-[80px] shrink-0 truncate",children:U}):null,Ms?s.jsx(ka,{sessionId:te.id,running:Et,className:"shrink-0 text-subtle-foreground"}):null]}):null]}):null]})]}),s.jsxs("div",{className:_("absolute right-3 flex h-5 min-w-6 items-center justify-end",B?"top-1/2 -translate-y-1/2":"top-2.5",f===te.id&&"hidden"),children:[s.jsx("div",{className:_("flex items-center justify-end",ls?"opacity-0":ee?"group-hover:opacity-0 group-focus-within:opacity-0":null),children:Rt&&!nt?s.jsx(ba,{label:Qs??"Needs input"}):Ps?s.jsx(ep,{label:"Session complete"}):Xt!==null||xs?s.jsxs("span",{className:"inline-flex items-center gap-1 typography-micro text-muted-foreground whitespace-nowrap",title:Xt!==null?`Snoozed until ${new Date(Xt).toLocaleString()}`:"Back from snooze",children:[s.jsx(R,{name:"alarm",className:"size-3 shrink-0"}),Ts]}):s.jsx("span",{className:"typography-micro text-subtle-foreground whitespace-nowrap",children:Ne})}),ee?s.jsx("div",{className:_("absolute inset-0 flex items-center justify-end",M||Dt?"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:yt?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button","aria-label":yt.label,className:"inline-flex size-6 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-interactive-active hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/50",onPointerDown:ye,onMouseDown:$e,onKeyDown:de=>de.stopPropagation(),onClick:de=>{de.preventDefault(),de.stopPropagation(),P(null),yt.run()},children:s.jsx(R,{name:yt.icon,className:"size-4"})})}),s.jsx(Ge,{side:"top",sideOffset:6,children:yt.hint})]}):s.jsx(Sx,{archiveLabel:"Archive",deleteLabel:"Delete",buttonSizeClass:"h-6 w-6",iconSizeClass:"h-3.5 w-3.5",onPointerDown:ye,onMouseDown:$e,onArchive:ht,onDelete:Je})}):null]})]}),nt?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",ee&&"group-hover:opacity-0 group-focus-within:opacity-0"),children:[Rt?null: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.5",children:[s.jsx("span",{className:"flex h-5 items-center",children:Rt?s.jsx("span",{className:"inline-flex size-3 shrink-0 items-center justify-center",children:s.jsx(ba,{label:Qs??"Needs input"})}):s.jsx(Is,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}),Ct?s.jsx(ka,{sessionId:te.id,running:Et,className:"typography-micro leading-4"}):null]})]}):null]}),hr]})}),Ft&&kt?t.children.map(de=>{const zt=Ie?Ie(de):{subtreeContainsEditing:J,menuOpenSessionId:le,nodeStructureKey:""};return s.jsx(l.Fragment,{children:W(de,n+1,re??r,o,Y,L?.globalSession?{globalSession:!0}:void 0,ae,zt)},de.session.id)}):null,s.jsx(jx,{open:ft,onOpenChange:os,descendantCount:Ve,exportIncludeSubtasks:Ot,setExportIncludeSubtasks:Bt,onExport:Rs})]},te.id)}const $x=l.memo(Ux,Bx),Kx=({open:e,onOpenChange:t,project:n,onSave:r})=>s.jsx(ss,{open:e,onOpenChange:t,children:s.jsx(ns,{className:"w-full max-w-2xl gap-0 overflow-hidden p-0",children:s.jsx(zs,{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(Um,{project:n,onIdentitySave:r}):null})})})});function fd(e){const{showDeletionDialog:t,setShowDeletionDialog:n,onCancel:r,onConfirm:o,confirmLabel:i}=e;return s.jsxs(An,{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(R,{name:"checkbox-blank",className:"h-4 w-4"}):s.jsx(R,{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 Wx(e){const{value:t,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,a=c=>fs(c);return s.jsx(ss,{open:!!t,onOpenChange:c=>{c||n(null)},children:s.jsxs(ns,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Hs,{children:[s.jsx(gs,{children:"Delete session?"}),s.jsx(Ds,{children:t&&t.descendantCount>0?t.descendantCount===1?`"${a(t.session)}" and its ${t.descendantCount} sub-task will be permanently deleted.`:`"${a(t.session)}" and its ${t.descendantCount} sub-tasks will be permanently deleted.`:`"${t?.session?a(t.session):"Untitled Session"}" will be permanently deleted.`})]}),s.jsx(fd,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:i,confirmLabel:"Delete"})]})})}function Gx(e){const{value:t,setValue:n,showDeletionDialog:r,setShowDeletionDialog:o,onConfirm:i}=e,a=t?.sessionCount??0,c=a===1?"Delete session?":"Delete sessions?",d=a===1?`${a} session will be permanently deleted.`:`${a} sessions will be permanently deleted.`;return s.jsx(ss,{open:!!t,onOpenChange:u=>{u||n(null)},children:s.jsxs(ns,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Hs,{children:[s.jsx(gs,{children:c}),s.jsx(Ds,{children:d})]}),s.jsx(fd,{showDeletionDialog:r,setShowDeletionDialog:o,onCancel:()=>n(null),onConfirm:i,confirmLabel:"Delete"})]})})}function Hx(e){const{value:t,setValue:n,onConfirm:r}=e,{git:o}=qs(),[i,a]=l.useState(null),[c,d]=l.useState(!1),[u,f]=l.useState(!1),[m,g]=l.useState(!1),b=t?.worktree.path??null;l.useEffect(()=>{let w=!1;return a(null),d(!1),f(!1),g(!1),!t||!b?()=>{w=!0}:(o.getGitStatus(b).then(S=>{if(!w){if(typeof S?.isClean!="boolean"){d(!0);return}a(S)}}).catch(()=>{w||d(!0)}),()=>{w=!0})},[o,t,b]);const h=i?.isClean===!1,p=(i?.ahead??0)>0,y=p&&!t?.worktree.branch,x=t?.worktree.branch?"The local branch will be kept.":"No local branch will be deleted.",C=!!(t&&i&&!c&&!t.hasActiveSession&&(!h&&!y||u)&&!m),j=t?.worktree.branch||t?.worktree.name||t?.worktree.path||"",A=async()=>{if(C){g(!0);try{await r({force:h})}finally{g(!1)}}};return s.jsx(ss,{open:!!t,onOpenChange:w=>{!w&&!m&&n(null)},children:s.jsxs(ns,{showCloseButton:!1,className:"max-w-md gap-5",children:[s.jsxs(Hs,{children:[s.jsx(gs,{children:"Close worktree?"}),s.jsx(Ds,{children:`Closing "${j}" removes its worktree directory. ${x}`})]}),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(R,{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(R,{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,h?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(R,{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(tr,{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,p?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. ${x}`:`This worktree has ${i?.ahead} unpushed commits. ${x}`}),y?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(R,{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(tr,{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(An,{className:"sm:justify-end",children:[s.jsx(Ae,{variant:"outline",size:"sm",onClick:()=>n(null),disabled:m,children:"Cancel"}),s.jsx(Ae,{variant:"destructive",size:"sm",onClick:()=>{A()},disabled:!C,children:m?"Closing…":"Close worktree"})]})]})})}function qx(e){const{value:t,setValue:n,onConfirm:r}=e;return s.jsx(ss,{open:!!t,onOpenChange:o=>{o||n(null)},children:s.jsxs(ns,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Hs,{children:[s.jsx(gs,{children:"Delete folder?"}),s.jsx(Ds,{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(An,{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 Vx=({updateDialogOpen:e,setUpdateDialogOpen:t,updateStore:n,editingProject:r,setEditingProjectDialogId:o,handleSaveProjectEdit:i,deleteSessionConfirm:a,setDeleteSessionConfirm:c,showDeletionDialog:d,setShowDeletionDialog:u,confirmDeleteSession:f,deleteFolderConfirm:m,setDeleteFolderConfirm:g,confirmDeleteFolder:b,closeWorktreeConfirm:h,setCloseWorktreeConfirm:p,confirmCloseWorktree:y,bulkDeleteConfirm:x,setBulkDeleteConfirm:C,confirmBulkDelete:j})=>s.jsxs(s.Fragment,{children:[s.jsx(Cc,{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(Kx,{open:!!r,onOpenChange:A=>{A||o(null)},project:r,onSave:i}),s.jsx(Wx,{value:a,setValue:c,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:f}),s.jsx(qx,{value:m,setValue:g,onConfirm:b}),s.jsx(Hx,{value:h,setValue:p,onConfirm:y}),s.jsx(Gx,{value:x,setValue:C,showDeletionDialog:d,setShowDeletionDialog:u,onConfirm:j})]}),Yx=({directories:e})=>{const t=l.useMemo(()=>{const r=new Set;return e.forEach(o=>{const i=Re(o)?.toLowerCase();i&&r.add(i)}),r},[e]),n=Qn(r=>{let o=0,i=!1;for(const a of r.catalog.byId.values()){const c=Re(a.directory)?.toLowerCase();!c||!t.has(c)||(ec(a.pendingInput)?o+=1:(a.lifecycle==="busy"||a.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=_f(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(Is,{variant:"inline",text:null,animationType:"spinner",speedMs:80,className:"text-primary text-xs shrink-0"})}):null},Qx=({selectedCount:e,archivedBucket:t,onRestore:n,onDelete:r,onDone:o})=>{const i=t?"Delete":"Archive",a="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(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:n,className:a,"aria-label":"Unarchive",children:s.jsx(R,{name:"inbox-unarchive",className:"h-4 w-4"})})}),s.jsx(Ge,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Unarchive"})})]}):null,s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:r,className:_(t?"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":a),"aria-label":i,children:s.jsx(R,{name:t?"delete-bin":"inbox-archive",className:"h-4 w-4"})})}),s.jsx(Ge,{side:"top",sideOffset:4,children:s.jsx("p",{children:i})})]}),s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:o,className:a,"aria-label":"Exit selection",children:s.jsx(R,{name:"close",className:"h-4 w-4"})})}),s.jsx(Ge,{side:"top",sideOffset:4,children:s.jsx("p",{children:"Exit selection"})})]})]})]})},Jx=e=>{if(typeof document>"u")return!1;const t=document.querySelectorAll(`[data-session-row="${CSS.escape(e)}"]`);if(t.length===0)return!1;for(const n of t)if(n.getAttribute("data-session-archived")!=="1")return!1;return!0},Xx=e=>{const{isInlineEditing:t,showDeletionDialog:n,foldersMap:r,folderScopesByProject:o,addSessionsToFolder:i,removeSessionsFromFolders:a,createFolderAndStartRename:c,resolveSessionDirectory:d,unarchiveSessions:u,deleteSessions:f,setBulkDeleteConfirm:m}=e,g=dt(T=>T.enabled),b=dt(T=>T.selectedIds.size),h=b>0,p=dt(T=>T.selectedIds),y=dt(T=>T.scopeKey),x=l.useCallback(()=>{dt.getState().toggleMode()},[]),C=l.useCallback(()=>{dt.getState().disable()},[]),j=l.useMemo(()=>{if(!h||typeof document>"u")return!1;let T=!1,I=!1;for(const M of p){const G=document.querySelectorAll(`[data-session-row="${CSS.escape(M)}"]`);for(const W of G)W.getAttribute("data-session-archived")==="1"?I=!0:T=!0}return I&&!T},[h,p]),A=l.useMemo(()=>{if(y)return y;if(!h||typeof document>"u")return null;for(const T of p){const M=document.querySelector(`[data-session-row="${CSS.escape(T)}"]`)?.getAttribute("data-session-scope");if(M&&M.length>0)return M}return null},[h,p,y]),w=l.useMemo(()=>{if(!A)return[];const T=o.get(A);return T&&T.length>0?T.map(I=>I.scopeKey):[A]},[A,o]),S=l.useMemo(()=>w.flatMap(T=>r[T]??[]),[r,w]),v=l.useCallback(T=>{for(const I of w)if((r[I]??[]).some(M=>M.id===T))return I;return null},[r,w]),k=l.useMemo(()=>{if(!h)return!1;for(const T of w)for(const I of r[T]??[])for(const M of I.sessionIds)if(p.has(M))return!0;return!1},[r,w,h,p]),E=l.useCallback((T,I)=>{const M=Array.from(p);for(const G of w)G!==T&&a(G,M);i(T,I,M)},[i,a,p,w]),P=l.useCallback(T=>{if(!h)return;const I=v(T);I&&E(I,T)},[h,E,v]),z=l.useCallback(()=>{const T=w[0];if(!T||!h)return;const I=c(T);I&&E(T,I.id)},[c,h,E,w]),K=l.useCallback(()=>{if(!h)return;const T=Array.from(p);for(const I of w)a(I,T)},[a,p,w,h]),q=l.useCallback(async()=>{const T=Array.from(p);if(T.length===0)return;const{deletedIds:I,failedIds:M}=await f(T);I.length>0&&oe.success(I.length===1?`Deleted ${I.length} session`:`Deleted ${I.length} sessions`),M.length>0&&oe.error(M.length===1?`Failed to delete ${M.length} session`:`Failed to delete ${M.length} sessions`),dt.getState().clear()},[f,p]),H=l.useCallback(()=>{if(h){if(!j){const T=Array.from(p).filter(I=>!Jx(I)).map(I=>({sessionId:I,directory:d(I),forkIds:[]}));dt.getState().clear(),Fc(T);return}if(!n){q();return}m({sessionCount:p.size})}},[j,q,d,p,n,m,h]),F=l.useCallback(async()=>{if(!h||!j)return;const T=Array.from(p),{restoredIds:I,failedIds:M}=await u(T);I.length>0&&oe.success(I.length===1?`Unarchived ${I.length} session`:`Unarchived ${I.length} sessions`),M.length>0&&oe.error(M.length===1?`Could not unarchive ${M.length} session`:`Could not unarchive ${M.length} sessions`),dt.getState().clear()},[j,h,p,u]),D=l.useCallback(async()=>{m(null),await q()},[q]);return l.useEffect(()=>{if(!g)return;const T=typeof navigator<"u"&&/Macintosh|Mac OS X/.test(navigator.userAgent||""),I=M=>{if(t)return;const G=M.target;if(G&&(G.tagName==="INPUT"||G.tagName==="TEXTAREA"||G.isContentEditable))return;const W=T?M.metaKey:M.ctrlKey;if(M.key==="Escape"){M.preventDefault(),dt.getState().disable();return}if(W&&M.key==="Backspace"){M.preventDefault(),H();return}if(W&&(M.key==="a"||M.key==="A")){const L=typeof document<"u"?Array.from(document.querySelectorAll("[data-session-row]")):[];if(L.length===0)return;M.preventDefault();const J=dt.getState().scopeKey??L[0]?.getAttribute("data-session-scope")??null,le=Y=>J?Y.getAttribute("data-session-scope")===J:!0,Ie=L.filter(le).map(Y=>Y.getAttribute("data-session-row")).filter(Y=>typeof Y=="string"&&Y.length>0);if(Ie.length===0)return;dt.getState().replaceAll(Ie,J||null)}};return window.addEventListener("keydown",I),()=>window.removeEventListener("keydown",I)},[H,t,g]),{selectionModeEnabled:g,hasSelection:h,selectedIdsSize:b,bulkScopeIsArchived:j,derivedSelectionScope:A,bulkScopeFolders:S,bulkCanRemoveFromFolder:k,handleToggleSelectionMode:x,handleExitSelectionMode:C,handleBulkMoveToFolder:P,handleBulkCreateFolderAndMove:z,handleBulkRemoveFromFolder:K,handleBulkDelete:H,handleBulkRestore:F,confirmBulkDelete:D}},Zx=(e,t)=>{const n=e??{};return delete n.projectSortOrder,delete n.showArchivedSessions,t<4&&delete n.displayMode,t<5&&delete n.sessionGroupingMode,n},ey=bs()(mc(e=>({stickyZoneHeaders:!0,toggleStickyZoneHeaders:()=>e(t=>({stickyZoneHeaders:!t.stickyZoneHeaders})),showRecentSection:!0,setShowRecentSection:t=>e({showRecentSection:t}),toggleRecentSection:()=>e(t=>({showRecentSection:!t.showRecentSection}))}),{name:"pichamber:session-display-settings",version:7,migrate:Zx})),fl="oc.sessions.projectCollapse",hl="oc.sessions.groupOrder",pl="oc.sessions.groupCollapse",ml="oc.sessions.activeSessionByProject",gl="oc.sessions.expandedParents.v3",ty=new Set,Fo=[],Tt=e=>{const t=l.useRef(e);return t.current=e,l.useCallback((...n)=>t.current(...n),[])},sy=({isVisible:e=!0,mobileVariant:t=!1,onSessionSelected:n,onNavigateAway:r,allowReselect:o=!1,hideDirectoryControls:i=!1,showOnlyMainWorkspace:a=!1})=>{si("react.session_sidebar_render"),Ht("ui.session_sidebar.render"),Ht(`ui.session_sidebar.render.${t?"mobile":"desktop"}`),Ht(`ui.session_sidebar.render.${e?"visible":"hidden"}`);const[c,d]=l.useState(!1),[u,f]=l.useState(""),m=l.useRef(null),g=l.useRef(null),[b,h]=l.useState(null),[p,y]=l.useState(""),[x,C]=l.useState(null),[j,A]=l.useState(new Set),w=l.useMemo(()=>hn(),[]),[S,v]=l.useState(new Set),k=nn(N=>N.selectedSpaceId),E=nn(N=>N.selectedWorktreePath),[P,z]=l.useState(new Map),[K,q]=l.useState(new Map),[H,F]=l.useState(!1),[D,T]=l.useState(null),[I,M]=l.useState(null),[G,W]=l.useState(""),[L,ae]=l.useState(null),[J,le]=l.useState(null),[Ie,Y]=l.useState(null),[B,$]=l.useState(null),X=rr(N=>N.ids),ee=zf(l.useCallback(N=>e?N.rankById:Yl,[e])),ie=Qn(N=>e?Uf(N.catalog):"",void 0,"catalog"),Ce=l.useMemo(()=>ie?ie.split("|"):Fo,[ie]),pe=l.useMemo(()=>new Set(Ce),[Ce]),je=Zl(Qo(N=>e?Object.entries(N.index.session.unseenCount).filter(([,Z])=>Z>0).map(([Z])=>Z).sort():Fo)),be=l.useMemo(()=>new Set(je),[je]),ze=rr(N=>N.toggle),[me,Pe]=l.useState(()=>{try{const N=hn().getItem(pl);if(!N)return new Set;const Z=JSON.parse(N);return new Set(Array.isArray(Z)?Z.filter(se=>typeof se=="string"):[])}catch{return new Set}}),[V,fe]=l.useState(()=>{try{const N=hn().getItem(hl);if(!N)return new Map;const Z=JSON.parse(N),se=new Map;return Object.entries(Z).forEach(([Le,Oe])=>{Array.isArray(Oe)&&se.set(Le,Oe.filter(tt=>typeof tt=="string"))}),se}catch{return new Map}}),xe=l.useMemo(()=>{try{const N=hn().getItem(ml);if(!N)return new Map;const Z=JSON.parse(N),se=new Map;return Object.entries(Z).forEach(([Le,Oe])=>{typeof Oe=="string"&&Oe.length>0&&se.set(Le,Oe)}),se}catch{return new Map}},[]),te=l.useCallback(N=>{try{w.setItem(ml,JSON.stringify(Object.fromEntries(N.entries())))}catch{}},[w]),[re,Be]=l.useState(new Map),ke=l.useRef(0),Q=jn(N=>N.homeDirectory),ve=jn(N=>N.currentDirectory),he=ot(N=>N.projects),Se=ot(N=>N.activeProjectId),qe=ot(N=>N.removeProject),Ue=ot(N=>N.setActiveProjectIdOnly),U=ot(N=>N.updateProjectMeta),ge=ot(N=>N.reorderProjects),ne=ue(N=>N.setActiveMainTab),_e=ue(N=>N.setSettingsDialogOpen),rt=ue(N=>N.setSettingsPage),mt=ue(N=>N.toggleHelpDialog),Ze=ue(N=>N.setSessionSwitcherOpen),Jt=ue(N=>N.setArchivePageOpen),gt=ue(N=>N.showDeletionDialog),Et=ue(N=>N.setShowDeletionDialog),rs=ue(N=>N.sidebarViewMode),Qe=i||a||!Rh(rs)?"workspace":rs,Ft=ue(N=>N.weekStartPreference),Lt=l.useMemo(()=>ig(Ft),[Ft]),kt=dg(e&&Qe==="timeline",Lt),Ee=ey(N=>N.stickyZoneHeaders),Ye=$f(u,120),Ne=l.useMemo(()=>Ye.trim().toLowerCase(),[Ye]),De=Ne.length>0,He=bt(N=>N.collapsedFolderIds),ft=bt(N=>N.foldersMap),os=bt(N=>N.getFoldersForScope),Ot=bt(N=>N.createFolder),Bt=bt(N=>N.renameFolder),Ve=bt(N=>N.deleteFolder),is=bt(N=>N.addSessionToFolder),Rs=bt(N=>N.addSessionsToFolder),Dt=bt(N=>N.removeSessionFromFolder),Ys=bt(N=>N.removeSessionsFromFolders),xt=bt(N=>N.toggleFolderCollapse),it=bt(N=>N.getSessionFolderId);Rg({enabled:e,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:g,sessionSearchContainerRef:m});const Xt=Kf(e),{git:_t}=qs(),xs=Qn(N=>N.connection,void 0,"chrome"),as=Qn(N=>{for(const Z of N.catalog.listStatusByDirectory.values())if(Z==="ready")return!0;return!1},void 0,"catalog"),yt=Xo({archived:!1}),wt=Xo({archived:!0}),Rt=Me(N=>N.setCurrentSession),Qs=Me(N=>N.updateSessionTitle),Ps=Me(N=>N.shareSession),Ts=Me(N=>N.unshareSession),Ct=_r(N=>N.projects),ls=_r(N=>N.refreshProject),nt=l.useMemo(()=>tc(he,{projects:Ct}),[he,Ct]),cs=l.useMemo(()=>{const N=new Map;for(const Z of he){const se=Re(Z.path);if(!se)continue;const Le=Ct.get(se)?.error;Le&&N.set(se,Le)}return N},[he,Ct]);l.useEffect(()=>{if(!k)return;const N=he.find(se=>se.id===k);if(!N){nn.getState().clearSpaceSelection();return}if(!E)return;(nt.get(Re(N.path)??N.path)??[]).some(se=>Re(se.path)===Re(E))||(nn.getState().clearSelectedWorktree(),oe.warning("The selected worktree is no longer available. Showing the project checkout instead."))},[nt,he,k,E]);const vt=Me(N=>N.openNewSessionDraft),At=l.useCallback(N=>{ue.getState().closeMainSurfaces(),vt(N),r?.()},[r,vt]),at=Rr(Qo(N=>({checkForUpdates:N.checkForUpdates,available:N.available,runtimeType:N.runtimeType,info:N.info,downloading:N.downloading,downloaded:N.downloaded,progress:N.progress,error:N.error,downloadUpdate:N.downloadUpdate,restartToUpdate:N.restartToUpdate}))),Ms=l.useMemo(()=>Wf(he,nt,{includeWorktrees:!0}),[nt,he]),lt=l.useMemo(()=>yt.filter(N=>Gg(N,Ms,{allowUnknownDirectory:!0,allowEmptyDirectorySet:!0,homeDirectory:Q})),[yt,Q,Ms]),Js=l.useMemo(()=>[...lt,...wt],[wt,lt]),Xs=Xe(),Pn=l.useMemo(()=>`${Xs}|${he.map(N=>`${N.id}:${Re(N.path)??""}`).join("|")}`,[he,Xs]),Fs=l.useMemo(()=>{const N=new Set;let Z=!0;for(const se of he){const Le=Re(se.path);if(!Le)continue;const Oe=Ct.get(Le)?.status??"idle";Oe==="failed"&&N.add(Le),(Oe==="idle"||Oe==="loading")&&(Z=!1)}return{complete:Z,unresolved:N}},[he,Ct]),Tn=Fs.complete?Pn:null;Fs.complete;const O=Fs.unresolved,{isTablet:ce}=Cn(),ye=t||ce,$e=Dg({mobileVariant:t,isTablet:ce}),{buildGroupSearchText:ht,filterSessionNodesForSearch:Je,buildGroupedSessions:St}=Eg({homeDirectory:Q,pinnedSessionIds:X,sessionOrderRanks:ee}),{scheduleCollapsedProjectsPersist:Pt}=Tg({safeStorage:w,keys:{sessionExpanded:gl,projectCollapse:fl,groupOrder:hl,groupCollapse:pl},groupOrderByProject:V,collapsedGroups:me,setExpandedParents:A,setCollapsedProjects:v}),ys=l.useMemo(()=>Gf(lt,X,ee),[X,ee,lt]),Mn=l.useMemo(()=>ys.map(N=>N.id).join("|"),[ys]),hr=l.useRef(null),de=l.useMemo(()=>{const N=hr.current;if(N&&N.signature===Mn)return N.map;const Z=new Map(ys.map((se,Le)=>[se.id,Le]));return hr.current={signature:Mn,map:Z},Z},[ys,Mn]),zt=l.useMemo(()=>{const N=new Map;ys.forEach(se=>{const Le=se.parentID;if(!Le)return;const Oe=N.get(Le)??[];Oe.push(se),N.set(Le,Oe)});const Z=Hl(X,ee);return N.forEach(se=>se.sort(Z)),N},[ys,X,ee]),Zs=l.useMemo(()=>s.jsx(qt,{icon:"chat-new",mobileVariant:t,onClick:()=>At(),children:"New session"}),[t,At]),Fn=l.useMemo(()=>he.find(N=>N.id===x)??null,[he,x]),pr=l.useCallback(N=>{x&&U(x,{label:N.label,defaultModel:N.defaultModel??null})},[x,U]),en=l.useCallback(()=>{const N=Rr.getState();if(N.available&&N.info){F(!0);return}at.checkForUpdates().then(()=>{const{available:Z,error:se}=Rr.getState();if(se){oe.error("Failed to check for updates",{description:se});return}if(!Z){oe.success("You are on the latest version");return}F(!0)})},[at]),tn=Hf(),Gi=l.useCallback(()=>{if(t&&Ze(!1),r?.(),tn?.openSettings){tn.openSettings();return}_e(!0)},[tn,t,r,Ze,_e]),bd=at.available&&(at.runtimeType==="desktop"||at.runtimeType==="web"),xd=Me(N=>N.deleteSession),Hi=Me(N=>N.deleteSessions),yd=Me(N=>N.unarchiveSession),wd=Me(N=>N.unarchiveSessions),{copiedSessionId:vd,handleSessionSelect:Sd,handleSessionDoubleClick:jd,handleSaveEdit:kd,handleCancelEdit:Cd,handleShareSession:Ad,handleCopyShareUrl:Nd,handleCopySessionId:Id,handleUnshareSession:Ed,handleDeleteSession:Dd,handleRestoreSession:Rd,confirmDeleteSession:Pd}=Pg({mobileVariant:t,allowReselect:o,onSessionSelected:n,isSessionSearchOpen:c,sessionSearchQuery:u,setSessionSearchQuery:f,setIsSessionSearchOpen:d,setActiveMainTab:ne,setSessionSwitcherOpen:Ze,setCurrentSession:Rt,updateSessionTitle:Qs,shareSession:Ps,unshareSession:Ts,deleteSession:xd,deleteSessions:Hi,unarchiveSession:yd,childrenMap:zt,showDeletionDialog:gt,setDeleteSessionConfirm:ae,deleteSessionConfirm:L,setEditingId:h,setEditTitle:y,editingId:b,editTitle:p}),Td=l.useCallback(()=>{if(!J)return;const{scopeKey:N,folderId:Z}=J;le(null),Ve(N,Z)},[J,Ve]),ao=l.useCallback(()=>{sr.requestDirectoryDialog()},[]),Md=l.useCallback(N=>{A(Z=>{const se=tp(Z,N);try{w.setItem(gl,JSON.stringify(Array.from(se)))}catch{}return se})},[w]),qi=l.useCallback((N,Z)=>{if(!N)return null;Z&&He.has(Z)&&xt(Z);const se=Ot(N,"New folder",Z);return M(se.id),W(se.name),se},[He,xt,Ot]),Ln=Tt(Sd),Fd=Tt(jd),Ld=Tt(kd),Od=Tt(Cd),Bd=Tt(Ad),_d=Tt(Nd),zd=Tt(Id),Ud=Tt(Ed),$d=Tt(Dd),Kd=Tt(Rd),lo=Tt(qi),Vi=l.useCallback((N,Z)=>{q(se=>{const Le=new Map(se);return Le.set(N,Z+7),Le})},[]),mr=l.useCallback(N=>{q(Z=>{if(!Z.has(N))return Z;const se=new Map(Z);return se.delete(N),se})},[]),Yi=l.useCallback(N=>{q(Z=>{let se=!1;const Le=new Map(Z),Oe=`${N}:`;for(const tt of Le.keys())tt.startsWith(Oe)&&(Le.delete(tt),se=!0);return se?Le:Z})},[]),co=l.useCallback(N=>{ke.current=Date.now()+150,Yi(N),v(Z=>{const se=new Set(Z);se.has(N)?se.delete(N):se.add(N);try{w.setItem(fl,JSON.stringify(Array.from(se)))}catch{}return Pt(se),se})},[Yi,w,Pt]),Qi=l.useRef(null);l.useEffect(()=>{const N=Qi.current;Qi.current=Se,Qe==="folder"&&(!N||!Se||N===Se||S.has(Se)&&co(Se))},[Se,S,Qe,co]);const Ls=l.useMemo(()=>he.map(N=>({...N,normalizedPath:Re(N.path)})).filter(N=>!!N.normalizedPath),[he]),Wd=l.useMemo(()=>Ls.map(N=>N.normalizedPath),[Ls]),Ji=qf(e?Wd:Fo);_g({enabled:e,normalizedProjects:Ls,gitRepoStatus:Ji,setProjectRepoStatus:z,setProjectRootBranches:Be});const Gd=l.useMemo(()=>qg(lt,Ls,nt,wt),[wt,nt,Ls,lt]);Kg({enabled:e,hasAuthoritativeGlobalSessions:as,sessions:Js});const{getSessionsForProject:Hd,getArchivedSessionsForProject:Xi}=zg({ownership:Gd}),uo=l.useRef(!1);Se&&P.has(Se)&&(uo.current=!!P.get(Se));const fo=ot(N=>N.manualProjectOrder),Zi=l.useRef(new Set),gr=sp(Zi.current,j,"project");Zi.current=gr;const ho={isVisible:e,mobileVariant:t,onSessionSelected:n,allowReselect:o,hideDirectoryControls:i,showOnlyMainWorkspace:a,isTablet:ce,catalogSessions:yt,archivedSessions:wt,projects:he,activeProjectId:Se,manualProjectOrder:fo,currentDirectory:ve,availableWorktreesByProject:nt,pinnedSessionIds:X,sessionOrderRanks:ee,foldersMap:ft,collapsedFolderIds:He,gitBranches:Xt,gitRepoStatus:Ji,updateStore:at,projectRepoStatus:P,projectRootBranches:re,resolvedWorktreeTopologyKey:Tn,unresolvedWorktreeProjectPaths:O,isSessionSearchOpen:c,sessionSearchQuery:u,editingId:b,editTitle:p,editingProjectDialogId:x,expandedParents:j,collapsedProjects:S,visibleSessionCountByGroup:K,updateDialogOpen:H,openSidebarMenuKey:D,renamingFolderId:I,renameFolderDraft:G,deleteSessionConfirm:L,deleteFolderConfirm:J,bulkDeleteConfirm:B,collapsedGroups:me},ea=l.useRef(null),ta=ea.current;if(ta){let N=!1;for(const Z of Object.keys(ho))Object.is(ta[Z],ho[Z])||(Ht(`ui.session_sidebar.source.${Z}`),N=!0);N||Ht("ui.session_sidebar.source.parent_or_context")}ea.current=ho;const sa=l.useMemo(()=>{const N=new Map(fo.map((Z,se)=>[Z,se]));return[...Ls].sort((Z,se)=>(N.get(Z.id)??1/0)-(N.get(se.id)??1/0))},[fo,Ls]),{projectSections:ws,groupSearchDataByGroup:na,sectionsForRender:qd,flatSectionsForRender:po,searchMatchCount:Vd}=hg({normalizedProjects:sa,getSessionsForProject:Hd,getArchivedSessionsForProject:Xi,availableWorktreesByProject:nt,projectRepoStatus:P,projectRootBranches:re,lastRepoStatus:uo.current,buildGroupedSessions:St,hasSessionSearchQuery:De,normalizedSessionSearchQuery:Ne,filterSessionNodesForSearch:Je,buildGroupSearchText:ht,foldersMap:ft,alwaysIncludeArchived:Qe==="timeline"}),On=l.useMemo(()=>{const se=(De||Qe==="timeline"?[...lt,...wt]:lt).filter(Oe=>or(gn(Oe),Q));if(se.length===0)return null;const Le=St(se,"~",[],null,!1).map(Oe=>De?{...Oe,sessions:Je(Oe.sessions,Ne)}:Oe).filter(Oe=>Oe.sessions.length>0);return Le.length===0?null:{project:{id:"__home__",path:"~",normalizedPath:"~",label:"No folder"},groups:Le}},[wt,St,Je,De,Q,Ne,lt,Qe]),Yd=l.useCallback(N=>or(gn(N),Q),[Q]),Qd=jg({viewMode:Qe,enabled:!De&&!a,projects:sa,archivedSessions:wt,getArchivedSessionsForProject:Xi,isGlobalSession:Yd,buildGroupedSessions:St,availableWorktreesByProject:nt,projectRepoStatus:P,projectRootBranches:re,lastRepoStatus:uo.current,selectedSpaceId:k,selectedWorktreePath:E,homeDirectory:Q}),Jd=l.useMemo(()=>{if(!De||!On)return 0;const N=Z=>Z.reduce((se,Le)=>se+1+N(Le.children),0);return On.groups.reduce((Z,se)=>Z+N(se.sessions),0)},[On,De]),Xd=l.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:Zd}=ug(V),{sectionsForSidebarRender:eu,filteredSectionsForSidebarRender:tu,totalSessionCount:su,sessionCountByProject:nu,hasActiveSessionByProject:ru,activeDirectoriesByProject:Bn,hasUnseenByProject:ou}=wg({projectSections:ws,flatSectionsForRender:po,sectionsForRender:qd,selectedSpaceId:k,selectedWorktreePath:E,homeDirectory:Q,activeSessionIdSet:pe,unreadSessionIdSet:be}),mo=l.useCallback(N=>{if(nn.getState().selectSpace(N),!N)return;Ue(N);const Z=ws.find(Oe=>Oe.project.id===N),se=Z?.groups.find(Oe=>Oe.isMain),Le=se?.sessions[0]?.session;Le?Ln(Le.id,se?.directory??Z?.project.normalizedPath??null,{keepPanelOpen:!0}):Z&&At({selectedProjectId:N,directoryOverride:Z.project.normalizedPath})},[At,ws,Ue,Ln]),iu=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",au=t?"size-5":"size-4",br=Tt((N,Z=0,se,Le,Oe=!1,tt,vs="project",sn)=>s.jsx($x,{node:N,depth:Z,groupDirectory:se,projectId:Le,archivedBucket:Oe,pinnedSessionIds:X,expandedParents:gr,hasSessionSearchQuery:De,normalizedSessionSearchQuery:Ne,editingId:b,setEditingId:h,editTitle:p,setEditTitle:y,handleSaveEdit:Ld,handleCancelEdit:Od,toggleParent:Md,handleSessionSelect:Ln,handleSessionDoubleClick:Fd,togglePinnedSession:ze,handleShareSession:Bd,copiedSessionId:vd,handleCopyShareUrl:_d,handleCopySessionId:zd,handleUnshareSession:Ud,openSidebarMenuKey:D,setOpenSidebarMenuKey:T,renamingFolderId:I,getFoldersForScope:os,getSessionFolderId:it,removeSessionFromFolder:Dt,addSessionToFolder:is,createFolderAndStartRename:lo,handleDeleteSession:$d,handleRestoreSession:Kd,mobileVariant:t,alwaysShowActions:ye,allowQuickArchiveAction:$e,renderSessionNode:br,secondaryMeta:tt,renderContext:vs,subtreeContainsEditing:sn?.subtreeContainsEditing??ty,menuOpenSessionId:sn?.menuOpenSessionId??null,nodeStructureKey:sn?.nodeStructureKey??"",childRenderExtrasFor:sn?.childRenderExtrasFor})),lu=l.useMemo(()=>{const N=new Map;return po.forEach(Z=>{const se=Z.groups[0];se?.folderScopes&&se.folderScopes.length>0&&N.set(Z.project.id,se.folderScopes)}),N},[po]),cu=l.useCallback((N,Z)=>{const se=[];return Z.forEach(Le=>{se.push(Le.directory),Le.folderScopes?.forEach(Oe=>se.push(Oe.directory))}),s.jsx(Yx,{directories:se})},[]),ra=l.useCallback(N=>{mr(N),Pe(Z=>{const se=new Set(Z);return se.has(N)?se.delete(N):se.add(N),se})},[mr]),du=l.useCallback((N,Z,se,Le,Oe,tt)=>s.jsx(Mb,{group:N,groupKey:Z,projectId:se,hideGroupLabel:Le,dragHandleProps:Oe,compactBodyPadding:tt,hasSessionSearchQuery:De,normalizedSessionSearchQuery:Ne,groupSearchDataByGroup:na,visibleSessionCount:K.get(Z),collapsedGroups:me,hideDirectoryControls:i,collapsedFolderIds:He,toggleFolderCollapse:xt,renameFolder:Bt,deleteFolder:Ve,showDeletionDialog:gt,setDeleteFolderConfirm:le,renderSessionNode:br,showMoreGroupSessions:Vi,resetGroupSessionLimit:mr,mobileVariant:t,alwaysShowActions:ye,activeProjectId:Se,setActiveProjectIdOnly:Ue,setActiveMainTab:ne,setSessionSwitcherOpen:Ze,openNewSessionDraft:At,addSessionToFolder:is,createFolderAndStartRename:lo,renamingFolderId:I,renameFolderDraft:G,setRenameFolderDraft:W,setRenamingFolderId:M,pinnedSessionIds:X,expandedParents:gr,sessionOrderIndex:de,editingId:b,editTitle:p,openSidebarMenuKey:D,activeActivitySessionIds:pe,unreadActivitySessionIds:be,onToggleCollapsedGroup:ra}),[De,Ne,na,K,me,i,He,xt,Bt,Ve,gt,br,Vi,mr,t,ye,Se,Ue,ne,Ze,At,is,lo,I,G,X,gr,de,b,p,D,pe,be,ra]),oa=!!(I||b||x),ia=l.useRef(lt);ia.current=lt;const uu=l.useCallback(N=>ia.current.find(Z=>Z.id===N)?.directory??null,[]),{selectionModeEnabled:go,hasSelection:aa,selectedIdsSize:fu,bulkScopeIsArchived:hu,derivedSelectionScope:pu,bulkScopeFolders:mu,bulkCanRemoveFromFolder:gu,handleToggleSelectionMode:bu,handleExitSelectionMode:xu,handleBulkMoveToFolder:yu,handleBulkCreateFolderAndMove:wu,handleBulkRemoveFromFolder:vu,handleBulkDelete:Su,handleBulkRestore:ju,confirmBulkDelete:ku}=Xx({isInlineEditing:oa,showDeletionDialog:gt,foldersMap:ft,folderScopesByProject:lu,addSessionsToFolder:Rs,removeSessionsFromFolders:Ys,createFolderAndStartRename:qi,resolveSessionDirectory:uu,unarchiveSessions:wd,deleteSessions:Hi,setBulkDeleteConfirm:$}),la=l.useCallback(()=>{ue.getState().closeMainSurfaces(),ne("chat"),t&&Ze(!1),vt(),r?.()},[t,r,vt,ne,Ze]),Cu=l.useCallback((N,Z)=>{const se=he.find(tt=>tt.id===N);if(!se)return;const Le=Re(Z.path)?.toLowerCase(),Oe=!!(Le&&Bn.get(N)?.has(Le));Y({projectId:N,projectPath:se.path,worktree:Z,hasActiveSession:Oe})},[Bn,he]),Au=l.useCallback(async({force:N})=>{const Z=Ie;if(!Z)return;const se=Re(Z.worktree.path)?.toLowerCase();if(!!(se&&Bn.get(Z.projectId)?.has(se))){Y({...Z,hasActiveSession:!0}),oe.warning("Stop the active session before closing this worktree.");return}if(!_t.deleteGitWorktree){oe.error("Closing worktrees is not supported by this runtime.");return}try{if(!(await _t.deleteGitWorktree(Z.projectPath,{directory:Z.worktree.path,force:N}))?.success)throw new Error("Git worktree removal was not confirmed by the server.");let tt=await ls(Z.projectPath,_t,{force:!0});const vs=Re(Z.worktree.path);tt!==null&&vs!==null&&tt.some(Iu=>Re(Iu.path)===vs)&&(tt=await ls(Z.projectPath,_t,{force:!0}));const sn=vs!==null&&Re(ve)===vs,Nu=vs!==null&&k===Z.projectId&&Re(E)===vs;(sn||Nu)&&mo(Z.projectId),Y(null),tt===null?oe.warning("Worktree closed, but the sidebar could not be refreshed."):oe.success("Worktree closed.")}catch(Oe){const tt=Oe instanceof Error?Oe.message:"Try again.";oe.error("Failed to close worktree.",{description:tt})}},[Bn,Ie,ve,_t,mo,ls,k,E]);return s.jsx(Vf,{delay:400,closeDelay:150,timeout:600,children:s.jsxs("div",{ref:m,className:_("relative flex h-full flex-col text-foreground overflow-x-hidden",t?"":"bg-transparent"),children:[s.jsx(Cg,{projectSections:ws,activeProjectId:Se,initialActiveSessionByProject:xe,persistActiveSessionByProject:te,handleSessionSelect:Ln,mobileVariant:t,openNewSessionDraft:vt,setActiveMainTab:ne,setSessionSwitcherOpen:Ze}),!i&&!t?s.jsx(Lb,{onNewSession:la,showSidebarToggle:!0}):null,s.jsx(Fb,{hideDirectoryControls:i,handleOpenDirectoryDialog:ao,onOpenArchive:()=>{t&&Ze(!1),Jt(!0)},onOpenSettings:t?Gi:void 0,onOpenInstances:t?tn?.openInstances:void 0,instanceLabel:t?tn?.instanceLabel:void 0,onOpenUpdate:t?tn?.openUpdate:void 0,headerActionIconClass:au,headerActionButtonClass:iu,isSessionSearchOpen:c,setIsSessionSearchOpen:d,sessionSearchInputRef:g,sessionSearchQuery:u,setSessionSearchQuery:f,hasSessionSearchQuery:De,searchMatchCount:Vd+(Qe!=="workspace"||k===null?Jd:0),selectionModeEnabled:go,onToggleSelectionMode:bu,mobileVariant:t,onClose:t?()=>Ze(!1):void 0}),xs==="error"||xs==="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&&ws.length>0&&Qe==="workspace"?s.jsx(_b,{projects:ws.map(N=>N.project),selectedProjectId:k,selectedWorktreePath:E,worktreesByProject:nt,worktreeErrorsByProject:cs,onSelectProject:mo,onSelectWorktree:(N,Z)=>{nn.getState().selectWorktree(N,Z),Ue(N);const Oe=ws.find(tt=>tt.project.id===N)?.groups.find(tt=>Re(tt.directory)===Re(Z))?.sessions[0]?.session;Oe?Ln(Oe.id,Z,{keepPanelOpen:!0}):At({selectedProjectId:N,directoryOverride:Z})},onCloseWorktree:Cu,onOpenDirectoryDialog:ao,onOpenProjectEditDialog:C,onRemoveProject:qe,totalSessionCount:su,getSessionCountForProject:N=>nu.get(N)??0,hasActiveSessionByProject:ru,activeDirectoriesByProject:Bn,hasUnseenByProject:ou,homeDirectory:Q,mobileVariant:t}):null,s.jsx(fx,{viewMode:Qe,timelineBoundaries:kt,onOpenDirectoryDialog:ao,stickyFolderHeaders:Ee,sectionsForRender:Qe==="workspace"?tu:eu,allFoldersOnlySection:Qe==="workspace"?k===null?On:null:On,isAllFoldersView:Qe==="workspace"?k===null:Qe==="timeline",projectSections:ws,activeProjectId:Se,showOnlyMainWorkspace:a,hasSessionSearchQuery:De,emptyState:Zs,searchEmptyState:Xd,pinnedSessionIds:X,archivedShelfItems:Qd,renderSessionNode:br,renderGroupSessions:du,homeDirectory:Q,collapsedProjects:S,hideDirectoryControls:i,projectRepoStatus:P,mobileVariant:t,alwaysShowActions:ye,toggleProject:co,setActiveProjectIdOnly:Ue,setActiveMainTab:ne,setSessionSwitcherOpen:Ze,openNewSessionDraft:At,openProjectEditDialog:C,removeProject:qe,reorderProjects:ge,getOrderedGroups:Zd,setGroupOrderByProject:fe,renderProjectStatusIndicator:cu,openSidebarMenuKey:D,setOpenSidebarMenuKey:T,isInlineEditing:oa}),t&&!(go&&aa)?s.jsxs("div",{className:"flex shrink-0 flex-col gap-2 px-4 pb-[calc(0.75rem+var(--oc-safe-area-bottom,0px))] pt-2",children:[s.jsx(Rc,{variant:"mobile"}),s.jsxs(Ae,{type:"button",variant:"default",size:"lg",className:"w-full",onClick:la,children:[s.jsx(R,{name:"chat-new",className:"size-4"}),"New session"]})]}):null,go&&aa?s.jsx(Qx,{selectedCount:fu,scopeKey:pu,scopeFolders:mu,archivedBucket:hu,onMoveToFolder:yu,onCreateFolderAndMove:wu,onRemoveFromFolder:vu,canRemoveFromFolder:gu,onRestore:ju,onDelete:Su,onDone:xu}):null,t?null:s.jsx(zb,{onOpenSettings:Gi,onOpenShortcuts:mt,onOpenAbout:()=>{rt("about"),_e(!0)},onOpenUpdate:en,showRuntimeButtons:!0,showUpdateButton:bd}),s.jsx(Vx,{updateDialogOpen:H,setUpdateDialogOpen:F,updateStore:at,editingProject:Fn,setEditingProjectDialogId:C,handleSaveProjectEdit:pr,deleteSessionConfirm:L,setDeleteSessionConfirm:ae,showDeletionDialog:gt,setShowDeletionDialog:Et,confirmDeleteSession:Pd,deleteFolderConfirm:J,setDeleteFolderConfirm:le,confirmDeleteFolder:Td,closeWorktreeConfirm:Ie,setCloseWorktreeConfirm:Y,confirmCloseWorktree:Au,bulkDeleteConfirm:B,setBulkDeleteConfirm:$,confirmBulkDelete:ku})]})})},nS=l.memo(sy),bl=6,Mt=.18,Hn=1.2,qn=.38,Lr=48,ny=(e,t)=>e==="left"?t<0:t>0,rS=(e,t,n)=>Math.min(1,Math.max(0,e==="left"?1+t/n:1-t/n)),oS=(e,t)=>t>=.999?"none":e==="left"?`translateX(${(t-1)*100}%)`:`translateX(${(1-t)*100}%)`,xl=(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)),iS=e=>{const{side:t,dx:n,dy:r,dt:o,progress:i,isDragging:a}=e,c=n/Math.max(1,o);if(a){const d=t==="left"?c<-Mt:c>Mt,u=t==="left"?c>Mt:c<-Mt;return d||!u&&i<qn}return Math.abs(n)>=Lr&&Math.abs(r)<=Math.abs(n)*Hn&&ny(t,n)},ry=e=>{const{side:t,isOpenAtStart:n,dx:r,dt:o,progress:i}=e,a=r/Math.max(1,o);return t==="left"?n?a<-Mt?!1:a>Mt?!0:i>qn:a>Mt?!0:a<-Mt?!1:i>qn:n?a>Mt?!1:a<-Mt?!0:i>qn:a<-Mt?!0:a>Mt?!1:i>qn},oy='button, a, input, textarea, select, [contenteditable="true"], [data-no-drawer-swipe]',iy=(e,t,n)=>{if(!(e instanceof Element))return!1;if(n?.excludeInteractive??!0){const i=e.closest(oy);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},Or=Object.freeze({chunks:Object.freeze([]),byteLength:0,lastSequence:-1}),Ii=512*1024,ay=new TextEncoder,ly=new TextDecoder,Lo=e=>{const t=ay.encode(e);if(t.byteLength<=Ii)return{text:e,byteLength:t.byteLength};let n=t.byteLength-Ii;for(;n<t.byteLength&&(t[n]&192)===128;)n+=1;const r=t.subarray(n);return{text:ly.decode(r),byteLength:r.byteLength}},ln=(e,t)=>`${e}\0${t}`,Oo=(e,t)=>{let n=null;for(const r of e.keys())t(r)&&(n??=new Map(e),n.delete(r));return n},cy="terminal-store";let yl=!1,wl=0;const Dr=()=>typeof globalThis.crypto?.randomUUID=="function"?`tab-${globalThis.crypto.randomUUID()}`:(wl+=1,`tab-${Date.now().toString(36)}-${wl.toString(36)}`),Bo=e=>typeof e=="object"&&e!==null,dy=e=>{const t=/^tab-(\d+)$/.exec(e);if(!t)return null;const n=Number(t[1]);return Number.isFinite(n)?n:null};function ct(e){let t=e.trim();for(;t.length>1&&t.endsWith("/");)t=t.slice(0,-1);return t}const uy=/^Terminal(?: (\d+))?$/,fy=e=>{let t=0;for(const n of e){const r=uy.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}`},_o=(e,t)=>({id:e,terminalSessionId:null,lifecycle:"idle",label:t,iconKey:null,isConnecting:!1,createdAt:Date.now(),previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1}),zo=e=>({tabs:[e],activeTabId:e.id}),$t=(e,t)=>e.tabs.findIndex(n=>n.id===t);let Uo=null,$o=null;const hy=e=>{if($o&&Uo?.sessions===e.sessions&&Uo.nextTabId===e.nextTabId)return $o;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 Uo={sessions:e.sessions,nextTabId:e.nextTabId},$o=t,t},py=()=>{const e=np(()=>Ph());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))}},we=bs()(Zr(mc((e,t)=>({sessions:new Map,buffers:new Map,projectActionRuns:{},nextChunkId:1,nextTabId:1,hasHydrated:typeof window>"u",ensureDirectory:n=>{const r=ct(n);r&&e(o=>{if(o.sessions.has(r))return o;const i=new Map(o.sessions),a=Dr(),c=_o(a,"Terminal");return i.set(r,zo(c)),{sessions:i,nextTabId:o.nextTabId+1}})},getDirectoryState:n=>{const r=ct(n);return t().sessions.get(r)},getActiveTab:n=>{const r=ct(n),o=t().sessions.get(r);if(!o)return;const i=o.activeTabId;return i?o.tabs.find(a=>a.id===i)??o.tabs[0]:o.tabs[0]},getBuffer:(n,r)=>t().buffers.get(ln(ct(n),r))??Or,createTab:n=>{const r=ct(n);if(!r)return"tab-invalid";const o=Dr();return e(i=>{const a=new Map(i.sessions),c=a.get(r),d=i.nextTabId+1,u=fy(c?.tabs??[]),f=_o(o,u);return c?a.set(r,{...c,tabs:[...c.tabs,f]}):a.set(r,zo(f)),{sessions:a,nextTabId:d}}),o},setActiveTab:(n,r)=>{const o=ct(n);e(i=>{const a=new Map(i.sessions),c=a.get(o);return!c||c.activeTabId===r||$t(c,r)<0?i:(a.set(o,{...c,activeTabId:r}),{sessions:a})})},setTabLabel:(n,r,o)=>{const i=ct(n),a=o.trim();a&&e(c=>{const d=new Map(c.sessions),u=d.get(i);if(!u)return c;const f=$t(u,r);if(f<0||u.tabs[f]?.label===a)return c;const m=[...u.tabs];return m[f]={...m[f],label:a},d.set(i,{...u,tabs:m}),{sessions:d}})},setTabIconKey:(n,r,o)=>{const i=ct(n);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=$t(d,r);if(u<0)return a;const f=o?.trim()||null;if(d.tabs[u]?.iconKey===f)return a;const m=[...d.tabs];return m[u]={...m[u],iconKey:f},c.set(i,{...d,tabs:m}),{sessions:c}})},closeTab:(n,r)=>{const o=ct(n);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const d=$t(c,r);if(d<0)return i;const u=c.tabs.filter(p=>p.id!==r),f=Object.fromEntries(Object.entries(i.projectActionRuns).filter(([,p])=>!(p.directory===o&&p.tabId===r))),m=Object.keys(f).length!==Object.keys(i.projectActionRuns).length,g=ln(o,r),b=i.buffers.has(g)?Oo(i.buffers,p=>p===g):null;if(u.length===0){const p=Dr(),y=_o(p,"Terminal");return a.set(o,zo(y)),{sessions:a,nextTabId:i.nextTabId+1,...b?{buffers:b}:{},...m?{projectActionRuns:f}:{}}}let h=c.activeTabId;return c.activeTabId===r&&(h=u[Math.min(d,u.length-1)]?.id??u[0]?.id??null),a.set(o,{...c,tabs:u,activeTabId:h}),{sessions:a,...b?{buffers:b}:{},...m?{projectActionRuns:f}:{}}})},setTabSessionId:(n,r,o)=>{const i=ct(n);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=$t(d,r);if(u<0)return a;const f=d.tabs[u],m=o!==null&&f.terminalSessionId!==o,g=o?"running":f.terminalSessionId?"exited":f.lifecycle,b={...f,terminalSessionId:o,lifecycle:g,isConnecting:!1},h=ln(i,r),p=m&&a.buffers.has(h)?Oo(a.buffers,x=>x===h):null,y=[...d.tabs];return y[u]=b,c.set(i,{...d,tabs:y}),{sessions:c,...p?{buffers:p}:{}}})},setTabLifecycle:(n,r,o)=>{const i=ct(n);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=$t(d,r);if(u<0)return a;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=ct(n);e(a=>{const c=new Map(a.sessions),d=c.get(i);if(!d)return a;const u=$t(d,r);if(u<0)return a;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 a=ct(n);e(c=>{const d=c.sessions.get(a);if(!d||$t(d,r)<0)return c;const u=ln(a,r),f=c.buffers.get(u)??Or;if(f.lastSequence>i)return c;const m=Lo(o);if(f.lastSequence===i&&f.byteLength===m.byteLength&&f.chunks.map(h=>h.data).join("")===m.text)return c;const g=c.nextChunkId,b=new Map(c.buffers);return b.set(u,{chunks:m.text?[{id:g,data:m.text,byteLength:m.byteLength}]:[],byteLength:m.byteLength,lastSequence:i}),{buffers:b,nextChunkId:m.text?g+1:g}})},appendToBuffer:(n,r,o,i,a)=>{if(!o)return;const c=ct(n);e(d=>{const u=d.sessions.get(c);if(!u||$t(u,r)<0)return d;const f=ln(c,r),m=d.buffers.get(f)??Or;if(i!==void 0&&i<=m.lastSequence)return d;const g=d.nextChunkId,b=Lo(o),h=a!==void 0&&a!==o?Lo(a).text:void 0,p={id:g,data:b.text,...h!==void 0?{replayData:h}:{},byteLength:b.byteLength},y=[...m.chunks,p];let x=m.byteLength+p.byteLength;for(;x>Ii&&y.length>1;){const j=y.shift();if(!j)break;x-=j.byteLength}const C=new Map(d.buffers);return C.set(f,{chunks:y,byteLength:x,lastSequence:i??m.lastSequence}),{buffers:C,nextChunkId:g+1}})},setTabPreviewUrl:(n,r,o,i={})=>{const a=ct(n);e(c=>{const d=new Map(c.sessions),u=d.get(a);if(!u)return c;const f=$t(u,r);if(f<0)return c;const m=u.tabs[f],g=i.autoOpened??m.previewAutoOpened,b=i.locked??m.previewUrlLocked;if(m.previewUrl===o&&m.previewAutoOpened===g&&m.previewUrlLocked===b)return c;const h=[...u.tabs];return h[f]={...m,previewUrl:o,previewAutoOpened:g,previewUrlLocked:b},d.set(a,{...u,tabs:h}),{sessions:d}})},markPreviewAutoOpened:(n,r)=>{const o=ct(n);e(i=>{const a=new Map(i.sessions),c=a.get(o);if(!c)return i;const d=$t(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},a.set(o,{...c,tabs:f}),{sessions:a}})},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=ct(n);e(o=>{const i=new Map(o.sessions);i.delete(r);const a=ln(r,""),c=Oo(o.buffers,u=>u.startsWith(a)),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:cy,storage:py(),partialize:hy,merge:(e,t)=>{if(!Bo(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"||!Bo(u))continue;const f=Array.isArray(u.tabs)?u.tabs:[],m=[],g=new Map;for(const y of f){if(!Bo(y))continue;const x=typeof y.id=="string"?y.id:null;if(!x)continue;const C=dy(x);C!==null&&(o=Math.max(o,C));const j=C===null?x:Dr();g.set(x,j),m.push({id:j,label:typeof y.label=="string"?y.label:"Terminal",iconKey:typeof y.iconKey=="string"?y.iconKey:null,terminalSessionId:null,lifecycle:"idle",createdAt:typeof y.createdAt=="number"?y.createdAt:Date.now(),isConnecting:!1,previewUrl:null,previewAutoOpened:!1,previewUrlLocked:!1})}if(m.length===0)continue;const b=typeof u.activeTabId=="string"?u.activeTabId:null,h=b?g.get(b)??b:null,p=h?m.some(y=>y.id===h):!1;r.set(d,{tabs:m,activeTabId:p?h:m[0].id})}const i=typeof e.nextTabId=="number"&&Number.isFinite(e.nextTabId)?e.nextTabId:1,a=Math.max(t.nextTabId,i,o+1);return{...t,sessions:r,buffers:new Map,nextChunkId:1,nextTabId:a,hasHydrated:!0}}})));if(typeof window<"u"&&!yl){yl=!0;const e=we.persist,t=()=>{we.getState().hasHydrated||we.setState({hasHydrated:!0})};e?.hasHydrated?.()?t():e?.onFinishHydration?e.onFinishHydration(t):t()}const my=(e,t)=>{const n=`${e??""} ${t??""}`;return/mac|iphone|ipad|darwin/i.test(n)?"mac":"other"},gy=e=>e.key.length===1?e.key.toLowerCase():e.code==="KeyC"?"c":e.code==="KeyV"?"v":e.code==="Insert"?"insert":e.key.toLowerCase(),by=(e,t,n)=>{if(e.altKey)return null;const r=gy(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},Vn=e=>typeof e=="string"&&e.trim().length>0;async function vl(e){return Vn(e)?(await hs(e)).ok:!1}async function xy(){if(typeof navigator>"u"||!navigator.clipboard?.readText)return null;try{return await navigator.clipboard.readText()||null}catch{return null}}const yy=(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),a=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,a))}},wy=(e,t)=>{const n=Math.max(0,Math.min(e.length-1,t)),r=a=>!!(a&&!/^\s+$/u.test(a));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 vy=null;const Sy=()=>vy??=Promise.all([pt(()=>import("./vendor-xterm-xterm-B-qIQCd3.js"),[]),pt(()=>import("./vendor-xterm-addon-fit-DX4qG4td.js"),[])]).then(([e,t])=>({Xterm:e,Fit:t})),jy=2e3,ky=()=>{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,jy))]).then(()=>{})},Cy=(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),a=Math.ceil((o.actualBoundingBoxAscent||n*.8)+(o.actualBoundingBoxDescent||n*.2))+2;if(i<1||a<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)/a))}},hd=l.forwardRef(({sessionKey:e,chunks:t,onInput:n,onResize:r,theme:o,fontFamily:i,fontSize:a,className:c,enableTouchScroll:d=!1,autoFocus:u=!0,isVisible:f=!0},m)=>{const g=l.useRef(null),b=l.useRef(null),h=l.useRef(null),p=l.useRef(n),y=l.useRef(r),x=l.useRef(o),C=l.useRef(i),j=l.useRef(a),A=l.useRef(null),w=l.useRef(null),S=l.useRef(null),v=l.useRef(""),k=l.useRef(!1),E=l.useRef(0),P=l.useRef(f),z=l.useRef(!1),[K,q]=l.useState(0),[H,F]=l.useState(0),[D,T]=l.useState(!1),[I,M]=l.useState(!1);p.current=n,y.current=r,P.current=f,x.current=o,C.current=i,j.current=a,l.useLayoutEffect(()=>{const Y=g.current;if(!Y)return;const B=Cy(Y,i,a);w.current=B,B&&y.current(B.cols,B.rows)},[i,a]);const G=l.useCallback(()=>{const Y=g.current,B=b.current;if(!Y||!B||!h.current||!P.current)return;const $=Y.getBoundingClientRect();if(!($.width<24||$.height<24))try{h.current.fit();const X={cols:B.cols,rows:B.rows};(!A.current||A.current.cols!==X.cols||A.current.rows!==X.rows)&&(A.current=X,y.current(X.cols,X.rows)),z.current||(z.current=!0,q(ee=>ee+1))}catch{}},[]),W=l.useCallback(()=>{if(k.current||!v.current||!b.current)return;const Y=b.current,B=v.current;if(v.current="",!B)return;k.current=!0;const $=E.current;Y.write(B,()=>{b.current!==Y||E.current!==$||(k.current=!1,v.current&&W())})},[]),L=l.useCallback(()=>{S.current=null,v.current="",k.current=!1,E.current+=1;const Y=b.current;if(!Y){F(B=>B+1);return}try{Y.reset()}catch{F(B=>B+1)}},[]),ae=l.useCallback(Y=>{Y?.preventDefault(),M(Vn(b.current?.getSelection())),T(!0)},[]),J=l.useCallback(Y=>{Y.stopPropagation();const B=b.current,$=B?.getSelection()??"";B?.focus(),Vn($)&&vl($)},[]),le=l.useCallback(Y=>{Y.stopPropagation();const B=b.current;B?.focus(),xy().then($=>{$&&b.current===B&&B&&B.paste($)})},[]),Ie=l.useCallback(Y=>{Y.stopPropagation();const B=b.current;B?.focus();try{B?.selectAll()}catch{}M(Vn(B?.getSelection()))},[]);return l.useEffect(()=>{const Y=g.current;if(!Y)return;let B=!1,$=null,X=null,ee=null,ie=null,Ce=[];const pe=()=>{$&&P.current&&($.options.cursorBlink=!0)},je=me=>{me.relatedTarget instanceof Node&&Y.contains(me.relatedTarget)||$&&($.options.cursorBlink=!1)},be=()=>{$&&P.current&&Y.contains(document.activeElement)&&($.options.cursorBlink=!0)},ze=()=>{$&&($.options.cursorBlink=!1)};return Y.addEventListener("focusin",pe),Y.addEventListener("focusout",je),window.addEventListener("focus",be),window.addEventListener("blur",ze),Promise.all([Sy(),ky()]).then(([{Xterm:me,Fit:Pe}])=>{if(B)return;const V=x.current,fe=C.current,xe=j.current;$=new me.Terminal({...yo(fe,xe,V),...w.current??{}});const te=new Pe.FitAddon;$.loadAddon(te),$.open(Y),b.current=$,h.current=te;const re=typeof navigator>"u"?"other":my(navigator.userAgentData?.platform??navigator.platform??"",navigator.userAgent??""),Be=$;$.attachCustomKeyEventHandler(ke=>{if(ke.type!=="keydown")return!0;const Q=Be.getSelection(),ve=by({key:ke.key,code:ke.code,ctrlKey:ke.ctrlKey,shiftKey:ke.shiftKey,metaKey:ke.metaKey,altKey:ke.altKey},re,Vn(Q));return ve==="copy"?(vl(Q),!1):ve!=="ignore"}),Ce=[$.onData(ke=>p.current(ke))],X=new ResizeObserver(()=>{ee&&clearTimeout(ee),ee=setTimeout(G,80)}),X.observe(Y),G(),ie=requestAnimationFrame(G)}),()=>{B=!0;const me=document.activeElement;me instanceof HTMLElement&&Y.contains(me)&&(me.blur(),window.Capacitor?.getPlatform?.()==="android"&&pt(async()=>{const{Keyboard:V}=await import("./vendor-capacitor-keyboard-335osRpd.js");return{Keyboard:V}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:V})=>V.hide()).catch(()=>{})),X?.disconnect(),ee&&clearTimeout(ee),ie!==null&&cancelAnimationFrame(ie),Y.removeEventListener("focusin",pe),Y.removeEventListener("focusout",je),window.removeEventListener("focus",be),window.removeEventListener("blur",ze),Ce.forEach(Pe=>Pe.dispose()),$?.dispose(),b.current=null,h.current=null,A.current=null,S.current=null,v.current="",k.current=!1,E.current+=1,z.current=!1}},[G,H]),l.useEffect(()=>{const Y=b.current;Y&&(Y.options.theme=yo(i,a,o).theme,Y.options.fontFamily=yo(i,a,o).fontFamily,Y.options.fontSize=a)},[i,a,o]),l.useEffect(()=>{const Y=b.current,B=g.current;!Y||!B||(Y.options.cursorBlink=f&&document.hasFocus()&&B.contains(document.activeElement))},[f,K]),l.useEffect(()=>{if(!b.current)return;if(t.length===0){S.current!==null&&L();return}const B=S.current;let $=-1;if(B!==null){for(let ie=t.length-1;ie>=0;ie-=1){const Ce=t[ie].id;if(Ce===B){$=ie;break}if(Ce<B)break}if($<0){L();return}}const X=$<0,ee=$>=0?t.slice($+1):t;v.current+=ee.map(ie=>X?ie.replayData??ie.data:ie.data).join(""),S.current=t.at(-1)?.id??null,W()},[t,W,K,L]),l.useEffect(()=>{if(!u||!f)return;const Y=requestAnimationFrame(()=>b.current?.focus());return()=>cancelAnimationFrame(Y)},[u,f,K,e]),l.useEffect(()=>{const Y=g.current,B=b.current;if(!d||!Y||!B)return;let $=null,X=null,ee="idle",ie=0,Ce=0,pe=0,je=0,be=null;const ze=Math.max(12,a+2),me=()=>{window.Capacitor?.getPlatform?.()==="android"&&pt(async()=>{const{Keyboard:ve}=await import("./vendor-capacitor-keyboard-335osRpd.js");return{Keyboard:ve}},__vite__mapDeps([45,10,4,6])).then(({Keyboard:ve})=>ve.show()).catch(()=>{})},Pe=()=>{X&&(clearTimeout(X),X=null)},V=(Q,ve)=>{const he=Y.querySelector("canvas");return he?yy(Q,ve,he.getBoundingClientRect(),B.cols,B.rows):null},fe=(Q,ve)=>{const he=Y.querySelector("canvas");if(!he)return;const Se=he.getBoundingClientRect(),qe=Se.left+(ve.column+.5)/B.cols*Se.width,Ue=Se.top+(ve.row+.5)/B.rows*Se.height;he.dispatchEvent(new MouseEvent(Q,{bubbles:!0,cancelable:!0,button:0,buttons:1,clientX:qe,clientY:Ue}))},xe=()=>{document.dispatchEvent(new MouseEvent("mouseup",{bubbles:!0,cancelable:!0,button:0,buttons:0}))},te=Q=>{Q.pointerType!=="touch"||$!==null||($=Q.pointerId,ee="pending",ie=Q.clientX,Ce=Q.clientY,pe=Q.clientY,je=0,be=null,Y.setPointerCapture(Q.pointerId),X=setTimeout(()=>{if(X=null,$!==Q.pointerId||ee!=="pending")return;const ve=V(ie,Ce);if(!ve)return;const he=B.buffer.active,Se=Math.max(0,he.length-B.rows-he.viewportY+ve.row),qe=he.getLine(Se),Ue=Array.from({length:B.cols},(ne,_e)=>qe?.getCell(_e)?.getChars()??""),U=wy(Ue,ve.column),ge={column:U.startColumn,row:ve.row};be={column:U.endColumn,row:ve.row},ee="selecting",fe("mousedown",ge),fe("mousemove",be)},350))},re=Q=>{if($!==Q.pointerId)return;if(ee==="selecting"){const Se=V(Q.clientX,Q.clientY);Se&&(!be||Se.column!==be.column||Se.row!==be.row)&&(be=Se,fe("mousemove",Se)),Q.cancelable&&Q.preventDefault();return}if(ee==="pending"){if(Math.hypot(Q.clientX-ie,Q.clientY-Ce)<8)return;Pe(),ee="scrolling"}if(ee!=="scrolling")return;const ve=pe-Q.clientY;pe=Q.clientY,je+=ve;const he=Math.trunc(je/ze);he&&(B.scrollLines(he),je-=he*ze),Q.cancelable&&Q.preventDefault()},Be=Q=>{if($!==Q.pointerId)return;const ve=ee==="pending",he=ee==="selecting";Pe(),Y.hasPointerCapture(Q.pointerId)&&Y.releasePointerCapture(Q.pointerId),$=null,ee="idle",he&&xe(),ve&&(B.focus(),me())},ke=Q=>{if($!==Q.pointerId)return;const ve=ee==="selecting";Pe(),Y.hasPointerCapture(Q.pointerId)&&Y.releasePointerCapture(Q.pointerId),$=null,ee="idle",ve&&xe()};return Y.addEventListener("pointerdown",te),Y.addEventListener("pointermove",re,{passive:!1}),Y.addEventListener("pointerup",Be),Y.addEventListener("pointercancel",ke),()=>{Pe(),Y.removeEventListener("pointerdown",te),Y.removeEventListener("pointermove",re),Y.removeEventListener("pointerup",Be),Y.removeEventListener("pointercancel",ke)}},[d,a,K]),l.useImperativeHandle(m,()=>({focus:()=>b.current?.focus(),fit:G,getSelection:()=>{const Y=b.current,B=Y?.getSelectionPosition(),$=Y?.getSelection()??"";return!B||!$.trim()?null:{text:$,startLine:B.start.y+1,endLine:B.end.y+1}}}),[G]),s.jsxs(ro,{open:D,onOpenChange:T,children:[s.jsx(oo,{render:s.jsx("div",{ref:g,"data-terminal-owner":"main",className:_("terminal-viewport-container h-full w-full overflow-hidden touch-none",c),onContextMenu:ae})}),s.jsxs(io,{className:"min-w-[180px]",children:[s.jsxs(Ks,{disabled:!I,onClick:J,children:[s.jsx(R,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy"]}),s.jsxs(Ks,{onClick:le,children:[s.jsx(R,{name:"clipboard",className:"mr-2 h-4 w-4"})," ","Paste"]}),s.jsx(td,{}),s.jsx(Ks,{onClick:Ie,children:"Select all"})]})]})});hd.displayName="TerminalViewport";const Ay=({directory:e,tabId:t,sessionId:n,sessionKey:r,isActive:o,isTerminalVisible:i,terminal:a,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,lastViewportSizeRef:m,onInput:g,controllerRef:b})=>{const h=we(j=>e&&t?j.getBuffer(e,t).chunks:Or.chunks),p=l.useRef(null),y=o&&i,x=l.useCallback(j=>{p.current=j,b&&(b.current=o?j:b.current),!o&&b&&b.current===j&&(b.current=null)},[b,o]);l.useEffect(()=>{if(!o||!i)return;const j=requestAnimationFrame(()=>{p.current?.fit()});return()=>cancelAnimationFrame(j)},[o,i,r,n]);const C=l.useCallback((j,A)=>{if(!o)return;const w=m.current;(!w||w.cols!==j||w.rows!==A)&&(m.current={cols:j,rows:A}),n&&a.resize({sessionId:n,cols:j,rows:A}).catch(()=>{})},[o,m,n,a]);return s.jsx("div",{className:_("h-full w-full",o?"block":"hidden"),"aria-hidden":!o,children:s.jsx(hd,{ref:x,sessionKey:r,chunks:h,onInput:g,onResize:C,theme:c,fontFamily:d,fontSize:u,enableTouchScroll:f,autoFocus:y,isVisible:y},r)})},Sl=({items:e,activeId:t,onSelect:n,onClose:r,onCreate:o,disabled:i=!1})=>{const a=e.find(c=>c.id===t)??e[0]??null;return s.jsxs(Vt,{modal:!1,children:[s.jsx(Yt,{asChild:!0,children:s.jsxs(Ae,{type:"button",variant:"ghost",size:"sm",disabled:i,title:a?`Switch terminal, current: ${a.label}`:"Switch terminal","aria-label":a?`Switch terminal, current: ${a.label}`:"Switch terminal",className:"h-8 min-w-0 max-w-full justify-start gap-1.5 px-2 py-1 normal-case",children:[a?.icon??s.jsx(R,{name:"terminal",className:"size-4 shrink-0"}),s.jsx("span",{className:"min-w-0 truncate font-medium text-left",children:a?.label??"Terminal"}),s.jsx(R,{name:"arrow-down-s",className:"size-4 shrink-0 opacity-60"})]})}),s.jsxs(Qt,{align:"start",className:"w-64",children:[e.map(c=>{const d=c.id===(a?.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(R,{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(R,{name:"close",className:"size-3"})})]},c.id)}),s.jsx(vn,{}),s.jsxs(ut,{onClick:o,children:[s.jsx(R,{name:"add",className:"size-3.5"}),"New tab"]})]})]})},Ny=({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(R,{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]}),Iy=({isTouchTerminal:e,activeModifier:t,disabled:n,onKeyPress:r,onModifierToggle:o})=>{const i=e?"lg":"xs",a=e?"w-10 p-0":"w-9 p-0",c=d=>{e&&d.preventDefault()};return s.jsxs(s.Fragment,{children:[s.jsx(Ae,{type:"button",size:i,variant:"outline",onPointerDown:c,onClick:()=>r("esc"),disabled:n,children:"Esc"}),s.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("tab"),disabled:n,children:[s.jsx(R,{name:"arrow-right",className:"h-4 w-4"}),s.jsx("span",{className:"sr-only",children:"Tab"})]}),s.jsxs(Ae,{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(Ae,{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(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-up"),disabled:n,children:[s.jsx(R,{name:"arrow-up"}),s.jsx("span",{className:"sr-only",children:"Arrow up"})]}),s.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-left"),disabled:n,children:[s.jsx(R,{name:"arrow-left"}),s.jsx("span",{className:"sr-only",children:"Arrow left"})]}),s.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-down"),disabled:n,children:[s.jsx(R,{name:"arrow-down"}),s.jsx("span",{className:"sr-only",children:"Arrow down"})]}),s.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("arrow-right"),disabled:n,children:[s.jsx(R,{name:"arrow-right"}),s.jsx("span",{className:"sr-only",children:"Arrow right"})]}),s.jsxs(Ae,{type:"button",size:i,variant:"outline",className:a,onPointerDown:c,onClick:()=>r("enter"),disabled:n,children:[s.jsx(R,{name:"arrow-go-back"}),s.jsx("span",{className:"sr-only",children:"Enter"})]})]})},Ey="\x1B",Dy=new RegExp(`${Ey}\\[[0-9;?]*[ -/]*[@-~]`,"g"),Ry=/(https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[(?:::1|::)\])(?::\d{2,5})?(?:\/[^\s<>'"`]*)?)/gi,Py=/(?:➜\s*(?:Local|Network):)|\b(?:local|network|loopback|serving|listening|available|ready|started|running|server|vite|webpack|next\.js|astro|sveltekit|nuxt)\b/i,Ty=/Serving HTTP on .*? port (\d{2,5})/i,My=new Set([".",",",";",":","!","?"]),Fy=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,a=(o.match(new RegExp(`\\${n}`,"g"))||[]).length;if(i>a)break;t=o;continue}if(My.has(n)){t=t.slice(0,-1);continue}break}return t},jl=e=>{let t=Fy(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},Ly=e=>{if(!e)return null;const t=e.replace(Dy,""),n=t.match(Ty);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(`
|
|
59
|
+
`);for(const o of r){if(!Py.test(o))continue;const i=Array.from(o.matchAll(Ry));if(i.length===0)continue;const a=i.find(c=>{try{return!!new URL(jl(c[1])).port}catch{return!1}});return jl((a??i[0])[1])}return null},Oy=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 a=await st("/api/system/probe-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:n.toString()}),cache:"no-store",signal:o.signal});return a.ok?(await a.json().catch(()=>null))?.ok===!0:!1}catch{return!1}finally{window.clearTimeout(i)}},By={esc:"\x1B",tab:" ",enter:"\r","arrow-up":"\x1B[A","arrow-down":"\x1B[B","arrow-left":"\x1B[D","arrow-right":"\x1B[C"},_y=(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 By[e]},pd=e=>{const t=e[0]?.toUpperCase();return!t||t<"A"||t>"Z"?null:String.fromCharCode(t.charCodeAt(0)&31)},zy=(e,t)=>e&&(t==="ctrl"?pd(e)??e:e.length===1&&e!=="\x1B"?`\x1B${e}`:e),md={cols:80,rows:24},kl={Tab:"tab",Enter:"enter",ArrowUp:"arrow-up",ArrowDown:"arrow-down",ArrowLeft:"arrow-left",ArrowRight:"arrow-right",Escape:"esc"};class Uy{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,`
|
|
60
|
+
`),a=i.split(`
|
|
61
|
+
`),c=i.endsWith(`
|
|
62
|
+
`)?a.join(`
|
|
63
|
+
`):a.slice(0,-1).join(`
|
|
64
|
+
`);if(this.tail=i.endsWith(`
|
|
65
|
+
`)?"":(a[a.length-1]??"").slice(-1024),!c)return;const d=Ly(c);if(!d||this.pendingUrls.has(d))return;const u=this.probeGeneration;this.pendingUrls.add(d),Oy(d).then(f=>{if(this.pendingUrls.delete(d),!f||this.probeGeneration!==u)return;const m=we.getState().getDirectoryState(t)?.tabs.find(g=>g.id===n);!m||m.previewUrlLocked||m.previewUrl===d||o(t,n,d,{locked:!1,autoOpened:!1})})}}const $y=(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"?pd(o):null};function Ky({terminal:e,effectiveDirectory:t,activeTabId:n,terminalSessionId:r,terminalLifecycle:o,hasOpenedTerminalViewport:i,terminalHydrated:a,terminalShell:c,terminalLoginShell:d,terminalAppearanceRef:u,enableTabs:f,hasActiveContext:m,focusTerminalWhenWindowActive:g,tabs:b}){const h=we(B=>B.ensureDirectory),p=we(B=>B.setTabSessionId),y=we(B=>B.setTabLifecycle),x=we(B=>B.setConnecting),C=we(B=>B.appendToBuffer),j=we(B=>B.replaceBuffer),A=we(B=>B.setTabPreviewUrl),[w,S]=l.useState(null),[v,k]=l.useState(!1),[E,P]=l.useState(!1),z=l.useRef(new Map),K=l.useRef(null),q=l.useRef(n),H=l.useRef(r),F=l.useRef(t),D=l.useRef(null),T=l.useRef(new Set),I=l.useRef(new Map),M=l.useRef(b),G=l.useRef(a),W=l.useRef(i),L=l.useRef(e);M.current=b,G.current=a,W.current=i,L.current=e;const ae=l.useCallback(()=>{const B=q.current;B&&I.current.get(B)?.reset()},[]);l.useEffect(()=>{H.current=r},[r]),l.useEffect(()=>{!r||!e.updateAppearance||e.updateAppearance(r,u.current).catch(()=>{})},[u,e,r]),l.useEffect(()=>{q.current=n},[n]),l.useEffect(()=>{F.current=t},[t]);const J=l.useCallback(()=>{for(const B of z.current.values())try{B()}catch{}z.current.clear(),K.current=null,P(!1)},[]);l.useEffect(()=>()=>{J(),H.current=null},[J]);const le=l.useCallback((B,$,X)=>{let ee=I.current.get($);ee||(ee=new Uy,I.current.set($,ee)),ee.scan(B,$,X,A)},[A]),Ie=l.useCallback((B,$,X)=>{if(z.current.has(X)){K.current=X;return}const ee=Sa(),ie=()=>Sa()===ee&&F.current===B&&we.getState().getDirectoryState(B)?.tabs.find(pe=>pe.id===$)?.terminalSessionId===X,Ce=e.connect(X,{onEvent:pe=>{if(ie())switch(pe.type){case"snapshot":{q.current===$&&H.current===X?(x(B,$,!1),S(null),k(!1),P(!1),g()):x(B,$,!1),j(B,$,pe.data??"",pe.sequence??0),le(B,$,pe.data??""),pe.status==="exited"&&y(B,$,"exited");break}case"reconnecting":{q.current===$&&(S(null),k(!1),P(!0));break}case"data":{pe.data&&(C(B,$,pe.data,pe.sequence,pe.replayData),le(B,$,pe.data));break}case"exit":{const je=typeof pe.exitCode=="number"?pe.exitCode:null,be=typeof pe.signal=="number"?pe.signal:null,me=!!we.getState().getDirectoryState(B)?.tabs.find(Pe=>Pe.id===$)?.label?.startsWith("Action:");C(B,$,`\\r\\n[Process exited${je!==null?` with code ${je}`:""}${be!==null?` (signal ${be})`:""}]\\r\\n`),y(B,$,"exited"),q.current===$&&(x(B,$,!1),S(me?null:"Terminal session ended"),k(!1),P(!1));break}}},onError:(pe,je)=>{if(!ie())return;const be=q.current===$;if(!je){be&&(S(null),k(!1));return}if(pe.code==="SESSION_NOT_FOUND"&&!we.getState().getDirectoryState(B)?.tabs.find(me=>me.id===$)?.label?.startsWith("Action:")){be&&(S(null),k(!1),x(B,$,!1),P(!1)),p(B,$,null),y(B,$,"idle");return}be&&(P(!1),S(`Connection failed: ${pe.message}`),k(!0),x(B,$,!1),y(B,$,"exited"),p(B,$,null))}});z.current.set(X,()=>Ce.close()),K.current=X},[C,g,j,le,x,y,p,e]),Y=l.useMemo(()=>b.map(B=>`${B.id}:${B.terminalSessionId??""}`).join(","),[b]);return l.useEffect(()=>{if(!a||!i||!t)return;const B=t,$=new Set;for(const X of b)X.terminalSessionId&&($.add(X.terminalSessionId),Ie(B,X.id,X.terminalSessionId));for(const[X,ee]of z.current)if(!$.has(X)){try{ee()}catch{}z.current.delete(X)}},[Y,b,t,a,i,Ie]),l.useEffect(()=>Th(()=>{if(!G.current||!W.current)return;const B=F.current;if(!B)return;const $=[];for(const ee of M.current){if(!ee.terminalSessionId)continue;we.getState().getDirectoryState(B)?.tabs.find(Ce=>Ce.id===ee.id)?.terminalSessionId===ee.terminalSessionId&&$.push({id:ee.id,terminalSessionId:ee.terminalSessionId})}if(z.current.clear(),K.current=null,$.length===0)return;P(!0),S(null),k(!1);for(const ee of $)Ie(B,ee.id,ee.terminalSessionId);const X=D.current;if(X)for(const ee of $)L.current.resize({sessionId:ee.terminalSessionId,...X}).catch(()=>{})}),[Ie]),l.useEffect(()=>{let B=!1;if(!a||!i)return;if(!t){S(m?"No working directory available for terminal.":"Select a session to open the terminal.");return}return(async()=>{const X=t;if(!F.current||F.current!==X)return;if(!we.getState().getDirectoryState(X)){h(X);return}const ie=we.getState().getDirectoryState(X);if(!ie||ie.tabs.length===0)return;const Ce=ie.activeTabId??ie.tabs[0]?.id??null;if(!Ce)return;const pe=ie.tabs.find(V=>V.id===Ce)??ie.tabs[0],je=pe?.terminalSessionId??null,be=pe?.lifecycle??"idle",ze=!!pe?.label?.startsWith("Action:"),me=we.getState().getBuffer(X,Ce),Pe=me.byteLength>0||me.chunks.length>0;if(!je){if(be==="exited"){x(X,Ce,!1);return}if(ze&&Pe){x(X,Ce,!1);return}const V=`${X}\0${Ce}`;if(T.current.has(V))return;const fe=D.current??md;T.current.add(V),S(null),k(!1),P(!1),x(X,Ce,!0);try{const xe=await e.createSession({cwd:X,sessionId:Ce,cols:fe.cols,rows:fe.rows,shell:c,loginShell:d,...u.current});if(!we.getState().getDirectoryState(X)?.tabs.find(Be=>Be.id===Ce)){try{await e.close(xe.sessionId)}catch{}return}p(X,Ce,xe.sessionId);const re=D.current;re&&(re.cols!==fe.cols||re.rows!==fe.rows)&&e.resize({sessionId:xe.sessionId,...re}).catch(()=>{});return}catch(xe){const te=we.getState().getDirectoryState(X)?.tabs.find(re=>re.id===Ce);if(!te||te.terminalSessionId||(x(X,Ce,!1),F.current!==X||q.current!==Ce))return;S(xe instanceof Error?xe.message:"Failed to start terminal session"),k(!0),P(!1);return}finally{T.current.delete(V)}}!je||B||(H.current=je)})(),()=>{B=!0}},[m,t,r,o,n,i,f,a,h,x,y,p,e,d,c,u]),{connectionError:w,setConnectionError:S,isFatalError:v,setIsFatalError:k,isReconnectPending:E,setIsReconnectPending:P,terminalIdRef:H,lastViewportSizeRef:D,directoryRef:F,activeTabIdRef:q,disconnectStream:J,resetTerminalPreviewScan:ae,startStream:Ie}}function Wy({terminal:e,terminalIdRef:t,isReconnectPending:n,setConnectionError:r,showQuickKeys:o,isTerminalVisible:i,lastViewportSizeRef:a,terminalSessionId:c,useTouchTerminalInput:d}){const[u,f]=l.useState(null),m=l.useRef(null),g=l.useCallback(()=>{d||m.current?.focus()},[d]),b=l.useCallback(()=>{d||typeof document<"u"&&!document.hasFocus()||m.current?.focus()},[d]);l.useEffect(()=>{!o&&u!==null&&f(null)},[o,u]),l.useEffect(()=>{!c&&u!==null&&f(null)},[c,u]);const h=l.useCallback(j=>{if(!j||n)return;let A=j,w=!1;u&&j.length>0&&(A=zy(j,u),w=!0);const S=t.current;S&&(e.sendInput(S,A).catch(v=>{n||r(v instanceof Error?v.message:"Failed to send input")}),w&&(f(null),g()))},[u,g,n,r,e,t]),p=l.useCallback((j,A)=>{const w=a.current;if((!w||w.cols!==j||w.rows!==A)&&(a.current={cols:j,rows:A}),!i)return;const S=t.current;S&&e.resize({sessionId:S,cols:j,rows:A}).catch(()=>{})},[i,a,e,t]),y=l.useCallback(j=>{f(A=>A===j?null:j),g()},[g]),x=l.useCallback(j=>{const A=_y(j,u);A&&(h(A),f(null),g())},[u,g,h]),C=l.useCallback(j=>{if(j.repeat)return;const A=j.key;if(!A||A==="Control"||A==="Meta"||A==="Alt"||A==="Shift")return;const w=A.length===1?A.toLowerCase():A;if(w in kl){j.preventDefault(),j.stopPropagation(),x(kl[w]);return}const S=$y(j,u);S&&(j.preventDefault(),j.stopPropagation(),h(S),f(null),g())},[u,g,x,h]);return l.useEffect(()=>{if(!(!o||!u||!c))return window.addEventListener("keydown",C),()=>window.removeEventListener("keydown",C)},[u,C,o,c]),{activeModifier:u,setActiveModifier:f,terminalControllerRef:m,focusTerminalController:g,focusTerminalWhenWindowActive:b,handleViewportInput:h,handleViewportResize:p,handleModifierToggle:y,handleMobileKeyPress:x}}function Gy({terminal:e,effectiveDirectory:t,activeTabId:n,enableTabs:r,terminalShell:o,terminalLoginShell:i,terminalAppearanceRef:a,lastViewportSizeRef:c,directoryRef:d,activeTabIdRef:u,terminalIdRef:f,resetTerminalPreviewScan:m,startStream:g,setConnectionError:b,setIsFatalError:h,setIsReconnectPending:p}){const y=we(K=>K.createTab),x=we(K=>K.setActiveTab),C=we(K=>K.closeTab),j=we(K=>K.setTabSessionId),A=we(K=>K.setTabLifecycle),[w,S]=l.useState(!1),v=l.useCallback(async()=>{if(!t||w)return;const K=we.getState().getDirectoryState(t),q=n??K?.activeTabId??K?.tabs[0]?.id??null;if(!q)return;const H=K?.tabs.find(F=>F.id===q)?.terminalSessionId??null;if(!(!H||!e.restartSession)){S(!0),b(null),h(!1),p(!1),m();try{const F=c.current??md,D=await e.restartSession(H,{cwd:t,shell:o,loginShell:i,...F,...a.current});if(we.getState().getDirectoryState(t)?.tabs.find(I=>I.id===q)?.terminalSessionId!==H||(j(t,q,D.sessionId),A(t,q,"running"),d.current!==t||u.current!==q))return;f.current=D.sessionId,g(t,q,D.sessionId)}catch(F){if(we.getState().getDirectoryState(t)?.tabs.find(T=>T.id===q)?.terminalSessionId!==H||d.current!==t||u.current!==q)return;b(F instanceof Error?F.message:"Failed to restart terminal"),h(!1),p(!1),f.current=H,g(t,q,H)}finally{S(!1)}}},[n,u,d,t,r,w,c,m,b,h,p,A,j,g,e,a,f,i,o]),k=l.useCallback(async()=>{await v()},[v]),E=l.useCallback(()=>{if(!t)return;const K=y(t);x(t,K),b(null),h(!1),p(!1)},[y,t,x,b,h,p]),P=l.useCallback(K=>{t&&(x(t,K),b(null),h(!1),p(!1))},[t,x,b,h,p]),z=l.useCallback(K=>{if(!t)return;b(null),h(!1),p(!1);const q=we.getState().getDirectoryState(t)?.tabs.find(H=>H.id===K)?.terminalSessionId;(async()=>{q&&await e.close(q),C(t,K)})().catch(H=>b(H instanceof Error?H.message:"Terminal session ended"))},[C,t,b,h,p,e]);return{isRestarting:w,handleRestart:v,handleHardRestart:k,handleCreateTab:E,handleSelectTab:P,handleCloseTab:z}}const Hy=({directory:e})=>{const t=ot(d=>d.projects),n=_r(d=>d.projects),r=Nt(d=>d.projects),o=Nt(d=>d.projectsStatus),i=Nt(d=>d.loadProjects);l.useEffect(()=>{o==="idle"&&i()},[i,o]);const a=l.useMemo(()=>Yf(t,tc(t,{projects:n}),e),[e,t,n]),c=a?r[a.id]:void 0;return!c&&a&&o==="failed"?s.jsx("p",{className:"px-4 pt-2 typography-micro text-muted-foreground",role:"status",children:"Could not check whether this project is sandboxed. This terminal runs with your normal access either way."}):!c||c.mode==="off"?null:s.jsx("p",{className:"px-4 pt-2 typography-micro text-muted-foreground",role:"status",children:"This project is sandboxed, but this terminal runs outside the sandbox with your normal access."})},aS=({visible:e,onCloseView:t,terminalHeaderSlot:n})=>{const{terminal:r,runtime:o}=qs(),{currentTheme:i}=sc(),a=l.useRef({themeMode:"dark",terminalBackground:"",terminalForeground:""});a.current={themeMode:i.metadata.variant==="light"?"light":"dark",terminalBackground:i.colors.surface.background,terminalForeground:i.colors.syntax.base.foreground};const{monoFont:c}=Qf(),d=ue(ne=>ne.terminalFontSize),u=ue(ne=>ne.terminalShell),f=ue(ne=>ne.terminalLoginShells.includes(ne.terminalShell)),{isMobile:m,isTablet:g,hasTouchOnlyPointer:b}=Cn(),h=m||g,p=(h||b)&&o.platform==="web",y=!0,x=ue(ne=>ne.showTerminalQuickKeysOnDesktop),C=h||x,j=Me(ne=>ne.currentSessionId),A=Me(ne=>ne.newSessionDraft),w=j!==null||A?.open===!0,S=Jf()??null,v=we(ne=>S?ne.sessions.get(S):void 0),k=we(ne=>ne.hasHydrated),E=ue(ne=>ne.openContextPreview),P=l.useMemo(()=>v?v.activeTabId??v.tabs[0]?.id??null:null,[v,y]),z=l.useMemo(()=>{if(v)return P?v.tabs.find(ne=>ne.id===P)??v.tabs[0]:v.tabs[0]},[v,P]),K=l.useMemo(()=>(v?.tabs??[]).map(ne=>({icon:(()=>{const _e=ne.iconKey?Zn[ne.iconKey]??"terminal":"terminal";return s.jsx(R,{name:_e,className:"h-4 w-4"})})(),id:ne.id,label:ne.label,title:ne.label,closeLabel:"Close tab"})),[v?.tabs]),q=z?.terminalSessionId??null,H=z?.lifecycle??"idle",F=l.useMemo(()=>(v?.tabs??[]).map(ne=>({id:ne.id,terminalSessionId:ne.terminalSessionId,label:ne.label})),[v?.tabs]),D=z?.isConnecting??!1,T=z?.previewUrl??null,M=ue(ne=>ne.activeMainTab)==="terminal",G=e??M,[W,L]=l.useState(G);l.useEffect(()=>{G&&L(!0)},[G]);const{connectionError:ae,setConnectionError:J,isFatalError:le,setIsFatalError:Ie,isReconnectPending:Y,setIsReconnectPending:B,terminalIdRef:$,lastViewportSizeRef:X,directoryRef:ee,activeTabIdRef:ie,resetTerminalPreviewScan:Ce,startStream:pe}=Ky({terminal:r,effectiveDirectory:S,activeTabId:P,terminalSessionId:q,terminalLifecycle:H,hasOpenedTerminalViewport:W,terminalHydrated:k,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:a,enableTabs:y,hasActiveContext:w,tabs:F,focusTerminalWhenWindowActive:()=>{!p&&typeof document<"u"&&document.hasFocus()&&be.current?.focus()}}),{activeModifier:je,terminalControllerRef:be,focusTerminalWhenWindowActive:ze,handleViewportInput:me,handleModifierToggle:Pe,handleMobileKeyPress:V}=Wy({terminal:r,terminalIdRef:$,isReconnectPending:Y,setConnectionError:J,showQuickKeys:C,isTerminalVisible:G,lastViewportSizeRef:X,terminalSessionId:q,useTouchTerminalInput:p}),{isRestarting:fe,handleRestart:xe,handleHardRestart:te,handleCreateTab:re,handleSelectTab:Be,handleCloseTab:ke}=Gy({terminal:r,effectiveDirectory:S,activeTabId:P,enableTabs:y,terminalShell:u,terminalLoginShell:f,terminalAppearanceRef:a,lastViewportSizeRef:X,directoryRef:ee,activeTabIdRef:ie,terminalIdRef:$,resetTerminalPreviewScan:Ce,startStream:pe,setConnectionError:J,setIsFatalError:Ie,setIsReconnectPending:B});l.useEffect(()=>{if(!G||p)return;if(typeof window>"u"){ze();return}const ne=window.requestAnimationFrame(()=>{ze()});return()=>{window.cancelAnimationFrame(ne)}},[P,ze,G,p]);const Q=l.useMemo(()=>{const ne=_n[wo].stack;if(typeof window>"u")return(_n[c]??_n[wo]).stack;const rt=window.getComputedStyle(document.documentElement).getPropertyValue("--font-family-mono");return rt&&rt.trim().length>0?rt.trim():(_n[c]??_n[wo]).stack??ne},[c]),ve=l.useMemo(()=>Xf(i),[i]),he=`${S??"no-dir"}::${P??"no-tab"}`;if(l.useEffect(()=>{if(!G||p)return;const ne=be.current;if(!ne)return;const _e=()=>{ne.fit()};if(typeof window<"u"){const rt=window.requestAnimationFrame(()=>{_e(),ze()}),mt=[220,400].map(Ze=>window.setTimeout(_e,Ze));return()=>{window.cancelAnimationFrame(rt),mt.forEach(Ze=>window.clearTimeout(Ze))}}_e()},[ze,G,p,be,he,q]),l.useEffect(()=>{if(!G||!p)return;let ne=null;const _e=()=>{ne!==null&&window.cancelAnimationFrame(ne),ne=window.requestAnimationFrame(()=>{ne=null,be.current?.fit()})};return window.addEventListener("oc:keyboard-settled",_e),()=>{window.removeEventListener("oc:keyboard-settled",_e),ne!==null&&window.cancelAnimationFrame(ne)}},[G,be,he,p]),!w)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(!S)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:xe,className:"rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90",children:"Retry"})]});const Se=!q||D||fe||Y,qe=W,Ue=v?s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"min-w-0 flex-1",children:s.jsx(Sl,{items:K,activeId:P,onSelect:Be,onClose:ke,onCreate:re})}),s.jsx(Ae,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 shrink-0 p-0",onClick:re,title:"New tab","aria-label":"New tab",children:s.jsx(R,{name:"add",className:"h-4 w-4"})}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1 overflow-visible",children:[s.jsx(Ae,{type:"button",size:"xs",variant:"ghost",className:"h-8 w-8 p-0",onClick:()=>{xe()},disabled:fe,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(R,{name:"restart",className:"h-4 w-4"})}),T?s.jsxs(Ae,{type:"button",size:"xs",variant:"outline",className:"h-6 shrink-0 gap-1 px-2",onClick:()=>{S&&E(S,T)},title:"Open preview pane",children:[s.jsx(R,{name:"global",className:"h-3.5 w-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null]})]}):null,U=s.jsx(Iy,{isTouchTerminal:h,activeModifier:je,disabled:Se,onKeyPress:V,onModifierToggle:Pe}),ge=!n||h||C;return s.jsxs("div",{className:"flex h-full flex-col overflow-hidden bg-background",children:[Ue&&n?zu.createPortal(s.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-1.5",children:Ue}),n):null,h&&Ue&&!n&&v?s.jsx(Ny,{leading:s.jsx("div",{className:"min-w-0 flex-1 -ml-2",children:s.jsx(Sl,{items:K,activeId:P,onSelect:Be,onClose:ke,onCreate:re})}),actions:s.jsxs(s.Fragment,{children:[s.jsx(Ae,{type:"button",variant:"ghost",size:"icon",onClick:re,title:"New tab","aria-label":"New tab",children:s.jsx(R,{name:"add",className:"size-4"})}),s.jsx(Ae,{type:"button",variant:"ghost",size:"icon",onClick:()=>{xe()},disabled:fe,title:"Restart terminal","aria-label":"Restart terminal",children:s.jsx(R,{name:"restart",className:"size-4"})}),T?s.jsxs(Ae,{type:"button",variant:"outline",size:"sm",className:"h-8 shrink-0 gap-1 px-2",onClick:()=>{S&&E(S,T)},title:"Open preview pane",children:[s.jsx(R,{name:"global",className:"size-3.5 shrink-0"}),s.jsx("span",{className:"whitespace-nowrap",children:"Preview"})]}):null,t?s.jsx(Ae,{type:"button",variant:"ghost",size:"icon",onClick:t,title:"Close terminal view","aria-label":"Close terminal view",children:s.jsx(R,{name:"close",className:"size-4"})}):null]})}):null,!h&&ge?s.jsxs("div",{className:_("app-region-no-drag sticky top-0 z-20 shrink-0 bg-background text-xs","px-3 py-2"),children:[Ue&&!n?s.jsxs("div",{className:"flex items-center gap-2 pl-1 pr-1",children:[Ue,t?s.jsx(Ae,{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(R,{name:"close",className:"h-4 w-4"})}):null]}):null,!h&&C&&y&&v?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1 pl-1 pr-1",children:U}):null,!h&&C&&!v?s.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-1",children:U}):null]}):null,s.jsx(Hy,{directory:S}),s.jsxs("div",{className:"relative flex-1 overflow-hidden",style:{backgroundColor:ve.background},children:[s.jsx("div",{className:"h-full w-full box-border pl-4 pr-1.5 pt-3 pb-4",children:qe&&S&&v?v.tabs.map(ne=>{const _e=ne.id===P;return s.jsx(Ay,{directory:S,tabId:ne.id,sessionId:ne.terminalSessionId,sessionKey:`${S}::${ne.id}`,isActive:_e,isTerminalVisible:G,terminal:r,theme:ve,fontFamily:Q,fontSize:d,enableTouchScroll:p,lastViewportSizeRef:X,onInput:me,controllerRef:be},ne.id)}):null}),!Y&&ae&&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:ae}),le&&h&&s.jsx(Ae,{size:"sm",variant:"secondary",className:"h-6 px-2 py-0 text-xs",onClick:te,disabled:fe,title:"Force kill and create fresh session",type:"button",children:"Hard restart"})]})]}),h&&C?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:U})}):null]})},Ei=[{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"}],qy=new Set(Ei.map(e=>e.id)),Vy=e=>typeof e=="string"&&qy.has(e),lS=e=>Vy(e)?e:"changes",gd=e=>e==="pull-requests"||e==="issues",Yy=e=>e?Ei:Ei.filter(t=>!gd(t.id)),cS=(e,t)=>gd(e)?"changes":e,Qy=48,Jy=96,jt=(e,...t)=>{try{e?.(...t)}catch{}},Ko=(e,t)=>{if(typeof e=="function"){const n=e();return n>0?n:t}return typeof e=="number"&&e>0?e:t},dS=(e,t)=>{const n=l.useRef(t);n.current=t;const r=t.enabled;l.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"?Jy:Qy;let d=!1,u=!1,f=!1,m=null,g=!1,b=0,h=0,p=0,y=0;const x=()=>{d=!1,u=!1,f=!1,m=null},C=()=>{const E=n.current,P=m,z=g;u&&P&&(jt(P==="left"?E.onLeftProgress:E.onRightProgress,z?1:0),jt(E.onDragEnd,P,z)),x()},j=()=>{C(),u||x()},A=E=>{const P=n.current;if(P.enabled===!1){u&&m?C():x();return}if(E.touches.length!==1){u&&m?C():x();return}const z=E.touches[0],K=o.getBoundingClientRect(),q=o.clientWidth,H=!!P.leftOpen,F=!!P.rightOpen,D=T=>iy(T,o);if(H||F){if(D(E.target)){x();return}if(H&&F){const T=z.clientX<=K.left+c;z.clientX>=K.right-c?(m="right",g=!0):T?(m="left",g=!0):(m=H?"left":"right",g=!0)}else H?(m="left",g=!0):(m="right",g=!0);y=Ko(m==="left"?P.leftWidth:P.rightWidth,q),y<10&&(y=q||window.innerWidth||320),y<10&&(y=320),d=!0}else{if(D(E.target)){x();return}m=null,g=!1,y=0,d=!0}b=z.clientX,h=z.clientY,p=Date.now(),u=!1,f=!1},w=E=>{if(!d)return;if(E.touches.length!==1){j();return}const P=E.touches[0],z=P.clientX-b,K=P.clientY-h;if(!f){if(Math.abs(z)<bl&&Math.abs(K)<bl)return;if(Math.abs(K)>Math.abs(z)*Hn){x();return}if(!m){const F=n.current;m=z>0?"left":"right",y=Ko(m==="left"?F.leftWidth:F.rightWidth,o.clientWidth),y<10&&(y=window.innerWidth||320)}if(m==="left"){if(!g&&z<=0){x();return}if(g&&z>=0){x();return}}else{if(!g&&z>=0){x();return}if(g&&z<=0){x();return}}f=!0,u=!0,jt(n.current.onDragStart,m)}if(!u)return;E.cancelable&&E.preventDefault();const q=n.current,H=xl(m,g,z,y);jt(m==="left"?q.onLeftProgress:q.onRightProgress,H)},S=(E,P)=>{if(!d){x();return}const z=E-b,K=P-h;if(!m&&!g&&Math.abs(z)>=Lr&&Math.abs(K)<=Math.abs(z)*Hn){const I=n.current;m=z>0?"left":"right",y=Ko(m==="left"?I.leftWidth:I.rightWidth,o.clientWidth),y<10&&(y=window.innerWidth||320)}if(!m){x();return}const q=Math.max(1,Date.now()-p),H=n.current;if(!u){const I=Math.abs(z),M=Math.abs(K);I>=Lr&&M<=I*Hn?m==="left"&&!g&&z>0?(jt(H.onLeftProgress,1),jt(H.onLeftOpen)):m==="right"&&!g&&z<0?(jt(H.onRightProgress,1),jt(H.onRightOpen)):jt(m==="left"?H.onLeftProgress:H.onRightProgress,g?1:0):jt(m==="left"?H.onLeftProgress:H.onRightProgress,g?1:0);const G=m;x(),jt(H.onDragEnd,G);return}const F=xl(m,g,z,y),D=ry({side:m,isOpenAtStart:g,dx:z,dt:q,progress:F}),T=m;jt(T==="left"?D?H.onLeftOpen:H.onLeftClose:D?H.onRightOpen:H.onRightClose),x(),jt(H.onDragEnd,T,D)},v=E=>{const P=E.changedTouches[0];if(!P){x();return}const z=P.clientX-b,K=P.clientY-h;d&&(u||Math.abs(z)>=Lr&&Math.abs(K)<=Math.abs(z)*Hn)&&E.cancelable&&E.preventDefault(),S(P.clientX,P.clientY)},k=()=>{j()};return o.addEventListener("touchstart",A,{passive:!0}),o.addEventListener("touchmove",w,{passive:!1}),o.addEventListener("touchend",v,{passive:!1}),o.addEventListener("touchcancel",k,{passive:!0}),()=>{try{u&&m&&C()}catch{}o.style.touchAction=i,o.removeEventListener("touchstart",A),o.removeEventListener("touchmove",w),o.removeEventListener("touchend",v),o.removeEventListener("touchcancel",k)}},[e,r])};function uS({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(R,{name:"layout-column",className:"absolute inset-0 h-full w-full"})]})}function Cl({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 Xy=({sessionDirectory:e,draftDirectory:t,isNewSessionDraftOpen:n})=>n?t:e,Zy=({activeProjectLabel:e,openDirectory:t,homeDirectory:n})=>or(t,n)?null:e,Wo=()=>Us.filter(e=>ii.has(e.id)).map(e=>({...dc(e)})),ew=()=>{if(typeof window>"u")return ai;const e=window.localStorage.getItem("openInAppId");return e&&oi(e)?e:ai};let Go=!1,cn=!1,js=!1,ks=0,er=null;const Al=()=>{er&&(clearTimeout(er),er=null)},Bs=bs()((e,t)=>({selectedAppId:ew(),availableApps:Wo(),hasLoadedApps:!1,isCacheStale:!1,isScanning:!1,initialize:()=>{if(Go||typeof window>"u")return;Go=!0;const n=(d,u=!0)=>{if(!Array.isArray(d)||d.length===0){e({availableApps:Wo(),hasLoadedApps:u});return}const f=new Set(d.map(h=>h.name)),m=new Map(d.map(h=>[h.name,h.iconDataUrl??void 0])),b=Us.filter(h=>f.has(h.appName)||ii.has(h.id)).map(h=>({...dc(h),iconDataUrl:m.get(h.appName)}));e({availableApps:b,hasLoadedApps:!0})},r=async d=>{if(!Sn()||!Ur()||cn||t().hasLoadedApps&&!d)return;const f=Us.map(m=>m.appName);Al(),cn=!0,js=!1,e({isScanning:!0});try{const{apps:m,success:g,hasCache:b,isCacheStale:h}=await ja(f,d),p=g&&!b&&m.length===0&&ks<3;if(e({isCacheStale:b?h:!1}),n(m,g?!p:!1),g){if(p){const x=[800,1600,3200][ks]??3200;ks+=1,js=!0,er=setTimeout(()=>{r()},x);return}ks=0,js=!1;return}if(ks<3){const x=[1e3,3e3,7e3][ks]??7e3;ks+=1,js=!0,er=setTimeout(()=>{r()},x)}}finally{cn=!1,js||e({isScanning:!1})}};r();const o=d=>{const u=d.detail,f=u&&typeof u.openInAppId=="string"&&u.openInAppId.length>0&&oi(u.openInAppId)?u.openInAppId:null;f&&(window.localStorage.setItem("openInAppId",f),e({selectedAppId:f}))},i=()=>{r()},a=d=>{const u=d.detail;Array.isArray(u)&&(ks=3,js=!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",a),window.__pichamberAppReady&&r(),window.setTimeout(()=>{t().hasLoadedApps||r()},5e3)},loadInstalledApps:async n=>{if(Go||t().initialize(),!Sn()||!Ur()||cn||t().hasLoadedApps&&!n)return;const o=Us.map(i=>i.appName);Al(),n&&e({hasLoadedApps:!1}),cn=!0,js=!1,e({isScanning:!0});try{const{apps:i,hasCache:a,isCacheStale:c}=await ja(o,n),d=new Set(i.map(g=>g.name)),u=new Map(i.map(g=>[g.name,g.iconDataUrl??void 0])),m=Us.filter(g=>d.has(g.appName)||ii.has(g.id)).map(g=>({...g,iconDataUrl:u.get(g.appName)}));e({availableApps:m.length>0?m:Wo(),hasLoadedApps:m.length>0,isCacheStale:a?c:!1})}finally{cn=!1,js||e({isScanning:!1})}},selectApp:async n=>{oi(n)&&(e({selectedAppId:n}),typeof window<"u"&&window.localStorage.setItem("openInAppId",n),await ic({openInAppId:n}))}})),tw="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",sw="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",Ho=e=>({...e,fallbackIconDataUrl:e.id==="finder"&&window.__PICHAMBER_PLATFORM__==="darwin"?tw:e.id==="terminal"?sw:void 0}),Nl=({label:e,iconDataUrl:t,fallbackIconDataUrl:n})=>{const[r,o]=l.useState(!1),i=e.trim().slice(0,1).toUpperCase()||"?",a=t||n;return a&&!r?s.jsx("img",{src:a,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})},nw=({directory:e,className:t})=>{const n=Bs(h=>h.selectedAppId),r=Bs(h=>h.availableApps),o=Bs(h=>h.isCacheStale),i=Bs(h=>h.isScanning),a=Bs(h=>h.initialize),c=Bs(h=>h.loadInstalledApps),d=Bs(h=>h.selectApp);l.useEffect(()=>{a()},[a]);const u=Sn()&&Ur(),f=l.useMemo(()=>{const h=r.find(p=>p.id===n)??r.find(p=>p.id===ai)??r[0]??Us[0];return Ho(h||Us[0])},[r,n]);if(!u||!e||r.length===0)return null;const m=async h=>{await Mh(e,h.id,h.appName)||await lc(e,h.appName)},g=async h=>{await d(h.id),await m(h)},b=async()=>{(await hs(e)).ok&&oe.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:()=>{m(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(Nl,{label:f.label,iconDataUrl:f.iconDataUrl,fallbackIconDataUrl:f.fallbackIconDataUrl})}),s.jsxs(Vt,{children:[s.jsx(Yt,{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(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(Qt,{align:"end",className:"w-56 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{b()},children:[s.jsx(R,{name:"file-copy",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Copy path"})]}),s.jsx(vn,{}),r.map(h=>{const p=Ho(h);return s.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{g(h)},children:[s.jsx(Nl,{label:h.label,iconDataUrl:h.iconDataUrl,fallbackIconDataUrl:p.fallbackIconDataUrl}),s.jsx("span",{className:"typography-ui-label text-foreground",children:h.label}),f.id===h.id?s.jsx(R,{name:"check",className:"ml-auto h-4 w-4 text-primary"}):null]},h.id)}),o?s.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{c(!0)},children:[s.jsx(R,{name:"refresh",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Refresh apps"})]}):null]})]})]})},rw="\x1B",ow=new RegExp(`${rw}\\[[0-9;?]*[ -/]*[@-~]`,"g"),iw=/https?:\/\/[^\s<>'"`]+/gi,It="__pichamber_auto_discover_preview__",aw=15e3,lw=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},cw=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}},dw=e=>{const n=e.replace(ow,"").match(iw);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 a=new URL(i);a.port&&a.port.length>0&&o.push({raw:i,parsed:a})}catch{}if(o.length>0){const i=a=>{const{parsed:c}=a,d=c.hostname.toLowerCase(),u=d==="localhost"||d==="127.0.0.1"||d==="0.0.0.0"||d==="::1",f=c.pathname||"/",m=f.split("/").filter(Boolean).length,g=f==="/"||f==="",b=!!(c.search||c.hash);let h=0;return u&&(h+=50),g&&(h+=30),h-=Math.min(m*5,20),b&&(h-=10),h};return o.sort((a,c)=>i(c)-i(a)),o[0]?.parsed.origin??o[0]?.raw??null}return r[0]??null},uw=[{pattern:/^dev(:.*)?$/i},{pattern:/^start(:.*)?$/i},{pattern:/^preview(:.*)?$/i},{pattern:/^serve(:.*)?$/i},{pattern:/^develop(:.*)?$/i}],fw=["dev","start","preview","serve"];async function hw(e,t,n){if(!e)return null;const r=gw(t);if(r)return{command:r.command,label:r.name||"Start preview",actionId:r.id,previewUrlHint:r.openUrl};if(n){const o=bw(n);if(o){const i=await xw(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 pw(e)){const o=await mw(),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 pw(e){const t=`${e}/index.html`,n=await Qr(t,e);return typeof n=="string"&&n.trim().length>0}async function mw(){try{const e=await st("/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 gw(e){for(const t of e){const n=`${t.name} ${t.command}`.toLowerCase();if(fw.some(o=>n.includes(o)))return t}return null}function bw(e){for(const{pattern:t}of uw)for(const n of Object.keys(e))if(t.test(n))return n;return null}async function xw(e){const t=await Qr(`${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 Qr(`${e}/${r}`,e);if(typeof i=="string"&&i.trim().length>0)return o}return"npm"}async function Qr(e,t){if(t?.trim())try{const r=new URLSearchParams({path:e,directory:t,optional:"true"}),o=await st(`/api/fs/read?${r.toString()}`,{cache:"no-store"});if(o.ok)return o.text()}catch{}const n=ac()?.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 st(`/api/fs/read?path=${encodeURIComponent(e)}&optional=true`,{cache:"no-store"});return r.ok?r.text():null}catch{return null}}async function yw(e){try{const t=await Qr(`${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 ww=(e,t,n)=>new Promise(r=>{let o=!1,i=null,a=null;const c=d=>{o||(o=!0,a&&clearTimeout(a),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():a=setTimeout(()=>c(!1),n)});function vw({projectRef:e,directory:t,allowMobile:n=!1}){const{currentTheme:r}=sc(),{terminal:o}=qs(),{isMobile:i}=Cn(),a=ue(V=>V.terminalShell),c=ue(V=>V.terminalLoginShells.includes(V.terminalShell)),d=ue(V=>V.setSettingsPage),u=ue(V=>V.setSettingsDialogOpen),f=ue(V=>V.setSettingsProjectsSelectedId),m=ue(V=>V.openContextPreview),g=we(V=>V.ensureDirectory),b=we(V=>V.setTabLabel),h=we(V=>V.setTabIconKey),p=we(V=>V.setActiveTab),y=we(V=>V.setConnecting),x=we(V=>V.setTabSessionId),C=we(V=>V.setTabPreviewUrl),j=we(V=>V.projectActionRuns),A=we(V=>V.setProjectActionRun),w=we(V=>V.updateProjectActionRunStatus),S=we(V=>V.removeProjectActionRun),[v,k]=l.useState([]),[E,P]=l.useState(null),[z,K]=l.useState(!1),q=l.useRef({}),H=l.useRef({}),F=l.useRef({}),D=l.useRef({}),T=l.useRef(new Set),I=l.useRef(0),M=e?.id??null,G=e?.path??"",W=l.useMemo(()=>M?{id:M,path:G}:null,[M,G]),L=l.useCallback(async V=>{await $l(V)},[]),ae=l.useCallback(async()=>{if(!W)return;const V=I.current+1;I.current=V,K(!0);try{const fe=await Jo(W);if(I.current!==V)return;const xe=fe.actions;k(xe),P(te=>te===It||te&&xe.some(re=>re.id===te)?te:null)}catch{if(I.current!==V)return}finally{I.current===V&&K(!1)}},[W]),J=l.useMemo(()=>Ic(t||W?.path||""),[t,W?.path]),le=l.useMemo(()=>E?v.find(V=>V.id===E)??null:null,[v,E]),Ie=l.useMemo(()=>({id:It,name:"Auto-discover",command:"",icon:"scan-2",autoOpenUrl:!0}),[]),Y=!i,B=l.useMemo(()=>Y?[Ie,...v]:v,[v,Ie,Y]);l.useEffect(()=>{ae()},[ae]),l.useEffect(()=>{if(typeof window>"u")return;const V=fe=>{const xe=fe.detail;M&&(xe?.projectId&&xe.projectId!==M||ae())};return window.addEventListener(fi,V),()=>{window.removeEventListener(fi,V)}},[ae,M]),l.useEffect(()=>{E&&(E===It&&Y||v.some(V=>V.id===E)||P(null))},[v,Y,E]),l.useEffect(()=>{const V=()=>{const fe=we.getState(),xe=fe.sessions,te=fe.projectActionRuns;for(const[re,Be]of Object.entries(te)){const Q=xe.get(Be.directory)?.tabs.find(_e=>_e.id===Be.tabId);if(!Q||Q.terminalSessionId!==Be.sessionId){S(re);continue}const ve=H.current[re]??{lastSeenChunkId:null,openedUrl:!1,tail:"",openInPreview:!1};H.current[re]=ve;const he=B.find(_e=>_e.id===Be.actionId),Se=fe.getBuffer(Be.directory,Be.tabId).chunks;if(!he||Se.length===0)continue;const qe=Se.filter(_e=>ve.lastSeenChunkId===null||_e.id>ve.lastSeenChunkId);if(qe.length===0)continue;const Ue=qe.map(_e=>_e.data).join(""),U=`${ve.tail}${Ue}`,ge=!ve.openedUrl&&he.autoOpenUrl===!0?dw(U):null,ne=qe[qe.length-1]?.id??ve.lastSeenChunkId;if(ve.lastSeenChunkId=ne,ve.tail=U.slice(-512),ge)if(ve.openedUrl=!0,ve.openInPreview){const _e=te[re];_e&&(C(_e.directory,_e.tabId,ge,{locked:!1,autoOpened:!1}),_e.status==="waiting-for-preview"&&w(re,"running"),window.clearTimeout(D.current[re]),delete D.current[re],m(_e.directory,ge))}else L(ge),oe.success("Opened URL from action output");H.current[re]=ve}for(const re of Object.keys(H.current))te[re]||(delete H.current[re],window.clearTimeout(D.current[re]),delete D.current[re])};return V(),we.subscribe((fe,xe)=>{(fe.sessions!==xe.sessions||fe.buffers!==xe.buffers)&&V()})},[B,m,L,j,S,C,w]);const $=l.useCallback(async(V,fe={})=>{if(!J)throw new Error("No active directory");const xe=ds(J,V.id);g(J);const te=we.getState(),re=te.getDirectoryState(J);let Be=q.current[xe]||null;const ke=Be?!!re?.tabs.some(he=>he.id===Be):!1;(!Be||!ke)&&(Be=te.createTab(J),q.current[xe]=Be),b(J,Be,`Action: ${V.name}`),h(J,Be,V.icon||"play"),p(J,Be),fe.revealTerminal!==!1&&ue.getState().openContextPanelTab(J,{mode:"terminal"});const ve=we.getState().getDirectoryState(J)?.tabs.find(he=>he.id===Be);return{key:xe,tabId:Be,sessionId:ve?.terminalSessionId??null}},[g,J,p,h,b]),X=l.useCallback(async V=>{if(!n&&i)return;if(!J){oe.error("No active directory for action");return}const fe=ds(J,V.id),xe=j[fe];if(!(xe&&xe.status==="running")&&!T.current.has(fe)){T.current.add(fe);try{const te=V.id===It?await(async()=>{const[U,ge]=await Promise.all([Jo({id:W?.id??"",path:J}),yw(J)]),ne=await hw(J,U.actions,ge);if(!ne)throw new Error('No dev server command found. Configure a project action or add a "dev" script to package.json.');return{id:It,name:"Auto-discover",command:ne.command,icon:"scan-2",autoOpenUrl:!0,openUrl:ne.previewUrlHint||""}})():V,re=te.autoOpenUrl===!0&&(te.openUrl||"").trim().length>0,Be=!re&&V.id!==It,{key:ke,tabId:Q,sessionId:ve}=await $(te,{revealTerminal:Be});let he=ve;if(!he){y(J,Q,!0);try{he=(await o.createSession({cwd:J,sessionId:Q,shell:a,loginShell:c,themeMode:r.metadata.variant==="light"?"light":"dark",terminalBackground:r.colors.surface.background,terminalForeground:r.colors.syntax.base.foreground})).sessionId,x(J,Q,he)}finally{y(J,Q,!1)}}if(!he)throw new Error("Failed to create terminal session");F.current[ke]?.(),y(J,Q,!0);const Se=o.connect(he,{onEvent:U=>{U.type==="snapshot"&&(we.getState().replaceBuffer(J,Q,U.data??"",U.sequence??0),we.getState().setConnecting(J,Q,!1)),U.type==="data"&&typeof U.data=="string"&&U.data.length>0&&we.getState().appendToBuffer(J,Q,U.data,U.sequence,U.replayData),U.type==="exit"&&(we.getState().setTabLifecycle(J,Q,"exited"),we.getState().setConnecting(J,Q,!1),we.getState().removeProjectActionRun(ke),delete H.current[ke],F.current[ke]?.(),delete F.current[ke],window.clearTimeout(D.current[ke]),delete D.current[ke])},onError:(U,ge)=>{we.getState().setConnecting(J,Q,!1),ge&&(we.getState().setTabLifecycle(J,Q,"exited"),we.getState().setTabSessionId(J,Q,null),we.getState().removeProjectActionRun(ke))}});F.current[ke]=Se.close;const qe=te.autoOpenUrl?cw(te.openUrl):null;A({key:ke,directory:J,actionId:te.id,tabId:Q,sessionId:he,status:te.id===It&&!qe?"waiting-for-preview":"running"}),window.clearTimeout(D.current[ke]),delete D.current[ke],te.id===It&&!qe&&(D.current[ke]=window.setTimeout(()=>{const U=we.getState(),ge=U.projectActionRuns[ke];U.updateProjectActionRunStatus(ke,"running"),ge&&(U.setActiveTab(ge.directory,ge.tabId),ue.getState().openContextPanelTab(ge.directory,{mode:"terminal"})),delete D.current[ke]},aw)),H.current[ke]={lastSeenChunkId:null,openedUrl:!!qe||re,tail:"",openInPreview:te.id===It};const Ue=lw(te.command.trim().replace(/\r\n|\r/g,`
|
|
66
|
+
`));await o.sendInput(he,`${Ue}\r`),qe?(C(J,Q,qe,{locked:!0,autoOpened:!0}),m(J,qe),oe.success("Opened action URL")):re?(C(J,Q,null,{locked:!0}),oe.error("Invalid custom URL format")):C(J,Q,null,{locked:!1,autoOpened:!1})}catch(te){S(fe),delete H.current[fe],F.current[fe]?.(),delete F.current[fe],window.clearTimeout(D.current[fe]),delete D.current[fe],oe.error(te instanceof Error?te.message:"Failed to run action")}finally{T.current.delete(fe)}}},[r.colors.surface.background,r.colors.syntax.base.foreground,r.metadata.variant,$,n,i,J,c,a,m,j,S,y,A,C,x,W?.id,o]),ee=l.useCallback(async V=>{const fe=ds(J,V.id),xe=j[fe];if(!xe)return;w(fe,"stopping");const te=ww(o,xe.sessionId,1e3);try{await o.sendInput(xe.sessionId,"")}catch{}const re=await te;if(we.getState().getDirectoryState(xe.directory)?.tabs.find(Q=>Q.id===xe.tabId)?.terminalSessionId===xe.sessionId&&!re){if(typeof o.forceKill=="function")try{await o.forceKill({sessionId:xe.sessionId})}catch{}else try{await o.close(xe.sessionId)}catch{}x(xe.directory,xe.tabId,null)}S(fe),delete H.current[fe],F.current[fe]?.(),delete F.current[fe],window.clearTimeout(D.current[fe]),delete D.current[fe]},[J,j,S,x,o,w]),ie=l.useCallback(()=>{const V=le??B[0];if(!V)return;const fe=ds(J,V.id),xe=j[fe];if(xe?.status!=="stopping"){if(xe){ee(V);return}X(V)}},[B,J,X,j,le,ee]),Ce=l.useCallback((V,fe=!1)=>{if(P(V.id),!fe){X(V);return}const xe=ds(J,V.id),te=j[xe];if(te?.status!=="stopping"){if(te){ee(V);return}X(V)}},[J,X,j,ee]),pe=l.useCallback(()=>{W?.id&&(f(W.id),d("projects"),u(!0))},[u,d,f,W?.id]),je=le??B[0]??null,be=je?j[ds(J,je.id)]:null,ze=we(V=>be?V.sessions.get(be.directory)?.tabs.find(fe=>fe.id===be.tabId)?.previewUrl??null:null),me=!!((n||!i)&&W&&J),Pe=le??B[0]??null;return{shouldRender:me,isLoading:z,normalizedDirectory:J,resolvedSelected:Pe,displayActions:B,projectActionRuns:j,selectedRunPreviewUrl:ze,handlePrimaryClick:ie,handleSelectAction:Ce,openProjectActionsSettings:pe,openContextPreview:m}}const Il=({projectRef:e,directory:t,className:n,compact:r=!1,allowMobile:o=!1})=>{const{shouldRender:i,isLoading:a,normalizedDirectory:c,resolvedSelected:d,displayActions:u,projectActionRuns:f,selectedRunPreviewUrl:m,handlePrimaryClick:g,handleSelectAction:b,openProjectActionsSettings:h,openContextPreview:p}=vw({projectRef:e,directory:t,allowMobile:o});if(!i||!d)return null;const y=d.icon||"play",x=d.id===It?"scan-2":Zn[y]||"play",C=ds(c,d.id),j=f[C],A=j?.status==="stopping",w=j?.status==="waiting-for-preview",S=!!(j&&m),v=()=>{!j||!m||p(j.directory,m)},k=d.id===It;return r?s.jsxs("div",{className:"inline-flex items-center",children:[s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",disabled:a||A,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:g,"aria-label":j?`Stop ${d.name}`:`Run ${d.name}`,children:A||w?s.jsx(R,{name:"loader-4",className:"h-5 w-5 animate-spin text-[var(--status-warning)]"}):j?s.jsx(R,{name:"stop",className:"h-5 w-5 text-[var(--status-warning)]"}):s.jsx(R,{name:x,className:"h-5 w-5"})})}),k?s.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),S?s.jsxs(Ke,{children:[s.jsx(We,{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:v,children:s.jsx(R,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ge,{sideOffset:6,children:"Open preview"})]}):null,s.jsxs(Vt,{children:[s.jsx(Yt,{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(R,{name:"arrow-down-s",className:"h-3.5 w-3.5"})})}),s.jsxs(Qt,{align:"end",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ut,{className:"flex items-center gap-2",onClick:h,children:[s.jsx(R,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(vn,{}),u.map(E=>{const P=E.icon||"play",z=E.id===It?"scan-2":Zn[P]||"play",K=ds(c,E.id),q=f[K],H=!!q,F=q?.status==="stopping";return s.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{b(E,!0)},children:[s.jsx(R,{name:z,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:E.name}),F||q?.status==="waiting-for-preview"?s.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):H?s.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},E.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(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:g,disabled:a||A,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":j?`Stop ${d.name}`:`Run ${d.name}`,children:s.jsx("span",{className:"inline-flex h-4 w-4 shrink-0 items-center justify-center",children:A||w?s.jsx(R,{name:"loader-4",className:"h-4 w-4 animate-spin text-[var(--status-warning)]"}):j?s.jsx(R,{name:"stop",className:"h-4 w-4 text-[var(--status-warning)]"}):s.jsx(R,{name:x,className:"h-4 w-4"})})})}),k?s.jsx(Ge,{sideOffset:6,children:"Automatically discover and run the development server"}):null]}),S?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:v,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(R,{name:"global",className:"h-4 w-4"})})}),s.jsx(Ge,{sideOffset:6,children:"Open preview"})]}):null,s.jsxs(Vt,{children:[s.jsx(Yt,{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(R,{name:"arrow-down-s",className:"h-4 w-4"})})}),s.jsxs(Qt,{align:"start",className:"w-52 max-h-[70vh] overflow-y-auto",children:[s.jsxs(ut,{className:"flex items-center gap-2",onClick:h,children:[s.jsx(R,{name:"add",className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground",children:"Add new action"})]}),s.jsx(vn,{}),u.map(E=>{const P=E.icon||"play",z=E.id===It?"scan-2":Zn[P]||"play",K=ds(c,E.id),q=f[K],H=!!q,F=q?.status==="stopping";return s.jsxs(ut,{className:"flex items-center gap-2",onClick:()=>{b(E,!0)},children:[s.jsx(R,{name:z,className:"h-4 w-4"}),s.jsx("span",{className:"typography-ui-label text-foreground truncate",children:E.name}),F||q?.status==="waiting-for-preview"?s.jsx(R,{name:"loader-4",className:"ml-auto h-4 w-4 animate-spin text-[var(--status-warning)]"}):H?s.jsx(R,{name:"stop",className:"ml-auto h-4 w-4 text-[var(--status-warning)]"}):null]},E.id)})]})]})]})},Kt={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 Br(e){return e?.deploymentKind==="docker"?{name:Kt.docker,color:"#2496ED"}:e?.serverPlatform==="win32"?{name:Kt.windows,color:"#0078D4"}:e?.serverPlatform==="linux"?e.serverDistribution==="ubuntu"?{name:Kt.ubuntu,color:"#E95420"}:e.serverDistribution==="arch"?{name:Kt.arch,color:"#1793D1"}:e.serverDistribution==="nixos"?{name:Kt.nixos,color:"#5277C3"}:e.serverDistribution==="fedora"?{name:Kt.fedora,color:"#51A2DA"}:e.serverDistribution==="debian"?{name:Kt.debian,color:"#A81D33"}:e.serverDistribution==="centos"?{name:Kt.centos,color:"#932279"}:{name:Kt.linux}:e?.serverPlatform==="darwin"?{name:Kt.darwin}:{name:Kt.unknown}}const Sw=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 jw({open:e,onOpenChange:t}){const[n,r]=l.useState(null),o=l.useCallback(async()=>{const u=et();try{const f=await st("/api/version");if(!f.ok)throw new Error("Version request failed");const m=await f.json().catch(()=>null);u===et()&&r(m)}catch{u===et()&&r(null)}},[]);l.useEffect(()=>(o(),Nn(()=>{o()})),[o]);const i=Br(n),a=Sw(n),c=typeof n?.pichamberVersion=="string"?n.pichamberVersion:null,d=typeof window<"u"?window.location.origin:"";return s.jsxs(Vt,{open:e,onOpenChange:u=>{t(u),u&&o()},children:[s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx(Yt,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":"Show connected server information",className:_(En,"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5"),children:[s.jsx(R,{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(Ge,{children:s.jsx("p",{children:"Connected server information"})})]}),s.jsxs(Qt,{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(R,{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:a})]}),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:()=>{hs(d).then(u=>{u.ok?oe.success("Server address copied"):oe.error("Could not copy server address")})},children:[s.jsx("span",{className:"block max-w-[30ch] truncate font-mono",children:d}),s.jsx(R,{name:"file-copy",className:"size-3.5 shrink-0 text-muted-foreground"})]})]})})]})]})}const kw=({isMobile:e})=>{const n=qs().github??null,r=eo(i=>i.refresh),o=Gm();return l.useEffect(()=>{!n||e||r(n)},[n,e,r]),e||!n||!o?null:s.jsxs("span",{className:_(En,"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(R,{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]})]})},Cw=l.memo(function({isDesktopApp:t,currentInstanceLabel:n,compactCurrentInstanceLabel:r,currentInstanceIsLocal:o,currentInstanceIcon:i,isDesktopServicesOpen:a,setIsDesktopServicesOpen:c,refreshCurrentInstanceLabel:d,shortcutLabel:u,remoteUpdateInfo:f,remoteUpdateChecking:m,remoteUpdateError:g,onOpenRemoteUpdate:b}){return s.jsxs(Vt,{open:a,onOpenChange:h=>{c(h),h&&d()},children:[s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx(Yt,{asChild:!0,children:s.jsxs("button",{type:"button","aria-label":t?`Open instance, usage and MCP (current: ${n})`:"Open services, usage and MCP",className:_(En,t?"w-auto max-w-[14rem] justify-start gap-1.5 px-2.5":"h-8 w-8"),children:[s.jsx(R,{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(Ge,{children:s.jsx("p",{children:`Current instance: ${n} (${u("toggle_services_menu")})`})})]}),s.jsx(Qt,{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.`:m?"Looking for updates...":g||"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:b,children:"Update"}):null]})}),s.jsx(Zf,{embedded:!0,open:a,onOpenChange:()=>{},onHostSwitched:()=>c(!1)})]}):null})]})}),Aw=({action:e,onClose:t,sessionTitle:n,onConfirm:r})=>s.jsx(ss,{open:e!==null,onOpenChange:o=>{o||t()},children:s.jsxs(ns,{showCloseButton:!1,className:"max-w-sm gap-5",children:[s.jsxs(Hs,{children:[s.jsx(gs,{children:e==="delete"?"Delete session?":"Archive session?"}),s.jsx(Ds,{children:e==="delete"?`"${n}" will be permanently deleted.`:`"${n}" will be archived.`})]}),s.jsxs(An,{children:[s.jsx(Ae,{variant:"outline",size:"sm",onClick:t,children:"Cancel"}),s.jsx(Ae,{variant:"destructive",size:"sm",onClick:r,children:e==="delete"?"Delete":"Archive"})]})]})}),Nw=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},Wn=e=>{if(!e)return"";const t=e.replace(/\\/g,"/");return t==="/"?"/":t.replace(/\/+$/,"")},Iw=l.lazy(()=>pt(()=>import("./SessionSwitcherDropdown-CDOX-5Y2.js"),__vite__mapDeps([46,5,10,4,6,1,2,3,7,8,9,11,12])).then(e=>({default:e.SessionSwitcherDropdown}))),fS=({onToggleLeftDrawer:e,onToggleRightDrawer:t,leftDrawerOpen:n,rightDrawerOpen:r,tabletWorkspaceTab:o,onSelectTabletWorkspaceTab:i,tabletGitHubTabsAvailable:a=!1})=>{Ht("ui.header.render");const c=ue(O=>O.setSessionSwitcherOpen),d=ue(O=>O.toggleSidebar),u=ue(O=>O.isSidebarOpen),f=ue(O=>O.activeMainTab),m=ue(O=>O.setActiveMainTab),g=ue(O=>O.shortcutOverrides);ue(O=>O.timeFormatPreference),qs();const b=Me(O=>!!O.newSessionDraft?.open),h=Me(O=>O.currentSessionId),p=Xl(h??""),y=eh(h),x=l.useMemo(()=>{if(!y)return null;const O=y;return{title:y.title??null,directory:O.directory??null,created:y.time?.created??null,slug:O.slug??null,shareUrl:y.share?.url??null,parentId:y.parentID??null,messageCount:typeof y.messageCount=="number"?y.messageCount:null}},[y]),C=ot(Qo(O=>{if(!O.activeProjectId)return null;const ce=O.projects.find(ye=>ye.id===O.activeProjectId);return ce?{id:ce.id,path:ce.path,label:ce.label}:null})),j=jn(O=>O.homeDirectory),A=l.useMemo(()=>C?th(C):null,[C]),{isMobile:w}=Cn(),{enabled:S}=Ti(),v=!!(S&&i&&o!==void 0),k=l.useMemo(()=>[...Yy(a)],[a]),[E,P]=l.useState(!1),z=l.useRef(null),[K,q]=l.useState(()=>typeof window>"u"?!1:Sn()),H=l.useMemo(()=>cc(),[]),F=sh(),[D,T]=l.useState(!1),I=l.useMemo(()=>typeof navigator>"u"?!1:/Macintosh|Mac OS X/.test(navigator.userAgent||""),[]),M=nc(),G=l.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 ce=(navigator.userAgent||"").match(/Mac OS X (\d+)[._](\d+)/);if(!ce)return null;const ye=Number.parseInt(ce[1],10),$e=Number.parseInt(ce[2],10);return Number.isNaN(ye)?null:ye===10?$e:ye},[]);Te.useEffect(()=>{typeof window>"u"||q(Sn())},[]);const W=ue(O=>O.isSessionSwitcherOpen),[L,ae]=l.useState(!1),[J,le]=l.useState("Local"),[Ie,Y]=l.useState(!0),[B,$]=l.useState(()=>Br(null)),[X,ee]=l.useState(!1),[ie,Ce]=l.useState(null),[pe,je]=l.useState(!1),[be,ze]=l.useState(null),me=l.useRef(0),Pe=l.useMemo(()=>Nw(J),[J]),V=l.useCallback(async()=>{if(typeof window>"u"||!K)return;const O=et(),ce=()=>et()===O;try{const ye=await st("/api/version");if(!ce())return;const $e=ye.ok?await ye.json().catch(()=>null):null;if(!ce())return;if($(Br($e)),Ur()){le("Local"),Y(!0);return}Y(!1);const ht=await Fh();if(!ce())return;const Je=Lh(),St=Oh([Bh(Je),...ht.hosts]);if(St.id===_h){le("Local"),Y(!0);return}le(zh(St.label.trim()||"Instance"))}catch{ce()&&(le("Local"),Y(!0),$(Br(null)))}},[K]);Te.useEffect(()=>(V(),Nn(()=>{me.current+=1,Ce(null),ze(null),je(!1),ee(!1),V()})),[V]);const fe=l.useCallback(async()=>{const O=me.current+1;me.current=O;const ce=et(),ye=()=>me.current===O&&et()===ce;if(Ie){Ce(null),ze(null);return}je(!0),ze(null);try{const $e=new URLSearchParams({appType:"web",instanceMode:"remote"}),ht=await st(`/api/pi/update-check?${$e.toString()}`,{method:"GET",headers:{Accept:"application/json"}});if(!ht.ok)throw new Error(`Server responded with ${ht.status}`);const Je=await ht.json();if(!ye())return;Ce({available:Je.available??!1,version:Je.version,currentVersion:Je.currentVersion??"unknown",body:Je.body,nextSuggestedCheckInSec:typeof Je.nextSuggestedCheckInSec=="number"?Je.nextSuggestedCheckInSec:void 0,packageManager:Je.packageManager,updateCommand:Je.updateCommand,channel:Je.channel==="rc"?"rc":"stable"})}catch($e){if(!ye())return;Ce(null),ze($e instanceof Error?$e.message:"Failed to check remote instance updates")}finally{ye()&&je(!1)}},[Ie]);l.useEffect(()=>mm(()=>{Ie||fe()}),[fe,Ie]),l.useEffect(()=>{me.current+=1,Ce(null),ze(null),je(!1),ee(!1)},[Ie,J]),l.useEffect(()=>{if(!K||Ie)return;const O=3e3,ce=3600*1e3;let ye=!1,$e=null;const ht=Je=>{$e=window.setTimeout(()=>{if(ye||typeof document<"u"&&document.visibilityState!=="visible"){ht(ce);return}fe().finally(()=>{ye||ht(ce)})},Je)};return ht(O),()=>{ye=!0,$e!==null&&window.clearTimeout($e)}},[fe,Ie,J,K]);const xe=l.useCallback(()=>{if(ie?.available){ee(!0);return}fe()},[fe,ie?.available]),te=h?x??null:null,re=l.useRef(null),[Be,ke]=l.useState(0);l.useEffect(()=>{if(!h){re.current&&(re.current=null,ke($e=>$e+1));return}if(te){re.current={sessionId:h,session:te,expiresAt:Date.now()+2e3};return}const O=re.current;if(!O||O.sessionId!==h)return;const ce=O.expiresAt-Date.now();if(ce<=0){re.current=null,ke($e=>$e+1);return}const ye=window.setTimeout(()=>{re.current?.sessionId===h&&(re.current=null),ke($e=>$e+1)},ce);return()=>{window.clearTimeout(ye)}},[h,te]);const Q=(()=>{if(te)return te;if(!h)return null;const O=re.current;return O&&O.sessionId===h&&O.expiresAt>Date.now()?O.session:null})(),ve=l.useMemo(()=>{const O=typeof Q?.directory=="string"?Q.directory:"";return Wn(O||"")},[Q?.directory]),he=Me(O=>O.newSessionDraft?.open?Wn(O.newSessionDraft.directoryOverride??""):""),Se=l.useMemo(()=>Xy({sessionDirectory:ve,draftDirectory:he,isNewSessionDraftOpen:b}),[he,b,ve]),Ue=ei(Se||null),U=l.useMemo(()=>Zy({activeProjectLabel:A,openDirectory:Se,homeDirectory:j}),[A,j,Se]),ge=!!(U||Ue),ne=l.useMemo(()=>h?fs(Q,"Untitled session"):U??"PiChamber",[Q,h,U]),_e=nh(),rt=Me(O=>O.updateSessionTitle),mt=Me(O=>O.archiveSessions),Ze=Me(O=>O.deleteSessions),[Jt,gt]=l.useState(!1),[Et,rs]=l.useState(!1),Qe=l.useRef(!1),[Ft,Lt]=l.useState(""),[kt,Ee]=l.useState(null),Ye=l.useRef(null);l.useEffect(()=>{Qe.current=!1,rs(!1),gt(!1),Lt(""),Ee(null)},[h]);const Ne=l.useCallback(()=>{h&&(Lt(Q?.title?.trim()||ne),gt(!0))},[Q?.title,h,ne]),De=l.useCallback(async()=>{if(!h)return;const O=Ft.trim();O&&O!==Q?.title?.trim()&&await rt(h,O),gt(!1)},[Q?.title,h,Ft,rt]);l.useEffect(()=>{if(!Jt)return;const O=ce=>{const ye=ce.target;(!ye||!Ye.current?.contains(ye))&&De()};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[Jt,De]);const He=l.useCallback(()=>{h&&hs(h).then(O=>{oe[O.ok?"success":"error"](O.ok?"Session ID copied":"Failed to copy session ID")}).catch(()=>oe.error("Failed to copy session ID"))},[h]),ft=l.useCallback(async()=>{if(!h||!Se){oe.error("Nothing to export");return}try{await _e.syncSession(h)}catch{oe.error("Failed to load the complete session history");return}const O=[];if(O.length===0){oe.error("Nothing to export");return}const ce=ld(O,Q?.title??null),ye=ud(Q?.title??null);await dd(ce,ye)||cd(ce,ye),oe.success("Session exported")},[Q?.title,h,Se,_e]);p?.type==="busy"||p?.type;const os=l.useCallback(async()=>{if(!h||!kt)return;const O=rh(),ce=[h];for(let Je=0;Je<ce.length;Je+=1){const St=ce[Je];for(const Pt of O)Pt.parentID===St&&!ce.includes(Pt.id)&&ce.push(Pt.id)}const ye=kt;if(Ee(null),(ye==="archive"?await mt(ce):await Ze(ce)).failedIds.length>0){oe.error(ye==="archive"?"Failed to archive session":"Failed to delete session");return}oe.success(ye==="archive"?"Session archived":"Session deleted")},[mt,h,Ze,kt]),Ot=ue(O=>O.isArchivePageOpen),Bt=l.useMemo(()=>Ot?{title:"Archive",subtitle:null}:null,[Ot]),Ve=l.useMemo(()=>Wn(Se||C?.path||""),[C?.path,Se]),is=l.useCallback(()=>{Ve&&hs(Ve).then(O=>{oe[O.ok?"success":"error"](O.ok?"Working directory copied":"Failed to copy working directory")}).catch(()=>oe.error("Failed to copy working directory"))},[Ve]),Rs=l.useCallback(()=>{Ue&&hs(Ue).then(O=>{oe[O.ok?"success":"error"](O.ok?"Branch name copied":"Failed to copy branch name")}).catch(()=>oe.error("Failed to copy branch name"))},[Ue]),Dt=l.useMemo(()=>C?{id:C.id,path:C.path}:null,[C]),Ys=l.useRef(null);l.useEffect(()=>{!Dt||!Ve||(Ys.current={projectRef:Dt,directory:Ve})},[Ve,Dt]);const xt=l.useMemo(()=>Dt&&Ve?{projectRef:Dt,directory:Ve}:Ys.current,[Ve,Dt]),it=l.useCallback(()=>{if(typeof document>"u")return;const O=document.activeElement;if(!O)return;const ce=O.tagName;(ce==="INPUT"||ce==="TEXTAREA"||ce==="SELECT"||O.isContentEditable)&&O.blur()},[]),Xt=l.useCallback(()=>{if(w){it(),c(!W);return}d()},[it,w,W,c,d]),_t=l.useCallback(()=>{Jn("desktop_open_draft_mini_chat_window",{directory:Wn(Se||C?.path||""),projectId:C?.id??null,apiBaseUrl:ri(),clientToken:ni()}).catch(O=>{console.warn("[header] failed to open draft mini chat window",O)})},[C?.id,C?.path,Se]),xs=l.useCallback(()=>{if(b){_t();return}h&&Jn("desktop_open_session_mini_chat_window",{sessionId:h,directory:Wn(Se||C?.path||""),apiBaseUrl:ri(),clientToken:ni()}).catch(O=>{console.warn("[header] failed to open session mini chat window",O)})},[C?.path,h,_t,b,Se]),as=En,yt=eg,wt=l.useMemo(()=>n?"sessions":v?r&&o?o:null:r?"git":f,[f,v,n,r,o]),Rt=l.useCallback(()=>{n&&e&&e(),r&&t&&t(),!e&&W&&c(!1)},[W,n,e,t,r,c]),Qs=l.useCallback(()=>{e?.()},[e]),Ps=l.useCallback(()=>{t?.()},[t]),Ts=l.useMemo(()=>K&&I&&!D?"5.5rem":F?"max(calc(0.75rem + var(--oc-wco-left-inset, 0px)), 5.5rem)":!K||M?"calc(0.75rem + var(--oc-wco-left-inset, 0px))":"0.75rem",[K,D,I,F,M]);Te.useEffect(()=>{typeof document>"u"||document.documentElement.style.setProperty("--oc-titlebar-left-inset",Ts)},[Ts]);const Ct=u?"0.75rem":"var(--oc-titlebar-left-inset, 0.75rem)",ls=u?"0px":K&&M?"calc(var(--oc-titlebar-controls-width, 5.5rem) + 0.5rem)":S?"2.75rem":"2.5rem";Te.useEffect(()=>{if(!K||!I){T(!1);return}let O=!1;const ce=async()=>{try{const $e=await Jn("desktop_is_window_fullscreen");O||T($e===!0)}catch{O||T(!1)}},ye=()=>{ce()};return ce(),window.addEventListener("pichamber:window-resized",ye),()=>{O=!0,window.removeEventListener("pichamber:window-resized",ye)}},[K,I]);const nt=l.useMemo(()=>!K||!I||G===null?"":G>=26?"h-12":G<=15?"h-14":"",[K,I,G]),cs=l.useMemo(()=>{if(!(K&&!M))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))"}},[K,M]),vt=l.useCallback(()=>{if(typeof document>"u")return;const O=z.current?.getBoundingClientRect().height;if(O){const ce=`${O}px`,ye=document.documentElement.style;ye.getPropertyValue("--oc-header-height")!==ce&&ye.setProperty("--oc-header-height",ce)}},[]);Te.useEffect(()=>{if(typeof window>"u")return;vt();const O=z.current;if(!O||typeof ResizeObserver>"u")return()=>{};let ce=0;const ye=()=>{ce||(ce=requestAnimationFrame(()=>{ce=0,vt()}))},$e=new ResizeObserver(ye);return $e.observe(O),window.addEventListener("resize",ye),window.addEventListener("orientationchange",ye),()=>{ce&&cancelAnimationFrame(ce),$e.disconnect(),window.removeEventListener("resize",ye),window.removeEventListener("orientationchange",ye)}},[vt]),Te.useEffect(()=>{vt()},[vt,w,nt]);const At=l.useCallback(async O=>{const ce=O.target;ce.closest(".app-region-no-drag")||ce.closest("button, a, input, select, textarea")||O.button===0&&K&&await oh()},[K]),at=l.useMemo(()=>w?[{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"}]:[],[w]),Ms=l.useCallback(O=>Fi(zr(O,g)),[g]);Te.useEffect(()=>{!w&&f!=="chat"&&f!=="terminal"&&f!=="diagram"&&m("chat")},[f,w,m]),Te.useEffect(()=>{const O=ce=>{if(Uh(ce)&&!ce.shiftKey&&!ce.altKey){const ye=parseInt(ce.key,10);ye>=1&&ye<=at.length&&(ce.preventDefault(),w&&(it(),Rt()),m(at[ye-1].id))}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[it,Rt,w,m,at]),Te.useEffect(()=>{const O=ce=>{const ye=zr("toggle_services_menu",g);if($h(ce,ye)){ce.preventDefault(),L?ae(!1):(ae(!0),V());return}};return window.addEventListener("keydown",O),()=>window.removeEventListener("keydown",O)},[g,L,V]);const lt=O=>{const ce=f===O.id,ye=O.icon==="diff",$e=ye?null:O.icon,ht=O.id==="chat",Je=Pt=>ye?s.jsx(Cl,{size:Pt}):$e?s.jsx(R,{name:$e,className:`h-${Pt/4} w-${Pt/4}`}):null,St=s.jsxs("button",{type:"button",onClick:()=>m(O.id),className:_("relative flex h-8 items-center gap-2 px-3 rounded-lg typography-ui-label font-medium transition-colors",ce?"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",ht&&!w&&"min-w-[100px] justify-center"),"aria-label":O.label,"aria-selected":ce,role:"tab",children:[w?Je(20):s.jsxs(s.Fragment,{children:[Je(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(l.Fragment,{children:St},O.id)},Js=s.jsxs(s.Fragment,{children:[s.jsx(nw,{directory:Ve,className:"mr-1"}),K?s.jsx(Cw,{isDesktopApp:K,currentInstanceLabel:J,compactCurrentInstanceLabel:Pe,currentInstanceIsLocal:Ie,currentInstanceIcon:B,isDesktopServicesOpen:L,setIsDesktopServicesOpen:ae,refreshCurrentInstanceLabel:V,shortcutLabel:Ms,remoteUpdateInfo:ie,remoteUpdateChecking:pe,remoteUpdateError:be,onOpenRemoteUpdate:xe}):s.jsx(jw,{open:L,onOpenChange:ae}),s.jsx(kw,{isMobile:w})]}),Xs=H&&(b||!!h),Pn=()=>s.jsxs("div",{onMouseDown:At,className:_("app-region-drag relative flex h-12 select-none items-center pr-3",nt),style:cs,role:"tablist","aria-label":"Main navigation",children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:Ct}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:ls}}),s.jsxs("div",{className:"flex min-w-0 flex-1 items-center",children:[Bt?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 font-normal leading-tight text-foreground max-w-full",children:Bt.title}),Bt.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-subtle-foreground max-w-full",children:Bt.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(l.Suspense,{fallback:s.jsx("button",{type:"button",className:as,"aria-label":"Open session switcher",children:s.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})}),children:s.jsx(Iw,{align:"start",children:s.jsx("button",{type:"button",className:as,"aria-label":"Open session switcher",children:s.jsx(R,{name:"history",className:"h-[18px] w-[18px]"})})})}),s.jsxs("div",{className:"flex min-w-0 items-center gap-1.5 px-1",children:[Jt?s.jsxs("form",{ref:Ye,className:"flex w-full min-w-0 items-center gap-2 leading-tight",onSubmit:O=>{O.preventDefault(),De()},children:[s.jsx("input",{value:Ft,onChange:O=>Lt(O.target.value),autoFocus:!0,onKeyDown:O=>{O.stopPropagation(),O.key==="Escape"&>(!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(R,{name:"check",className:"size-4"})}),s.jsx("button",{type:"button",onClick:()=>gt(!1),"aria-label":"Cancel renaming session",title:"Cancel renaming session",className:"shrink-0 text-muted-foreground hover:text-foreground",children:s.jsx(R,{name:"close",className:"size-4"})})]}):s.jsxs(s.Fragment,{children:[s.jsx("span",{className:"min-w-0 truncate typography-ui-label font-normal leading-tight text-foreground",children:b?"New session":ne}),h&&!b?s.jsx(Dc,{sessionId:h}):null]}),ge?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-subtle-foreground",children:[U?s.jsx("span",{className:"truncate",children:U}):null,Ue?s.jsxs("span",{className:"inline-flex min-w-0 items-center gap-0.5",children:[s.jsx(R,{name:"git-branch",className:"h-3 w-3 flex-shrink-0 text-subtle-foreground"}),s.jsx("span",{className:"truncate",children:Ue})]}):null]})]}):null]}),s.jsx("div",{className:"flex h-[18px] shrink-0 items-center justify-center self-center",children:h&&!b&&!Jt?s.jsxs(Vt,{open:Et,onOpenChange:rs,onOpenChangeComplete:O=>{!O&&Qe.current&&(Qe.current=!1,Ne())},children:[s.jsx(Yt,{asChild:!0,children:s.jsx(Ae,{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(R,{name:"more",className:"size-4"})})}),s.jsxs(Qt,{align:"end",className:"min-w-[190px]",children:[s.jsxs(ut,{onClick:()=>{Qe.current=!0},children:[s.jsx(R,{name:"pencil-ai",className:"mr-2 size-4"}),"Rename"]}),s.jsxs(ut,{onClick:He,children:[s.jsx(R,{name:"file-copy",className:"mr-2 size-4"}),"Copy session ID"]}),s.jsxs(ut,{onClick:is,disabled:!Ve,children:[s.jsx(R,{name:"folder",className:"mr-2 size-4"}),"Copy working directory"]}),Ue?s.jsxs(ut,{onClick:Rs,children:[s.jsx(R,{name:"git-branch",className:"mr-2 size-4"}),"Copy branch name"]}):null,s.jsx(vn,{}),s.jsxs(ut,{onClick:()=>{ft()},children:[s.jsx(R,{name:"download",className:"mr-2 size-4"}),"Export Markdown"]}),s.jsx(vn,{}),s.jsxs(ut,{onClick:()=>Ee("archive"),children:[s.jsx(R,{name:"inbox-archive",className:"mr-2 size-4"}),"Archive"]}),s.jsxs(ut,{className:"text-destructive focus:text-destructive",onClick:()=>Ee("delete"),children:[s.jsx(R,{name:"delete-bin",className:"mr-2 size-4"}),"Delete"]})]})]}):null})]}),at.length>0&&s.jsx("div",{className:"flex items-center gap-1 rounded-lg bg-[var(--surface-muted)]/50 p-1",children:at.map(O=>lt(O))}),s.jsx("div",{className:"flex-1"}),s.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[s.jsx(Rc,{}),xt?s.jsx(Il,{projectRef:xt.projectRef,directory:xt.directory,className:"mr-1"}):null,s.jsx(tg,{visible:Xs,title:b?"New Mini Chat window":"Open session in Mini Chat",ariaLabel:b?"Open a new Mini Chat window":"Open current session in Mini Chat",onClick:xs,className:_(as,"mr-1"),Icon:"picture-in-picture-2"}),Js,s.jsx(ih,{visible:M})]})]})]}),Fs=()=>s.jsxs("div",{className:"app-region-drag relative flex items-center gap-2 px-3 py-2 select-none",children:[S&&s.jsxs(s.Fragment,{children:[s.jsx("div",{"aria-hidden":!0,className:"shrink-0 self-stretch",style:{width:Ct}}),s.jsx("div",{"aria-hidden":!0,className:"app-region-no-drag shrink-0 self-stretch",style:{width:ls}})]}),!S&&s.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e?s.jsx("button",{type:"button",onClick:Qs,className:_(yt,wt==="sessions"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":n?"Close sessions":"Open sessions",children:s.jsx(R,{name:"layout-left",className:"h-5 w-5"})}):W?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(R,{name:"arrow-left-s",className:"h-5 w-5"})}):s.jsx("button",{type:"button",onClick:Xt,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(R,{name:"play-list-add",className:"h-5 w-5"})}),!e&&W&&s.jsx("span",{className:"typography-ui-label font-semibold text-foreground",children:"Sessions"})]}),(!W||!!e)&&s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"app-region-no-drag flex min-w-0 flex-1 items-center",children:!v&&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:at.map(O=>{const ce=f===O.id,ye=O.icon==="diff",$e=ye?null:O.icon;return s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsxs("button",{type:"button",onClick:()=>{w&&(it(),Rt()),m(O.id)},"aria-label":O.label,"aria-selected":ce,role:"tab",className:_(yt,"relative rounded-lg",wt===O.id&&"bg-interactive-selection text-interactive-selection-foreground"),children:[ye?s.jsx(Cl,{className:"h-5 w-5"}):$e?s.jsx(R,{name:$e,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(Ge,{children:s.jsx("p",{children:O.label})})]},O.id)})})})})}),s.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[v&&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:k.map(O=>{const ce=r&&o===O.id;return s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:()=>{w&&(it(),Rt()),P(!1),i?.(O.id)},"aria-label":O.label,"aria-selected":ce,role:"tab",className:_(yt,"relative h-11 w-11 rounded-lg",ce&&"bg-interactive-selection text-interactive-selection-foreground"),children:s.jsx(R,{name:O.icon,className:"h-5 w-5"})})}),s.jsx(Ge,{children:s.jsx("p",{children:O.label})})]},O.id)})}),s.jsx(Zm,{open:E,onOpenChange:P,currentSessionId:h,effectiveDirectory:Se||null,isNewSessionDraftOpen:b})]}),xt&&s.jsx(Il,{projectRef:xt.projectRef,directory:xt.directory,compact:!0,allowMobile:!0,className:"h-9"}),t&&!v?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:Ps,className:_(yt,"relative",wt==="git"&&"bg-interactive-selection text-interactive-selection-foreground"),"aria-label":r?"Close git sidebar":"Open git sidebar",children:s.jsx(R,{name:"layout-right",className:"h-5 w-5"})})}),s.jsx(Ge,{children:s.jsx("p",{children:r?"Close git sidebar":"Open git sidebar"})})]}):null]})]})]}),Tn=_("header-safe-area relative z-10 bg-background",w&&"border-b border-border/50");return s.jsxs(s.Fragment,{children:[s.jsx("header",{ref:z,className:Tn,style:{"--padding-scale":"1"},children:w?Fs():Pn()}),s.jsx(Aw,{action:kt,onClose:()=>Ee(null),sessionTitle:ne,onConfirm:()=>{os()}}),s.jsx(Cc,{open:X,onOpenChange:ee,info:ie,downloading:!1,downloaded:!1,progress:null,error:be,onDownload:()=>{},onRestart:()=>{},runtimeType:"web"})]})},El="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",Ew="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",hS=()=>{const e=ue(b=>b.isSidebarOpen),t=ue(b=>b.toggleSidebar),n=ue(b=>b.shortcutOverrides),r=l.useRef(null),o=l.useRef(null),i=Fi(zr("toggle_sidebar",n)),a=nc(),{enabled:c}=Ti(),d=!e,u=a,f=d||u,m=u,g=l.useCallback(()=>{Jn("desktop_show_app_menu").catch(b=>{console.warn("[titlebar] failed to open app menu",b)})},[]);return l.useEffect(()=>{if(typeof document>"u")return;const b=j=>{document.documentElement.style.setProperty("--oc-titlebar-controls-width",`${Math.round(j)}px`)},h=j=>{document.documentElement.style.setProperty("--oc-titlebar-overlay-width",`${Math.round(j)}px`)};if(!m)return;const p=o.current,y=r.current;if(!p||!y){b(0),h(0);return}const x=()=>{const j=Math.max(p.getBoundingClientRect().width,p.scrollWidth);b(j),h(y.getBoundingClientRect().width)};if(x(),typeof ResizeObserver>"u")return;const C=new ResizeObserver(x);return C.observe(p),C.observe(y),()=>{C.disconnect()}},[m]),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(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:g,"aria-label":"Open PiChamber menu",className:_(El,"shrink-0"),children:s.jsx(R,{name:"menu-2",className:"h-[18px] w-[18px]"})})}),s.jsx(Ge,{children:s.jsx("p",{children:"PiChamber menu"})})]}):null,d?s.jsxs(Ke,{children:[s.jsx(We,{asChild:!0,children:s.jsx("button",{type:"button",onClick:t,"aria-label":"Open sessions",className:_(c?Ew:El,"shrink-0"),children:s.jsx(R,{name:"layout-left",className:c?"size-[18px]":"h-[18px] w-[18px]"})})}),s.jsx(Ge,{children:s.jsx("p",{children:`Open sessions (${i})`})})]}):null]})}):null},Dl=200,Dw="cubic-bezier(0.22, 1, 0.36, 1)",pS=e=>{const t=l.useMemo(()=>typeof window>"u"||typeof window.matchMedia!="function"?!1:window.matchMedia("(prefers-reduced-motion: reduce)").matches,[]),[n,r]=l.useState(e),[o,i]=l.useState(e);return l.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 a=window.setTimeout(()=>i(!1),Dl);return()=>window.clearTimeout(a)},[e,t]),{slidIn:n,layoutVisible:o,prefersReducedMotion:t,transition:t?"none":`transform ${Dl}ms ${Dw}`}},mS=()=>{uc()},gS=e=>{Me.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),ue.getState().prepareForRuntimeSwitch(e.previousRuntimeKey),we.getState().clearAll(),uc(),jn.getState().resetForRuntimeSwitch(),ah.getState().resetForRuntimeSwitch(),lh.getState().resetForRuntimeSwitch(),ch(),Kh(),Wh(),gh(),dh.getState().resetForRuntimeSwitch(),uh.getState().resetForRuntimeSwitch(),fh.getState().resetForRuntimeSwitch(),jm.getState().resetForRuntimeSwitch(),Cm.getState().resetForRuntimeSwitch(),Gt.setState({providers:[],isConnected:!1,isInitialized:!1,connectionPhase:"connecting",lastDisconnectReason:null}),ot.getState().resetForRuntimeSwitch(),hh(),ph(),rp.getState().reset(),Gh.getState().resetForRuntimeSwitch(),ql.getState().resetForRuntimeSwitch(e.runtimeKey),_r.getState().resetForRuntimeSwitch(e.runtimeKey),Hh(),Ws.getState().resetForRuntimeSwitch(e.runtimeKey),mh.getState().resetForRuntimeSwitch(),ts.getState().resetForRuntimeSwitch(),bt.getState().resetForRuntimeSwitch(e.runtimeKey),qh.getState().resetForRuntimeSwitch(e.runtimeKey),Me.getState().restoreForRuntimeSwitch(e.runtimeKey),ue.getState().restoreForRuntimeSwitch(e.runtimeKey);const t=ue.getState();li({sessionId:Me.getState().currentSessionId,tab:t.activeMainTab,isSettingsOpen:t.isSettingsDialogOpen,settingsPath:t.settingsPage,diffFile:t.pendingDiffFile},{replace:!0,force:!0})};export{fS as $,eo as A,Wv as B,Uv as C,Jm as D,Ja as E,Zm as F,iy as G,bl as H,Hn as I,ny as J,oS as K,rS as L,Ec as M,Lr as N,iS as O,nS as P,Yy as Q,aS as R,Dc as S,_i as T,Ny as U,lS as V,gd as W,cS as X,pS as Y,dS as Z,hS as _,_s as a,Cs as a$,_v as a0,gv as a1,mS as a2,gS as a3,Vw as a4,Qw as a5,Jw as a6,Yw as a7,Gw as a8,Hw as a9,Cv as aA,Bv as aB,Ov as aC,wv as aD,Pv as aE,Rv as aF,Ev as aG,qm as aH,Vm as aI,Oa as aJ,uS as aK,Op as aL,qw as aM,sm as aN,nm as aO,mv as aP,dm as aQ,iv as aR,Bi as aS,Cc as aT,nv as aU,lm as aV,jm as aW,Cm as aX,cv as aY,pm as aZ,ov as a_,Kw as aa,ro as ab,oo as ac,io as ad,Ks as ae,td as af,Bs as ag,Kc as ah,dr as ai,$c as aj,Xw as ak,vv as al,xv as am,bv as an,yv as ao,Lv as ap,Tv as aq,Mv as ar,Fv as as,Iv as at,Nv as au,jv as av,Sv as aw,kv as ax,Hm as ay,Av as az,Rn as b,av as b0,lv as b1,fm as b2,pv as b3,fv as b4,ym as b5,km as b6,im as b7,hm as b8,uv as b9,Oi as ba,rv as bb,As as bc,Um as bd,rm as be,Ac as bf,um as bg,fr as bh,Zw as bi,om as bj,hv as bk,dv as bl,ev as bm,tv as bn,sv as bo,Dv as bp,Mm as bq,cm as br,_p as bs,am as bt,zp as bu,gb as c,Kn as d,Dn as e,Gm as f,Hv as g,Kv as h,Ns as i,ts as j,zv as k,tS as l,sS as m,Yv as n,ed as o,qv as p,$v as q,Gv as r,wi as s,Vv as t,Ww as u,Jv as v,Xv as w,Zv as x,eS as y,Qv as z};
|