@pi-chamber/web 1.0.7 → 1.0.8-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/AgentsSurface-BmHImX8m.js +1 -0
- package/dist/assets/ChoicesArtifact-C71fGOm2.js +1 -0
- package/dist/assets/DiagramView-BZQxoiZu.js +1 -0
- package/dist/assets/{DiffView-BxW6BuOC.js → DiffView-C70pbgk-.js} +6 -6
- package/dist/assets/FileSaveConflictDialog-Cu8c3gBV.js +3 -0
- package/dist/assets/FilesView-nFJYEdRw.js +6 -0
- package/dist/assets/GitHubDetailScaffold-Jvv_tgbl.js +11 -0
- package/dist/assets/GitHubLinkPicker-BXD2ODRi.js +1 -0
- package/dist/assets/GitHubListPrimitives-BWI706F0.js +1 -0
- package/dist/assets/{GitView-DD33ngnM.js → GitView-MIDG5RYW.js} +5 -5
- package/dist/assets/{IssuesSurface-BAY_eyX5.js → IssuesSurface-uNlozeu0.js} +2 -2
- package/dist/assets/{JsonTreeView-DpXbUrAl.js → JsonTreeView-CSLsTriz.js} +1 -1
- package/dist/assets/{MarkdownRendererImpl-Cn63lAmn.js → MarkdownRendererImpl-Cs-7BfWi.js} +3 -3
- package/dist/assets/PatchDiff-axbsnbTJ.js +1 -0
- package/dist/assets/PierreDiffViewer-lwn6w_5w.js +147 -0
- package/dist/assets/PullRequestsSurface-o_AXDjbO.js +2 -0
- package/dist/assets/{SessionSwitcherContent-CscYekC1.js → SessionSwitcherContent-C4CMlcbv.js} +1 -1
- package/dist/assets/SessionSwitcherDropdown-DCBVuCoo.js +2 -0
- package/dist/assets/SessionUnreadDot-DyeIrsro.js +1 -0
- package/dist/assets/SettingsView-BHBpt2Um.js +7 -0
- package/dist/assets/{SettingsWindow-gxjULdm1.js → SettingsWindow-Cb4st5y5.js} +1 -1
- package/dist/assets/{StickyHorizontalScrollbar-DNsbTLS7.js → StickyHorizontalScrollbar-CMbTn5WQ.js} +1 -1
- package/dist/assets/SubagentsArtifact-BzeMEoFP.js +1 -0
- package/dist/assets/ToolOutputDialog-BP2mOWdV.js +8 -0
- package/dist/assets/ToolPartDiffPreview-D49XBR9b.js +1 -0
- package/dist/assets/{VirtualizedFileDiff-BrbPymTL.js → VirtualizedFileDiff-CLgDONEQ.js} +4 -4
- package/dist/assets/{Virtualizer-okhy9Aq3.js → Virtualizer-PxblpQn6.js} +1 -1
- package/dist/assets/VisualFrame-CJrAvWSo.js +22 -0
- package/dist/assets/VisualsArtifact-DqLGgU-Q.js +1 -0
- package/dist/assets/{collapsible-D6qdoq7-.js → collapsible-BeyKtQGB.js} +1 -1
- package/dist/assets/{computeVirtualFileMetrics-G4csGiKs.js → computeVirtualFileMetrics-DmO6H8u6.js} +2 -2
- package/dist/assets/contextFileOpenGuard-DOK251YW.js +1 -0
- package/dist/assets/{fileTreeStatus-Bskhj4qT.js → fileTreeStatus-CnzR7kxA.js} +2 -2
- package/dist/assets/gitStatusPredicates-4kPg2t6j.js +1 -0
- package/dist/assets/githubLink-QvaLfNNT.js +10 -0
- package/dist/assets/{index-I2QYqABE.js → index-B2v0_mez.js} +8 -8
- package/dist/assets/index-D3F4JrPN.css +1 -0
- package/dist/assets/{index-ComwtfT4.js → index-DMX9wT1Z.js} +1 -1
- package/dist/assets/{main-DoiadX0a.js → main-BW9J3Y72.js} +2 -2
- package/dist/assets/main-BirYxac2.js +137 -0
- package/dist/assets/{markdownCore-DczkEluO.js → markdownCore-CxmcPur8.js} +2 -2
- package/dist/assets/miniChat-BRB11eEs.js +2 -0
- package/dist/assets/{mobile-BucKVm1P.js → mobile-DJZYYCuB.js} +2 -2
- package/dist/assets/{nativeFileSave-Cp9i5QGd.js → nativeFileSave-B6QpoPRn.js} +1 -1
- package/dist/assets/pi-session-focus-preference-PWoh3LNA.js +9 -0
- package/dist/assets/{renderDiffWithHighlighter-PL82AR81.js → renderDiffWithHighlighter-C48T6YFJ.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-N-BQdJl0.js +2 -0
- package/dist/assets/{renderFileWithHighlighter-CYgfbA4F.js → renderFileWithHighlighter-8Kt2MyTN.js} +1 -1
- package/dist/assets/{renderMobileApp-Bp74b_Lo.js → renderMobileApp-B7cT7m5b.js} +3 -3
- package/dist/assets/runtimeEndpointReset-BC6yGnxN.js +62 -0
- package/dist/assets/runtimeSurface-kIEoYsPP.js +1 -0
- package/dist/assets/selection-BTEdLRVK.js +1 -0
- package/dist/assets/useAppFontEffects-EcTZ_I_I.js +225 -0
- package/dist/assets/useGitHubRemoteSearch-DIBHNu8r.js +1 -0
- package/dist/assets/useSwitcherItems-DfLbfX37.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-C_DsTJis.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/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 +87 -0
- package/plugins/visuals/files.js +74 -0
- package/plugins/visuals/package.json +32 -0
- package/server/index.js +20 -0
- package/server/lib/github/DOCUMENTATION.md +4 -2
- package/server/lib/github/gh-cli.js +35 -9
- package/server/lib/github/gh-cli.test.js +122 -0
- package/server/lib/notifications/pi-notification-watcher.js +3 -0
- package/server/lib/notifications/pi-notification-watcher.test.js +10 -0
- package/server/lib/open-url/DOCUMENTATION.md +1 -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/routes-extension-events.test.js +115 -0
- package/server/lib/pi/routes.js +307 -5
- package/server/lib/pi/routes.test.js +296 -1
- package/server/lib/pi/session-daemon/DOCUMENTATION.md +25 -8
- package/server/lib/pi/session-daemon/extension-bridge.js +89 -29
- package/server/lib/pi/session-daemon/extension-config.js +719 -0
- package/server/lib/pi/session-daemon/extension-config.test.js +618 -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.js +568 -61
- package/server/lib/pi/session-daemon/session-daemon.test.js +164 -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/supervisor.js +22 -3
- package/server/lib/pi/settings-store.js +14 -0
- package/server/lib/pi/settings-store.test.js +11 -0
- package/server/lib/plugins/DOCUMENTATION.md +186 -0
- package/server/lib/plugins/daemon-sync.js +78 -0
- package/server/lib/plugins/daemon-sync.supervisor.test.js +83 -0
- package/server/lib/plugins/daemon-sync.test.js +96 -0
- package/server/lib/plugins/impact.js +139 -0
- package/server/lib/plugins/impact.test.js +82 -0
- package/server/lib/plugins/manifest.js +195 -0
- package/server/lib/plugins/manifest.test.js +118 -0
- package/server/lib/plugins/registry.js +59 -0
- package/server/lib/plugins/routes.js +92 -0
- package/server/lib/plugins/routes.test.js +219 -0
- package/server/lib/plugins/service.js +161 -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-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/main-DyFfbllq.js +0 -137
- package/dist/assets/miniChat-Ck6MEZ9Q.js +0 -2
- package/dist/assets/pi-session-focus-preference-Dx0UXPoO.js +0 -9
- package/dist/assets/renderElectronMiniChatApp-Cb7s7dWl.js +0 -2
- 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
|
@@ -1,137 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/DiffView-BxW6BuOC.js","assets/vendor-boot-3SaHYVb1.js","assets/vendor-react-Bz1tRBxM.js","assets/vendor-clsx-B-dksMZM.js","assets/index-I2QYqABE.js","assets/vendor-zustand-CXhN0IMY.js","assets/vendor-vite-runtime-DD1OZmLC.js","assets/vendor-tailwind-merge-BKkUfl9q.js","assets/vendor-fuse.js-t_7AcMTv.js","assets/index-BaLCg7tL.css","assets/useAppFontEffects-ZTyNwFk6.js","assets/runtimeSurface-CFwnvks_.js","assets/nativeFileSave-Cp9i5QGd.js","assets/gitStatusPredicates-DQEO4Psc.js","assets/VirtualizedFileDiff-BrbPymTL.js","assets/web-components-CGDpzixf.js","assets/computeVirtualFileMetrics-G4csGiKs.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/renderDiffWithHighlighter-PL82AR81.js","assets/vendor-diff-C3JhlQdm.js","assets/PierreDiffViewer-wc6cB6qw.js","assets/StickyHorizontalScrollbar-DNsbTLS7.js","assets/runtimeEndpointReset-7nWYnKd4.js","assets/SessionUnreadDot-CbqRq6h_.js","assets/permissionStore-zIpxq9Pq.js","assets/runtimeEndpointReset-BV3KOtdA.css","assets/vendor-xterm-xterm-css-DDGTF8rc.css","assets/appThemeRegistry-Ca8eGRB9.js","assets/registerCustomTheme-C-h6lsYW.js","assets/contextFileOpenGuard-UU86YHgI.js","assets/FilesView-DECxN8Z0.js","assets/vendor-codemirror-lang-javascript-Bx_FIyZF.js","assets/vendor-lezer-javascript-BH2Etgoy.js","assets/vendor-lezer-lr-HY6Yc0Vr.js","assets/vendor-codemirror-autocomplete-WThuuUAz.js","assets/vendor-codemirror-lang-json-DIvqf9Pb.js","assets/vendor-lezer-json-CE-QUCwM.js","assets/vendor-codemirror-lang-css-D1wpUg3Z.js","assets/vendor-lezer-css-Cb8vp67u.js","assets/vendor-codemirror-lang-html-DbL8oT9H.js","assets/vendor-lezer-html-UQMsUwj-.js","assets/vendor-codemirror-lang-markdown-v3yG2sbf.js","assets/vendor-lezer-markdown-xFL3Evwf.js","assets/vendor-codemirror-language-data-B03xgzP2.js","assets/vendor-codemirror-lang-python-b-JqEwQy.js","assets/vendor-lezer-python-BNRFWCb0.js","assets/shell-CjFT_Tl9.js","assets/FileSaveConflictDialog-Bzz8FNMq.js","assets/vendor-react-drawio-IYnLUY5N.js","assets/fileTreeStatus-Bskhj4qT.js","assets/JsonTreeView-DpXbUrAl.js","assets/Virtualizer-okhy9Aq3.js","assets/renderFileWithHighlighter-CYgfbA4F.js","assets/vendor-codemirror-search-Dw3Wpu15.js","assets/vendor-replit-codemirror-vim-D1Fe7FiY.js","assets/vendor-replit-codemirror-vim-core-FHzKdNUS.js","assets/GitView-DD33ngnM.js","assets/GitHubDetailScaffold-CWsWycRd.js","assets/vendor-dompurify-BGCr_sdL.js","assets/collapsible-D6qdoq7-.js","assets/vendor-base-ui-BCqPBzDj.js","assets/PullRequestsSurface-BZvJkT1I.js","assets/useGitHubRemoteSearch-BF3ohpsh.js","assets/GitHubListPrimitives-Dlv3tC4d.js","assets/IssuesSurface-BAY_eyX5.js","assets/githubLink-ByPAyFjh.js","assets/DiagramView-BB-aZobi.js","assets/SettingsView-DcF-At5E.js","assets/vendor-qrcode-gzL9QFkg.js","assets/vendor-dijkstrajs-COg3n3zL.js","assets/vendor-aparajita-capacitor-secure-storage-DVZvgYu4.js","assets/SettingsWindow-gxjULdm1.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{aZ as Mn,a_ as _t,a$ as Ss,j as e,b0 as In,b1 as Ln,bc as On,ce as ks,b2 as Cs,bg as Bn,bh as Fn,be as Ns,bf as Ps,c0 as Rs,bd as Es,cf as tn,cb as gt,aQ as nn,aR as Ts}from"./vendor-boot-3SaHYVb1.js";import{R as s,a as Le}from"./vendor-react-Bz1tRBxM.js";/* empty css */import{h as X,f as pe,z as Mt,aQ as Ds,a1 as $n,cy as As,b as _s,a as Wn,aa as Ms,$ as Is,au as $e,cz as Ls,j as _e,bN as Os,H as Bs,M as Fs,k as zn,O as $s,br as Ws,bs as zs,cA as sn,cB as ct,u as rn,as as Hs,a0 as Us,bi as Vs,W as Hn,X as Un,bO as Ks,cC as Xs,cD as qs,p as Ys,ap as Gs,q as Js,v as Vn,o as Qs}from"./index-I2QYqABE.js";import{_ as Fe}from"./vendor-vite-runtime-DD1OZmLC.js";import{l as Zs,am as on,an as er,ao as tr,ap as nr,aq as sr,ar as rr,as as or,at,au as ar,av as ir,aw as lr,ax as cr,ay as dr,az as ur,aA as hr,aB as fr,aC as pr,aD as Kn,aE as mr,aF as gr,aG as xr,aH as wr,aI as br,aJ as yr,aK as Xn,aL as qn,aM as It,T as Yn,aN as vr,al as jr,aj as Sr,aO as kr,m as Cr,w as Nr,t as Pr,v as Rr,H as an,C as ln,A as cn,S as dn,n as Er,p as Tr,q as Dr,F as Ar,O as _r,W as Mr}from"./runtimeEndpointReset-7nWYnKd4.js";import{as as vt,I as U,E as Be,c6 as ft,B as ne,ah as pt,t as ye,P as Ht,h as Te,o as st,cR as Ct,cS as Ir,cT as Ut,a$ as Lt,aR as Qe,aS as Ze,b0 as Ot,aT as et,b1 as Bt,bv as Ge,bT as Gn,z as jt,y as mt,cU as Vt,b2 as un,aP as Lr,av as Kt,aw as Xt,aB as qt,ax as Yt,ay as Gt,aC as Or,bU as Br,cV as Fr,cW as $r,ba as Jn,O as Je,cX as dt,v as Qn,cY as Wr,cw as zr,cZ as ze,bF as Zn,c_ as Hr,c$ as Ur,d0 as Jt,d1 as Vr,bj as es,A as hn,bb as Kr,aI as Xr,d2 as qr,d3 as Yr,bc as fn,b9 as Gr,b as Jr,c as Qr,bq as Zr,a as pn,bL as eo,r as Nt,az as to,bQ as no,bM as so,d4 as ro,d5 as oo,d6 as ao,d7 as io,d8 as it,d9 as lt,da as lo,bW as co,bk as uo,au as ho,bu as fo,ac as po,ad as mo,ae as go,$ as xo,_ as wo,a4 as bo,Y as yo,a5 as vo,a0 as jo,a1 as So,a2 as ko,a3 as Co,a6 as No,a7 as Po,aa as Ro,ab as Eo}from"./useAppFontEffects-ZTyNwFk6.js";import{g as ts,F as To,a as Do,u as Ao,i as _o,s as Mo,b as Io,c as Lo,d as Oo,e as mn,f as ns,h as Bo}from"./fileTreeStatus-Bskhj4qT.js";import{v as ss,g as rs}from"./contextFileOpenGuard-UU86YHgI.js";import"./vendor-clsx-B-dksMZM.js";import"./vendor-zustand-CXhN0IMY.js";import"./vendor-tailwind-merge-BKkUfl9q.js";import"./vendor-fuse.js-t_7AcMTv.js";import"./SessionUnreadDot-CbqRq6h_.js";/* empty css */import"./nativeFileSave-Cp9i5QGd.js";import"./permissionStore-zIpxq9Pq.js";import"./runtimeSurface-CFwnvks_.js";const Fo=280,gn=4,$o=({transform:t})=>({...t,y:0}),Wo=({id:t,children:n,className:r})=>{const{attributes:a,listeners:i,setNodeRef:o,transform:u,transition:l,isDragging:c}=Bn({id:t});return e.jsx("div",{ref:o,"data-sortable-tab-id":t,style:{transform:Fn.Transform.toString(u),transition:l},className:pe("h-full rounded-md",r,c&&"opacity-50"),...a,...i,children:n})},zo=({id:t,children:n,className:r})=>e.jsx("div",{className:pe("h-full",r),"data-sortable-tab-id":t,children:n}),os=({items:t,activeId:n,onSelect:r,onClose:a,onReorder:i,layoutMode:o="scrollable",variant:u="default",activePillInsetClassName:l,activePillButtonClassName:c,inactiveTabsIconOnly:f=!1,animateActivePill:x,activePillLowercase:b=!0,nonCompositedIndicator:d=!1,className:g})=>{const p=X(O=>O.isMobile),{isTablet:$}=vt(),k=p||$,D=s.useRef(null),[I,K]=s.useState({left:!1,right:!1}),w=s.useMemo(()=>t.map(O=>O.id),[t]),P=o==="scrollable",v=u==="default",_=u==="active-pill",R=_||u==="animated",Q=v,q=R||Q,z=_&&P,ee=R,oe=x??R,H=typeof i=="function",se=H?Wo:zo,C=s.useRef(new Map),[W,re]=s.useState(null),[E,B]=s.useState(!1),[Z,ue]=s.useState(null),ge=s.useRef(!1),he=s.useRef(0),xe=s.useRef(n),je=s.useRef(null),Ne=s.useMemo(()=>{if(!q||!Z||!n||Z===n)return 0;const O=t.findIndex(de=>de.id===Z),V=t.findIndex(de=>de.id===n);return O<0||V<0?0:O>V?gn:-gn},[n,t,Z,q]),we=Mn(_t(Ss,{activationConstraint:{distance:8}})),me=s.useCallback((O,V)=>!O||!V?O===V:Math.abs(O.left-V.left)<.5&&Math.abs(O.top-V.top)<.5&&Math.abs(O.width-V.width)<.5&&Math.abs(O.height-V.height)<.5,[]),ve=s.useCallback((O,V)=>{if(V){C.current.set(O,V);return}C.current.delete(O)},[]),Ce=s.useCallback(()=>{if(!q||!n){re(L=>L===null?L:null);return}const O=D.current,V=C.current.get(n);if(!O||!V){re(L=>L===null?L:null);return}let de=0,M=0,te=V;for(;te&&te!==O;)de+=te.offsetLeft,M+=te.offsetTop,te=te.offsetParent;const S={left:de,top:M,width:V.offsetWidth,height:V.offsetHeight};re(L=>me(L,S)?L:S)},[n,me,q]),be=s.useCallback(()=>{if(!P){K({left:!1,right:!1});return}const O=D.current;if(!O){K({left:!1,right:!1});return}K({left:O.scrollLeft>2,right:O.scrollLeft+O.clientWidth<O.scrollWidth-2})},[P]);s.useEffect(()=>{if(!P){K({left:!1,right:!1});return}const O=D.current;if(!O)return;be(),O.addEventListener("scroll",be,{passive:!0});const V=new ResizeObserver(be);return V.observe(O),()=>{O.removeEventListener("scroll",be),V.disconnect()}},[P,t.length,be]),s.useEffect(()=>{if(!P)return;const O=D.current;if(!O)return;const V=de=>{if(de.ctrlKey||Math.abs(de.deltaY)<=Math.abs(de.deltaX))return;const M=O.scrollWidth-O.clientWidth;if(M<=0)return;const te=de.deltaMode===WheelEvent.DOM_DELTA_LINE?de.deltaY*16:de.deltaMode===WheelEvent.DOM_DELTA_PAGE?de.deltaY*O.clientWidth:de.deltaY;de.preventDefault(),O.scrollLeft=Math.min(M,Math.max(0,O.scrollLeft+te))};return O.addEventListener("wheel",V,{passive:!1}),()=>{O.removeEventListener("wheel",V)}},[P]),s.useEffect(()=>{if(!q){re(null);return}Ce();const O=D.current;if(!O)return;const V=new ResizeObserver(()=>{performance.now()-he.current>Fo&&B(!1),Ce()});if(V.observe(O),n){const de=C.current.get(n);de&&V.observe(de)}return()=>{V.disconnect()}},[n,t.length,Ce,q]),s.useLayoutEffect(()=>{Ce()});const ke=w.join("\0");s.useLayoutEffect(()=>{if(!q){ge.current=!1,B(!1);return}const O=je.current!==ke;if(je.current=ke,!ge.current){ge.current=!0,xe.current=n;return}const V=xe.current!==n;if(xe.current=n,!V||O){B(!1);return}he.current=performance.now(),B(!0)},[n,ke,q]),s.useEffect(()=>{if(!P||!n)return;const O=D.current;if(!O)return;const V=window.requestAnimationFrame(()=>{const de=typeof window.CSS?.escape=="function"?window.CSS.escape(n):n.replace(/"/g,'\\"'),M=O.querySelector(`[data-sortable-tab-id="${de}"]`);M&&(M.scrollIntoView({block:"nearest",inline:"nearest"}),be())});return()=>{window.cancelAnimationFrame(V)}},[n,P,t.length,be]);const Pe=s.useCallback(O=>{if(!i)return;const{active:V,over:de}=O;!de||V.id===de.id||i(String(V.id),String(de.id))},[i]),Re=e.jsxs("div",{className:pe("relative flex h-full min-w-0 flex-1",g),children:[P&&I.left?e.jsx("div",{className:pe("pointer-events-none absolute inset-y-0 left-0 z-20 bg-gradient-to-r to-transparent",R?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,P&&I.right?e.jsx("div",{className:pe("pointer-events-none absolute inset-y-0 right-0 z-20 bg-gradient-to-l to-transparent",R?"w-8 from-[var(--surface-background)]":"w-6 from-background")}):null,e.jsxs("div",{ref:D,className:pe("relative flex h-full min-w-0 flex-1",R?"items-center overflow-x-hidden overflow-y-hidden":"items-stretch",R&&"@container/pill-tabs",R&&"pill-tabs__track",R&&(l??"gap-0.5 py-0.5"),Q&&"items-center overflow-y-hidden",ee&&"rounded-[10px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[color-mix(in_srgb,var(--foreground)_4%,transparent)] p-0.5 gap-0.5",P?"overflow-x-auto scrollbar-none":"overflow-x-hidden"),style:P?{scrollbarWidth:"none",msOverflowStyle:"none"}:void 0,role:"tablist","aria-label":"Tabs",children:[R&&W?e.jsx("div",{className:pe("pointer-events-none absolute left-0 top-0 z-0 rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] bg-[var(--surface-elevated)]","border border-[color-mix(in_srgb,var(--foreground)_7%,transparent)]","shadow-[0_1px_2px_color-mix(in_srgb,var(--foreground)_10%,transparent),0_2px_6px_color-mix(in_srgb,var(--foreground)_6%,transparent)]",oe&&E&&(d?"pill-tabs__indicator--is-animated-layout":"pill-tabs__indicator--is-animated")),style:d?{left:`${W.left+Ne}px`,top:`${W.top}px`,width:`${W.width}px`,height:`${W.height}px`}:{transform:`translate3d(${W.left+Ne}px, ${W.top}px, 0)`,width:`${W.width}px`,height:`${W.height}px`}}):null,Q&&W?e.jsx("div",{className:pe("pointer-events-none absolute left-0 -bottom-px z-10 h-[3px] rounded-t-[2px] bg-[var(--primary-base)]",E&&"underline-tabs__indicator--is-animated"),style:{transform:`translate3d(${W.left+Ne}px, 0, 0)`,width:`${W.width}px`},"aria-hidden":!0}):null,t.map(O=>{const V=O.id===n,de=f&&R&&!V&&!!O.icon,M=!de,te=!!O.icon,S=f&&R&&V&&!P&&!z,L=O.closable!==!1&&!!a,F=L&&!!O.icon,ae=P||z?void 0:R?S?"flex-none basis-auto":p?"flex-1 basis-0 min-w-0":"flex-1 basis-0 min-w-fit":"min-w-0 flex-1 basis-0",ie=L?Y=>{Y.button===1&&(Y.preventDefault(),Y.stopPropagation(),a?.(O.id))}:void 0,m=L?Y=>{Y.button===1&&Y.preventDefault()}:void 0,A=Y=>te?e.jsxs("span",{className:Y,children:[e.jsx("span",{className:pe("flex items-center justify-center transition-opacity",F&&(k?"opacity-0":"group-hover:opacity-0")),children:O.icon}),F?e.jsx("span",{role:"button",tabIndex:-1,className:pe("absolute inset-0 z-20 flex !min-h-0 !min-w-0 items-center justify-center rounded-sm text-muted-foreground transition-opacity hover:text-foreground",k?"opacity-100":"opacity-0 group-hover:opacity-100"),onPointerDown:ce=>ce.stopPropagation(),onClick:ce=>{ce.stopPropagation(),a?.(O.id)},"aria-label":O.closeLabel??`Close ${O.label} tab`,title:O.closeLabel??`Close ${O.label} tab`,children:e.jsx(U,{name:"close",className:"h-3.5 w-3.5"})}):null]}):null;return e.jsx(se,{id:O.id,className:ae,children:e.jsxs("div",{ref:Y=>ve(O.id,Y),onAuxClick:ie,onMouseDown:m,className:pe("group flex h-full min-w-0 flex-nowrap items-center",P||z?"shrink-0":R?"w-full":"w-full min-w-0",R?"relative z-10 bg-transparent":V?"relative z-10 bg-transparent text-foreground":"relative z-10 bg-transparent text-muted-foreground hover:text-foreground"),children:[e.jsx("button",{type:"button",role:"tab","aria-selected":V,"aria-label":de?O.title??O.label:void 0,onClick:()=>r(O.id),onPointerDown:q?()=>{B(!0),ue(O.id)}:void 0,onPointerUp:q?()=>ue(null):void 0,onPointerLeave:q?()=>ue(null):void 0,onPointerCancel:q?()=>ue(null):void 0,className:pe(R?"animated-tabs__button pill-tabs__button relative z-10 flex flex-1 min-w-0 flex-nowrap items-center justify-center rounded-[9px] [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-[50px] text-sm font-medium transition-colors duration-150 !min-h-0":"flex h-full min-w-0 flex-nowrap items-center typography-micro",R&&b?"lowercase":null,R&&(de?"gap-0":"gap-1.5"),R?z?"shrink-0 whitespace-nowrap px-3 text-center":P?"max-w-56 shrink-0 px-3 text-center":de?"px-2 !min-w-0 text-center":S?"shrink-0 whitespace-nowrap px-3 text-center":"px-3 text-center":P?"max-w-56 justify-start truncate px-3 text-left":"w-full justify-center truncate px-3 text-center",R?c??(_?p?"h-[38px]":"h-[31px]":"h-7"):null,R?V?"text-foreground":"text-muted-foreground hover:text-foreground":null,R?"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--interactive-focus-ring)] focus-visible:ring-offset-1 focus-visible:ring-offset-background":null),title:O.title??O.label,children:R?e.jsxs(e.Fragment,{children:[A("relative flex h-4 w-4 shrink-0 items-center justify-center"),M?e.jsx("span",{className:"animated-tabs__label truncate",children:O.label}):null]}):e.jsxs("span",{className:pe("flex min-w-0 flex-nowrap items-center gap-1.5",!P&&"justify-center"),children:[A(pe("relative flex h-4 w-4 shrink-0 items-center justify-center transition-colors duration-200 ease-out",V?"text-[var(--primary-base)]":"text-muted-foreground")),e.jsx("span",{className:"truncate leading-[1.2]",children:O.label})]})}),L&&!F?e.jsx("button",{type:"button",onPointerDown:Y=>{Y.stopPropagation()},onClick:Y=>{Y.stopPropagation(),a?.(O.id)},className:pe("relative z-20 inline-flex !min-h-0 !min-w-0 items-center justify-center transition-opacity",R?"-ml-2.5 mr-1 h-[88%] w-5 self-center !aspect-auto rounded-md":"aspect-square h-[65%] min-h-4 max-h-5 rounded-sm mr-1",R?V?"text-muted-foreground hover:bg-transparent hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-transparent hover:text-foreground group-hover:opacity-100":V?"text-muted-foreground hover:bg-interactive-hover/60 hover:text-foreground":"text-muted-foreground opacity-0 hover:bg-interactive-hover/80 hover:text-foreground group-hover:opacity-100"),"aria-label":O.closeLabel??`Close ${O.label} tab`,title:O.closeLabel??`Close ${O.label} tab`,children:e.jsx(U,{name:"close",className:"h-3 w-3"})}):null]})},O.id)})]})]});return H?e.jsxs(In,{sensors:we,collisionDetection:Ln,onDragEnd:Pe,modifiers:[$o],children:[e.jsx(On,{items:w,strategy:ks,children:Re}),e.jsx(Cs,{dropAnimation:null})]}):Re},xn=280,wn=280,bn=500,Ho=({isOpen:t,isMobile:n,children:r,className:a,topBar:i})=>{const o=X(y=>y.sidebarWidth),u=X(y=>y.setSidebarWidth),[l,c]=s.useState(!1),f=s.useRef(0),x=s.useRef(o||xn),b=s.useRef(null),d=s.useRef(null),g=s.useRef(null),p=s.useCallback(y=>Math.min(bn,Math.max(wn,y)),[]),$=s.useCallback(y=>{const R=g.current;R&&(R.style.width=`${y}px`,R.style.minWidth=`${y}px`,R.style.maxWidth=`${y}px`,R.style.setProperty("--oc-left-sidebar-width",`${y}px`))},[]);s.useEffect(()=>{n&&l&&c(!1)},[n,l]),s.useEffect(()=>{l||(b.current=null,d.current=null)},[l]);const k=Zs(t);if(n)return null;const D=Math.min(bn,Math.max(wn,o||xn)),I=k.layoutVisible?D:0,K=y=>{if(t){try{y.currentTarget.setPointerCapture(y.pointerId)}catch{}d.current=y.pointerId,c(!0),f.current=y.clientX,x.current=I,b.current=I,$(I),y.preventDefault()}},w=y=>{if(n||!l||d.current!==y.pointerId)return;const R=y.clientX-f.current,Q=p(x.current+R);b.current!==Q&&(b.current=Q,$(Q))},P=y=>{if(d.current!==y.pointerId||n)return;try{y.currentTarget.releasePointerCapture(y.pointerId)}catch{}const R=p(b.current??I);d.current=null,b.current=null,c(!1),u(R)},v=l?b.current??I:I,_=l?v:I;return e.jsxs("aside",{ref:g,className:pe("relative flex h-full overflow-hidden motion-reduce:transition-none","bg-sidebar",a),style:{width:`${_}px`,minWidth:`${_}px`,maxWidth:`${_}px`,"--oc-left-sidebar-width":`${l?v:D}px`,overflowX:"clip",transform:l||k.slidIn?"translateX(0)":"translateX(-100%)",transition:l?"none":k.transition},"aria-hidden":!t||_===0,children:[t&&e.jsx("div",{className:"pointer-events-none absolute inset-0 z-30 shadow-[inset_-2px_0_10px_-2px_rgb(0_0_0_/_0.06)]","aria-hidden":"true"}),t&&e.jsx("div",{className:pe("absolute right-0 top-0 z-20 h-full w-[3px] cursor-col-resize hover:bg-[var(--interactive-border)]/80 transition-colors",l&&"bg-[var(--interactive-border)]"),onPointerDown:K,onPointerMove:w,onPointerUp:P,onPointerCancel:P,role:"separator","aria-orientation":"vertical","aria-label":"Resize left panel"}),e.jsxs("div",{className:pe("relative z-10 flex h-full shrink-0 flex-col",l&&"pointer-events-none",!t&&"pointer-events-none select-none"),style:{width:"var(--oc-left-sidebar-width)",overflowX:"hidden"},"aria-hidden":!t,children:[i,e.jsx("div",{className:"min-h-0 flex-1 overflow-y-auto",children:e.jsx(Be,{children:r})})]})]})},Uo=t=>{if(!t||typeof t!="object")return!1;const n=t;return typeof n.x=="number"&&typeof n.y=="number"},yn=t=>!t||typeof t!="object"?!1:Object.values(t).every(n=>typeof n=="string"),rt=t=>{if(!t||typeof t!="object")return!1;const n=t,r=n.bounds;return typeof n.tag=="string"&&typeof n.text=="string"&&typeof n.selector=="string"&&typeof n.path=="string"&&!!r&&typeof r?.x=="number"&&typeof r?.y=="number"&&typeof r?.width=="number"&&typeof r?.height=="number"&&Uo(n.center)&&yn(n.attributes)&&yn(n.computedStyle)&&Array.isArray(n.ancestry)},St=({pageUrl:t,viewport:n,devicePixelRatio:r,target:a,screenshotAttached:i,intro:o})=>{const u=a.text.trim(),l=Object.entries(a.attributes).map(([g,p])=>`${g}="${p}"`).join(" "),c=a.computedStyle,f=a.bounds,x=a.center,b=o.replace(/[.:]+$/g,""),d=a.ancestry.map(g=>g.selectorPart).join(" > ");return[`${b}:`,`Page: ${t||"preview"}`,`Viewport: ${n.width}x${n.height}, DPR ${r}`,`Screenshot: ${i?"attached":"not attached"}`,`Element: ${a.tag}`,u?`Text: ${u}`:null,`- Selector: ${a.selector}`,`- Path: ${a.path}`,d?`- Ancestry: ${d}`:null,l?`- Attributes: ${l}`:null,`- Bounds: x=${Math.round(f.x)}, y=${Math.round(f.y)}, width=${Math.round(f.width)}, height=${Math.round(f.height)}`,`- Center: x=${Math.round(x.x)}, y=${Math.round(x.y)}`,`Styles: display=${c.display}; position=${c.position}; font=${c.fontWeight} ${c.fontSize} / ${c.lineHeight} ${c.fontFamily}; color=${c.color}; background=${c.backgroundColor}; z-index=${c.zIndex}`].filter(g=>typeof g=="string").join(`
|
|
3
|
-
`)},We=new Map,Vo=3e4,as=t=>{const n=We.get(t);return n?n.expiresAt-Date.now()<=Vo?(We.delete(t),null):n:null},nt="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=",Pt=new Map;function is(t){const n="#ffffff",r=t.defaultView??window;try{const a=t.body?r.getComputedStyle(t.body).backgroundColor:"";if(a&&a!=="rgba(0, 0, 0, 0)"&&a!=="transparent")return a;const i=r.getComputedStyle(t.documentElement).backgroundColor;if(i&&i!=="rgba(0, 0, 0, 0)"&&i!=="transparent")return i}catch{}return n}const ls=t=>new Promise((n,r)=>{const a=new FileReader;a.onloadend=()=>n(typeof a.result=="string"?a.result:nt),a.onerror=()=>r(a.error??new Error("Failed to read image blob")),a.readAsDataURL(t)}),Ko=async(t,n=.82)=>{const r=await new Promise(a=>t.toBlob(a,"image/jpeg",n));return r&&(await ls(r)).split(",",2)[1]||""},Rt=async(t,n)=>{try{const r=await fetch(t,{credentials:n});return r.ok?await ls(await r.blob()):null}catch{return null}},Xo=async t=>{if(t.protocol!=="http:"&&t.protocol!=="https:")return"";const n=t.origin,r=as(n);if(r)return`${r.proxyBasePath}${t.pathname}${t.search}${t.hash}`;const a=Pt.get(n),i=a??(async()=>{try{const u=await Mt("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:t.toString(),allowExternal:!0})});if(!u.ok)return We.delete(n),null;const l=await u.json(),c=typeof l.proxyBasePath=="string"?l.proxyBasePath:"",f=typeof l.expiresAt=="number"?l.expiresAt:0;if(!c)return We.delete(n),null;const x={proxyBasePath:c,expiresAt:f};return We.set(n,x),x}catch{return We.delete(n),null}finally{Pt.delete(n)}})();a||Pt.set(n,i);const o=await i;return o?`${o.proxyBasePath}${t.pathname}${t.search}${t.hash}`:""},cs=async(t,n)=>{if(!t||t.startsWith("data:"))return t;try{const r=new URL(t,n.baseURI);if(r.origin===window.location.origin||r.protocol!=="http:"&&r.protocol!=="https:")return await Rt(r.toString(),"include")??nt;const a=await Xo(r),i=a?await Rt(a,"include"):null;return i||(await Rt(r.toString(),"omit")??nt)}catch{return nt}},qo=async(t,n)=>{if(!t||t==="none"||!t.includes("url("))return t;const r=Array.from(t.matchAll(/url\((['"]?)(.*?)\1\)/g));let a=t;for(const i of r){const o=i[2]||"";if(!o||o.startsWith("data:"))continue;const u=await cs(o,n);a=a.replace(i[0],`url("${u}")`)}return a},vn=t=>t.complete?Promise.resolve():new Promise(n=>{t.addEventListener("load",()=>n(),{once:!0}),t.addEventListener("error",()=>n(),{once:!0})}),ds=t=>{const n=t.style.cssText;return()=>{t.style.cssText=n}},Yo=t=>{const n=Number.parseFloat(t.lineHeight);if(Number.isFinite(n)&&n>0)return n;const r=Number.parseFloat(t.fontSize);return Number.isFinite(r)&&r>0?r*1.2:16},Go=(t,n,r)=>{const a=[],i=t.defaultView??window,u=Array.from(t.querySelectorAll('button, a, summary, label, [role="button"], [role="link"], [role="menuitem"], [role="tab"], nav *, header *'));for(const l of u){const c=l.textContent?.replace(/\s+/g," ").trim()??"";if(!c||!c.includes(" "))continue;const f=l.getBoundingClientRect();if(f.width<=0||f.height<=0||f.right<0||f.bottom<0||f.left>n||f.top>r)continue;const x=i.getComputedStyle(l);if(x.display==="none"||x.visibility==="hidden"||Number(x.opacity)===0)continue;const b=x.getPropertyValue("text-wrap"),d=x.getPropertyValue("text-wrap-mode"),g=x.whiteSpace.includes("nowrap")||b==="nowrap"||d==="nowrap",p=f.height<=Yo(x)*1.7;!g&&(!p||f.width>n*.72)||(a.push(ds(l)),l.style.whiteSpace="nowrap",l.style.overflowWrap="normal",l.style.wordBreak="normal",l.style.setProperty("text-wrap","nowrap"),l.style.setProperty("text-wrap-mode","nowrap"))}return()=>{for(let l=a.length-1;l>=0;l-=1)a[l]?.()}},Jo=(t,n,r,a)=>{const i=[],o=t.defaultView??window,u=o.scrollX||t.documentElement.scrollLeft||t.body?.scrollLeft||0,l=o.scrollY||t.documentElement.scrollTop||t.body?.scrollTop||0,c=Array.from(t.querySelectorAll("*")).filter(f=>{const x=o.getComputedStyle(f);if(x.position!=="fixed"||x.display==="none"||x.visibility==="hidden"||Number(x.opacity)===0)return!1;const b=f.getBoundingClientRect();return b.width>0&&b.height>0&&b.right>=0&&b.bottom>=0&&b.left<=n&&b.top<=r}).filter((f,x,b)=>!b.some((d,g)=>g<x&&d.contains(f)));for(const f of c){const x=f.getBoundingClientRect(),b=o.getComputedStyle(f),d=Math.ceil(x.width)+8,g=Math.ceil(x.height)+2;a?.add(f),i.push(ds(f)),f.style.position="absolute",f.style.top=`${x.top+l}px`,f.style.left=`${x.left+u}px`,f.style.right="auto",f.style.bottom="auto",f.style.width=`${d}px`,f.style.minWidth=`${d}px`,f.style.height=`${g}px`,f.style.minHeight=`${g}px`,f.style.margin="0",f.style.boxSizing="border-box",f.style.transform="none",b.zIndex!=="auto"&&(f.style.zIndex=b.zIndex)}return()=>{for(let f=i.length-1;f>=0;f-=1)i[f]?.()}},us=async(t,n,r,a={})=>{const i=[],o=t.defaultView??window,u=b=>{if(b===t.documentElement||b===t.body)return!0;try{const d=b.getBoundingClientRect();return d.width>0&&d.height>0&&d.right>=0&&d.bottom>=0&&d.left<=n&&d.top<=r}catch{return!1}};if(a.applyLayoutWorkarounds){const b=new WeakSet;i.push(Jo(t,n,r,b)),i.push(Go(t,n,r))}const l=new Map;for(const b of Array.from(t.images))l.set(b,b.currentSrc||b.src||b.getAttribute("src")||"");const c=Array.from(t.querySelectorAll("picture"));for(const b of c){const d=Array.from(b.querySelectorAll("source"));if(d.length===0)continue;const g=d.map(p=>({source:p,srcset:p.getAttribute("srcset"),sizes:p.getAttribute("sizes")}));i.push(()=>{for(const p of g)p.srcset===null?p.source.removeAttribute("srcset"):p.source.setAttribute("srcset",p.srcset),p.sizes===null?p.source.removeAttribute("sizes"):p.source.setAttribute("sizes",p.sizes)});for(const p of d)p.removeAttribute("srcset"),p.removeAttribute("sizes")}const f=Array.from(t.images).filter(b=>u(b));await Promise.all(f.map(async b=>{const d=l.get(b)||b.currentSrc||b.src||b.getAttribute("src")||"";if(!d)return;await vn(b);const g=await cs(d,t),p={src:b.getAttribute("src"),srcset:b.getAttribute("srcset"),sizes:b.getAttribute("sizes")};i.push(()=>{p.src===null?b.removeAttribute("src"):b.setAttribute("src",p.src),p.srcset===null?b.removeAttribute("srcset"):b.setAttribute("srcset",p.srcset),p.sizes===null?b.removeAttribute("sizes"):b.setAttribute("sizes",p.sizes)}),b.removeAttribute("srcset"),b.removeAttribute("sizes"),b.setAttribute("src",g||nt),await vn(b)}));const x=Array.from(t.querySelectorAll("*")).filter(u);return await Promise.all(x.map(async b=>{const d=o.getComputedStyle(b).backgroundImage;if(!d||d==="none"||!d.includes("url("))return;const g=await qo(d,t);if(g===d)return;const p=b.style.backgroundImage;i.push(()=>{b.style.backgroundImage=p}),b.style.backgroundImage=g})),()=>{for(let b=i.length-1;b>=0;b-=1)try{i[b]?.()}catch{}}},Qo=()=>{try{return!!window.__previewCaptureDebug}catch{return!1}},wt=(...t)=>{Qo()&&console.info("[preview-capture]",...t)},hs=(t,n=8)=>{const r=[];try{const a=t.querySelectorAll("*");for(const i of a){const o=i.scrollTop||0,u=i.scrollLeft||0;if(o<=0&&u<=0)continue;const l=i.tagName.toLowerCase(),c=i.id?`#${i.id}`:"",f=typeof i.className=="string"&&i.className?`.${i.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";if(r.push({selector:`${l}${c}${f}`,scrollTop:o,scrollLeft:u,clientWidth:i.clientWidth,clientHeight:i.clientHeight,scrollWidth:i.scrollWidth,scrollHeight:i.scrollHeight}),r.length>=n)break}}catch{}return r},ut="data-oc-fixed-pin",Zo=(t,n,r)=>{if(n<=0&&r<=0)return()=>{};const a=t.defaultView;if(!a)return()=>{};const i=[],o=[];try{for(const u of t.querySelectorAll("*")){if(a.getComputedStyle(u).position!=="fixed")continue;const l=u.getBoundingClientRect();if(!(l.width>0&&l.height>0))continue;u.setAttribute(ut,JSON.stringify({top:l.top+r,left:l.left+n,width:l.width,height:l.height})),i.push(u);const c=u.tagName.toLowerCase(),f=typeof u.className=="string"&&u.className?`.${u.className.trim().split(/\s+/).slice(0,2).join(".")}`:"";o.push({selector:`${c}${f}`,top:Math.round(l.top),left:Math.round(l.left),width:Math.round(l.width),height:Math.round(l.height)})}}catch{}return wt("tagged fixed elements",o),()=>{for(const u of i)try{u.removeAttribute(ut)}catch{}}},ea={name:"oc-fixed-pin",afterClone(t){const n=t?.clone;if(!(!n||typeof n.querySelectorAll!="function"))for(const r of n.querySelectorAll(`[${ut}]`)){let a;try{a=JSON.parse(r.getAttribute(ut)||"")}catch{continue}r.style.setProperty("position","absolute","important"),r.style.setProperty("top",`${a.top}px`,"important"),r.style.setProperty("left",`${a.left}px`,"important"),r.style.setProperty("right","auto","important"),r.style.setProperty("bottom","auto","important"),r.style.setProperty("width",`${a.width}px`,"important"),r.style.setProperty("height",`${a.height}px`,"important"),r.removeAttribute(ut)}}},tt="data-oc-scroll-pin",ta=t=>{const n=[],r=hs(t,64);try{const o=t.documentElement,u=t.body;for(const l of t.querySelectorAll("*")){const c=l.scrollTop||0,f=l.scrollLeft||0;if(c<=0&&f<=0)continue;const x=l!==o&&l!==u;x&&l.setAttribute(tt,JSON.stringify({top:c,left:f})),n.push({el:l,top:c,left:f,tagged:x})}}catch{}return{reapply:()=>{for(const o of n)try{o.el.scrollHeight,o.el.scrollTop!==o.top&&(o.el.scrollTop=o.top),o.el.scrollLeft!==o.left&&(o.el.scrollLeft=o.left)}catch{}},cleanup:()=>{for(const o of n)if(o.tagged)try{o.el.removeAttribute(tt)}catch{}},snapshot:r}},na={name:"oc-nested-scroll",afterClone(t){const n=t?.clone;if(!n||typeof n.querySelectorAll!="function")return;const r=n.ownerDocument;if(r)for(const a of n.querySelectorAll(`[${tt}]`)){let i;try{i=JSON.parse(a.getAttribute(tt)||"")}catch{a.removeAttribute(tt);continue}const o=`translate(${-i.left}px, ${-i.top}px)`,u=a.children.length===1&&a.firstElementChild instanceof HTMLElement&&a.firstElementChild.style.willChange==="transform"?a.firstElementChild:null;if(u)u.style.transform=o;else{a.style.overflow="hidden";const l=r.createElement("div");for(l.style.transform=o,l.style.willChange="transform",l.style.display="inline-block",l.style.width="100%";a.firstChild;)l.appendChild(a.firstChild);a.appendChild(l)}a.removeAttribute(tt)}}},fs=async(t,n)=>{if(Ds())try{const r=t.getBoundingClientRect(),a=await $n("desktop_capture_page_rect",{x:r.left,y:r.top,width:r.width,height:r.height});if(!a)throw new Error("Desktop screenshot capture is not available");const i=new Image;await new Promise((p,$)=>{i.onload=()=>p(),i.onerror=()=>$(new Error("Failed to load desktop preview screenshot")),i.src=`data:${a.mime};base64,${a.base64}`});const o=Math.max(1,i.naturalWidth||a.width||Math.floor(r.width)),u=Math.max(1,i.naturalHeight||a.height||Math.floor(r.height)),c=Math.min(1,1200/o),f=document.createElement("canvas");f.width=Math.floor(o*c),f.height=Math.floor(u*c);const x=f.getContext("2d");if(!x)return null;x.scale(c,c),x.drawImage(i,0,0,o,u);const b=o/Math.max(1,r.width),d=u/Math.max(1,r.height);x.fillStyle="rgba(37, 99, 235, 0.28)",x.strokeStyle="rgb(37, 99, 235)",x.lineWidth=Math.max(2,2*b),x.fillRect(n.bounds.x*b,n.bounds.y*d,n.bounds.width*b,n.bounds.height*d),x.strokeRect(n.bounds.x*b,n.bounds.y*d,n.bounds.width*b,n.bounds.height*d);const g=await new Promise(p=>f.toBlob(p,"image/jpeg",.82));return g?new File([g],`preview-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch(r){console.warn("[preview] failed to capture annotation screenshot:",r)}return await ra(t,n)},kt=async(t,n,r,a,i,o)=>{if(!t)return null;try{const u=new Image;await new Promise((k,D)=>{u.onload=()=>k(),u.onerror=()=>D(new Error("Failed to load desktop browser screenshot")),u.src=`data:image/jpeg;base64,${t}`});const l=Math.max(1,u.naturalWidth||n),c=Math.max(1,u.naturalHeight||r),x=Math.min(1,1200/l),b=document.createElement("canvas");b.width=Math.floor(l*x),b.height=Math.floor(c*x);const d=b.getContext("2d");if(!d)return null;d.scale(x,x),d.drawImage(u,0,0,l,c);const g=l/Math.max(1,a||l),p=c/Math.max(1,i||c);d.fillStyle="rgba(37, 99, 235, 0.14)",d.strokeStyle="rgb(37, 99, 235)",d.lineWidth=Math.max(2,2*g),d.fillRect(o.bounds.x*g,o.bounds.y*p,o.bounds.width*g,o.bounds.height*p),d.strokeRect(o.bounds.x*g,o.bounds.y*p,o.bounds.width*g,o.bounds.height*p);const $=await new Promise(k=>b.toBlob(k,"image/jpeg",.82));return $?new File([$],`browser-annotation-${Date.now()}.jpg`,{type:"image/jpeg"}):null}catch{return null}};async function sa(t,n){try{const r=t.contentWindow,a=t.contentDocument??r?.document,i=a?.documentElement;if(!r||!a||!i)return null;const o=t.getBoundingClientRect(),u=Math.max(1,Math.ceil(r.innerWidth||t.clientWidth||o.width)),l=Math.max(1,Math.ceil(r.innerHeight||t.clientHeight||o.height)),c=a.body,f=a.scrollingElement instanceof HTMLElement?a.scrollingElement:null,x=r.scrollX||0,b=r.scrollY||0,d=r.pageXOffset||0,g=r.pageYOffset||0,p=r.visualViewport?.pageLeft||r.visualViewport?.offsetLeft||0,$=r.visualViewport?.pageTop||r.visualViewport?.offsetTop||0,k=i.scrollLeft||0,D=i.scrollTop||0,I=c?.scrollLeft||0,K=c?.scrollTop||0,w=f?.scrollLeft||0,P=f?.scrollTop||0,v=Math.max(x,d,p,k,I,w),_=Math.max(b,g,$,D,K,P);wt("scroll sources",{windowScrollX:x,windowScrollY:b,pageScrollX:d,pageScrollY:g,visualViewportScrollX:p,visualViewportScrollY:$,rootScrollX:k,rootScrollY:D,bodyScrollX:I,bodyScrollY:K,scrollingElementScrollX:w,scrollingElementScrollY:P,scrollingElementTag:f?.tagName?.toLowerCase()??null,resolvedScrollX:v,resolvedScrollY:_,nestedScrolledElements:hs(a)});const y=Math.max(u,i.scrollWidth||0,c?.scrollWidth||0,Math.ceil(i.getBoundingClientRect().width||0)),R=Math.max(l,i.scrollHeight||0,c?.scrollHeight||0,Math.ceil(i.getBoundingClientRect().height||0)),Q=Math.min(2,Math.max(1,window.devicePixelRatio||1)),q=i.style.scrollBehavior,z=c?.style.scrollBehavior??"";i.style.scrollBehavior="auto",c&&(c.style.scrollBehavior="auto");const ee=ta(a);wt("nested scroll snapshot",ee.snapshot);let oe=()=>{},H=()=>{};try{await a.fonts?.ready.catch(()=>{}),oe=await us(a,u,l,{applyLayoutWorkarounds:!1}),r.scrollTo(v,_),H=Zo(a,v,_),ee.reapply();const{snapdom:se}=await Fe(async()=>{const{snapdom:ve}=await import("./vendor-zumer-snapdom-SJzqoCHV.js");return{snapdom:ve}},[]),C={backgroundColor:is(a),cache:"disabled",dpr:Q,embedFonts:!0,fast:!1,height:R,outerShadows:!0,outerTransforms:!0,placeholders:!0,plugins:[ea,na],quality:.82,width:y},re=await(await se(i,C)).toCanvas();if(!re.width||!re.height)return null;const E=re.width/Math.max(1,y),B=re.height/Math.max(1,R),Z=Math.min(re.width,Math.max(1,Math.round(u*E))),ue=Math.min(re.height,Math.max(1,Math.round(l*B))),ge=Math.max(0,re.width-Z),he=Math.max(0,re.height-ue),xe=Math.min(ge,Math.max(0,Math.round(v*E))),je=Math.min(he,Math.max(0,Math.round(_*B)));wt("capture geometry",{viewportWidth:u,viewportHeight:l,captureWidth:y,captureHeight:R,canvasWidth:re.width,canvasHeight:re.height,xScale:E,yScale:B,sourceX:xe,sourceY:je,sourceWidth:Z,sourceHeight:ue});const Ne=a.createElement("canvas");Ne.width=Z,Ne.height=ue;const we=Ne.getContext("2d");if(!we)return null;we.drawImage(re,xe,je,Z,ue,0,0,Z,ue);const me=await Ko(Ne,.82);return me?await kt(me,u,l,u,l,n):null}finally{H(),ee.cleanup(),oe(),r.scrollTo(v,_),ee.reapply(),i.style.scrollBehavior=q,c&&(c.style.scrollBehavior=z)}}catch(r){return console.warn("[preview] failed to capture iframe DOM screenshot with snapDOM:",r),null}}async function ra(t,n){const r=await sa(t,n);if(r)return r;try{const a=t.contentWindow,i=t.contentDocument??a?.document,o=i?.documentElement;if(!a||!i||!o)return null;const u=t.getBoundingClientRect(),l=Math.max(1,Math.ceil(a.innerWidth||t.clientWidth||u.width)),c=Math.max(1,Math.ceil(a.innerHeight||t.clientHeight||u.height)),f=a.scrollX||i.documentElement.scrollLeft||i.body?.scrollLeft||0,x=a.scrollY||i.documentElement.scrollTop||i.body?.scrollTop||0,b=i.body,d=Math.max(c,o.scrollHeight||0,b?.scrollHeight||0),g=Math.min(2,Math.max(1,window.devicePixelRatio||1)),p=o.style.scrollBehavior,$=b?.style.scrollBehavior??"";o.style.scrollBehavior="auto",b&&(b.style.scrollBehavior="auto");let k="",D=()=>{};try{await i.fonts?.ready.catch(()=>{}),D=await us(i,l,c,{applyLayoutWorkarounds:!0}),a.scrollTo(f,x);const{getFontEmbedCSS:K,toJpeg:w}=await Fe(async()=>{const{getFontEmbedCSS:v,toJpeg:_}=await import("./vendor-html-to-image-BeoRn2gJ.js");return{getFontEmbedCSS:v,toJpeg:_}},[]),P=await K(o).catch(()=>"");k=await w(o,{quality:.82,pixelRatio:g,width:l,height:c,backgroundColor:is(i),imagePlaceholder:nt,fontEmbedCSS:P||void 0,style:{transform:`translate(${-f}px, ${-x}px)`,transformOrigin:"top left",minWidth:`${l}px`,minHeight:`${d}px`},cacheBust:!0})}finally{D(),a.scrollTo(f,x),o.style.scrollBehavior=p,b&&(b.style.scrollBehavior=$)}const I=k.split(",",2)[1]||"";return I?await kt(I,l,c,l,c,n):null}catch(a){return console.warn("[preview] failed to capture iframe DOM screenshot:",a),null}}const jn=200,oa=(t,n)=>n==="all"?!0:n==="errors"?t.level==="error"||t.level==="runtime"||t.level==="resource":n==="warnings"?t.level==="warn":t.level==="log"||t.level==="info"||t.level==="debug",ht=t=>{const n=ft.getState();n.setPendingSyntheticParts([...n.pendingSyntheticParts??[],{text:t,synthetic:!0}])},aa=async t=>{const n=await t.json().catch(()=>({}));if(!t.ok)return{ok:!1,message:typeof n.error=="string"?n.error:`HTTP ${t.status}`};const r=typeof n.proxyBasePath=="string"?n.proxyBasePath:"",a=typeof n.previewToken=="string"?n.previewToken:"";return!r||!a?{ok:!1,message:"Could not start preview proxy."}:{ok:!0,target:{proxyBasePath:r,previewToken:a,expiresAt:typeof n.expiresAt=="number"?n.expiresAt:0}}},ps=t=>{if(typeof window>"u")return"";try{return new URL(t||window.location.href,window.location.href).origin}catch{return window.location.origin}},Sn=(t,n,r)=>{t.postMessage(r,ps(n))},ia=t=>{if(!t)return t;try{const n=new URL(t);return n.searchParams.delete("oc_preview_token"),n.searchParams.delete("oc_client_token"),n.searchParams.delete("oc_url_token"),n.toString()}catch{return t}},ms=`new Promise((resolve) => {
|
|
4
|
-
const existing = document.getElementById('__pichamber_desktop_browser_overlay');
|
|
5
|
-
if (existing) existing.remove();
|
|
6
|
-
if (typeof window.__pichamberDesktopBrowserCancelInspect === 'function') {
|
|
7
|
-
try { window.__pichamberDesktopBrowserCancelInspect(); } catch { /* webview not ready */ }
|
|
8
|
-
}
|
|
9
|
-
const overlay = document.createElement('div');
|
|
10
|
-
overlay.id = '__pichamber_desktop_browser_overlay';
|
|
11
|
-
overlay.style.cssText = 'position:fixed;z-index:2147483647;pointer-events:none;border:2px solid #60a5fa;background:rgba(96,165,250,.24);border-radius:3px;display:none;box-sizing:border-box;';
|
|
12
|
-
document.documentElement.appendChild(overlay);
|
|
13
|
-
const cssEscape = (value) => {
|
|
14
|
-
try { return CSS.escape(value); } catch { return String(value).replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); }
|
|
15
|
-
};
|
|
16
|
-
const selectorPart = (element) => {
|
|
17
|
-
const tag = element.tagName.toLowerCase();
|
|
18
|
-
if (element.id) return tag + '#' + cssEscape(element.id);
|
|
19
|
-
const className = String(element.className || '').trim().split(/\\s+/).filter(Boolean).slice(0, 3).map((part) => '.' + cssEscape(part)).join('');
|
|
20
|
-
return tag + className;
|
|
21
|
-
};
|
|
22
|
-
const metadata = (element) => {
|
|
23
|
-
const rect = element.getBoundingClientRect();
|
|
24
|
-
const style = getComputedStyle(element);
|
|
25
|
-
const ancestry = [];
|
|
26
|
-
let current = element;
|
|
27
|
-
while (current && current.nodeType === Node.ELEMENT_NODE && ancestry.length < 8) {
|
|
28
|
-
ancestry.unshift({ tag: current.tagName.toLowerCase(), id: current.id || undefined, className: typeof current.className === 'string' ? current.className : undefined, selectorPart: selectorPart(current) });
|
|
29
|
-
current = current.parentElement;
|
|
30
|
-
}
|
|
31
|
-
const attrs = {};
|
|
32
|
-
for (const attr of Array.from(element.attributes || []).slice(0, 16)) attrs[attr.name] = attr.value.slice(0, 300);
|
|
33
|
-
const path = ancestry.map((entry) => entry.selectorPart).join(' > ');
|
|
34
|
-
return {
|
|
35
|
-
frame: 'top',
|
|
36
|
-
tag: element.tagName.toLowerCase(),
|
|
37
|
-
text: String(element.innerText || element.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 500),
|
|
38
|
-
selector: element.id ? '#' + cssEscape(element.id) : path,
|
|
39
|
-
path,
|
|
40
|
-
bounds: { x: rect.x, y: rect.y, width: rect.width, height: rect.height },
|
|
41
|
-
center: { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 },
|
|
42
|
-
attributes: attrs,
|
|
43
|
-
computedStyle: { display: style.display, position: style.position, fontWeight: style.fontWeight, fontSize: style.fontSize, lineHeight: style.lineHeight, fontFamily: style.fontFamily, color: style.color, backgroundColor: style.backgroundColor, zIndex: style.zIndex },
|
|
44
|
-
ancestry,
|
|
45
|
-
};
|
|
46
|
-
};
|
|
47
|
-
const move = (event) => {
|
|
48
|
-
const element = document.elementFromPoint(event.clientX, event.clientY);
|
|
49
|
-
if (!element || element === overlay || element === document.documentElement || element === document.body) return;
|
|
50
|
-
const rect = element.getBoundingClientRect();
|
|
51
|
-
overlay.style.display = 'block';
|
|
52
|
-
overlay.style.left = rect.left + 'px';
|
|
53
|
-
overlay.style.top = rect.top + 'px';
|
|
54
|
-
overlay.style.width = rect.width + 'px';
|
|
55
|
-
overlay.style.height = rect.height + 'px';
|
|
56
|
-
};
|
|
57
|
-
const cleanup = () => {
|
|
58
|
-
window.removeEventListener('mousemove', move, true);
|
|
59
|
-
window.removeEventListener('click', click, true);
|
|
60
|
-
window.removeEventListener('keydown', keydown, true);
|
|
61
|
-
if (window.__pichamberDesktopBrowserCancelInspect === cancel) {
|
|
62
|
-
delete window.__pichamberDesktopBrowserCancelInspect;
|
|
63
|
-
}
|
|
64
|
-
};
|
|
65
|
-
const cancel = () => {
|
|
66
|
-
cleanup();
|
|
67
|
-
overlay.remove();
|
|
68
|
-
resolve(null);
|
|
69
|
-
};
|
|
70
|
-
const click = (event) => {
|
|
71
|
-
event.preventDefault();
|
|
72
|
-
event.stopPropagation();
|
|
73
|
-
const element = document.elementFromPoint(event.clientX, event.clientY);
|
|
74
|
-
const result = element ? metadata(element) : null;
|
|
75
|
-
cleanup();
|
|
76
|
-
overlay.remove();
|
|
77
|
-
resolve(result);
|
|
78
|
-
};
|
|
79
|
-
const keydown = (event) => {
|
|
80
|
-
if (event.key !== 'Escape') return;
|
|
81
|
-
cancel();
|
|
82
|
-
};
|
|
83
|
-
window.__pichamberDesktopBrowserCancelInspect = cancel;
|
|
84
|
-
window.addEventListener('mousemove', move, true);
|
|
85
|
-
window.addEventListener('click', click, true);
|
|
86
|
-
window.addEventListener('keydown', keydown, true);
|
|
87
|
-
});`,bt=`(() => {
|
|
88
|
-
if (typeof window.__pichamberDesktopBrowserCancelInspect === 'function') {
|
|
89
|
-
window.__pichamberDesktopBrowserCancelInspect();
|
|
90
|
-
return;
|
|
91
|
-
}
|
|
92
|
-
const overlay = document.getElementById('__pichamber_desktop_browser_overlay');
|
|
93
|
-
if (overlay) overlay.remove();
|
|
94
|
-
})()`,la=`(() => {
|
|
95
|
-
if (window.__pichamberSameWebviewNavigationInstalled) return;
|
|
96
|
-
window.__pichamberSameWebviewNavigationInstalled = true;
|
|
97
|
-
|
|
98
|
-
const navigate = (rawUrl) => {
|
|
99
|
-
if (typeof rawUrl !== 'string' || rawUrl.length === 0) return false;
|
|
100
|
-
try {
|
|
101
|
-
const url = new URL(rawUrl, window.location.href);
|
|
102
|
-
if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;
|
|
103
|
-
window.location.assign(url.href);
|
|
104
|
-
return true;
|
|
105
|
-
} catch (_error) {
|
|
106
|
-
return false;
|
|
107
|
-
}
|
|
108
|
-
};
|
|
109
|
-
|
|
110
|
-
const originalOpen = window.open.bind(window);
|
|
111
|
-
window.open = (url, target, features) => {
|
|
112
|
-
if (navigate(url)) return null;
|
|
113
|
-
return originalOpen(url, target, features);
|
|
114
|
-
};
|
|
115
|
-
|
|
116
|
-
document.addEventListener('click', (event) => {
|
|
117
|
-
if (event.defaultPrevented) return;
|
|
118
|
-
const target = event.target;
|
|
119
|
-
if (!(target instanceof Element)) return;
|
|
120
|
-
const anchor = target.closest('a[target="_blank"][href]');
|
|
121
|
-
if (!(anchor instanceof HTMLAnchorElement)) return;
|
|
122
|
-
if (!navigate(anchor.href)) return;
|
|
123
|
-
event.preventDefault();
|
|
124
|
-
event.stopPropagation();
|
|
125
|
-
}, true);
|
|
126
|
-
})()`,ca=/^(localhost|127(\.\d{1,3}){1,3}|0\.0\.0\.0|\[::1?\]|10(\.\d{1,3}){3}|172\.(1[6-9]|2\d|3[01])(\.\d{1,3}){2}|192\.168(\.\d{1,3}){2}|[^/:?#]+\.(local|localhost))(?=[:/?#]|$)/i,Ft=t=>{try{return new URL(t).host||t}catch{return t}},ot=t=>{const n=t.trim();if(!n)return"about:blank";try{const r=ca.test(n)?"http":"https",a=new URL(n.includes("://")?n:`${r}://${n}`);return a.protocol!=="http:"&&a.protocol!=="https:"?"about:blank":a.toString()}catch{return"about:blank"}},kn=async(t,n)=>{const r=t.contentWindow;if(!r)throw new Error("Iframe window is not available");const i=r.eval.call(r,n);return await Promise.resolve(i)};class da{constructor(n,r,a,i){this.tab=n,this.start=r,this.listener=a,this.deps=i}tab;start;listener;deps;socket=null;active=!1;disposed=!1;failures=0;retryTimer=null;generation=0;claimed=!1;setActive(n){if(!(this.disposed||n===this.active)){if(this.active=n,n){this.failures=0,this.connect();return}this.clearRetry(),this.closeSocket(),this.listener.onPhase("idle")}}retry(){this.disposed||!this.active||(this.clearRetry(),this.closeSocket(),this.failures=0,this.connect())}send(n){return this.socket?.readyState!==1?!1:(this.socket.send(JSON.stringify(n)),!0)}ack(){this.send({type:"ack"})}dispose(){this.disposed=!0,this.active=!1,this.clearRetry(),this.closeSocket()}clearRetry(){this.retryTimer!==null&&this.deps.clearTimeout(this.retryTimer),this.retryTimer=null}closeSocket(){this.generation+=1;const n=this.socket;if(this.socket=null,!!n){n.onopen=null,n.onmessage=null,n.onerror=null,n.onclose=null;try{n.close(1e3)}catch{}}}scheduleReconnect(){if(this.disposed||!this.active||this.retryTimer!==null)return;const n=on[Math.min(this.failures,on.length-1)];this.failures+=1,this.listener.onPhase("reconnecting"),this.retryTimer=this.deps.setTimeout(()=>{this.retryTimer=null,this.connect()},n)}async connect(){if(this.disposed||!this.active)return;const n=++this.generation;this.listener.onPhase(this.failures>0?"reconnecting":"connecting");let r;try{const{url:u,popup:l}=this.start();r=await this.deps.open(this.tab,u,this.claimed?null:l??null)}catch{n===this.generation&&this.scheduleReconnect();return}const{socket:a,urlAuthToken:i}=r;if(n!==this.generation||this.disposed||!this.active){try{a.close(1e3)}catch{}return}this.socket=a,a.binaryType="arraybuffer";let o=!1;a.onopen=()=>{o=!0,this.claimed=!0,this.failures=0,this.listener.onPhase("open"),this.listener.onOpen()},a.onmessage=u=>{if(typeof u.data=="string"){const c=er(u.data);c&&this.listener.onMessage(c);return}const l=tr(u.data);l?this.listener.onFrame(l.header,l.jpeg):this.ack()},a.onerror=()=>{},a.onclose=u=>{if(this.socket!==a)return;this.socket=null,o||this.deps.forgetToken(i);const l=o?nr(u.code):"reconnect";if(l==="unavailable"){this.listener.onPhase("unavailable");return}if(l==="stop"){this.listener.onPhase("failed");return}if(l==="closed"){this.listener.onPhase("closed");return}this.scheduleReconnect()}}}const ua=5e3,ha=5,fa=t=>({project:t.filter(n=>n.inProject),others:t.filter(n=>!n.inProject&&n.title).slice(0,ha)}),Cn=({label:t,servers:n,onOpen:r})=>e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"px-1 typography-micro text-muted-foreground",children:t}),e.jsx("div",{className:"flex flex-col overflow-hidden rounded-md border border-border/60",children:n.map(a=>{const i=`localhost:${a.port}`;return e.jsxs("button",{type:"button",className:"flex min-w-0 flex-col gap-0.5 border-b border-border/60 px-3 py-2 text-left last:border-b-0 hover:bg-interactive-hover focus-visible:bg-interactive-hover focus-visible:outline-none",onClick:()=>r(a.url),children:[e.jsx("span",{className:"truncate typography-ui-label text-foreground",children:a.title||i}),e.jsx("span",{className:"truncate typography-micro text-muted-foreground",children:[a.title?i:null,a.process].filter(Boolean).join(" · ")})]},a.port)})})]}),pa=({directory:t,onOpen:n})=>{const[r,a]=s.useState(null);return s.useEffect(()=>{let i=!1,o=null,u=null;const l=async()=>{if(document.visibilityState==="visible"){u=new AbortController;try{const c=await sr(t,u.signal);i||a(fa(c))}catch{}}i||(o=setTimeout(()=>{l()},ua))};return l(),()=>{i=!0,u?.abort(),o&&clearTimeout(o)}},[t]),!r||r.project.length===0&&r.others.length===0?null:e.jsxs("div",{className:"pointer-events-auto flex w-full max-w-sm flex-col gap-4 text-left",children:[r.project.length>0?e.jsx(Cn,{label:"Running in this project",servers:r.project,onOpen:n}):null,r.others.length>0?e.jsx(Cn,{label:r.project.length>0?"Other servers":"Running on the server",servers:r.others,onOpen:n}):null]})},ma=({command:t})=>e.jsxs("div",{className:"flex items-center gap-2 rounded-md border border-border/60 bg-[var(--surface-elevated)] py-1 pl-3 pr-1",children:[e.jsx("code",{className:"min-w-0 flex-1 overflow-x-auto whitespace-nowrap typography-code text-foreground",children:t}),e.jsx(ne,{type:"button",variant:"ghost",size:"xs",onClick:()=>{pt(t).then(n=>{n.ok?ye.success("Command copied"):ye.error("Could not copy the command")})},children:"Copy"})]}),ga=t=>{const n=t.problem,r=t.installCommands;return!n||n.kind==="missing"?{title:"Install Chrome on the server",body:"The server browser runs Google Chrome or Chromium on the machine running PiChamber. Install one there, then check again. To use a browser installed somewhere else, set PICHAMBER_BROWSER_CHROME to its executable and restart PiChamber.",commands:r}:n.kind==="missing-env"?{title:`${n.envKey} does not point to a browser`,body:`PiChamber was started with ${n.envKey} set, but no file exists at that path. Fix the path or unset it, then restart PiChamber.`,commands:[]}:n.kind==="sandbox-root"||n.kind==="launch-failed"&&n.reason==="sandbox-root"?{title:"Chrome will not run as root with its sandbox",body:"PiChamber runs as root on this server, and Chrome refuses to start its sandbox as root. Run PiChamber as a regular user, or allow Chrome to run without its sandbox below.",commands:[]}:n.reason==="missing-library"?{title:"Chrome is missing system libraries",body:`Chrome could not start because ${n.library??"a library"} is not installed on the server. Installing Chrome with its dependencies adds what it needs.`,commands:r,detail:n.detail}:n.reason==="sandbox-namespaces"?{title:"Chrome's sandbox is not available",body:"This server does not allow the user namespaces Chrome uses for its sandbox, which is common in containers. Enable unprivileged user namespaces, or allow Chrome to run without its sandbox below.",commands:[],detail:n.detail}:{title:"Chrome did not start",body:"The server browser could not start Chrome. The output below may explain why.",commands:[],detail:n.detail}},xa=t=>{const n=t.problem;return!n||t.allowNoSandbox?!1:n.kind==="sandbox-root"?!0:n.kind==="launch-failed"&&(n.reason==="sandbox-root"||n.reason==="sandbox-namespaces")},wa=({status:t,onRetry:n,onUseDevice:r})=>{const[a,i]=s.useState(!1),o=ga(t),u=async()=>{i(!0);try{await rr({allowNoSandbox:!0}),n()}catch(l){ye.error(l instanceof Error?l.message:"Could not save the setting")}finally{i(!1)}};return e.jsx("div",{className:"absolute inset-0 overflow-y-auto bg-background",children:e.jsxs("div",{className:"mx-auto flex max-w-xl flex-col gap-4 px-6 py-10",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx("span",{className:"typography-ui-header text-foreground [text-wrap:balance]",children:o.title}),e.jsx("p",{className:"typography-meta text-muted-foreground [text-wrap:pretty]",children:o.body})]}),o.commands.length>0?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:o.commands.length===1?"Run this on the server:":"Run one of these on the server:"}),o.commands.map(l=>e.jsx(ma,{command:l},l))]}):null,xa(t)?e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx("p",{className:"typography-micro text-muted-foreground [text-wrap:pretty]",children:"Without its sandbox, a page that exploits a bug in Chrome can reach the server with the permissions PiChamber runs with. Only do this on a machine you are comfortable exposing to the sites you open."}),e.jsx("div",{children:e.jsx(ne,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{u()},children:"Allow without sandbox"})})]}):null,o.detail?e.jsx("pre",{className:"max-h-48 overflow-auto whitespace-pre-wrap rounded-md border border-border/60 bg-[var(--surface-elevated)] p-3 typography-code text-muted-foreground",children:o.detail}):null,e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(ne,{type:"button",size:"sm",onClick:n,children:"Check again"}),e.jsx(ne,{type:"button",variant:"ghost",size:"sm",onClick:r,children:"Load on this device instead"})]})]})})},ba=t=>t.kind==="beforeunload"?{message:"Leave this page? Changes you made may not be saved.",accept:"Leave",dismiss:"Stay"}:t.kind==="alert"?{message:t.message,accept:"OK",dismiss:null}:{message:t.message,accept:"OK",dismiss:"Cancel"},ya=({multiple:t,uploading:n,onChoose:r,onCancel:a})=>e.jsxs("div",{className:"absolute inset-x-0 top-0 flex flex-wrap items-center gap-2 border-b border-border bg-[var(--surface-elevated)] px-3 py-2",children:[e.jsx("span",{className:"min-w-0 flex-1 typography-micro text-foreground",children:t?"This page asks for files.":"This page asks for a file."}),e.jsx(ne,{type:"button",size:"xs",disabled:n,onClick:r,children:n?"Uploading...":t?"Choose files":"Choose file"}),e.jsx(ne,{type:"button",variant:"ghost",size:"xs",disabled:n,onClick:a,children:"Cancel"})]}),va=({dialog:t,promptText:n,onPromptTextChange:r,onRespond:a})=>{const i=ba(t);return e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/60 p-4",children:e.jsxs("form",{className:"flex w-full max-w-sm flex-col gap-3 rounded-lg border border-border bg-[var(--surface-elevated)] p-4 shadow-lg",onSubmit:o=>{o.preventDefault(),a(!0)},children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:`${Ft(t.url)} says`}),e.jsx("p",{className:"max-h-48 overflow-y-auto whitespace-pre-wrap typography-meta text-foreground [text-wrap:pretty]",children:i.message}),t.kind==="prompt"?e.jsx("input",{autoFocus:!0,value:n,onChange:o=>r(o.target.value),className:"h-8 rounded-md border border-border/50 bg-background px-2 typography-meta text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":"Answer"}):null,e.jsxs("div",{className:"flex justify-end gap-2",children:[i.dismiss?e.jsx(ne,{type:"button",variant:"ghost",size:"sm",onClick:()=>a(!1),children:i.dismiss}):null,e.jsx(ne,{type:"submit",size:"sm",autoFocus:t.kind!=="prompt",children:i.accept})]})]})})},ja=({onReload:t})=>e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 bg-background p-6 text-center",children:[e.jsx("span",{className:"typography-ui-header text-foreground",children:"This page crashed"}),e.jsx(ne,{type:"button",variant:"outline",size:"sm",onClick:t,children:"Reload"})]}),Sa=({phase:t,status:n,failure:r,hasFrame:a,showBlank:i,directory:o,onRetry:u,onSetupRetry:l,onUseDevice:c,onOpenAddress:f})=>t==="unavailable"?n?e.jsx(wa,{status:n,onRetry:l,onUseDevice:c}):e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 bg-background p-6 text-center",children:[e.jsx("span",{className:"typography-ui-header text-foreground",children:"The server browser is not available"}),r?e.jsx("span",{className:"max-w-md typography-micro text-muted-foreground [text-wrap:pretty]",children:r}):null,e.jsx(ne,{type:"button",variant:"outline",size:"sm",onClick:u,children:"Try again"})]}):t==="failed"?e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3 bg-background p-6 text-center",children:[e.jsx("span",{className:"typography-ui-header text-foreground",children:"Could not open this tab"}),e.jsx(ne,{type:"button",variant:"outline",size:"sm",onClick:u,children:"Try again"})]}):(t==="connecting"||t==="reconnecting")&&!a?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background typography-micro text-muted-foreground",children:t==="connecting"?"Starting the server browser...":"Reconnecting to the server browser..."}):t==="reconnecting"?e.jsx("div",{className:"absolute inset-x-0 top-0 border-b border-border bg-[var(--surface-elevated)] px-3 py-1.5 typography-micro text-muted-foreground",children:"Reconnecting to the server browser..."}):i?e.jsxs("div",{className:"pointer-events-none absolute inset-0 flex flex-col items-center justify-center-safe gap-6 overflow-y-auto bg-background p-6 text-center",children:[e.jsx(Ht,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"}),e.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground [text-wrap:pretty]",children:"Pages run in a browser on the PiChamber server, so localhost addresses reach the server."}),e.jsx(pa,{directory:o,onOpen:f})]}):null,ka=({decode:t,paint:n,ack:r})=>{let a={busy:!1,pending:null};const i=async(o,u)=>{const l=a;l.busy=!0;let c=null;try{c=await t(u)}catch{}if(a!==l){c?.close();return}try{c&&n(c,o)}finally{c?.close(),r(),l.busy=!1;const f=l.pending;l.pending=null,f&&i(f.header,f.jpeg)}};return{onFrame(o,u){if(a.busy){a.pending&&r(),a.pending={header:o,jpeg:u};return}i(o,u)},reset(){a={busy:!1,pending:null}}}},Ca=t=>{const n=s.useRef(null),r=s.useRef(null),[a,i]=s.useState(null),o=s.useRef(t);o.current=t;const[u]=s.useState(()=>ka({decode:f=>createImageBitmap(new Blob([f],{type:"image/jpeg"})),paint:(f,x)=>{const b=n.current,d=b?.getContext("2d");b&&d&&(b.width!==f.width&&(b.width=f.width),b.height!==f.height&&(b.height=f.height),d.drawImage(f,0,0));const g=r.current;r.current=x,(!g||g.width!==x.width||g.height!==x.height)&&i({width:x.width,height:x.height})},ack:()=>o.current()})),l=s.useCallback((f,x)=>u.onFrame(f,x),[u]),c=s.useCallback(()=>u.reset(),[u]);return{canvasRef:n,headerRef:r,frameSize:a,onFrame:l,reset:c}},Na=500,Nn=6,Pn=["left","middle","right"],Pa=()=>typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform||navigator.userAgent),Ra=({send:t,canvasRef:n,headerRef:r,areaHeight:a,inspecting:i,onInspectHover:o,onInspectPick:u})=>{const l=s.useRef(null),c=s.useRef({at:0,x:0,y:0,count:0}),f=s.useRef(null),x=s.useRef(null),b=s.useRef(a);b.current=a;const d=s.useCallback((w,P)=>{const v=n.current,_=r.current;return!v||!_?null:or(w,P,v.getBoundingClientRect(),_)},[n,r]),g=s.useCallback(()=>l.current?.focus({preventScroll:!0}),[]);s.useEffect(()=>{const w=n.current;if(!w)return;const P=v=>{v.preventDefault();const _=d(v.clientX,v.clientY);if(!_)return;const y=v.deltaMode===1?40:v.deltaMode===2?b.current():1;t({type:"mouse",action:"wheel",..._,deltaX:v.deltaX*y,deltaY:v.deltaY*y,modifiers:at(v)})};return w.addEventListener("wheel",P,{passive:!1}),()=>w.removeEventListener("wheel",P)},[n,d,t]);const p=w=>{w.preventDefault(),g();const P=d(w.clientX,w.clientY);if(!P)return;if(w.pointerType==="touch"){f.current={id:w.pointerId,startX:w.clientX,startY:w.clientY,lastX:w.clientX,lastY:w.clientY,moved:!1},w.currentTarget.setPointerCapture(w.pointerId);return}if(w.button===3||w.button===4){t({type:w.button===3?"back":"forward"});return}if(i){w.button===0&&u(P);return}const v=Pn[w.button]??"left",_=c.current,y=performance.now(),R=Math.abs(w.clientX-_.x)<5&&Math.abs(w.clientY-_.y)<5;_.count=y-_.at<Na&&R?Math.min(3,_.count+1):1,_.at=y,_.x=w.clientX,_.y=w.clientY,w.currentTarget.setPointerCapture(w.pointerId),x.current={id:w.pointerId,button:v,point:P},t({type:"mouse",action:"down",...P,button:v,buttons:w.buttons,clickCount:_.count,modifiers:at(w)})},$=w=>{const P=d(w.clientX,w.clientY);if(!P)return;const v=f.current;if(w.pointerType==="touch"){if(!v||v.id!==w.pointerId||((Math.abs(w.clientX-v.startX)>Nn||Math.abs(w.clientY-v.startY)>Nn)&&(v.moved=!0),!v.moved))return;const _=r.current,y=w.currentTarget.getBoundingClientRect(),R=_&&y.width>0?_.width/y.width:1;t({type:"mouse",action:"wheel",...P,deltaX:(v.lastX-w.clientX)*R,deltaY:(v.lastY-w.clientY)*R}),v.lastX=w.clientX,v.lastY=w.clientY;return}if(i){o(P);return}x.current?.id===w.pointerId&&(x.current.point=P),t({type:"mouse",action:"move",...P,buttons:w.buttons,modifiers:at(w)})},k=w=>{const P=d(w.clientX,w.clientY);if(!P)return;if(w.pointerType==="touch"){const _=f.current;if(f.current=null,!_||_.id!==w.pointerId||_.moved)return;if(i){u(P);return}t({type:"mouse",action:"down",...P,button:"left",buttons:1,clickCount:1}),t({type:"mouse",action:"up",...P,button:"left",buttons:0,clickCount:1});return}if(i||w.button===3||w.button===4)return;x.current?.id===w.pointerId&&(x.current=null);const v=Pn[w.button]??"left";t({type:"mouse",action:"up",...P,button:v,buttons:w.buttons,clickCount:c.current.count||1,modifiers:at(w)})},D=(w,P)=>({type:"key",action:w,key:P.key,code:P.code,keyCode:P.keyCode,location:P.nativeEvent.location,repeat:P.repeat,modifiers:at(P)});return{keyboardRef:l,focusKeyboard:g,canvasHandlers:{onPointerDown:p,onPointerMove:$,onPointerUp:k,onPointerCancel:w=>{f.current=null;const P=x.current;!P||P.id!==w.pointerId||(x.current=null,t({type:"mouse",action:"up",...P.point,button:P.button,buttons:0,clickCount:1}))},onMouseDown:w=>w.preventDefault(),onContextMenu:w=>w.preventDefault()},keyboardHandlers:{onKeyDown:w=>{w.nativeEvent.isComposing||w.keyCode===229||ar(w,Pa())||(w.preventDefault(),w.stopPropagation(),t(D("down",w)))},onKeyUp:w=>{w.nativeEvent.isComposing||w.keyCode===229||(w.stopPropagation(),t(D("up",w)))},onPaste:w=>{w.preventDefault();const P=w.clipboardData.getData("text/plain");P&&t({type:"text",text:P})},onCompositionEnd:w=>{w.data&&t({type:"text",text:w.data}),w.currentTarget.value=""},onInput:w=>{w.nativeEvent.isComposing||(w.currentTarget.value="")}}}},Ea={url:"about:blank",title:"",loading:!1,canGoBack:!1,canGoForward:!1,crashed:!1},Ta=1500,Da=({initialUrl:t,directory:n,pageId:r,popupId:a,onScreen:i,routeToggle:o,onRouteChange:u})=>{const l=s.useMemo(()=>ir(n,r),[n,r]),c=X(h=>h.updateBrowserPage),f=X(h=>h.openBrowserPopup),x=X(h=>h.closeBrowserPage),b=Te(h=>h.currentSessionId),d=Te(h=>h.newSessionDraft?.open),g=ft(h=>h.addAttachedFile),p=ot(t),$=p!=="about:blank"?p:"",[k,D]=s.useState(Ea),[I,K]=s.useState("idle"),[w,P]=s.useState(null),[v,_]=s.useState(""),[y,R]=s.useState($),[Q,q]=s.useState("default"),[z,ee]=s.useState(null),[oe,H]=s.useState(""),[se,C]=s.useState(null),[W,re]=s.useState(!1),[E,B]=s.useState(!1),[Z,ue]=s.useState(null),[ge,he]=s.useState({width:0,height:0}),[xe,je]=s.useState(()=>typeof document>"u"||document.visibilityState==="visible"),Ne=s.useRef(null),we=s.useRef(null),me=s.useRef(null),ve=s.useRef($),Ce=s.useRef(a);Ce.current=a;const be=s.useRef(null),ke=s.useRef(!1),Pe=s.useRef(new Map),Re=s.useRef({seq:0,inFlight:!1,queued:null}),O=s.useRef(ge);O.current=ge;const V=s.useCallback(h=>me.current?.send(h)??!1,[]),{canvasRef:de,headerRef:M,frameSize:te,onFrame:S,reset:L}=Ca(()=>me.current?.ack()),F=s.useCallback((h,T)=>{!h||h==="about:blank"||!n||!r||c(n,r,{url:h,title:T})},[n,r,c]),ae=s.useCallback(h=>{const T=ot(h);if(T==="about:blank"){ye.warning("Enter an http or https address");return}ve.current=T,R(T),V({type:"navigate",url:T})||(be.current=T)},[V]),ie=s.useCallback(()=>{const{width:h,height:T}=O.current;h<=0||T<=0||V({type:"viewport",width:Math.round(h),height:Math.round(T),dpr:window.devicePixelRatio||1})},[V]),m=s.useCallback(async(h,T)=>{if(!(b??(d?"draft":null))){ye.error("Open a chat session before attaching preview annotations");return}const fe=T?await kt(T.base64,T.width,T.height,T.cssWidth,T.cssHeight,h):null;fe&&await g(fe);const Se=T?.cssWidth??M.current?.width??0,Ie=T?.cssHeight??M.current?.height??0;ht(St({pageUrl:ve.current,viewport:{width:Se,height:Ie},devicePixelRatio:T&&T.cssWidth>0?T.width/T.cssWidth:1,target:h,screenshotAttached:!!fe,intro:fe?"This is a selected DOM element from the in-app preview. A screenshot of the visible preview area with the selected element highlighted is attached.":"This is a selected DOM element from the in-app preview."})),ye.success("Preview annotation attached to chat")},[g,b,M,d]),A=h=>{switch(h.type){case"state":{const T={url:h.url,title:h.title,loading:h.loading,canGoBack:h.canGoBack,canGoForward:h.canGoForward,crashed:h.crashed};D(T),T.url&&T.url!=="about:blank"&&(ve.current=T.url,F(T.url,T.title)),ke.current||R(T.url==="about:blank"?"":T.url);return}case"cursor":q(h.cursor||"default");return;case"dialog":ee(h),H(h.defaultPrompt||"");return;case"dialog-closed":ee(null);return;case"file-chooser":C({id:h.id,multiple:h.multiple});return;case"file-chooser-closed":C(T=>T?.id===h.id?null:T);return;case"clipboard":pt(h.text);return;case"notice":h.kind==="blocked-server-network"?ye.warning(`Blocked a page from opening ${Ft(h.url)}`,{description:"Sites on the internet cannot send the server browser to addresses on the server or its network. Type the address to open it yourself."}):h.kind==="unsupported-address"?ye.warning("The server browser opens http and https addresses only"):h.kind==="upload-failed"?ye.error("Upload failed",{description:h.message}):ye.error(`Could not load ${Ft(h.url)}`,{description:h.message});return;case"popup":f(n,r,h.id)||ye.warning("A page opened a popup, but too many tabs are open",{description:"Close a tab, then try again."});return;case"download":{const T=Pe.current;if(T.get(h.id)===h.state)return;if(T.set(h.id,h.state),h.state==="completed"){const{id:J,filename:fe}=h;ye.success(`Downloaded ${fe}`,{action:{label:"Save",onClick:()=>{dr(J,fe).catch(Se=>{ye.error(Se instanceof Error?Se.message:`Could not download ${fe}`)})}}})}else h.state==="canceled"&&ye.error(`Download of ${h.filename} failed`);return}case"inspect-hover":{const T=Re.current;if(h.requestId!==T.seq)return;T.inFlight=!1,ue(rt(h.target)?h.target:null);const J=T.queued;T.queued=null,J&&ce(J.x,J.y);return}case"inspect-pick":ue(null),rt(h.target)&&m(h.target,h.screenshot);return;case"unavailable":h.status&&P(h.status),_(h.message||"");return}},Y=s.useRef(A);Y.current=A;const ce=(h,T)=>{const J=Re.current;if(J.inFlight){J.queued={x:h,y:T};return}J.seq+=1,J.inFlight=V({type:"inspect",x:h,y:T,requestId:J.seq})},De=Ra({send:V,canvasRef:de,headerRef:M,areaHeight:()=>O.current.height,inspecting:E,onInspectHover:h=>ce(h.x,h.y),onInspectPick:h=>{Re.current.seq+=1,V({type:"inspect",...h,pick:!0,requestId:Re.current.seq}),B(!1)}}),{focusKeyboard:Me}=De;s.useEffect(()=>{const h=new da(l,()=>({url:be.current||ve.current,popup:Ce.current}),{onPhase:T=>{K(T),T==="open"&&P(null)},onOpen:()=>{Ce.current&&X.getState().updateBrowserPage(n,r,{popupId:null}),L(),Re.current.inFlight=!1,ie();const T=be.current;be.current=null,T&&h.send({type:"navigate",url:T})},onMessage:T=>Y.current(T),onFrame:S},{open:hr,forgetToken:ur,setTimeout:(T,J)=>window.setTimeout(T,J),clearTimeout:T=>window.clearTimeout(T)});return me.current=h,()=>{h.dispose(),me.current===h&&(me.current=null)}},[n,S,r,L,ie,l]),s.useEffect(()=>{I==="closed"&&x(n,r)},[x,n,r,I]);const Ae=i&&ge.width>0&&ge.height>0&&xe;s.useEffect(()=>{if(Ae){me.current?.setActive(!0);return}const h=window.setTimeout(()=>me.current?.setActive(!1),Ta);return()=>window.clearTimeout(h)},[Ae]),s.useEffect(()=>{const h=()=>je(document.visibilityState==="visible");return document.addEventListener("visibilitychange",h),()=>document.removeEventListener("visibilitychange",h)},[]),s.useEffect(()=>{const h=Ne.current;if(!h)return;const T=new ResizeObserver(([J])=>{const{width:fe,height:Se}=J.contentRect;he(Ie=>Ie.width===fe&&Ie.height===Se?Ie:{width:fe,height:Se})});return T.observe(h),()=>T.disconnect()},[]),s.useEffect(()=>{if(I!=="open")return;const h=window.setTimeout(ie,80);return()=>window.clearTimeout(h)},[ge,I,ie]),s.useEffect(()=>{if(I!=="unavailable"||w)return;let h=!1;return lr().then(T=>{h||P(T)}).catch(T=>{h||_(T instanceof Error?T.message:"Could not check the server browser")}),()=>{h=!0}},[I,w]),s.useEffect(()=>{!$||$===ve.current||ae($)},[t]),s.useEffect(()=>{if(!E)return;const h=T=>{T.key==="Escape"&&(T.preventDefault(),T.stopImmediatePropagation(),B(!1),ue(null))};return window.addEventListener("keydown",h,!0),()=>window.removeEventListener("keydown",h,!0)},[E]);const Ve=h=>{V({type:"dialog",accept:h,text:z?.kind==="prompt"?oe:void 0}),ee(null),Me()},Ke=async h=>{const T=se;if(!T||!h||h.length===0)return;const J=T.multiple?Array.from(h):[h[0]];if(J.reduce((fe,Se)=>fe+Se.size,0)>fr){ye.warning(J.length===1?"The file is too large":"The files are too large together",{description:"The server browser uploads under 50 MB at a time."}),we.current&&(we.current.value="");return}re(!0);try{const fe=await Promise.all(J.map(Se=>pr(Se)));V({type:"file-chooser",id:T.id,uploadIds:fe})}catch(fe){ye.error(fe instanceof Error?fe.message:"Upload failed")}finally{re(!1),we.current&&(we.current.value="")}},j=te?cr(te,ge):null,G=k.url!=="about:blank",le=I==="open"&&!G&&!k.loading;return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!k.canGoBack,onClick:()=>V({type:"back"}),"aria-label":"Back",title:"Back",children:e.jsx(U,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!k.canGoForward,onClick:()=>V({type:"forward"}),"aria-label":"Forward",title:"Forward",children:e.jsx(U,{name:"arrow-right",className:"h-3.5 w-3.5"})}),k.loading?e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>V({type:"stop"}),"aria-label":"Stop loading",title:"Stop loading",children:e.jsx(U,{name:"close",className:"h-3.5 w-3.5"})}):e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!G,onClick:()=>V({type:"reload"}),"aria-label":"Reload",title:"Reload",children:e.jsx(U,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:h=>{h.preventDefault(),ke.current=!1,ae(y),Me()},children:e.jsx("input",{value:y,onChange:h=>R(h.target.value),onFocus:h=>{ke.current=!0,h.currentTarget.select()},onBlur:()=>{ke.current=!1},placeholder:"Enter an address",className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":"Browser address"})}),o,e.jsx(ne,{type:"button",variant:E?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!G||I!=="open","aria-pressed":E,onClick:()=>{B(h=>!h),ue(null)},title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(U,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!G,onClick:()=>{st(k.url)},title:"Open in system browser","aria-label":"Open in system browser",children:e.jsx(U,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{ref:Ne,className:"relative min-h-0 flex-1 overflow-hidden bg-background",children:[e.jsx("div",{className:"absolute inset-0 flex items-start justify-start",children:e.jsxs("div",{className:"relative",style:j?{width:j.width,height:j.height}:{width:"100%",height:"100%"},children:[e.jsx("canvas",{ref:de,className:"block h-full w-full touch-none select-none outline-none",style:{cursor:E?"crosshair":Q},...De.canvasHandlers,"aria-label":k.title?`Web page: ${k.title}`:"Web page",role:"img"}),E&&Z&&te&&j?e.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:Z.bounds.x*j.scale,top:Z.bounds.y*j.scale,width:Z.bounds.width*j.scale,height:Z.bounds.height*j.scale},children:e.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[Z.tag,Z.text?` · ${Z.text}`:""]})}):null]})}),e.jsx("textarea",{ref:De.keyboardRef,className:"pointer-events-none absolute left-0 top-0 h-px w-px resize-none opacity-0","aria-label":"Keyboard input for the web page",autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:!1,tabIndex:-1,...De.keyboardHandlers}),e.jsx("input",{ref:we,type:"file",className:"hidden",multiple:se?.multiple===!0,onChange:h=>{Ke(h.target.files)}}),se?e.jsx(ya,{multiple:se.multiple,uploading:W,onChoose:()=>we.current?.click(),onCancel:()=>V({type:"file-chooser",id:se.id,uploadIds:[]})}):null,z?e.jsx(va,{dialog:z,promptText:oe,onPromptTextChange:H,onRespond:Ve}):null,k.crashed?e.jsx(ja,{onReload:()=>V({type:"reload"})}):null,e.jsx(Sa,{phase:I,status:w,failure:v,hasFrame:te!==null,showBlank:le,directory:n,onRetry:()=>me.current?.retry(),onSetupRetry:()=>{P(null),_(""),me.current?.retry()},onUseDevice:()=>u("device"),onOpenAddress:ae})]})]})},Aa=t=>{try{return new URL(t).host||t}catch{return t}},_a=({route:t,onRouteChange:n})=>{const r=t==="server",a=r?"Pages run in a browser on the PiChamber server, so localhost means the server. Switch to load them on this device.":"Pages load on this device, so localhost means this device. Switch to run them on the PiChamber server.";return e.jsx(ne,{type:"button",variant:"ghost",size:"xs",className:"shrink-0 typography-micro",onClick:()=>n(r?"device":"server"),title:a,"aria-label":r?"Running on the server. Switch to this device":"Loading on this device. Switch to server",children:r?"Server":"This device"})},$t=()=>typeof window<"u"&&!!window.__PICHAMBER_ELECTRON__,Ma=({initialUrl:t,directory:n,pageId:r,routeToggle:a,onRouteChange:i})=>{const o=s.useRef(null),u=X(E=>E.updateBrowserPage),[l,c]=s.useState(null),f=ot(t),x=f!=="about:blank"?f:"",[b,d]=s.useState(x),[g,p]=s.useState(x),[$,k]=s.useState(()=>x?[x]:[]),[D,I]=s.useState(()=>x?0:-1),[K,w]=s.useReducer(E=>E+1,0),[P,v]=s.useState(!!x),[_,y]=s.useState(!1),R=Te(E=>E.currentSessionId),Q=Te(E=>E.newSessionDraft?.open),q=ft(E=>E.addAttachedFile),z=s.useCallback(E=>{!E||E==="about:blank"||!n||!r||u(n,r,{url:E})},[n,r,u]),ee=s.useCallback(E=>{const B=ot(E),Z=B!=="about:blank"?B:"";p(Z),d(Z),v(!!Z),z(Z),k(ue=>{if(!Z)return I(-1),[];const ge=D>=0?ue.slice(0,D+1):[];if(ge[ge.length-1]===Z)return I(ge.length-1),ge;const he=[...ge,Z];return I(he.length-1),he})},[D,z]),oe=s.useCallback(E=>{const B=$[E];B&&(I(E),p(B),d(B),v(!0),z(B))},[$,z]),H=s.useCallback(()=>{if(g){v(!0);try{o.current?.contentWindow?.location.reload()}catch{w()}}},[g]);s.useEffect(()=>{if(!g)return;const E=new AbortController;return mr(g,window.location.origin,E.signal).then(B=>{B.framing==="refused"&&c(g)}).catch(()=>{}),()=>E.abort()},[g]);const se=l&&l===g?Aa(g):null;s.useEffect(()=>{!x||x===g||ee(x)},[t]);const C=s.useCallback(async E=>{if(!(R??(Q?"draft":null))){ye.error("Open a chat session before attaching preview annotations");return}const Z=o.current,ue=Z?.contentWindow,ge=Z?.getBoundingClientRect(),he={width:Number.isFinite(ue?.innerWidth)?ue?.innerWidth??ge?.width??0:ge?.width??0,height:Number.isFinite(ue?.innerHeight)?ue?.innerHeight??ge?.height??0:ge?.height??0},xe=Z?await fs(Z,E):null,je=!!xe;xe&&await q(xe),ht(St({pageUrl:g,viewport:he,devicePixelRatio:window.devicePixelRatio||1,target:E,screenshotAttached:je,intro:je?"This is a selected DOM element from the in-app preview. A screenshot of the visible preview area with the selected element highlighted is attached.":"This is a selected DOM element from the in-app preview."})),ye.success("Preview annotation attached to chat")},[q,R,g,Q]),W=s.useCallback(()=>{const E=o.current;E&&kn(E,bt).catch(()=>{})},[]);s.useEffect(()=>{if(!_)return;const E=B=>{B.key==="Escape"&&(B.preventDefault(),B.stopImmediatePropagation(),y(!1),W())};return window.addEventListener("keydown",E,!0),()=>window.removeEventListener("keydown",E,!0)},[W,_]),s.useEffect(()=>()=>W(),[W]);const re=s.useCallback(()=>{const E=o.current;if(!(!E||!g)){if(_){y(!1),W();return}y(!0),(async()=>{try{const B=await kn(E,ms);if(y(!1),!B||!rt(B))return;await C(B)}catch{y(!1),ye.error("This page cannot be inspected on this device. Switch to Server to inspect it.")}})()}},[C,W,g,_]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:D<=0,onClick:()=>oe(D-1),"aria-label":"Back",title:"Back",children:e.jsx(U,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:D<0||D>=$.length-1,onClick:()=>oe(D+1),"aria-label":"Forward",title:"Forward",children:e.jsx(U,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:H,"aria-label":"Reload",title:"Reload",children:e.jsx(U,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:E=>{E.preventDefault(),ee(b)},children:e.jsx("input",{value:b,onChange:E=>d(E.target.value),placeholder:"Enter an address",className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":"Browser address"})}),a,e.jsx(ne,{type:"button",variant:_?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:re,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(U,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",disabled:!g,onClick:()=>{st(g)},title:"Open in system browser","aria-label":"Open in system browser",children:e.jsx(U,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden bg-background",children:[g?e.jsx("iframe",{ref:o,src:g,title:"Web browser",className:"absolute inset-0 h-full w-full border-0 bg-background",allow:"clipboard-read; clipboard-write; fullscreen",allowFullScreen:!0,onLoad:()=>v(!1)},`${r}:${K}`):e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[e.jsx(Ht,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"}),e.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground [text-wrap:pretty]",children:"Pages load on this device, so localhost addresses reach this device. Many sites refuse to load inside other pages here; Server opens them."})]}),P&&!se?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null,se?e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-4 bg-background p-6 text-center",children:[e.jsx("span",{className:"max-w-sm typography-ui-header text-foreground [text-wrap:balance]",children:`${se} can't be shown here`}),e.jsx("span",{className:"max-w-sm typography-micro text-muted-foreground [text-wrap:pretty]",children:"This site doesn't allow being shown inside other pages. Use Server to open it in PiChamber, or open it in your system browser."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[e.jsx(ne,{type:"button",size:"sm",onClick:()=>i("server"),children:"Use server"}),e.jsx(ne,{type:"button",size:"sm",variant:"outline",onClick:()=>{st(g)},children:"Open in system browser"})]})]}):null]})]})},Ia=({initialUrl:t,directory:n,pageId:r,routeToggle:a})=>{const i=s.useRef(null),o=X(y=>y.updateBrowserPage),u=ot(t),l=u!=="about:blank"?u:"",[c,f]=s.useState(l),[x,b]=s.useState(l),[d]=s.useState(u),[g,p]=s.useState(!1),[$,k]=s.useState(!0),D=s.useRef(null),I=s.useCallback(y=>{!y||y==="about:blank"||!n||!r||o(n,r,{url:y})},[n,r,o]),K=Te(y=>y.currentSessionId),w=Te(y=>y.newSessionDraft?.open),P=ft(y=>y.addAttachedFile),v=s.useCallback(y=>{const R=i.current;if(typeof R?.loadURL=="function")try{R.loadURL(ot(y))}catch{}},[]);s.useEffect(()=>{const y=i.current;if(!y)return;const R=C=>{!C||C==="about:blank"||(b(C),f(C),I(C))},Q=()=>{try{R(y.getURL())}catch{}},q=C=>{const W=C.url;R(typeof W=="string"?W:"")},z=()=>{D.current&&clearTimeout(D.current),D.current=setTimeout(()=>k(!0),200)},ee=()=>{D.current&&clearTimeout(D.current),k(!1),Q()},oe=C=>{const W=C.detail;(W?.disposition==="new-window"||W?.disposition==="foreground-tab"||W?.disposition==="background-tab")&&(C.preventDefault(),W.url&&v(W.url))},H=C=>{const W=C.title;typeof W=="string"&&n&&r&&o(n,r,{title:W})},se=()=>{try{y.executeJavaScript?.(la,!0).catch(()=>{})}catch{}};y.addEventListener("did-navigate",q),y.addEventListener("did-navigate-in-page",q),y.addEventListener("did-start-loading",z),y.addEventListener("did-stop-loading",ee),y.addEventListener("new-window",oe),y.addEventListener("page-title-updated",H),y.addEventListener("dom-ready",se);try{y.isLoading()||(k(!1),Q())}catch{}return se(),()=>{D.current&&clearTimeout(D.current),y.removeEventListener("did-navigate",q),y.removeEventListener("did-navigate-in-page",q),y.removeEventListener("did-start-loading",z),y.removeEventListener("did-stop-loading",ee),y.removeEventListener("new-window",oe),y.removeEventListener("page-title-updated",H),y.removeEventListener("dom-ready",se)}},[n,v,r,I,o]),s.useEffect(()=>{const y=setTimeout(()=>k(!1),3e4);return()=>clearTimeout(y)},[]),s.useEffect(()=>{if(!g)return;const y=R=>{if(R.key!=="Escape")return;R.preventDefault(),R.stopImmediatePropagation(),p(!1);const Q=i.current;try{Q?.executeJavaScript?.(bt).catch(()=>{})}catch{}};return window.addEventListener("keydown",y,!0),()=>window.removeEventListener("keydown",y,!0)},[g]),s.useEffect(()=>{const y=i.current;return()=>{try{const R=y?.getURL?.();R&&R!=="about:blank"&&o(n,r,{url:R})}catch{}try{y?.executeJavaScript?.(bt).catch(()=>{})}catch{}}},[n,r,o]),s.useEffect(()=>{!l||l===x||v(l)},[t]);const _=s.useCallback(()=>{const y=i.current;if(y){if(g){p(!1);try{y.executeJavaScript?.(bt).catch(()=>{})}catch{}return}p(!0),y.executeJavaScript?.(ms,!0).then(async R=>{if(p(!1),!R||!rt(R))return;if(!(K??(w?"draft":null))){ye.error("Open a chat session before attaching preview annotations");return}const q=typeof y.getWebContentsId=="function"?y.getWebContentsId():null;if(q==null)return;const z=await Ir("desktop_browser_capture_page",{webContentsId:q}),ee=await y.executeJavaScript?.("({ width: window.innerWidth, height: window.innerHeight })",!0).catch(()=>null),oe=Number.isFinite(ee?.width)?ee.width:z.width,H=Number.isFinite(ee?.height)?ee.height:z.height,se=await kt(z.base64,z.width,z.height,oe,H,R),C=!!se;se&&await P(se),ht(St({pageUrl:x,viewport:{width:oe,height:H},devicePixelRatio:window.devicePixelRatio||1,target:R,screenshotAttached:C,intro:"This is a selected DOM element from the in-app preview. A screenshot of the visible preview area with the selected element highlighted is attached."})),ye.success("Preview annotation attached to chat")}).catch(()=>p(!1))}},[P,K,x,g,w]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{i.current?.goBack?.()}catch{}},children:e.jsx(U,{name:"arrow-left",className:"h-3.5 w-3.5"})}),e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{i.current?.goForward?.()}catch{}},children:e.jsx(U,{name:"arrow-right",className:"h-3.5 w-3.5"})}),e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{try{i.current?.reload?.()}catch{}},children:e.jsx(U,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx("form",{className:"min-w-0 flex-1",onSubmit:y=>{y.preventDefault(),v(c)},children:e.jsx("input",{value:c,onChange:y=>f(y.target.value),className:"h-7 w-full rounded-md border border-border/50 bg-[var(--surface-elevated)] px-2 typography-micro text-foreground outline-none focus:border-[var(--interactive-focus-ring)]","aria-label":"Browser address"})}),a,e.jsx(ne,{type:"button",variant:g?"secondary":"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:_,title:"Inspect preview element","aria-label":"Inspect preview element",children:e.jsx(U,{name:"cursor",className:"h-3.5 w-3.5"})}),e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{st(x)},children:e.jsx(U,{name:"external-link",className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"relative min-h-0 flex-1 overflow-hidden bg-background",children:[e.jsx("webview",{ref:i,src:d,partition:"persist:pichamber-browser",allowpopups:!0,style:{position:"absolute",inset:0,width:"100%",height:"100%",border:"none"}}),!x&&!$?e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-6 bg-background p-6 text-center",children:[e.jsx(Ht,{width:140,height:140,className:"opacity-20"}),e.jsx("span",{className:"typography-ui-header text-muted-foreground",children:"Web browser"})]}):null,$?e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-background/70 typography-micro text-muted-foreground",children:"Loading..."}):null]})]})},Rn=28,La=t=>t.length>Rn?`${t.slice(0,Rn-1)}…`:t,Oa=({page:t,directory:n,route:r,onScreen:a})=>{const i=X(x=>x.updateBrowserPage),o=X(x=>x.setBrowserRoutePreference),u=s.useCallback(x=>{i(n,t.id,{route:x}),$t()&&o(x)},[n,t.id,o,i]),l=e.jsx(_a,{route:r,onRouteChange:u}),c={initialUrl:t.url??"",directory:n,pageId:t.id,onScreen:a,routeToggle:l,onRouteChange:u};if(r==="server")return e.jsx(Da,{...c,popupId:t.popupId??null},r);const f=$t()?Ia:Ma;return e.jsx(f,{...c},r)},Ba=({directory:t,browser:n,onScreen:r})=>{const a=X(g=>g.browserRoutePreference),i=X(g=>g.openContextBrowser),o=X(g=>g.activateBrowserPage),u=X(g=>g.closeBrowserPage),l=X(g=>g.updateBrowserPage),c=s.useMemo(()=>n?.pages??[],[n]),f=n?.activePageId??null;s.useEffect(()=>{for(const g of c)g.route||l(t,g.id,{defaultRoute:Ct(null,a)})},[t,c,a,l]);const x=s.useMemo(()=>c.map(g=>{const p=As(g);return{id:g.id,label:La(p),title:g.url&&g.url!==p?`${p}
|
|
127
|
-
${g.url}`:p,closeLabel:`Close ${p}`}}),[c]),b=()=>{i(t,"",{target:"new",route:Ct(null,a)})},d=g=>{Kn(t,g),u(t,g)};return e.jsxs("div",{className:"absolute inset-0 flex flex-col bg-background",children:[e.jsxs("div",{className:"flex h-9 shrink-0 items-stretch border-b border-border bg-[var(--surface-background)]",children:[e.jsx(os,{items:x,activeId:f,onSelect:g=>o(t,g),onClose:d,layoutMode:"scrollable",variant:"default"}),e.jsx(ne,{type:"button",variant:"ghost",size:"sm",className:"mx-1 my-auto h-7 w-7 shrink-0 p-0",onClick:b,title:"New browser tab","aria-label":"New browser tab",children:e.jsx(U,{name:"add",className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"relative min-h-0 flex-1",children:c.map(g=>{const p=Ct(g.route,a),$=g.id===f,k=p==="device"&&$t();return e.jsx("div",{className:pe("absolute inset-0",!$&&(k?"invisible pointer-events-none":"hidden")),"aria-hidden":$?void 0:!0,children:e.jsx(Oa,{page:g,directory:t,route:p,onScreen:r&&$})},g.id)})})]})},Fa=8,Ue=new Map,Qt=t=>JSON.stringify([_s(),t]),En=t=>{const n=Qt(t),r=Ue.get(n);return r?(r.touchedAt=Date.now(),Ue.delete(n),Ue.set(n,r),r):null},Et=t=>{const n=Qt(t),r=Ue.get(n);if(r)return r.touchedAt=Date.now(),r;if(Ue.size>=Fa){const i=Ue.keys().next().value;i!==void 0&&Ue.delete(i)}const a={childrenByDir:{},loadErrorsByDir:{},loadedDirs:new Set,touchedAt:Date.now()};return Ue.set(n,a),a},$a=t=>{Ue.delete(Qt(t))},Wa=(t,n)=>e.jsx(Ut,{filePath:t,extension:n}),za=({node:t,root:n,isExpanded:r,isActive:a,isBrowserClient:i,status:o,badge:u,permissions:l,downloadFile:c,onSelect:f,onToggle:x,onRevealPath:b,onOpenDialog:d})=>{const g=t.type==="directory",{canRename:p,canCreateFile:$,canCreateFolder:k,canDelete:D,canReveal:I}=l,K=!g&&!!c,w=I&&!i&&Wn()&&Ms(),P=p||$||k||D||K||w,[v,_]=s.useState(!1),[y,R]=s.useState(!1),Q=s.useCallback(H=>{P&&(H?.preventDefault(),R(!0))},[P]),q=s.useCallback(()=>{g?x(t.path):f(t)},[g,t,f,x]),z=s.useCallback(H=>{H.stopPropagation(),R(!1),_(!0)},[]),ee=({Item:H,Separator:se})=>e.jsxs(e.Fragment,{children:[p&&e.jsxs(H,{onClick:C=>{C.stopPropagation(),d("rename",t)},children:[e.jsx(U,{name:"edit",className:"mr-2 h-4 w-4"})," ","Rename"]}),e.jsxs(H,{onClick:C=>{C.stopPropagation(),pt(t.path).then(W=>{if(W.ok){ye.success("Path copied");return}ye.error("Copy failed")})},children:[e.jsx(U,{name:"file-copy",className:"mr-2 h-4 w-4"})," ","Copy path"]}),!g&&c&&e.jsxs(H,{onClick:C=>{C.stopPropagation(),c(t.path).catch(W=>{console.error("Download failed:",W),ye.error("Operation failed")})},children:[e.jsx(U,{name:"download",className:"mr-2 h-4 w-4"})," ",i?"Download":"Save"]}),w&&e.jsxs(H,{onClick:C=>{C.stopPropagation(),b(t.path)},children:[e.jsx(U,{name:"folder-received",className:"mr-2 h-4 w-4"})," ",Is()]}),g&&($||k)&&e.jsxs(e.Fragment,{children:[e.jsx(se,{}),$&&e.jsxs(H,{onClick:C=>{C.stopPropagation(),d("createFile",t)},children:[e.jsx(U,{name:"file-add",className:"mr-2 h-4 w-4"})," ","New file"]}),k&&e.jsxs(H,{onClick:C=>{C.stopPropagation(),d("createFolder",t)},children:[e.jsx(U,{name:"folder-add",className:"mr-2 h-4 w-4"})," ","New folder"]})]}),D&&e.jsxs(e.Fragment,{children:[e.jsx(se,{}),e.jsxs(H,{onClick:C=>{C.stopPropagation(),d("delete",t)},className:"text-destructive focus:text-destructive",children:[e.jsx(U,{name:"delete-bin",className:"mr-2 h-4 w-4"})," ","Delete"]})]})]}),oe=s.useCallback(H=>{const se=ts(n,t.path);se&&(H.dataTransfer.setData("application/x-pichamber-file-path",se),H.dataTransfer.effectAllowed="copy")},[t.path,n]);return e.jsxs(gr,{open:y,onOpenChange:R,children:[e.jsxs(xr,{render:e.jsx("div",{className:"group relative flex items-center",onContextMenu:Q}),children:[e.jsxs("button",{type:"button",onClick:q,onContextMenu:Q,draggable:!0,onDragStart:oe,className:pe("flex w-full items-center gap-1.5 rounded-md px-2 py-1 text-left text-foreground transition-colors select-none",P&&"group-hover:pr-8 group-focus-within:pr-8",a?"bg-interactive-selection/70":"hover:bg-interactive-hover/40","cursor-grab active:cursor-grabbing"),children:[g?r?e.jsx(U,{name:"folder-open",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):e.jsx(U,{name:"folder-3",className:"h-4 w-4 flex-shrink-0 text-muted-foreground"}):Wa(t.path,t.extension),e.jsx("span",{className:"min-w-0 flex-1 truncate typography-meta",title:t.path,children:t.name}),!g&&o&&e.jsx(To,{status:o,className:P?"group-hover:invisible group-focus-within:invisible":void 0}),g&&u&&e.jsx(Do,{badge:u,className:P?"group-hover:invisible group-focus-within:invisible":void 0})]}),P&&e.jsx("div",{className:"absolute right-1 top-1/2 -translate-y-1/2 opacity-0 focus-within:opacity-100 group-hover:opacity-100",children:e.jsxs(Lt,{open:v,onOpenChange:_,children:[e.jsxs(Qe,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("span",{className:"inline-flex",children:e.jsx(Ot,{asChild:!0,children:e.jsx(ne,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:z,title:"File menu","aria-label":"File menu",children:e.jsx(U,{name:"more-2-fill",className:"h-4 w-4"})})})})}),e.jsx(et,{side:"bottom",sideOffset:6,children:"File menu"})]}),e.jsx(Bt,{align:"end",side:"bottom",onCloseAutoFocus:()=>_(!1),children:ee({Item:Ge,Separator:Gn})})]})})]}),e.jsx(wr,{className:"min-w-[180px]",children:ee({Item:br,Separator:yr})})]})},Ha=(t,n)=>t.node===n.node&&t.root===n.root&&t.isExpanded===n.isExpanded&&t.isActive===n.isActive&&t.isBrowserClient===n.isBrowserClient&&t.status===n.status&&t.badge===n.badge&&t.permissions===n.permissions&&t.downloadFile===n.downloadFile&&t.onSelect===n.onSelect&&t.onToggle===n.onToggle&&t.onRevealPath===n.onRevealPath&&t.onOpenDialog===n.onOpenDialog,Ua=s.memo(za,Ha),gs=t=>{const{files:n}=jt(),r=X(o=>o.openContextFile),a=$e(o=>o.setSelectedPath),i=$e(o=>o.addOpenPath);return s.useCallback(async o=>{if(!t)return;const u=await ss(n,o,{directory:t});if(!u.ok){ye.error(rs(u.reason));return}a(t,o),i(t,o),r(t,o)},[i,n,r,t,a])},Va=280,Ka=({onBackToFile:t})=>{const{files:n,runtime:r}=jt(),a=Ls(r.platform),i=mt()??"",o=_e(i.trim()),u=Os(),l=Vt(i),[c,f]=s.useState(""),x=s.useRef(null),b=s.useRef(null),[d,g]=s.useState(!1);s.useLayoutEffect(()=>{const j=b.current;if(!j||typeof ResizeObserver>"u")return;const G=()=>g(j.clientWidth<Va);G();const le=new ResizeObserver(G);return le.observe(j),()=>le.disconnect()},[]);const p=c.trim().length>0,{results:$,searching:k,failed:D}=Ao({directory:i,query:c,chrome:"desktop",showGitignored:u}),[I,K]=s.useState({}),[w,P]=s.useState({}),v=s.useRef(new Set),_=s.useRef(new Set),y=s.useRef(null);s.useEffect(()=>{if(!o){K({}),P({}),v.current=new Set;return}const j=En(o);j?(K({...j.childrenByDir}),P({...j.loadErrorsByDir}),v.current=new Set(j.loadedDirs)):(K({}),P({}),v.current=new Set)},[o]),s.useEffect(()=>{if(!o)return;const j=Et(o);j.childrenByDir=I},[o,I]),s.useEffect(()=>{if(!o)return;const j=Et(o);j.loadErrorsByDir=w},[o,w]),s.useEffect(()=>{if(!o)return;const j=Et(o);j.loadedDirs=new Set(v.current)},[o,I,w]),s.useEffect(()=>()=>{if(!o)return;const j=En(o);j&&j.loadedDirs.size===0&&Object.keys(j.childrenByDir).length===0&&$a(o)},[o]);const R=s.useMemo(()=>[],[]),Q=s.useMemo(()=>[],[]),q=$e(j=>o?j.byRoot[o]?.expandedPaths??R:R),z=$e(j=>o?j.byRoot[o]?.selectedPath??null:null),ee=$e(j=>j.setSelectedPath),oe=$e(j=>j.removeOpenPathsByPrefix),H=$e(j=>j.toggleExpandedPath),se=$e(j=>j.collapseAllExpandedPaths),C=X(j=>o?j.contextPanelByDirectory[o]?.tabs??Q:Q),W=s.useMemo(()=>new Set(C.map(j=>j.mode==="file"?j.targetPath:null).filter(j=>typeof j=="string"&&j.length>0).map(j=>_e(j))),[C]),re=s.useCallback(j=>{n.revealPath&&n.revealPath(j).catch(()=>{ye.error("Failed to reveal path")})},[n]),E=s.useCallback((j,G)=>{const le=G.filter(h=>h&&typeof h.name=="string"&&h.name.length>0).filter(h=>!_o(h.name)&&(u||!Mo(h.name))).map(h=>{const T=h.name,J=_e(h.path||""),fe=J?Io(J)?J:_e(`${j}/${J}`):_e(`${j}/${T}`),Se=h.isDirectory?"directory":"file",Ie=Se==="file"&&T.includes(".")?T.split(".").pop()?.toLowerCase():void 0;return{name:T,path:fe,type:Se,extension:Ie}});return Lo(le)},[u]),B=s.useCallback(async(j,G)=>{const le=_e(j.trim());if(!le||v.current.has(le)||_.current.has(le))return;_.current=new Set(_.current),_.current.add(le);const h=n.listDirectory?n.listDirectory(le).then(T=>T.entries.map(J=>({name:J.name,path:J.path,isDirectory:J.isDirectory}))):Bs(le).then(T=>T.map(J=>({name:J.name,path:J.path,isDirectory:J.isDirectory})));try{const T=await h;if(G?.())return;const J=E(le,T);v.current=new Set(v.current),v.current.add(le),P(fe=>{if(!fe[le])return fe;const Se={...fe};return delete Se[le],Se}),K(fe=>({...fe,[le]:J}))}catch(T){if(G?.())return;const J=T instanceof Error?T.message:String(T??"");console.error("Failed to load sidebar directory:",T),P(fe=>({...fe,[le]:J}))}finally{_.current=new Set(_.current),_.current.delete(le)}},[n,E]),Z=s.useCallback(async()=>{if(!o)return;y.current?.abort();const j=new AbortController;y.current=j;try{const le=($e.getState().byRoot[o]?.expandedPaths??[]).map(J=>_e(J)).filter(J=>!!J&&J!==o&&J.startsWith(`${o}/`)),h=[o,...le];v.current=new Set(v.current);for(const J of h)v.current.delete(J);P(J=>{if(Object.keys(J).length===0)return J;const fe={...J};let Se=!1;for(const Ie of h)Ie in fe&&(delete fe[Ie],Se=!0);return Se?fe:J});const T=()=>j.signal.aborted;await B(o,T);for(let J=0;J<le.length&&!j.signal.aborted;J+=3){const fe=le.slice(J,J+3);await Promise.all(fe.map(Se=>B(Se,T)))}}catch(G){if(j.signal.aborted)return;console.error("Failed to refresh sidebar tree:",G)}finally{y.current===j&&(y.current=null)}},[B,o]),ue=s.useCallback(async j=>{if(!j){await Z();return}const G=_e(j);v.current=new Set(v.current),v.current.delete(G),_.current=new Set(_.current),_.current.delete(G),await B(G)},[B,Z]),ge=s.useCallback(()=>{o&&ee(o,null)},[o,ee]),{operation:he,target:xe,inputValue:je,setInputValue:Ne,submitting:we,inputRef:me,open:ve,close:Ce,submit:be,capabilities:{canCreateFile:ke,canCreateFolder:Pe,canRename:Re,canDelete:O}}=Oo({files:n,root:o,selectedPath:z??"",refreshDirectory:ue,removeOpenPathsByPrefix:oe,clearSelectedPath:ge}),V=!!n.revealPath,de=s.useMemo(()=>({canRename:Re,canCreateFile:ke,canCreateFolder:Pe,canDelete:O,canReveal:V}),[Re,ke,Pe,O,V]);s.useEffect(()=>{o&&(y.current?.abort(),v.current=new Set,_.current=new Set,P({}),K(j=>Object.keys(j).length===0?j:{}),B(o))},[B,o,u]),s.useEffect(()=>{if(!o||q.length===0)return;const j=q.map(h=>_e(h)).filter(h=>!!h&&h!==o&&h.startsWith(`${o}/`)&&!v.current.has(h)&&!_.current.has(h)).sort((h,T)=>h.split("/").length-T.split("/").length);if(j.length===0)return;let G=!1;const le=()=>G;return(async()=>{for(let h=0;h<j.length&&!G;h+=3){const T=j.slice(h,h+3);await Promise.all(T.map(J=>B(J,le)))}})(),()=>{G=!0}},[q,B,o]);const M=s.useMemo(()=>{const j=new Map;if(!l?.files)return j;for(const G of l.files)G.index==="A"||G.working_dir==="?"?j.set(G.path,"git-added"):G.index==="D"?j.set(G.path,"git-deleted"):(G.index==="M"||G.working_dir==="M")&&j.set(G.path,"git-modified");return j},[l]),te=s.useMemo(()=>{const j=new Map;if(!l?.files||!o)return j;for(const G of l.files){const le=G.index==="M"||G.working_dir==="M",h=G.index==="A"||G.working_dir==="?";if(!le&&!h)continue;const T=G.path.split("/");if(T.length<=1)continue;let J=o;for(let fe=0;fe<T.length-1;fe++){J=`${J}/${T[fe]}`;let Se=j.get(J);Se||(Se={modified:0,added:0},j.set(J,Se)),le&&Se.modified++,h&&Se.added++}}return j},[l,o]),S=s.useCallback(j=>{const G=j.startsWith(o+"/")?j.slice(o.length+1):j,le=M.get(G);return le||(W.has(j)&&j!==z?"open":null)},[W,M,o,z]),L=s.useCallback(j=>{if(te.size===0)return null;const G=te.get(j);return G&&G.modified+G.added>0?G:null},[te]),F=gs(o),ae=s.useCallback(j=>F(j.path),[F]),ie=$e(j=>j.expandPaths),m=s.useRef(null),A=s.useRef(null);s.useEffect(()=>{if(!o||!z)return;A.current=z;const j=mn(z,o);if(j.length!==0){ie(o,j);for(const G of j)B(G)}},[ie,o,z]);const Y=X(j=>j.fileTreeReveal),ce=X(j=>j.clearFileTreeReveal),De=s.useRef("nearest");s.useEffect(()=>{if(!o||!Y)return;const j=Y.path;if(ce(),f(""),_e(j)===_e(o)){m.current?.firstElementChild?.scrollIntoView({block:"start"});return}const G=mn(`${j}/_`,o);if(G.length!==0){A.current=j,De.current="start",ie(o,G);for(const le of G)B(le)}},[ce,ie,Y,o]),s.useEffect(()=>{const j=A.current,G=m.current;if(!j||!G)return;const le=G.querySelector(`[data-tree-path="${CSS.escape(j)}"]`);le&&(A.current=null,le.scrollIntoView({block:De.current}),De.current="nearest")},[I,q,p]);const Me=s.useCallback(async j=>{const G=_e(j);o&&(H(o,G),v.current.has(G)||await B(G))},[B,o,H]);function Ae(j,G){return(I[j]??[]).map(h=>{const T=h.type==="directory",J=T&&q.includes(h.path),fe=z===h.path;return e.jsxs("li",{className:"relative","data-tree-path":h.path,children:[e.jsx(Ua,{node:h,root:o,isExpanded:J,isActive:fe,isBrowserClient:a,status:T?void 0:S(h.path),badge:T?L(h.path):void 0,permissions:de,downloadFile:n.downloadFile,onSelect:ae,onToggle:Me,onRevealPath:re,onOpenDialog:ve}),T&&J&&e.jsxs("ul",{className:"relative ml-[15px] flex flex-col border-l border-border/50 pl-1.5",children:[w[h.path]?e.jsxs("li",{className:"flex items-center gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{className:"min-w-0 flex-1 truncate text-[var(--status-error)]",title:w[h.path],children:w[h.path]}),e.jsxs(ne,{variant:"ghost",size:"xs",className:"h-6 gap-1",onClick:()=>{ue(h.path)},children:[e.jsx(U,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):null,Ae(h.path)]})]},h.path)})}const Ve=!!(o&&I[o]),Ke=o?w[o]:null;return e.jsxs("section",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[e.jsxs("div",{ref:b,className:"flex h-9 shrink-0 items-center gap-0.5 border-b border-border/60 pl-1.5 pr-1",children:[t?e.jsxs(ne,{variant:"ghost",size:"xs",onClick:t,className:"mr-1 shrink-0 text-muted-foreground hover:text-foreground",children:[e.jsx(U,{name:"arrow-left",className:"size-3.5"}),"Back to file"]}):null,e.jsxs("div",{className:"relative min-w-0 flex-1",children:[e.jsx(U,{name:"search",className:"pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-subtle-foreground"}),e.jsx(un,{ref:x,value:c,onChange:j=>f(j.target.value),onKeyDown:j=>{j.key!=="Escape"||!c||(j.preventDefault(),f(""))},placeholder:"Search","aria-label":"Search files",className:"h-7 rounded-md bg-transparent pl-7 pr-7 typography-meta ring-0 md:typography-meta placeholder:text-subtle-foreground focus:ring-1"}),c.trim().length>0?e.jsx("button",{type:"button","aria-label":"Clear search",title:"Clear search",className:"absolute right-1.5 top-1/2 inline-flex size-4 -translate-y-1/2 items-center justify-center text-muted-foreground hover:text-foreground",onClick:()=>{f(""),x.current?.focus()},children:e.jsx(U,{name:"close",className:"size-3.5"})}):null]}),d?e.jsxs(Lt,{children:[e.jsxs(Qe,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("span",{className:"inline-flex shrink-0",children:e.jsx(Ot,{asChild:!0,children:e.jsx(ne,{variant:"ghost",size:"sm",className:"size-7 p-0","aria-label":"File actions",children:e.jsx(U,{name:"more-fill",className:"size-4"})})})})}),e.jsx(et,{side:"bottom",sideOffset:6,children:"File actions"})]}),e.jsxs(Bt,{align:"end",side:"bottom",children:[ke?e.jsxs(Ge,{onClick:()=>ve("createFile",{path:i,type:"directory"}),children:[e.jsx(U,{name:"file-add",className:"mr-2 size-4"})," ","New file"]}):null,Pe?e.jsxs(Ge,{onClick:()=>ve("createFolder",{path:i,type:"directory"}),children:[e.jsx(U,{name:"folder-add",className:"mr-2 size-4"})," ","New folder"]}):null,ke||Pe?e.jsx(Gn,{}):null,e.jsxs(Ge,{onClick:()=>{Z()},children:[e.jsx(U,{name:"refresh",className:"mr-2 size-4"})," ","Refresh"]}),e.jsxs(Ge,{onClick:()=>{o&&se(o)},children:[e.jsx(U,{name:"collapse-vertical",className:"mr-2 size-4"})," ","Collapse all folders"]})]})]}):e.jsxs(e.Fragment,{children:[ke||Pe?e.jsxs(Lt,{children:[e.jsxs(Qe,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("span",{className:"inline-flex shrink-0",children:e.jsx(Ot,{asChild:!0,children:e.jsx(ne,{variant:"ghost",size:"sm",className:"size-7 p-0","aria-label":"New file or folder",children:e.jsx(U,{name:"add",className:"size-4"})})})})}),e.jsx(et,{side:"bottom",sideOffset:6,children:"New file or folder"})]}),e.jsxs(Bt,{align:"end",side:"bottom",children:[ke?e.jsxs(Ge,{onClick:()=>ve("createFile",{path:i,type:"directory"}),children:[e.jsx(U,{name:"file-add",className:"mr-2 size-4"})," ","New file"]}):null,Pe?e.jsxs(Ge,{onClick:()=>ve("createFolder",{path:i,type:"directory"}),children:[e.jsx(U,{name:"folder-add",className:"mr-2 size-4"})," ","New folder"]}):null]})]}):null,e.jsxs(Qe,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("span",{className:"inline-flex shrink-0",children:e.jsx(ne,{variant:"ghost",size:"sm",onClick:()=>{Z()},className:"size-7 p-0","aria-label":"Refresh",children:e.jsx(U,{name:"refresh",className:"size-4"})})})}),e.jsx(et,{side:"bottom",sideOffset:6,children:"Refresh"})]}),e.jsxs(Qe,{children:[e.jsx(Ze,{asChild:!0,children:e.jsx("span",{className:"inline-flex shrink-0",children:e.jsx(ne,{variant:"ghost",size:"sm",onClick:()=>{o&&se(o)},className:"size-7 p-0","aria-label":"Collapse all folders",children:e.jsx(U,{name:"collapse-vertical",className:"size-4"})})})}),e.jsx(et,{side:"bottom",sideOffset:6,children:"Collapse all folders"})]})]})]}),e.jsx(Lr,{outerClassName:"flex-1 min-h-0",className:"px-1 py-2",children:e.jsx("ul",{ref:m,className:"flex flex-col",children:p&&k?e.jsxs("li",{className:"flex items-center gap-1.5 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx(U,{name:"loader-4",className:"size-4 animate-spin"}),"Searching..."]}):p&&D?e.jsx("li",{className:"px-2 py-1 typography-meta text-[var(--status-error)]",children:"Search failed. Edit the search to try again."}):p&&$.length===0?e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground text-pretty",children:`No files match “${c.trim()}”.`}):p?$.map(j=>{const G=j.relativePath||ts(o??"",j.path);return e.jsx("li",{children:e.jsx(ns,{path:G||j.path,status:S(j.path),active:z===j.path,match:c,onClick:()=>{ae(j)},onDragStart:le=>{!G||G==="."||(le.dataTransfer.setData("application/x-pichamber-file-path",G),le.dataTransfer.effectAllowed="copy")}})},j.path)}):Ke?e.jsxs("li",{className:"flex flex-col gap-2 px-2 py-1 typography-meta text-muted-foreground",children:[e.jsx("span",{children:Ke}),e.jsxs(ne,{variant:"outline",size:"xs",className:"w-fit gap-1.5",onClick:()=>{Z()},children:[e.jsx(U,{name:"refresh",className:"h-3.5 w-3.5"}),"Refresh"]})]}):Ve&&o?Ae(o):e.jsx("li",{className:"px-2 py-1 typography-meta text-muted-foreground",children:"Loading..."})})}),e.jsx(Kt,{open:!!he,onOpenChange:j=>!j&&Ce(),children:e.jsxs(Xt,{children:[e.jsxs(qt,{children:[e.jsxs(Yt,{children:[he==="createFile"&&"Create file",he==="createFolder"&&"Create folder",he==="rename"&&"Rename",he==="delete"&&"Delete"]}),e.jsxs(Gt,{children:[he==="createFile"&&`Create a new file in ${xe?.path??"root"}`,he==="createFolder"&&`Create a new folder in ${xe?.path??"root"}`,he==="rename"&&`Rename ${xe?.name??""}`,he==="delete"&&`Are you sure you want to delete ${xe?.name??""}? This action cannot be undone.`]})]}),he!=="delete"&&e.jsx("div",{className:"py-4",children:e.jsx(un,{ref:me,value:je,onChange:j=>Ne(j.target.value),placeholder:he==="rename"?"New name":"Name",onKeyDown:j=>{j.key==="Enter"&&be()},autoFocus:!0})}),e.jsxs(Or,{children:[e.jsx(ne,{variant:"outline",onClick:Ce,disabled:we,children:"Cancel"}),e.jsx(ne,{variant:he==="delete"?"destructive":"default",onClick:()=>{be()},disabled:we||he!=="delete"&&!je.trim(),children:we?e.jsx(U,{name:"loader-4",className:"size-4 animate-spin"}):he==="delete"?"Delete":"Confirm"})]})]})})]})},Xa=200,qa=480,Ya=280,Ga=160,Ja=({visible:t,overlay:n=!1,onDismissOverlay:r})=>{const a=X(v=>v.contextEditorTreeWidth),i=X(v=>v.setContextEditorTreeWidth),[o,u]=s.useState(!1),l=s.useRef(0),c=s.useRef(a),f=s.useRef(null),x=s.useRef(null),b=s.useRef(null),d=s.useCallback(v=>Math.min(qa,Math.max(Xa,Math.round(v))),[]),[g,p]=s.useState(null);s.useLayoutEffect(()=>{const v=b.current?.parentElement;if(!v)return;const _=new ResizeObserver(([y])=>{const R=y?.contentRect.width??0;p(R>0?Math.round(R):null)});return _.observe(v),()=>_.disconnect()},[]);const $=s.useCallback(v=>n?g??v:g===null?v:Math.max(Ga,Math.min(v,g-Ya)),[n,g]),k=$(a),D=s.useCallback(v=>{const _=b.current;_&&(_.style.width=`${v}px`,_.style.setProperty("--oc-editor-tree-width",`${v}px`))},[]),I=v=>{if(t){try{v.currentTarget.setPointerCapture(v.pointerId)}catch{}x.current=v.pointerId,u(!0),l.current=v.clientX,c.current=k,f.current=k,v.preventDefault()}},K=v=>{if(!o||x.current!==v.pointerId)return;const _=l.current-v.clientX,y=$(d(c.current+_));f.current!==y&&(f.current=y,D(y))},w=v=>{if(x.current!==v.pointerId)return;try{v.currentTarget.releasePointerCapture(v.pointerId)}catch{}const _=d(f.current??a);x.current=null,f.current=null,u(!1),i(_)},P=t?k:0;return e.jsxs("div",{ref:b,className:pe("h-full flex-shrink-0 overflow-hidden bg-background will-change-[width] motion-reduce:transition-none",n?"absolute inset-y-0 right-0 z-20":"relative border-l border-border",!t&&"border-l-0"),style:{width:`${o?f.current??P:P}px`,"--oc-editor-tree-width":`${o?f.current??k:k}px`,overflowX:"clip",transitionProperty:o?"none":"width",transitionDuration:"200ms",transitionTimingFunction:"cubic-bezier(0.22, 1, 0.36, 1)"},"aria-hidden":!t,children:[t&&!n&&e.jsx("div",{className:pe("absolute left-0 top-0 z-20 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",o&&"bg-[var(--interactive-border)]"),onPointerDown:I,onPointerMove:K,onPointerUp:w,onPointerCancel:w,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsx("div",{className:pe("relative z-10 h-full shrink-0 transition-opacity duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",o&&"pointer-events-none",!t&&"pointer-events-none select-none opacity-0"),style:{width:"var(--oc-editor-tree-width)"},"aria-hidden":!t,onKeyDown:n&&r?v=>{v.key==="Escape"&&!v.defaultPrevented&&r()}:void 0,children:e.jsx(Ka,{onBackToFile:n?r:void 0})})]})},Qa=({directory:t})=>{const n=_e(t.trim()),r=Vt(t),a=gs(n),i=s.useMemo(()=>{const o=new Set,u=[];for(const l of r?.files??[]){if(o.has(l.path))continue;o.add(l.path);const c=Bo(l);!c||c==="git-deleted"||u.push({path:l.path,status:c})}return u},[r?.files]);return e.jsx("div",{className:"h-full overflow-y-auto",children:e.jsx("div",{className:"flex min-h-full flex-col justify-center px-5 py-8",children:e.jsxs("div",{className:"mx-auto w-full max-w-sm",children:[e.jsx("h2",{className:"typography-ui-label font-medium text-foreground",children:"No file open"}),e.jsx("p",{className:"mt-1 typography-meta text-muted-foreground text-pretty",children:i.length>0?"Pick a file from the tree, or open one the session changed.":"Pick a file from the tree to view or edit it."}),i.length>0?e.jsxs("section",{className:"mt-4","aria-label":"Changed files",children:[e.jsx("h3",{className:"px-2 typography-micro font-medium text-subtle-foreground",children:i.length===1?"1 changed file":`${i.length} changed files`}),e.jsx("ul",{className:"mt-1 flex flex-col",children:i.map(({path:o,status:u})=>e.jsx("li",{children:e.jsx(ns,{path:o,status:u,onClick:()=>{a(`${n}/${o}`)}})},o))})]}):null]})})})},Za="x-pichamber-preview-target-error",ei=t=>{const n=t.get(Za);return n==="missing"||n==="expired"||n==="invalid-token"?n:null},ti=(t,n)=>ei(t)?n?"stop-retrying":"retry-registration":"none";function ni(t){const[n,r]=s.useState("");return s.useEffect(()=>{if(!t){r("");return}let a=!1;return r(""),Fs(zn()).then(i=>{!a&&i&&r(t)}).catch(()=>{}),()=>{a=!0}},[t]),n}const si=({rawUrl:t,onNavigate:n})=>{const{currentTheme:r}=Br(),[a,i]=s.useReducer(M=>M+1,0),[o,u]=s.useReducer(M=>M+1,0),[l,c]=s.useState({status:"idle"}),f=s.useRef(null),x=s.useRef(1),[b,d]=s.useState(!1),[g,p]=s.useState(!1),[$,k]=s.useState("all"),[D,I]=s.useState([]),[K,w]=s.useState(!1),[P,v]=s.useState(null),_=Te(M=>M.currentSessionId),y=Te(M=>M.newSessionDraft?.open),R=mt(),Q=ft(M=>M.addAttachedFile);let q=null;try{q=t?new URL(t):null}catch{q=null}const z=q?q.hostname==="localhost"||q.hostname==="127.0.0.1"||q.hostname==="::1"||q.hostname==="[::1]"||q.hostname==="0.0.0.0":!1,ee=q?q.hostname==="0.0.0.0"?new URL(q.toString().replace("0.0.0.0","127.0.0.1")):q:null,oe=ee?ee.toString():"",H=oe?`${zn()||"same-origin"}|${oe}`:"",se=r.metadata.variant;s.useEffect(()=>{if(!oe||!z){c({status:"idle"});return}const M=as(H);if(M?.previewToken){c({status:"ready",proxyBasePath:M.proxyBasePath,previewToken:M.previewToken,expiresAt:M.expiresAt});return}M&&We.delete(H);let te=!1;return c({status:"loading"}),(async()=>{try{const S=await Mt("/api/preview/targets",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({url:oe})}),L=await aa(S);if(!L.ok){We.delete(H),te||c({status:"error",message:L.message});return}We.set(H,L.target),te||c({status:"ready",...L.target})}catch(S){if(We.delete(H),!te){const L=S instanceof Error?S.message:String(S);c({status:"error",message:L})}}})(),()=>{te=!0}},[z,H,o,oe]);const C=ee&&(ee.protocol==="http:"||ee.protocol==="https:")?ee.toString():"",W=z&&l.status==="ready"?`${l.proxyBasePath}|${l.previewToken||""}|${a}`:"",re=ni(W),E=z&&l.status==="ready"&&ee&&re===W?(()=>{const M=ee.pathname||"/",te=new URLSearchParams(ee.search);te.delete("oc_url_token"),te.delete("oc_client_token"),te.set("ocPreview",String(a)),te.set("oc_preview_token",l.previewToken||"");const S=te.toString(),L=ee.hash||"";return $s().authenticatedAsset(`${l.proxyBasePath}${M}${S?`?${S}`:""}${L}`)})():"",B=z?E:C,Z=z?ia(E):C,ue=z&&(l.status==="loading"||l.status==="idle"||re!==W),ge=z&&l.status==="error",he=s.useCallback(M=>{if(!(_??(y?"draft":null))||!R){ye.error("Open a chat session before attaching preview annotations");return}const S=t||B||"",L=typeof window<"u"?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0},F=typeof window<"u"?window.devicePixelRatio:1;(async()=>{let ae=!1;try{const ie=f.current,m=ie?await fs(ie,M):null;m&&(await Q(m),ae=!0)}catch{ae=!1}ht(St({pageUrl:S,viewport:L,devicePixelRatio:F,target:M,screenshotAttached:ae,intro:"This is a selected DOM element from the in-app preview."})),ye.success("Preview annotation attached to chat")})()},[Q,_,R,B,y,t]);s.useEffect(()=>{d(!1),I([]),p(!1),k("all"),w(!1),v(null),x.current=1},[B]),s.useEffect(()=>{const M=f.current?.contentWindow;!b||!M||Sn(M,E,{source:"pichamber-preview-parent",version:1,type:"set-inspect-mode",enabled:K})},[b,K,E]),s.useEffect(()=>{const M=f.current?.contentWindow;!b||!M||Sn(M,E,{source:"pichamber-preview-parent",version:1,type:"set-color-scheme",scheme:se})},[b,se,E]),s.useEffect(()=>{if(!K||typeof window>"u")return;const M=te=>{te.key==="Escape"&&(te.preventDefault(),te.stopImmediatePropagation(),w(!1))};return window.addEventListener("keydown",M,!0),()=>window.removeEventListener("keydown",M,!0)},[K]),s.useEffect(()=>{if(!z||typeof window>"u")return;const M=L=>{if(typeof L=="string")return L;if(L==null)return"";try{return JSON.stringify(L)}catch{return String(L)}},te=L=>{const F=x.current;x.current+=1,I(ae=>{const ie=[...ae,{...L,id:F}];return ie.length>jn?ie.slice(ie.length-jn):ie})},S=L=>{if(L.source!==f.current?.contentWindow)return;const F=L.data;if(!(!F||F.source!=="pichamber-preview-bridge"||F.version!==1)){if(F.type==="ready"){d(!0);return}if(F.type==="console"){const ae=F.level==="error"||F.level==="warn"||F.level==="info"||F.level==="debug"?F.level:"log",ie=Array.isArray(F.args)?F.args.map(M).filter(Boolean):[];te({level:ae,message:ie.join(" "),ts:typeof F.ts=="number"?F.ts:Date.now()});return}if(F.type==="runtime-error"){const ae=M(F.filename),ie=typeof F.line=="number"?F.line:null,m=typeof F.column=="number"?F.column:null,A=ae?`${ae}${ie!==null?`:${ie}${m!==null?`:${m}`:""}`:""}`:"",Y=M(F.stack);te({level:"runtime",message:M(F.message)||"Runtime error",details:[A,Y].filter(Boolean).join(`
|
|
128
|
-
`),ts:typeof F.ts=="number"?F.ts:Date.now()});return}if(F.type==="resource-error"){const ae=M(F.tag)||"resource",ie=M(F.url);te({level:"resource",message:ie?`${ae}: ${ie}`:ae,details:M(F.outerHTML),ts:typeof F.ts=="number"?F.ts:Date.now()});return}if(F.type==="hover"){v(rt(F.target)?F.target:null);return}if(F.type==="select"&&rt(F.target)){v(F.target),w(!1),he(F.target);return}if(F.type==="navigate-preview"){const ae=typeof F.url=="string"?F.url:"",ie=F.navigation==="external"?"external":"proxy";if(ae&&ie==="external"){st(ae);return}ae&&n(ae)}}};return window.addEventListener("message",S),()=>{window.removeEventListener("message",S)}},[he,z,n]);const xe=D.filter(M=>M.level==="error"||M.level==="runtime"||M.level==="resource").length,je=D.filter(M=>oa(M,$)),Ne=s.useCallback(()=>{const M=[`Preview URL: ${t||B||""}`,`Events: ${D.length}`,""].join(`
|
|
129
|
-
`),te=D.map(S=>{const L=new Date(S.ts).toISOString(),F=S.details?`
|
|
130
|
-
${S.details}`:"";return`[${L}] [${S.level}] ${S.message}${F}`}).join(`
|
|
131
|
-
`);pt(`${M}${te}`).then(S=>{S.ok?ye.success("Preview console copied"):ye.error("Failed to copy preview console")})},[D,B,t]),we=s.useCallback(()=>{if(!(_??(y?"draft":null))||!R){ye.error("Open a chat session before attaching preview logs");return}const te=[`Preview URL: ${t||B||""}`,`Events: ${D.length}`,""].join(`
|
|
132
|
-
`),S=D.map(L=>{const F=new Date(L.ts).toISOString(),ae=L.details?`
|
|
133
|
-
${L.details}`:"";return`[${F}] [${L.level}] ${L.message}${ae}`}).join(`
|
|
134
|
-
`);ht(`These are browser console logs from the dev server running for this project.
|
|
135
|
-
|
|
136
|
-
${te}${S}`),ye.success("Preview console attached to chat")},[D,_,R,B,y,t]),[me,ve]=s.useState("unknown"),Ce=s.useRef(0),be=s.useRef(0),ke=s.useRef(""),Pe=s.useRef(""),Re=15e3;s.useEffect(()=>{if(!E){ve("unknown"),ke.current="",Ce.current=0,be.current=0;return}let M=!1,te=null;ke.current!==H&&(ke.current=H,Ce.current=Date.now(),be.current=0);const S=L=>{te=setTimeout(()=>{M||i()},L)};return ve("unknown"),(async()=>{const F=await(async()=>{try{return await Mt(E,{method:"GET",credentials:"include",cache:"no-store",redirect:"manual"})}catch{return null}})();if(M)return;if(!F){ve("unreachable"),S(5e3);return}const ae=ti(F.headers,Pe.current===H);if(ae!=="none"){if(We.delete(H),ae==="retry-registration")Pe.current=H,c({status:"loading"}),u();else{const A=await F.json().catch(()=>({}));if(M)return;const Y=typeof A?.error=="string"?A.error:`HTTP ${F.status}`;c({status:"error",message:Y})}return}if(F.status!==502){Pe.current="",ve("reachable");return}const ie=Ce.current||Date.now();if(Date.now()-ie<Re){ve("starting"),be.current+=1;const A=be.current,Y=Math.min(2e3,250*Math.pow(2,Math.min(4,A)));S(Y);return}ve("unreachable"),S(5e3)})(),()=>{M=!0,te&&clearTimeout(te)}},[H,E,a]);const O=z&&l.status==="ready"&&(me==="unknown"||me==="starting"),V=z&&l.status==="ready"&&me==="unreachable",de=s.useCallback(M=>{if(!z||l.status!=="ready"||typeof window>"u")return;const te=M.currentTarget.contentWindow;if(te)try{const S=te.location,L=ps(E);if(S.origin!==L||S.pathname.startsWith(l.proxyBasePath))return;const F=`${l.proxyBasePath}${S.pathname}${S.search}${S.hash}`;te.location.replace(F)}catch{}},[z,E,l]);return e.jsxs("div",{className:"absolute inset-0 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b border-border bg-[var(--surface-background)] px-2 py-1",children:[e.jsx("div",{className:"min-w-0 flex-1 truncate typography-micro text-muted-foreground",title:Z||t,children:Z||t||"No preview URL"}),e.jsx(ne,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>i(),title:"Reload preview","aria-label":"Reload preview",disabled:!B,children:e.jsx(U,{name:"refresh",className:"h-3.5 w-3.5"})}),e.jsx(ne,{type:"button",size:"sm",variant:"ghost",className:"h-7 w-7 p-0",onClick:()=>{C&&st(C)},title:"Open in browser","aria-label":"Open in browser",disabled:!C,children:e.jsx(U,{name:"external-link",className:"h-3.5 w-3.5"})}),z?e.jsx(ne,{type:"button",size:"sm",variant:K?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>w(M=>!M),title:"Inspect preview element","aria-label":"Inspect preview element",disabled:!b,children:e.jsx(U,{name:"cursor",className:"h-3.5 w-3.5"})}):null,z?e.jsxs(ne,{type:"button",size:"sm",variant:g?"secondary":"ghost",className:"h-7 gap-1 px-2",onClick:()=>p(M=>!M),title:b?"Open preview console":"Waiting for preview console","aria-label":b?"Open preview console":"Waiting for preview console",disabled:!b&&D.length===0,children:[e.jsx(U,{name:"terminal-box",className:"h-3.5 w-3.5"}),xe>0?e.jsx("span",{className:"typography-micro text-status-error",children:xe}):null]}):null]}),e.jsxs("div",{className:"relative min-h-0 flex-1 bg-background",children:[O?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[e.jsx("div",{children:"Starting dev server..."}),e.jsx("div",{className:"text-xs opacity-70",children:"Waiting for the server to accept connections."})]}):V?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 px-6 text-center text-sm text-muted-foreground",children:[e.jsx("div",{children:"Dev server is not responding."}),e.jsx("div",{className:"text-xs opacity-70",children:"Make sure your dev server is still running, then retry."}),e.jsx(ne,{type:"button",size:"sm",variant:"outline",onClick:()=>i(),children:"Retry"})]}):B&&(!z||me==="reachable")?e.jsxs("div",{className:"relative h-full w-full",children:[e.jsx("iframe",{ref:f,src:B,title:"Preview",className:"h-full w-full border-0",style:{colorScheme:se},onLoad:de,sandbox:z?"allow-scripts allow-same-origin allow-forms allow-popups allow-downloads":"allow-scripts allow-forms"},`${B}:${a}`),K&&P?e.jsx("div",{className:"pointer-events-none absolute rounded-sm border-2 border-[var(--interactive-focus-ring)] bg-[var(--interactive-focus-ring)]/35",style:{left:P.bounds.x,top:P.bounds.y,width:P.bounds.width,height:P.bounds.height},children:e.jsxs("div",{className:"absolute -top-6 left-0 max-w-64 truncate rounded bg-[var(--surface-elevated)] px-2 py-0.5 typography-micro text-foreground shadow",children:[P.tag,P.text?` · ${P.text}`:""]})}):null]}):ue?e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Connecting preview proxy..."}):ge?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-2 px-6 text-sm text-muted-foreground",children:[e.jsx("div",{children:"Could not start preview proxy."}),l.status==="error"?e.jsx("div",{className:"text-center text-xs opacity-70",children:l.message}):null]}):e.jsx("div",{className:"flex h-full items-center justify-center px-6 text-sm text-muted-foreground",children:"Preview needs a valid http(s) URL."}),g?e.jsxs("div",{className:"absolute inset-x-3 bottom-3 z-10 max-h-[45%] overflow-hidden rounded-xl border border-border/70 bg-[var(--surface-elevated)] shadow-lg",children:[e.jsxs("div",{className:"flex items-center justify-between border-b border-border/50 px-3 py-2",children:[e.jsx("div",{className:"typography-ui-label text-foreground",children:"Preview console"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ne,{type:"button",size:"xs",variant:"ghost",onClick:we,disabled:D.length===0,children:"Attach"}),e.jsx(ne,{type:"button",size:"xs",variant:"ghost",onClick:Ne,disabled:D.length===0,children:"Copy"}),e.jsx(ne,{type:"button",size:"xs",variant:"ghost",onClick:()=>I([]),disabled:D.length===0,children:"Clear"})]})]}),e.jsx("div",{className:"flex items-center gap-1 border-b border-border/30 px-3 py-1.5",children:["all","errors","warnings","logs"].map(M=>e.jsx(ne,{type:"button",size:"xs",variant:$===M?"secondary":"ghost",onClick:()=>k(M),children:M==="all"?"All":M==="errors"?"Errors":M==="warnings"?"Warnings":"Logs"},M))}),e.jsx("div",{className:"max-h-64 overflow-auto p-2 typography-code text-xs",children:D.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No preview console events yet."}):je.length===0?e.jsx("div",{className:"px-2 py-3 text-muted-foreground",children:"No events match this filter."}):je.map(M=>e.jsx("div",{className:"border-b border-border/30 px-2 py-1 last:border-b-0",children:e.jsxs("div",{className:"flex gap-2",children:[e.jsx("span",{className:pe("shrink-0 uppercase",M.level==="error"||M.level==="runtime"||M.level==="resource"?"text-status-error":M.level==="warn"?"text-status-warning":"text-muted-foreground"),children:M.level}),e.jsx("span",{className:"min-w-0 break-words text-foreground",children:M.message})]})},M.id))})]}):null]})]})},Zt=t=>t,Wt=t=>{const n=Zt(t).type;return typeof n=="string"?n:""},ri=t=>{const n=Zt(t).tool;return typeof n=="string"?n:""},oi=t=>{const n=Zt(t).text;return typeof n=="string"?n:""},ai=t=>{const n=Wt(t);return n==="tool"?ri(t).trim().toLowerCase()||"tool":n||"unknown"},ii=t=>{if(t.length===0)return"";const n=[];for(const r of t){const a=ai(r);n.includes(a)||n.push(a)}return n.join(" + ")},li=t=>t.replace(/\s+/g," ").trim(),ci=t=>{for(const r of t)if(Wt(r)==="text"){const a=li(oi(r));if(a.length===0)continue;return a}const n=t.filter(r=>Wt(r)!=="text").length;return n===0?"":`${n} attachment${n===1?"":"s"}`},di=(t,n,r)=>`${r(t)} / ${r(n)}`,ui=t=>{if(t==="12h")return!0;if(t==="24h")return!1},hi=(t,n)=>{if(!t||!Number.isFinite(t))return"-";const r=ui(n);return new Date(t).toLocaleString(void 0,{month:"numeric",day:"numeric",hour:r===!1?"2-digit":"numeric",minute:"2-digit",...r===void 0?{}:{hour12:r}})},fi={input:0,output:0,reasoning:0,cacheRead:0,cacheWrite:0,total:0},yt={user:0,assistant:0,tool:0,other:0},pi=t=>typeof t!="number"||!Number.isFinite(t)||t<0?0:t,Tt=t=>It(t),mi=(...t)=>{for(const n of t)if(typeof n=="string"&&n.trim().length>0)return n;return""},Oe=t=>typeof t=="string"?t.length:typeof t=="number"||typeof t=="boolean"?String(t).length:Array.isArray(t)?t.reduce((n,r)=>n+Oe(r),0):t&&typeof t=="object"?Object.values(t).reduce((n,r)=>n+Oe(r),0):0,gi=(t,n)=>{const r=t,a=typeof r.type=="string"?r.type:"";if(a==="reasoning")return{...yt,assistant:Oe(r.text)+Oe(r.content)};const i=mi(r.text,r.content,r.value,r.source?.value,r.source?.text?.value);return a==="tool"||n==="tool"?{user:0,assistant:0,tool:Oe(r.input)+Oe(r.output)+Oe(r.error)+Oe(r.call?.input)+Oe(r.call?.output)+Oe(r.call?.error)+Oe(r.raw)+Math.round(Oe(r.metadata)*.25)+Math.round(Oe(r.state)*.1),other:0}:n==="user"?{user:i.length,assistant:0,tool:0,other:0}:n==="assistant"?{user:0,assistant:i.length,tool:0,other:0}:{user:0,assistant:0,tool:0,other:i.length}},Tn=(t,n)=>({user:t.user+n.user,assistant:t.assistant+n.assistant,tool:t.tool+n.tool,other:t.other+n.other}),xi=t=>{const n=dt(t.info);return n.isUser?"user":n.role==="assistant"?"assistant":n.role==="tool"?"tool":"other"},wi=(t,n)=>{if(t.length===0)return{...yt};const r=t.reduce((a,i)=>{const o=xi(i);let u={...yt};for(const l of i.parts)u=Tn(u,gi(l,o));return Tn(a,u)},{...yt});return r.user+=n.length,{user:Math.ceil(r.user/4),assistant:Math.ceil(r.assistant/4),tool:Math.ceil(r.tool/4),other:Math.ceil(r.other/4)}},qe=t=>t.toLocaleString("en-US"),bi=t=>!Number.isFinite(t)||t<=0?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}).format(0):new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t<.01?4:2,maximumFractionDigits:t<.01?4:2}).format(t),yi=(t,n)=>!t||!Number.isFinite(t)?"-":zr(t,n,{month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}),vi=(t,n,r)=>{const a=t.find(o=>o.id===n),i=a?.models?.find(o=>o.id===r);return{providerName:a?.name||n||"-",modelName:i?.name||r||"-",contextLimit:typeof i?.limit?.context=="number"?i.limit.context:null}},ji=()=>{const t=X(p=>p.timeFormatPreference),[n,r]=s.useState({}),{value:a,show:i,clear:o}=Fr(null,2e3),u=Te(p=>p.currentSessionId),l=Te(p=>p.currentSessionDirectory),c=$r(),f=Jn(u??""),x=Je(p=>p.providers);s.useEffect(()=>{r(p=>Object.keys(p).length>0?{}:p),o()},[o,l,u]);const b=s.useCallback(async(p,$)=>{(await pt($)).ok?i(p):o()},[o,i]),d=s.useMemo(()=>{const p=u?c.find(E=>E.id===u)??null:null,$=f.filter(E=>dt(E.info).role==="assistant"),k=f.filter(E=>dt(E.info).isUser);let D=null;for(let E=$.length-1;E>=0;E-=1){const B=$[E];if(Tt(B).total>0){D=B;break}}const I=D?Tt(D):fi,K=D?.info?.usage,w=Xn({input:I.input,cache:{read:I.cacheRead,write:I.cacheWrite}}),P=$.reduce((E,B)=>{const Z=pi(B.info.cost);return E+Z},0),v=D?.info?.model??null,_=vi(x,v?.providerID||"",v?.modelID||""),y=_.contextLimit,R=K?qn(K):I.total,Q=y&&y>0?Math.min(999,R/y*100):0,q=[...f].reverse().find(E=>dt(E.info).isUser&&typeof E.info.system=="string")?.info?.system||"",z=wi(f,q),ee=z.user,oe=z.assistant,H=z.tool,se=K?0:Math.max(0,I.input-ee-oe-H),C=ee+oe+H+se,W=f[0]?.info?.time?.created,re=f.length>0?f[f.length-1]?.info?.time?.created:null;return{sessionTitle:Qn(p),messagesCount:f.length,userMessagesCount:k.length,assistantMessagesCount:$.length,createdAt:p?.time?.created??W??null,lastActivityAt:re??p?.time?.created??null,providerModel:_,tokenBreakdown:I,usagePercent:Q,cacheHitRate:w,totalAssistantCost:P,contextLimit:y,contextWindowTokens:R,hasUsage:K!==void 0,breakdown:{user:ee,assistant:oe,tool:H,other:se},breakdownTotal:C}},[u,x,f,c]);if(!u)return e.jsx("div",{className:"flex h-full items-center justify-center p-6 text-center typography-ui-label text-muted-foreground",children:"Open a session to inspect context."});const g=[{key:"user",label:"User",value:d.breakdown.user,color:"var(--status-success)"},{key:"assistant",label:"Assistant",value:d.breakdown.assistant,color:"var(--primary-base)"},{key:"tool",label:"Tool calls",value:d.breakdown.tool,color:"var(--status-warning)"},...d.hasUsage?[]:[{key:"other",label:"Other",value:d.breakdown.other,color:"var(--surface-muted-foreground)"}]];return e.jsx("div",{className:"h-full overflow-y-auto bg-background",children:e.jsxs("div",{className:"mx-auto w-full max-w-[52rem] px-5 py-6",children:[e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"typography-ui-header font-semibold text-foreground truncate",children:d.sessionTitle}),e.jsxs("div",{className:"mt-1 flex flex-wrap items-center gap-x-2 gap-y-0.5 typography-micro text-subtle-foreground",children:[e.jsxs("span",{children:[d.providerModel.providerName," / ",d.providerModel.modelName]}),d.createdAt&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"·"}),e.jsx("span",{children:yi(d.createdAt,t)})]})]})]}),e.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsx("span",{className:"typography-micro text-muted-foreground",children:"Context"}),e.jsxs("span",{className:"typography-micro tabular-nums text-subtle-foreground",children:[qe(d.contextWindowTokens),d.contextLimit?` / ${qe(d.contextLimit)}`:""]})]}),e.jsx("div",{className:"mt-2.5 flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:d.usagePercent>0&&e.jsx("div",{className:"rounded-full transition-all duration-300",style:{width:`${Math.max(.5,d.usagePercent)}%`,backgroundColor:d.usagePercent>80?"var(--status-warning)":"var(--primary-base)"}})}),e.jsx("div",{className:"mt-1.5 typography-micro font-medium tabular-nums text-foreground/80",children:`${d.usagePercent.toFixed(1)}% used`})]}),e.jsx("div",{className:"mb-5 grid grid-cols-2 gap-2",children:[{label:"Messages",value:qe(d.messagesCount)},{label:"User",value:qe(d.userMessagesCount)},{label:"Assistant",value:qe(d.assistantMessagesCount)},{label:"Cost",value:bi(d.totalAssistantCost)}].map(p=>e.jsxs("div",{className:"rounded-lg bg-[var(--surface-elevated)]/70 px-3 py-2.5",children:[e.jsx("div",{className:"typography-micro text-subtle-foreground",children:p.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:p.value})]},p.label))}),e.jsxs("div",{className:"mb-5 rounded-lg bg-[var(--surface-elevated)]/70 px-4 py-3.5",children:[e.jsx("div",{className:"typography-micro text-muted-foreground mb-2.5",children:"Last assistant message"}),e.jsx("div",{className:"grid grid-cols-3 gap-x-4 gap-y-2.5",children:[{label:"Input",value:d.tokenBreakdown.input,format:"count"},{label:"Output",value:d.tokenBreakdown.output,format:"count"},{label:"Reasoning",value:d.tokenBreakdown.reasoning,format:"count"},{label:"Cache read",value:d.tokenBreakdown.cacheRead,format:"count"},{label:"Cache write",value:d.tokenBreakdown.cacheWrite,format:"count"},{label:"Cache hit",value:d.cacheHitRate.hasInput?d.cacheHitRate.percent:null,format:"percent"}].map(p=>e.jsxs("div",{children:[e.jsx("div",{className:"typography-micro text-subtle-foreground",children:p.label}),e.jsx("div",{className:"mt-0.5 typography-ui-label tabular-nums text-foreground",children:p.value!==null&&p.value!==void 0?p.format==="percent"?`${p.value.toFixed(1)}%`:qe(p.value):"—"})]},p.label))})]}),e.jsxs("div",{className:"mb-6",children:[e.jsx("div",{className:"flex h-1 w-full overflow-hidden rounded-full bg-[var(--surface-subtle)]",children:g.map(p=>p.value<=0||d.breakdownTotal<=0?null:e.jsx("div",{style:{width:`${p.value/d.breakdownTotal*100}%`,backgroundColor:p.color}},p.key))}),e.jsx("div",{className:"mt-2 flex flex-wrap items-center gap-x-4 gap-y-1",children:g.map(p=>{const $=d.breakdownTotal>0?p.value/d.breakdownTotal*100:0;return e.jsxs("div",{className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:p.color}}),e.jsxs("span",{className:"typography-micro text-subtle-foreground",children:[p.label," ",e.jsxs("span",{className:"tabular-nums",children:[$.toFixed(0),"%"]})]})]},p.key)})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"typography-micro text-muted-foreground",children:"Raw messages"}),e.jsx("div",{className:"mt-2.5 space-y-1",children:[...f].reverse().map(p=>{const k=dt(p.info).role,D=k==="assistant",I=k==="user",K=n[p.info.id]===!0,w=a===p.info.id,P=p.info.time?.created??null,v=ii(p.parts),_=D?Tt({info:p.info,parts:p.parts}):null,y=I?ci(p.parts):"",R=hi(P,t),Q=v||"—",q=_?di(_.input,_.output,qe):"",z=k||"unknown",ee=v?`${z}: ${v}`:z,oe=K?JSON.stringify({info:p.info,parts:p.parts},null,2):"";return e.jsxs("div",{className:"overflow-hidden rounded-lg bg-[var(--surface-elevated)]/70",children:[e.jsx("button",{type:"button",className:"w-full cursor-pointer px-3 py-1.5 text-left hover:bg-[var(--interactive-hover)]","aria-expanded":K,onClick:()=>{r(H=>({...H,[p.info.id]:H[p.info.id]!==!0}))},children:e.jsxs("div",{className:"grid items-center gap-x-2 whitespace-nowrap typography-micro",style:{gridTemplateColumns:D?"minmax(0, 1fr) 7.5rem max-content":"minmax(0, 1fr) max-content"},children:[I?e.jsxs("span",{className:"min-w-0 truncate text-muted-foreground",children:[e.jsx("span",{className:"typography-ui-label text-foreground",children:"user:"})," ",y]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"min-w-0 truncate text-muted-foreground",children:D?Q:ee}),D&&e.jsx("span",{className:"text-right text-muted-foreground tabular-nums",children:q})]}),e.jsx("span",{className:"text-right text-muted-foreground",children:R})]})}),K&&e.jsx("div",{className:"border-t border-[var(--surface-subtle)] p-0",children:e.jsxs("div",{className:"group relative max-h-[26rem] w-full overflow-auto bg-[var(--surface-background)]",children:[e.jsx("div",{className:"absolute top-1 right-2 z-10 opacity-0 transition-opacity group-hover:opacity-100",children:e.jsx("button",{type:"button",className:"rounded p-1 text-muted-foreground transition-colors hover:bg-interactive-hover/60 hover:text-foreground",onClick:H=>{H.stopPropagation(),b(p.info.id,oe)},"aria-label":w?"Copied":"Copy JSON",title:w?"Copied":"Copy",children:w?e.jsx(U,{name:"check",className:"size-3.5"}):e.jsx(U,{name:"file-copy",className:"size-3.5"})})}),e.jsx(Wr,{language:"json",code:oe,style:{margin:0,padding:"0.75rem",background:"transparent",fontSize:"var(--text-micro)",lineHeight:"1.35"},wrap:!0})]})})]},p.info.id)})})]})]})})},Si=ze(()=>Fe(()=>import("./DiffView-BxW6BuOC.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53])).then(t=>({default:t.DiffView}))),ki=ze(()=>Fe(()=>import("./FilesView-DECxN8Z0.js"),__vite__mapDeps([54,1,2,3,4,5,6,7,8,9,10,11,12,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,51,52,33,34,18,19,20,21,22,23,24,25,26,27,28,29,30,31,71,72,46,47,48,49,50,73,74,15,16,17,32,35,36,37,38,39,40,41,75,76,77,78,79,45])).then(t=>({default:t.FilesView}))),Ci=ze(()=>Fe(()=>import("./GitView-DD33ngnM.js"),__vite__mapDeps([80,6,1,2,3,10,4,5,7,8,9,11,12,46,47,48,49,50,13,81,82,83,84,44,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,14,42,43,45,51,52])).then(t=>({default:t.GitView}))),Ni=ze(()=>Fe(()=>import("./PullRequestsSurface-BZvJkT1I.js"),__vite__mapDeps([85,6,1,2,3,86,4,5,7,8,9,10,11,12,46,47,48,49,50,87,81,82,44,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,14,42,43,45,51,52])).then(t=>({default:t.PullRequestsSurface}))),Pi=ze(()=>Fe(()=>import("./IssuesSurface-BAY_eyX5.js"),__vite__mapDeps([88,1,2,3,86,4,5,6,7,8,9,10,11,12,46,47,48,49,50,87,81,82,89])).then(t=>({default:t.IssuesSurface}))),Ri=380,Ei=1400,xs=600,Ti=100,Di=24,Dn=720,An=t=>Number.isFinite(t)?Math.min(Ei,Math.max(Ri,Math.round(t))):xs,Ai=t=>{const n=t?.parentElement?.clientWidth;return!n||n<=0?null:n},_i=(t,n)=>{if(!t)return"";const r=t.replace(/\\/g,"/"),a=n.replace(/\\/g,"/").replace(/\/+$/,"");return a&&r.startsWith(a+"/")?r.slice(a.length+1):r},zt=(t,n=null)=>t==="file"?"Files":t==="diff"?"Changes":t==="preview"?"Preview":t==="browser"?"Browser":t==="git"?Jt(n).label:t==="terminal"?"Terminal":t==="pull-requests"?"Pull requests":t==="issues"?"Issues":t==="extensions"?"Extensions":"Context",ws=t=>{if(!t)return null;const n=t.replace(/\\/g,"/").trim();if(!n)return null;const r=n.split("/").filter(Boolean);return r.length===0?n:r[r.length-1]||null},Mi=(t,n=null)=>{if(t.label)return t.label;if(t.mode==="file")return ws(t.targetPath)||"Files";if(t.mode==="preview"){const r=t.targetPath;if(r)try{const a=new URL(r);return a.host||a.hostname||"Preview"}catch{}return"Preview"}return t.mode==="diff"?"Changes":zt(t.mode,n)},Dt=(t,n=null)=>{if(t.mode==="file")return t.targetPath?e.jsx(Ut,{filePath:t.targetPath,className:"h-3.5 w-3.5"}):void 0;if(t.mode==="diff")return e.jsx(vr,{className:"h-3.5 w-3.5"});if(t.mode==="git")return e.jsx(U,{name:Jt(n).icon,className:"h-3.5 w-3.5"});if(t.mode==="terminal")return e.jsx(U,{name:"terminal-box",className:"h-3.5 w-3.5"});if(t.mode==="context")return e.jsx(U,{name:"pie-chart",className:"h-3.5 w-3.5"});if(t.mode==="preview")return e.jsx(U,{name:"global",className:"h-3.5 w-3.5 text-[var(--status-info)]"});if(t.mode==="browser")return e.jsx(U,{name:"global",className:"h-3.5 w-3.5"});if(t.mode==="pull-requests")return e.jsx(U,{name:"git-pull-request",className:"h-3.5 w-3.5"});if(t.mode==="issues")return e.jsx(U,{name:"task",className:"h-3.5 w-3.5"});if(t.mode==="extensions")return e.jsx(U,{name:"plug-2",className:"h-3.5 w-3.5"})},Ii=(t,n)=>t.length<=n?t:`${t.slice(0,n-3)}...`,Li=()=>{const t=mt()??"",n=s.useMemo(()=>_e(t),[t]),r=X(N=>n?N.contextPanelByDirectory[n]:void 0),a=X(N=>N.closeContextPanel),i=X(N=>N.closeContextPanelTab),o=X(N=>N.openContextPanelTab),u=X(N=>N.toggleContextPanelExpanded),l=X(N=>N.setContextPanelWidth),c=X(N=>N.setActiveContextPanelTab),f=X(N=>N.reorderContextPanelTabs),x=$e(N=>N.setSelectedPath),b=X(N=>N.openContextPreview),d=X(N=>N.contextEditorTreeVisible),g=X(N=>N.toggleContextEditorTree),p=Te(N=>N.currentSessionId),$=s.useMemo(()=>r?.tabs??[],[r?.tabs]),k=$.find(N=>N.id===r?.activeTabId)??$[$.length-1]??null,D=!!(r?.isOpen&&k),I=!!(D&&r?.expanded),[K,w]=s.useState(null),P=r?.width,v=Vr,_=K??(typeof window<"u"?window.innerWidth:xs*2),y=An(P??Math.round(v*_)),R=Zn(n||null),[Q,q]=s.useState(!1),[z,ee]=s.useState(null),[oe,H]=s.useState(null),[se,C]=s.useState(null),[W,re]=s.useState(null),E=s.useRef(0),B=s.useRef(y),Z=s.useRef(null),ue=s.useRef(null),ge=s.useRef(null),he=s.useRef(!1);s.useLayoutEffect(()=>{const N=ge.current?.parentElement;if(!N||typeof ResizeObserver>"u")return;const Ee=new ResizeObserver(()=>{w(N.clientWidth||null)});return Ee.observe(N),w(N.clientWidth||null),()=>Ee.disconnect()},[]),s.useEffect(()=>{if(!D||he.current){he.current=D;return}const N=window.requestAnimationFrame(()=>{ge.current?.focus({preventScroll:!0})});return he.current=!0,()=>window.cancelAnimationFrame(N)},[D]);const xe=s.useRef(null),je=s.useRef(null),Ne=s.useCallback(()=>{je.current=null;const N=ge.current,Ee=Z.current;!N||Ee===null||N.style.setProperty("--oc-context-panel-width",`${Ee}px`)},[]);s.useEffect(()=>()=>{je.current!==null&&clearTimeout(je.current)},[]);const we=s.useCallback(N=>{const Ee=An(N),He=xe.current;return He===null?Ee:Math.min(Ee,Math.max(1,He))},[]),me=s.useCallback(N=>{!D||I||!n||(ue.current=N.pointerId,q(!0),E.current=N.clientX,B.current=y,Z.current=y,xe.current=Ai(ge.current),document.documentElement.style.cursor="col-resize",N.preventDefault())},[n,I,D,y]),ve=s.useCallback(()=>{const N=we(Z.current??y);Z.current=null,xe.current=null,je.current!==null&&(clearTimeout(je.current),je.current=null),document.documentElement.style.cursor="",n&&l(n,N),q(!1),ue.current=null},[we,n,l,y]);s.useEffect(()=>{if(!Q)return;const N=Xe=>{if(ue.current!==Xe.pointerId)return;const js=E.current-Xe.clientX,en=we(B.current+js);Z.current!==en&&(Z.current=en,je.current===null&&(je.current=setTimeout(Ne,Ti)))},Ee=Xe=>{ue.current===Xe.pointerId&&ve()},He=()=>{ve()};return window.addEventListener("pointermove",N),window.addEventListener("pointerup",Ee),window.addEventListener("pointercancel",Ee),window.addEventListener("blur",He),()=>{window.removeEventListener("pointermove",N),window.removeEventListener("pointerup",Ee),window.removeEventListener("pointercancel",Ee),window.removeEventListener("blur",He)}},[Ne,we,ve,Q]),s.useEffect(()=>{Q||(Z.current=null,document.documentElement.style.cursor="")},[Q]);const Ce=s.useCallback(()=>{n&&a(n)},[a,n]),be=s.useCallback(()=>{n&&u(n)},[n,u]),ke=s.useCallback(N=>{N.key==="Escape"&&(Hr(N.target)||(N.preventDefault(),N.stopPropagation(),Ce()))},[Ce]);s.useEffect(()=>{if(!(!n||!k)&&k.mode==="file"&&k.targetPath){x(n,k.targetPath,{allowOutsideRoot:!0});return}},[k,n,x]);const Pe=s.useCallback(N=>{!n||k?.mode!=="diff"||o(n,{mode:"diff",targetPath:k.targetPath,stagedDiff:N==="staged",diffScope:N})},[k,n,o]),Re=k?.mode==="file"||k?.mode==="preview",O=s.useMemo(()=>k?$.filter(N=>N.mode===k.mode):[],[k,$]),V=s.useMemo(()=>O.map(N=>{const Ee=Mi(N,R),He=Ii(Ee,Di),Xe=_i(N.targetPath,t);return{id:N.id,label:He,icon:Dt(N,R),title:Xe?`${Ee}: ${Xe}`:Ee,closeLabel:`Close ${He} tab`}}),[O,t,R]),de=k?.mode==="pull-requests",M=k?.mode==="issues",te=X(N=>N.gitReturnToFile?.directory===n?N.gitReturnToFile.focusPath:null),S=k?.mode==="context"?e.jsx(ji,{}):k?.mode==="extensions"?e.jsx(Ur,{sessionId:p}):k?.mode==="git"?e.jsx(s.Suspense,{fallback:null,children:e.jsx(Ci,{isActive:D,gitHeaderSlot:k?.mode==="git"?oe:null,onlyFilePath:te})}):k?.mode==="pull-requests"?e.jsx(s.Suspense,{fallback:null,children:e.jsx(Ni,{headerActionsSlot:de?W:null,headerActionsPresentation:"desktop"},`pull-requests:${n}`)}):k?.mode==="issues"?e.jsx(s.Suspense,{fallback:null,children:e.jsx(Pi,{headerActionsSlot:M?W:null,headerActionsPresentation:"desktop"},`issues:${n}`)}):k?.mode==="preview"?e.jsx(si,{rawUrl:k.targetPath??"",onNavigate:N=>b(t,N)}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(U,{name:"global",className:"h-12 w-12 text-subtle-foreground"}),e.jsx("div",{className:"typography-ui-header text-foreground",children:"Preview"}),e.jsx("div",{className:"max-w-sm typography-micro text-muted-foreground",children:"Use Project Actions or a terminal Preview button to open a preview."})]}),L=s.useMemo(()=>$.filter(N=>N.mode==="browser"),[$]),F=s.useMemo(()=>$.filter(N=>N.mode==="diff"),[$]),ae=s.useMemo(()=>$.some(N=>N.mode==="terminal"),[$]),ie=s.useMemo(()=>$.some(N=>N.mode==="file"),[$]),m=s.useMemo(()=>$.some(N=>N.mode==="file"&&N.targetPath),[$]),A=k?.mode==="file"?k.targetPath??null:null,Y=I?K:y,ce=!!(m&&Y!==null&&Y<Dn),[De,Me]=s.useState(!1);s.useEffect(()=>{Me(!1)},[A]);const Ae=!m&&Y!==null&&Y<Dn,Ve=Ae?!0:ce?De:d,Ke=X(N=>N.fileTreeReveal);s.useEffect(()=>{Ke&&(ce?Me(!0):X.getState().contextEditorTreeVisible||g())},[Ke,g,ce]);const j=s.useCallback(()=>{if(ce){Me(N=>!N);return}g()},[g,ce]),G=k?.mode==="file",le=X(N=>N.gitReturnToFile),h=X(N=>N.clearGitReturnToFile),T=X(N=>N.showAllGitChanges),J=le&&le.directory===n&&k?.mode==="git"?$.find(N=>N.id===le.tabId&&N.mode==="file"&&N.targetPath)??null:null;s.useEffect(()=>{le&&(!D||k?.mode!=="git"||le.directory!==n)&&h()},[k?.mode,h,n,le,D]);const fe=k?.mode==="terminal",Se=k?.mode==="git",Ie=k?.mode==="diff",ys=e.jsxs("header",{className:"flex h-10 items-stretch border-b border-border",children:[Re?e.jsx(os,{items:V,activeId:k?.id??null,onSelect:N=>{n&&c(n,N)},onClose:N=>{if(n){for(const Ee of $.find(He=>He.id===N)?.browser?.pages??[])Kn(n,Ee.id);i(n,N)}},onReorder:(N,Ee)=>{n&&f(n,N,Ee)},layoutMode:"scrollable",variant:"default"}):fe?e.jsx("div",{ref:N=>{ee(N)},className:"flex min-w-0 flex-1 items-center px-1"}):Se?e.jsx("div",{ref:N=>{H(N)},className:"flex min-w-0 flex-1 items-center overflow-hidden px-1"}):Ie?e.jsx("div",{ref:N=>{C(N)},className:"flex min-w-0 flex-1 items-center overflow-hidden px-1"}):de||M?e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 px-3",children:[k?Dt(k,R):null,e.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:k?zt(k.mode,R):null}),e.jsx("span",{className:"min-w-0 flex-1"}),e.jsx("div",{ref:N=>{re(N)},className:"flex shrink-0 items-center gap-1"})]}):e.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-1.5 px-3",children:[k?Dt(k,R):null,e.jsx("span",{className:"truncate typography-ui-label font-medium text-foreground",children:k?zt(k.mode,R):null})]}),e.jsxs("div",{className:"flex items-center gap-1 px-1.5",children:[G&&!Ae?e.jsx(ne,{type:"button",variant:"ghost",size:"sm",onClick:j,className:pe("h-8 w-8 p-0",Ve&&"bg-interactive-selection text-foreground"),title:Ve?"Hide file tree":"Show file tree","aria-label":"Toggle file tree","aria-pressed":Ve,children:e.jsx(U,{name:"node-tree",className:"size-4"})}):null,e.jsx(ne,{type:"button",variant:"ghost",size:"sm",onClick:be,className:"h-8 w-8 p-0",title:I?"Collapse panel":"Expand panel","aria-label":I?"Collapse panel":"Expand panel",children:I?e.jsx(U,{name:"fullscreen-exit",className:"size-4"}):e.jsx(U,{name:"fullscreen",className:"size-4"})}),e.jsx(ne,{type:"button",variant:"ghost",size:"sm",onClick:Ce,className:"h-8 w-8 p-0",title:"Close panel","aria-label":"Close panel",children:e.jsx(U,{name:"close",className:"size-4"})})]})]}),vs=D?I?{"--oc-context-panel-width":K!==null?`${K}px`:"100%",width:K!==null?`${K}px`:"100%",maxWidth:"100%"}:{width:"min(var(--oc-context-panel-width), 100%)",maxWidth:"100%",overflowX:"clip","--oc-context-panel-width":`${y}px`}:{"--oc-context-panel-width":`${y}px`,width:0,maxWidth:"100%",overflowX:"clip"};return e.jsxs("aside",{ref:ge,"data-context-panel":"true",tabIndex:-1,inert:!D||void 0,className:pe("flex min-h-0 flex-col overflow-hidden bg-background",I?"absolute inset-y-0 right-0 z-20 min-w-0":"relative h-full flex-shrink-0",!D&&"pointer-events-none","will-change-[width] motion-reduce:transition-none","transition-[width] duration-200 ease-[cubic-bezier(0.22,1,0.36,1)]"),onKeyDownCapture:ke,style:vs,children:[D&&!I&&e.jsx("div",{"aria-hidden":"true",className:"absolute left-0 top-0 z-40 h-full w-px bg-border"}),D&&e.jsx("div",{"aria-hidden":"true",className:"absolute right-0 top-0 z-40 h-full w-px bg-border"}),!I&&e.jsx("div",{className:pe("absolute left-0 top-0 z-50 h-full w-[3px] cursor-col-resize transition-colors hover:bg-[var(--interactive-border)]/80",Q&&"bg-[var(--interactive-border)]"),onPointerDown:me,role:"separator","aria-orientation":"vertical","aria-label":"Resize context panel"}),e.jsxs("div",{className:pe("relative z-10 flex h-full min-h-0 shrink-0 flex-col duration-200 ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none","transition-[width,opacity]",!D&&"pointer-events-none select-none opacity-0"),style:{width:I?K!==null?`${K}px`:"100%":"var(--oc-context-panel-width)"},"aria-hidden":!D,children:[ys,e.jsxs("div",{className:pe("relative min-h-0 flex-1 overflow-hidden",Q&&"pointer-events-none"),children:[ie?e.jsxs("div",{className:pe("absolute inset-0 flex",G?"flex":"hidden"),children:[e.jsx("div",{className:"relative h-full min-w-0 flex-1",children:m?e.jsx(s.Suspense,{fallback:null,children:e.jsx(ki,{mode:"editor-only",isVisible:D&&G})}):Ae?null:e.jsx(Qa,{directory:t})}),e.jsx(Ja,{visible:Ve,overlay:ce||Ae,onDismissOverlay:ce?()=>Me(!1):void 0})]}):null,L.map(N=>e.jsx("div",{className:pe("absolute inset-0",k?.id!==N.id&&"hidden"),children:e.jsx(Ba,{directory:n,browser:N.browser,onScreen:D&&k?.id===N.id})},N.id)),D?F.filter(N=>k?.id===N.id).map(N=>e.jsx("div",{className:"absolute inset-0",children:e.jsx(s.Suspense,{fallback:null,children:e.jsx(Si,{hideStackedFileSidebar:!0,stackedDefaultCollapsedAll:!0,pinSelectedFileHeaderToTopOnNavigate:!0,showOpenInEditorAction:!0,diffScope:N.diffScope??(N.stagedDiff?"staged":"working"),onDiffScopeChange:Pe,targetFilePath:N.targetPath,flushContent:!0,toolbarSlot:Ie?se:null})})},N.id)):null,ae?e.jsx("div",{className:pe("absolute inset-0",k?.mode==="terminal"?"block":"hidden"),children:e.jsx(Yn,{visible:D&&k?.mode==="terminal",terminalHeaderSlot:fe?z:null})}):null,D&&k?.mode==="git"?e.jsxs("div",{className:"flex h-full min-h-0 flex-col",children:[J?e.jsxs("div",{className:"flex h-9 shrink-0 items-center border-b border-border/60 pl-1.5 pr-1",children:[e.jsxs(ne,{variant:"ghost",size:"xs",onClick:()=>{h(),c(n,J.id)},className:"min-w-0 text-muted-foreground hover:text-foreground",children:[e.jsx(U,{name:"arrow-left",className:"size-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:`Back to ${ws(J.targetPath)??"file"}`})]}),le?.focusPath?e.jsx(ne,{variant:"ghost",size:"xs",onClick:T,className:"ml-auto shrink-0 text-muted-foreground hover:text-foreground",children:"Show all changes"}):null]}):null,e.jsx("div",{className:"relative min-h-0 flex-1",children:S})]}):D&&!G&&k?.mode!=="browser"&&k?.mode!=="diff"&&k?.mode!=="terminal"?S:null]})]})]})},Oi=150,Bi=500,Fi=[],Ye=t=>t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t),xt=(t,n)=>{if(!t||typeof t!="object")return;const r=t[n];return typeof r=="number"&&Number.isFinite(r)?r:void 0},$i=t=>t>99?"99+":String(t),Wi=t=>t>=90?"text-[var(--status-error)]":t>=75?"text-[var(--status-warning)]":"text-[var(--status-success)]",zi=({surface:t,isActive:n,showActivityDot:r,label:a,description:i,badgeCount:o,badgeAriaLabel:u,badgeDescription:l,orderNumber:c,showOrderNumber:f,onSelect:x,chartPercentage:b,chartDetails:d})=>{const{attributes:g,listeners:p,setNodeRef:$,transform:k,transition:D,isDragging:I}=Bn({id:t.id}),K=o!=null&&o>0?$i(o):null;return e.jsx("div",{ref:$,style:{transform:Fn.Translate.toString(k),transition:D},className:pe("relative",I&&"z-10 opacity-70"),children:e.jsxs(Qe,{delayDuration:Oi,children:[e.jsx(Ze,{asChild:!0,children:e.jsxs("button",{type:"button",...g,...p,onClick:()=>x(t),"aria-label":u??a,"aria-pressed":n,className:pe("flex h-9 w-9 touch-none select-none items-center justify-center rounded-md transition-colors",n?"bg-interactive-selection text-foreground":"text-muted-foreground hover:bg-interactive-hover hover:text-foreground"),children:[t.id==="context"&&typeof b=="number"?e.jsx(fn,{percentage:b,className:"size-[18px] -rotate-90"}):e.jsx(U,{name:t.icon,className:"h-[18px] w-[18px]"}),f&&c!=null?e.jsx("span",{"aria-hidden":"true",className:"absolute right-0 top-0 flex h-4 min-w-4 items-center justify-center rounded-full bg-surface-muted px-1 text-[0.625rem] font-medium leading-none text-muted-foreground",children:c===10?"0":c}):K?e.jsx("span",{"aria-hidden":"true",className:"absolute -right-0.5 -top-0.5 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[0.625rem] font-semibold leading-none",style:{backgroundColor:"var(--status-info-background)",color:"var(--status-info)"},children:K}):r?e.jsx("span",{"aria-hidden":"true",className:"absolute right-1 top-1 h-1.5 w-1.5 rounded-full bg-[var(--status-info)]"}):null]})}),e.jsx(et,{side:"left",sideOffset:8,className:t.id==="context"&&d?"p-0 border-0 bg-transparent shadow-none":void 0,children:t.id==="context"&&d?e.jsx("div",{className:"w-[300px] overflow-hidden rounded-lg border border-border/70 bg-[var(--surface-elevated)] p-2 shadow-[0_8px_24px_rgb(0_0_0_/_0.18)]",children:e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5",children:[e.jsx("span",{className:"flex size-5 shrink-0 items-center justify-center text-muted-foreground",children:e.jsx(fn,{percentage:d.percentage,className:"size-[18px] -rotate-90"})}),e.jsx("span",{className:"shrink-0 typography-ui-label text-muted-foreground",children:a}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-right typography-ui-label font-medium text-foreground",children:d.hasData?e.jsxs("span",{className:"inline-flex items-baseline gap-1.5 tabular-nums",children:[e.jsxs("span",{className:pe("font-semibold",Wi(d.percentage)),children:[d.percentage.toFixed(1),"%"]}),e.jsx("span",{className:"text-muted-foreground",children:`${Ye(d.totalTokens)}/${Ye(d.contextLimit)}`})]}):e.jsx("span",{className:"typography-micro text-muted-foreground",children:"No data yet"})})]}),d.hasData?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Used tokens"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Ye(d.totalTokens)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Context limit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Ye(d.contextLimit)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Output limit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Ye(d.outputLimit)})]}),typeof d.cacheRead=="number"&&typeof d.cacheWrite=="number"?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache read"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Ye(d.cacheRead)})]}),e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache write"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:Ye(d.cacheWrite)})]})]}):null,typeof d.cacheHitPercent=="number"?e.jsxs("div",{className:"flex justify-between rounded-xl px-2.5 py-1.5 typography-micro",children:[e.jsx("span",{className:"text-muted-foreground",children:"Cache hit"}),e.jsx("span",{className:"font-medium text-foreground tabular-nums",children:`${d.cacheHitPercent.toFixed(1)}%`})]}):null]}):e.jsx("div",{className:"px-2.5 py-2 typography-micro text-muted-foreground",children:i})]})}):e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{children:a}),e.jsx("span",{className:"typography-micro text-muted-foreground",children:i}),l?e.jsx("span",{className:"typography-micro text-muted-foreground",children:l}):null]})})]})})},Hi=()=>{const t=mt(),n=t?Ws(t):"",r=X(S=>n?S.contextPanelByDirectory[n]:void 0),a=X(S=>S.contextRailOrder),i=X(S=>S.setContextRailOrder),o=X(S=>S.openContextSurface),u=X(S=>S.shortcutOverrides),{screenWidth:l}=vt(),{git:c,github:f}=jt(),x=Vt(n||null),b=Zn(n||null),d=es(S=>S.ensureStatus),g=hn(S=>S.ensureScope);s.useEffect(()=>{n&&d(n,c)},[n,d,c]),s.useEffect(()=>{!n||!f||g(n,f)},[n,g,f]);const p=s.useMemo(()=>zs("switch_context_surface",u),[u]),[$,k]=s.useState(!1);s.useEffect(()=>{const S=new Set;let L=null,F=!1;const ae=ce=>ce.length===1&&ce>="0"&&ce<="9",ie=()=>{sn(p,S)?!F&&L===null&&(L=setTimeout(()=>k(!0),Bi)):(F=!1,L!==null&&(clearTimeout(L),L=null),k(!1))},m=ce=>{if(S.add(ce.key.toLowerCase()),ae(ce.key)&&sn(p,S)){F=!0,L!==null&&(clearTimeout(L),L=null),k(!1);return}ie()},A=ce=>{S.delete(ce.key.toLowerCase()),ie()},Y=()=>{S.clear(),F=!1,L!==null&&(clearTimeout(L),L=null),k(!1)};return window.addEventListener("keydown",m,!0),window.addEventListener("keyup",A,!0),window.addEventListener("blur",Y),()=>{window.removeEventListener("keydown",m,!0),window.removeEventListener("keyup",A,!0),window.removeEventListener("blur",Y),L!==null&&clearTimeout(L)}},[p]);const D=Mn(_t(Ps,{activationConstraint:{distance:8}}),_t(Ns,{activationConstraint:{delay:200,tolerance:6}})),I=r?.tabs??Fi,K=I.find(S=>S.id===r?.activeTabId)??null,w=r?.isOpen?K?.mode??null:null,P=x?.files.length??0,v=Te(S=>S.currentSessionId),_=Te(S=>!!S.newSessionDraft?.open),y=Je(S=>S.providers),R=Je(S=>S.currentProviderId),Q=Je(S=>S.currentModelId),q=Je(S=>S.getCurrentModel()),z=Je(S=>S.getModelMetadata);Je(S=>S.modelsMetadata.size);const ee=Kr(s.useCallback(S=>v?S.sessionModelSelections.get(v)??null:null,[v])),oe=Jn(v??""),H=s.useMemo(()=>{for(let S=oe.length-1;S>=0;S-=1){const L=oe[S];if(L?.info.role==="assistant")try{if(It(L).total>0)return L}catch{continue}}return null},[oe]),C=s.useMemo(()=>{for(let S=oe.length-1;S>=0;S-=1){const L=oe[S]?.info;if(L.role!=="user")continue;const F=L.model,ae=F?.providerID??F?.providerId,ie=F?.modelID??F?.modelId;if(typeof ae=="string"&&ae.trim()&&typeof ie=="string"&&ie.trim())return{providerID:ae,modelID:ie}}return null},[oe])??(()=>{const S=H?.info.model,L=S?.providerID??S?.providerId,F=S?.modelID??S?.modelId;return L&&F?{providerID:L,modelID:F}:null})()??(ee?{providerID:ee.providerId,modelID:ee.modelId}:null)??(R&&Q?{providerID:R,modelID:Q}:null),re=(C?y.find(S=>S.id===C.providerID):void 0)?.models.find(S=>S.id===C?.modelID),E=C?z(C.providerID,C.modelID):void 0,B=xt(re?.limit,"context")??E?.limit?.context??xt(q?.limit,"context")??0,Z=xt(re?.limit,"output")??E?.limit?.output??xt(q?.limit,"output")??0,ue=H?(()=>{try{return It(H)}catch{return null}})():null,ge=H?.info?.usage,he=ge?qn(ge):ue?.total??0,xe=!_&&he>0&&B>0?Math.min(he/B*100,999):0,Ne=!_&&!!H&&he>0&&B>0?xe:null,we=ue?Xn({input:ue.input,cache:{read:ue.cacheRead,write:ue.cacheWrite}}):null,me=we?.hasInput?we.percent:null,ve=s.useMemo(()=>{const S=!!H&&he>0&&B>0;return{percentage:xe,totalTokens:he,contextLimit:B,outputLimit:Z,cacheRead:ue?.cacheRead??null,cacheWrite:ue?.cacheWrite??null,cacheHitPercent:me,hasData:S}},[ue,me,B,H,Z,xe,he]),Ce=Xr(S=>v?S.reducer.bySession.get(v)?.extensionWidgets:void 0,(S,L)=>S===L,v?`session:${v}`:"chrome"),be=s.useMemo(()=>Ce?.size?[...Ce.entries()].map(([S,L])=>`${S}:${L.lines.join(`
|
|
137
|
-
`)}`).join(";"):"",[Ce]),ke=be!=="",Pe=s.useRef({});s.useEffect(()=>{w==="extensions"&&v&&be&&(Pe.current[v]=be)},[w,v,be]);const Re=v?Pe.current[v]??"":"",O=w!=="extensions"&&be!==""&&Re!==be,V=hn(S=>n?S.entriesByDirectory[n]??null:null),de=s.useMemo(()=>{if(!V)return{isLoading:!0,hasResult:!1,hasGitHubRepo:!1,hasError:!1};const S=V.scope?.repositories??[];return{isLoading:V.isLoading,hasResult:!!(V.scope||V.error),hasGitHubRepo:S.some(L=>!!(L.host&&L.owner&&L.repo&&!L.disabledReason)),hasError:!!(V.error&&!V.scope)}},[V]),M=s.useMemo(()=>qr({railOrder:a,tabs:I,githubScope:de,hasExtensionContent:ke}),[a,l,I,de,ke]),te=s.useCallback(S=>{const{active:L,over:F}=S;if(!F||L.id===F.id)return;const ae=Yr(X.getState().contextRailOrder).map(A=>A.id),ie=ae.indexOf(L.id),m=ae.indexOf(F.id);ie===-1||m===-1||i(Rs(ae,ie,m))},[i]);return n?e.jsx("nav",{"aria-label":"Panel surfaces",className:"flex h-full w-11 flex-shrink-0 flex-col items-center gap-1 bg-background py-2",children:e.jsx(In,{sensors:D,collisionDetection:Ln,onDragEnd:te,children:e.jsx(On,{items:M.map(S=>S.id),strategy:Es,children:M.map((S,L)=>{const F=S.id==="git"?Jt(b):null,ae=F?{...S,...F}:S,ie=ae.label,m=S.id==="git"&&b===!0?P:0,A=m>0?m:null,Y=S.id==="context",ce=S.id==="extensions"?O:!1;return e.jsx(zi,{surface:ae,isActive:w===S.mode,showActivityDot:ce,label:ie,description:ae.description,badgeCount:A,badgeAriaLabel:A!==null?A===1?`${ie}, ${A} changed file`:`${ie}, ${A} changed files`:null,badgeDescription:A!==null?A===1?`${A} changed file`:`${A} changed files`:null,chartPercentage:Y?Ne:void 0,chartDetails:Y?ve:void 0,orderNumber:L+1,showOrderNumber:$,onSelect:De=>o(n,De.mode)},S.id)})})})}):null},Ui=(t,n)=>!t||n.length===0?"":JSON.stringify([t,n]),Vi=(t,n,r,a)=>!r||a!==r||t.length===0?[]:ct(t,n,i=>i.name,{limit:10,threshold:.4}),Ki=new Set,Xi=[{keys:["↑","↓"],label:"Navigate"},{keys:["↵"],label:"Open"},{keys:["Esc"],label:"Close"}],At=t=>{if(!t)return"";const n=t.replace(/\\/g,"/"),r=n.startsWith("//");let a=n.replace(/\/+/g,"/");r&&!a.startsWith("//")&&(a=`/${a}`);const i=a==="/",o=/^[A-Za-z]:\/$/.test(a);return!i&&!o&&(a=a.replace(/\/+$/,"")),a},qi=()=>{const t=X(m=>m.isCommandPaletteOpen),n=X(m=>m.setCommandPaletteOpen),r=X(m=>m.setActiveMainTab),a=X(m=>m.setSettingsDialogOpen),i=X(m=>m.setSettingsPage),o=X(m=>m.setSessionSwitcherOpen),u=X(m=>m.toggleSidebar),l=X(m=>m.openContextOverview),c=X(m=>m.openContextSurface),f=X(m=>m.openContextFile),x=X(m=>m.shortcutOverrides),b=Te(m=>m.openNewSessionDraft),d=Te(m=>m.setCurrentSession),g=Gr({archived:!1}),p=Jr(s.useCallback(m=>t?m.ids:Ki,[t])),$=Qr(s.useCallback(m=>t?m.rankById:Zr,[t])),k=rn(m=>m.currentDirectory),D=rn(m=>m.homeDirectory),I=pn(m=>m.getActiveProject()),K=pn(m=>m.projects),w=mt(),P=Hs(m=>m.searchFiles),{files:v,git:_}=jt(),y=es(m=>m.ensureStatus),{isMobile:R}=vt(),Q=s.useMemo(()=>w?At(w):null,[w]),[q,z]=s.useState(""),oe=eo(q,200).trim(),H=q.trim();s.useEffect(()=>{t&&z("")},[t]),s.useEffect(()=>{if(!t||!_)return;const m=setTimeout(()=>{const A=new Set;for(const Y of g){const ce=Nt(Y);!ce||A.has(ce)||(A.add(ce),y(ce,_))}},0);return()=>clearTimeout(m)},[t,g,_,y]);const se=s.useCallback(()=>n(!1),[n]),C=s.useCallback(m=>()=>{se(),m()},[se]),W=s.useMemo(()=>{const m=[{id:"new-session",title:"New session",icon:e.jsx(U,{name:"chat-new",className:"mr-2 h-4 w-4"}),shortcutId:"new_chat",searchText:"New session",onSelect:C(()=>{r("chat"),o(!1),b()})},{id:"add-project",title:"Add folder",icon:e.jsx(U,{name:"folder-add",className:"mr-2 h-4 w-4"}),searchText:"Add folder",onSelect:C(()=>{to.requestDirectoryDialog()})},{id:"toggle-sidebar",title:R?"Show session switcher":"Toggle sidebar",icon:e.jsx(U,{name:"layout-left",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_sidebar",searchText:R?"Show session switcher":"Toggle sidebar",onSelect:C(()=>{if(R){const{isSessionSwitcherOpen:A}=X.getState();o(!A)}else u()})},{id:"toggle-terminal",title:"Toggle terminal",icon:e.jsx(U,{name:"terminal-box",className:"mr-2 h-4 w-4"}),shortcutId:"toggle_terminal",searchText:"Toggle terminal",onSelect:C(()=>{k&&c(k,"terminal")})},{id:"context-usage",title:"Show context usage",icon:e.jsx(U,{name:"pie-chart",className:"mr-2 h-4 w-4"}),searchText:"Show context usage",onSelect:C(()=>{k&&l(k)})},{id:"open-settings",title:"Open settings…",icon:e.jsx(U,{name:"settings-3",className:"mr-2 h-4 w-4"}),shortcutId:"open_settings",searchText:"Open settings…",onSelect:C(()=>a(!0))}];return Us()&&m.splice(1,0,{id:"new-mini-chat",title:"New Mini Chat window",icon:e.jsx(U,{name:"window",className:"mr-2 h-4 w-4"}),shortcutId:"new_mini_chat",searchText:"New Mini Chat window",onSelect:C(()=>{$n("desktop_open_draft_mini_chat_window",{directory:At(k||I?.path||""),projectId:I?.id??null}).catch(A=>{console.warn("[command-palette] failed to open draft mini chat window",A)})})}),m},[C,R,r,o,b,u,c,k,l,a,I?.id,I?.path]),re=s.useMemo(()=>{const m=Wn();return{isWeb:!m&&Vs(),isDesktop:m,isMobile:R}},[R]),E=s.useMemo(()=>jr.filter(m=>m.slug!=="home").filter(m=>m.isAvailable?m.isAvailable(re):!0).map(m=>{const A=Sr(m.slug)??"settings-3",Y=(m.keywords??[]).join(" ");return{id:`settings:${m.slug}`,title:m.title,icon:e.jsx(U,{name:A,className:"mr-2 h-4 w-4"}),searchText:`${m.title} ${m.group} ${Y}`,onSelect:C(()=>{i(m.slug),a(!0)})}}),[re,C,i,a]),B=s.useMemo(()=>no(g,p,$),[g,p,$]),Z=so(),ue=s.useCallback(m=>{if(!m)return null;let A=null;for(const Y of K){const ce=Y.path.replace(/\/+$/,"");(m===ce||m.startsWith(`${ce}/`))&&(!A||ce.length>A.path.length)&&(A=Y)}return A},[K]),ge=s.useCallback((m,A)=>{if(!m)return null;const Y=Z.get(m)?.trim()||null;if(!Y||Y==="HEAD"||!A)return Y;const ce=A.path.replace(/\/+$/,"");return m===ce||Y===Z.get(ce)?.trim()?null:Y},[Z]),[he,xe]=s.useState([]),[je,Ne]=s.useState(""),we=Ui(Q,oe);s.useEffect(()=>{if(!t){xe([]),Ne("");return}if(!we){xe([]),Ne("");return}if(!Q){xe([]),Ne("");return}let m=!1;return P(Q,oe,10,{type:"file"}).then(A=>{m||(xe(A.map(Y=>({path:At(Y.path),name:Y.name,relativePath:Y.relativePath}))),Ne(we))}).catch(()=>{m||(xe([]),Ne(we))}),()=>{m=!0}},[t,Q,oe,we,P]);const me=H.length>0,ve=s.useMemo(()=>me?ct(W,H,m=>m.searchText,{limit:7,noFuzzy:!0}):W.map(m=>({item:m,score:0})),[W,H,me]),Ce=s.useMemo(()=>me?ct(E,H,m=>m.searchText,{limit:7,noFuzzy:!0}):[],[E,H,me]),be=s.useMemo(()=>me?ct(B,H,m=>m.title||"",{limit:7,threshold:.2}):B.slice(0,5).map(m=>({item:m,score:0})),[B,H,me]),ke=s.useMemo(()=>t?Vi(he,oe,we,je):[],[t,he,je,we,oe]),Pe=t&&we.length>0&&je!==we,Re=s.useMemo(()=>{if(!me)return[];const m=K.map(A=>({...A,displayName:A.label||A.path.split("/").pop()||A.path,searchText:`${A.label||""} ${A.path}`}));return ct(m,H,A=>A.searchText,{limit:7,threshold:.4})},[K,H,me]),O=ve.map(m=>m.item),V=Ce.map(m=>m.item),de=be.map(m=>m.item),M=me?ke.map(m=>m.item):[],te=me?Re.map(m=>m.item):[],S=s.useMemo(()=>{if(!me)return["commands","sessions"];const m=Y=>Y.length?Y[0].score:1/0,A=[{key:"commands",score:m(ve)},{key:"settings",score:m(Ce)},{key:"sessions",score:m(be)},{key:"files",score:m(ke)},{key:"projects",score:m(Re)}];return A.sort((Y,ce)=>Y.score-ce.score),A.map(Y=>Y.key)},[me,ve,Ce,be,ke,Re]),L=s.useCallback(m=>{se(),d(m.id,Nt(m))},[se,d]),F=s.useCallback(async m=>{if(!Q)return;const A=await ss(v,m,{directory:Q});if(!A.ok){ye.error(rs(A.reason));return}f(Q,m),se()},[Q,v,f,se]),ae=s.useCallback((m,A)=>{se(),b({selectedProjectId:m,directoryOverride:A})},[se,b]),ie=s.useCallback(m=>Hn(Un(m,x)),[x]);return e.jsxs(Kt,{open:t,onOpenChange:n,children:[e.jsxs(qt,{className:"sr-only",children:[e.jsx(Yt,{children:"Command palette"}),e.jsx(Gt,{children:"Search files, sessions, and commands."})]}),e.jsxs(Xt,{showCloseButton:!1,className:pe("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:[e.jsxs(ro,{shouldFilter:!1,className:pe("rounded-none","[&_[data-slot=command-input-wrapper]]:h-12 [&_[data-slot=command-input-wrapper]]:border-border/60 [&_[data-slot=command-input-wrapper]]:px-3.5","[&_[cmdk-input]]:h-12 [&_[cmdk-input]]:text-[length:var(--text-markdown)] md:[&_[cmdk-input]]:text-[length:var(--text-ui-label)]","[&_[cmdk-list]]:p-1.5 [&_[cmdk-group]]:p-0 [&_[cmdk-group]+[cmdk-group]]:mt-1","[&_[cmdk-group-heading]]:px-2.5 [&_[cmdk-group-heading]]:pb-1 [&_[cmdk-group-heading]]:pt-1.5 [&_[cmdk-group-heading]]:text-[length:var(--text-micro)]","[&_[cmdk-item]]:gap-2.5 [&_[cmdk-item]]:px-2.5 [&_[cmdk-item]]:py-1.5 [&_[cmdk-item]]:text-[length:var(--text-ui-label)]"),children:[e.jsx(oo,{value:q,onValueChange:z,placeholder:"Search files, sessions, commands..."}),e.jsxs(ao,{children:[e.jsx(io,{children:"No results found."}),S.map(m=>m==="commands"&&O.length>0?e.jsx(it,{heading:"Commands",children:O.map(A=>e.jsxs(lt,{value:A.id,onSelect:A.onSelect,children:[A.icon,e.jsx("span",{children:A.title}),A.shortcutId?e.jsx(lo,{children:ie(A.shortcutId)}):null]},A.id))},"commands"):m==="settings"&&V.length>0?e.jsx(it,{heading:"Settings",children:V.map(A=>e.jsxs(lt,{value:A.id,onSelect:A.onSelect,children:[A.icon,e.jsx("span",{children:A.title})]},A.id))},"settings"):m==="sessions"&&de.length>0?e.jsx(it,{heading:"Sessions",children:de.map(A=>{const Y=Qn(A),ce=Nt(A),De=ue(ce),Me=ge(ce,De),Ae=De?co(De):uo(ce,D)?"No folder":null;return e.jsxs(lt,{value:`session:${A.id}`,onSelect:()=>L(A),children:[e.jsx(U,{name:"chat-ai-3",className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"min-w-0 flex-1 truncate",children:Y}),Ae||Me?e.jsxs("span",{className:"ml-auto inline-flex min-w-0 max-w-[45%] shrink items-center gap-1.5 text-muted-foreground typography-meta",children:[Ae?e.jsx("span",{className:"min-w-0 max-w-[140px] shrink-0 truncate",children:Ae}):null,Me?e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1",children:[e.jsx(U,{name:"git-branch",className:"h-3 w-3 shrink-0"}),e.jsx(ho,{value:Me,className:"min-w-0 max-w-[120px]"})]}):null]}):null]},A.id)})},"sessions"):m==="files"&&M.length>0?e.jsx(it,{heading:"Files",children:M.map(A=>{const Y=Ks(A.relativePath||A.name,{maxLength:80});return e.jsxs(lt,{value:`file:${A.path}`,onSelect:()=>{F(A.path)},children:[e.jsx(Ut,{filePath:A.path,className:"mr-2 size-4 shrink-0"}),e.jsx("span",{className:"truncate","aria-label":A.relativePath,children:Y})]},`file:${A.path}`)})},"files"):m==="projects"&&te.length>0?e.jsx(it,{heading:"Projects",children:te.map(A=>{const Y=A.displayName;return e.jsxs(lt,{value:`project:${A.id}`,onSelect:()=>ae(A.id,A.path),children:[e.jsx(fo,{directory:A.path,label:Y,className:"mr-2 size-4"}),e.jsx("span",{className:"truncate",children:Y}),e.jsx("span",{className:"ml-auto inline-flex items-center text-muted-foreground typography-meta truncate max-w-[160px]",children:A.path})]},`project:${A.id}`)})},"projects"):null),Pe?e.jsx("div",{className:"px-3 py-2 typography-meta text-muted-foreground",children:"Searching files..."}):null]})]}),R?null:e.jsx("div",{className:"flex min-h-10 shrink-0 items-center border-t border-border/60 bg-[var(--surface-muted)]/40 px-3 py-2 typography-micro text-muted-foreground",children:e.jsx(kr,{hints:Xi.map(m=>m.label==="Close"?{...m,onSelect:()=>n(!1)}:m)})})]})]})},Yi=(t,n,r)=>qs(t)?Hn(Un(t,r)):n,Gi=()=>{const t=X(o=>o.isHelpDialogOpen),n=X(o=>o.setHelpDialogOpen),r=X(o=>o.shortcutOverrides),a=Xs(),i=[{categoryKey:"Navigation & commands",items:[{id:"open_command_palette",descriptionKey:"Open command palette",icon:"command",keys:""},{id:"open_help",descriptionKey:"Show Keyboard Shortcuts (this dialog)",icon:"question",keys:""},{id:"toggle_sidebar",descriptionKey:"Toggle session sidebar",icon:"layout-left",keys:""},{id:"add_selection_to_chat",descriptionKey:"Add selection to chat",icon:"add",keys:""},{id:"open_model_selector",descriptionKey:"Open model selector",icon:"ai-generate-2",keys:""},{keys:["↑↓"],descriptionKey:"Navigate Models (in picker)",icon:"ai-generate-2"},{keys:["←→"],descriptionKey:"Adjust Thinking Mode (in picker, when supported)",icon:"brain-ai-3"},{id:"cycle_thinking_variant",descriptionKey:"Cycle thinking (global shortcut)",icon:"brain-ai-3",keys:""},{keys:[`Shift + Alt + ${a} + N`],descriptionKey:"New Window (desktop only)",icon:"window"}]},{categoryKey:"Session management",items:[{id:"new_chat",descriptionKey:"Create new session",icon:"add",keys:""},{id:"focus_input",descriptionKey:"Focus chat input",icon:"text",keys:""},{id:"cycle_session_folder",descriptionKey:"Cycle session folder",icon:"folder-open",keys:""},{id:"cycle_draft_folder",descriptionKey:"Cycle draft folder",icon:"folder-3",keys:""},{id:"open_timeline_dialog",descriptionKey:"Open conversation timeline",icon:"history",keys:""},{id:"abort_run",descriptionKey:"Abort active run (double press)",icon:"close-circle",keys:""}]},{categoryKey:"Panels",items:[{id:"open_right_sidebar",descriptionKey:"Open right sidebar",icon:"layout-right",keys:""},{id:"toggle_terminal",descriptionKey:"helpDialog.item.toggleTerminalDock",icon:"window",keys:""},{keys:[`${a} + 1...0`],descriptionKey:"Switch Context Panel Surface (number key)",icon:"layout-right"}]},{categoryKey:"Interface",items:[{id:"cycle_theme",descriptionKey:"Cycle Theme (Light → Dark → System)",icon:"palette",keys:""},{id:"toggle_services_menu",descriptionKey:"helpDialog.item.toggleServicesMenu",icon:"stack",keys:""},{id:"open_settings",descriptionKey:"Open settings",icon:"settings-3",keys:""}]}];return e.jsx(Kt,{open:t,onOpenChange:n,children:e.jsxs(Xt,{className:"w-[92vw] max-w-[1120px] h-[84vh] max-h-[900px] flex flex-col overflow-hidden",children:[e.jsxs(qt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(U,{name:"command",className:"h-5 w-5"}),"Keyboard shortcuts"]}),e.jsx(Gt,{children:"Use these keyboard shortcuts to navigate PiChamber efficiently"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto mt-3 pr-1",children:e.jsx("div",{className:"grid grid-cols-1 gap-6 md:grid-cols-2 md:gap-x-10",children:i.map(o=>e.jsxs("div",{className:"min-w-0 break-inside-avoid",children:[e.jsx("h3",{className:"typography-meta font-semibold text-muted-foreground uppercase tracking-wider mb-2",children:o.categoryKey}),e.jsx("div",{className:"space-y-1",children:o.items.map(u=>{const l=u.id?Yi(u.id,Array.isArray(u.keys)?u.keys[0]:u.keys,r):Array.isArray(u.keys)?u.keys:u.keys.split(" / ");return e.jsxs("div",{className:"flex items-center justify-between py-1 px-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[u.icon&&e.jsx(U,{name:u.icon,className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"typography-meta",children:u.descriptionKey})]}),e.jsx("div",{className:"flex items-center gap-1",children:(Array.isArray(l)?l:[l]).map((c,f)=>e.jsxs(s.Fragment,{children:[f>0&&e.jsx("span",{className:"typography-meta text-muted-foreground mx-1",children:"or"}),e.jsx("kbd",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 typography-meta font-mono bg-muted rounded border border-border/20",children:c})]},`${c}-${f}`))})]},u.id||u.descriptionKey)})})]},o.categoryKey))})})]})})},Ji=s.createContext(null),Qi=({children:t,value:n})=>e.jsx(Ji.Provider,{value:n,children:t}),_n=ze(()=>Fe(()=>import("./GitView-DD33ngnM.js"),__vite__mapDeps([80,6,1,2,3,10,4,5,7,8,9,11,12,46,47,48,49,50,13,81,82,83,84,44,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,14,42,43,45,51,52])).then(t=>({default:t.GitView}))),Zi=ze(()=>Fe(()=>import("./DiffView-BxW6BuOC.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53])).then(t=>({default:t.DiffView}))),el=ze(()=>Fe(()=>import("./FilesView-DECxN8Z0.js"),__vite__mapDeps([54,1,2,3,4,5,6,7,8,9,10,11,12,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,51,52,33,34,18,19,20,21,22,23,24,25,26,27,28,29,30,31,71,72,46,47,48,49,50,73,74,15,16,17,32,35,36,37,38,39,40,41,75,76,77,78,79,45])).then(t=>({default:t.FilesView}))),tl=ze(()=>Fe(()=>import("./DiagramView-BB-aZobi.js"),__vite__mapDeps([90,1,2,3,10,4,5,6,7,8,9,11,12,71,72])).then(t=>({default:t.DiagramView}))),nl=ze(()=>Fe(()=>import("./SettingsView-DcF-At5E.js").then(t=>t.h),__vite__mapDeps([91,1,2,3,4,5,6,7,8,9,10,11,12,46,47,48,49,50,92,93,94,83,84])).then(t=>({default:t.SettingsView}))),sl=ze(()=>Fe(()=>import("./SettingsWindow-gxjULdm1.js"),__vite__mapDeps([95,1,2,3,4,5,6,7,8,9,10,11,12,91,46,47,48,49,50,92,93,94,83,84])).then(t=>({default:t.SettingsWindow}))),rl=()=>{const t=X(C=>C.isSidebarOpen),n=X(C=>C.activeMainTab),r=X(C=>C.setIsMobile),a=X(C=>C.isSessionSwitcherOpen),i=X(C=>C.isSettingsDialogOpen),o=X(C=>C.setSettingsDialogOpen),[u,l]=s.useState(!1);s.useEffect(()=>{i&&l(!0)},[i]),s.useEffect(()=>{const C=()=>X.getState().closeMainSurfaces(),W=Te.subscribe((E,B)=>{const Z=!!E.currentSessionId&&E.currentSessionId!==B.currentSessionId,ue=!!E.newSessionDraft?.open&&E.newSessionDraft!==B.newSessionDraft;(Z||ue)&&C()}),re=X.subscribe((E,B)=>{E.activeMainTab!==B.activeMainTab&&C()});return()=>{W(),re()}},[]);const{isMobile:c}=vt(),f=s.useRef(!1),[x,b]=s.useState(!1),[d,g]=s.useState(!1),[p,$]=s.useState(!1),[k,D]=s.useState(!1),I=s.useCallback(C=>{b(C),X.getState().setSessionSwitcherOpen(C)},[]),K=s.useRef(typeof window>"u"?0:window.innerWidth),w=s.useRef(null),P=s.useRef(!1),v=s.useRef(!1),_=s.useRef(!1),y=s.useRef(null),R=s.useRef(null),Q=tn(-K.current),q=Le.useRef(0),z=tn(K.current),ee=Le.useRef(0);Le.useEffect(()=>{c&&(q.current=window.innerWidth,ee.current=window.innerWidth)},[c]),Le.useEffect(()=>{if(!c)return;const C=()=>{const W=window.innerWidth;q.current=W,ee.current=W,x||Q.get()<-10&&Q.set(-W),d||z.get()>10&&z.set(W)};return window.addEventListener("resize",C),window.addEventListener("orientationchange",C),()=>{window.removeEventListener("resize",C),window.removeEventListener("orientationchange",C)}},[c,Q,z,x,d]),Le.useEffect(()=>{if(!c){$(!1);return}x&&$(!0);const C=q.current||K.current||(typeof window<"u"?window.innerWidth:0),W=gt(Q,x?0:-C,{type:"spring",stiffness:400,damping:35,mass:.8});return y.current=W,()=>W.stop()},[x,c,Q]),Le.useEffect(()=>{if(!c){D(!1);return}d&&D(!0);const C=ee.current||K.current||(typeof window<"u"?window.innerWidth:0),W=gt(z,d?0:C,{type:"spring",stiffness:400,damping:35,mass:.8});return R.current=W,()=>W.stop()},[c,d,z]),Le.useEffect(()=>{if(c)return Q.on("change",C=>{const W=q.current||K.current,re=x||C>-W+.5;$(E=>E===re?E:re)})},[c,Q,x]),Le.useEffect(()=>{if(c)return z.on("change",C=>{const W=ee.current||K.current,re=d||C<W-.5;D(E=>E===re?E:re)})},[c,d,z]),Le.useEffect(()=>{c&&!a&&x&&I(!1)},[a,c,x,I]),Le.useEffect(()=>{if(!c){f.current=!1;return}f.current||(f.current=!0,I(!1),g(!1))},[c,I]),Le.useEffect(()=>{if(!c||n!=="chat"||x||d||i)return;let C=!1,W;return(E=>{W=window.setTimeout(()=>{if(C)return;const B=Te.getState(),Z=X.getState();Z.activeMainTab!=="chat"||Z.isSettingsDialogOpen||B.currentSessionId||B.newSessionDraft?.open||B.openNewSessionDraft({automatic:!0})},E)})(500),()=>{C=!0,W!==void 0&&window.clearTimeout(W)}},[n,c,i,x,d]),Le.useEffect(()=>{!c||!i||(I(!1),g(!1))},[c,i,I]),s.useEffect(()=>{X.getState().isMobile!==c&&r(c)},[c,r]);const oe=s.useCallback(()=>{x&&I(!1),g(!d)},[x,d,I]);Cr(w,{enabled:c,leftOpen:x,rightOpen:d,leftWidth:()=>q.current||K.current||(typeof window<"u"?window.innerWidth:0),rightWidth:()=>ee.current||K.current||(typeof window<"u"?window.innerWidth:0),onLeftProgress:C=>{const W=q.current||K.current||(typeof window<"u"?window.innerWidth:0);Q.set(W*(C-1))},onRightProgress:C=>{const W=ee.current||K.current||(typeof window<"u"?window.innerWidth:0);z.set(W*(1-C))},onLeftOpen:()=>{d&&g(!1),I(!0)},onLeftClose:()=>I(!1),onRightOpen:()=>{x&&I(!1),g(!0)},onRightClose:()=>g(!1),onDragStart:C=>{P.current=!0,C==="left"?(v.current=x,y.current?.stop(),p||$(!0)):(_.current=d,R.current?.stop(),k||D(!0))},onDragEnd:(C,W)=>{if(P.current=!1,C==="left"&&typeof W=="boolean"){const re=v.current;if(W===re){const E=q.current||K.current||(typeof window<"u"?window.innerWidth:0),B=gt(Q,re?0:-E,{type:"spring",stiffness:400,damping:35,mass:.8});y.current=B}}if(C==="right"&&typeof W=="boolean"){const re=_.current;if(W===re){const E=ee.current||K.current||(typeof window<"u"?window.innerWidth:0),B=gt(z,re?0:E,{type:"spring",stiffness:400,damping:35,mass:.8});R.current=B}}}});const H=s.useMemo(()=>{if(!c&&n!=="terminal"&&n!=="diagram"||c&&n==="git"&&(d||k))return null;switch(n){case"git":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(_n,{isActive:!0})});case"diff":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(Zi,{})});case"terminal":return e.jsx(Yn,{onCloseView:()=>X.getState().setActiveMainTab("chat")});case"files":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(el,{})});case"diagram":return e.jsx(s.Suspense,{fallback:null,children:e.jsx(tl,{})});default:return null}},[n,c,k,d]),se=n==="chat";return e.jsxs(Nr,{children:[e.jsx(Pr,{}),e.jsxs("div",{"data-page-scroll-lock":"true",className:pe("main-content-safe-area",c?"flex h-[100dvh] flex-col":"relative flex h-[100dvh]","bg-background"),children:[e.jsx(qi,{}),e.jsx(Gi,{}),e.jsx(Rr,{}),c?e.jsxs(Qi,{value:{leftDrawerOpen:x,rightDrawerOpen:d,toggleLeftDrawer:()=>{const C=!x;d&&g(!1),I(C)},toggleRightDrawer:oe,leftDrawerX:Q,rightDrawerX:z,leftDrawerWidth:q,rightDrawerWidth:ee,setMobileLeftDrawerOpen:I,setRightSidebarOpen:g},children:[!i&&e.jsx(an,{onToggleLeftDrawer:()=>{const C=!x;d&&g(!1),I(C)},onToggleRightDrawer:()=>{oe()},leftDrawerOpen:x,rightDrawerOpen:d}),e.jsx("div",{"data-page-scroll-lock":"true",className:pe("flex flex-1 overflow-hidden relative",i&&"hidden"),children:e.jsxs("main",{ref:w,className:"w-full h-full overflow-hidden bg-background relative","data-page-scroll-lock":"true",style:{touchAction:"pan-x pan-y"},children:[e.jsx("div",{className:pe("absolute inset-0",!se&&"invisible"),children:e.jsx(Be,{children:e.jsx(ln,{active:se&&!i})})}),H&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Be,{children:H})}),e.jsx(Be,{children:e.jsx(cn,{})}),e.jsx(nn.div,{className:pe("absolute inset-0 z-20 bg-sidebar",!p&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:Q},"aria-hidden":!x,children:e.jsx(Be,{children:e.jsx(dn,{mobileVariant:!0,isVisible:p})})}),e.jsx(nn.div,{className:pe("absolute inset-0 z-20 bg-sidebar",!k&&"pointer-events-none invisible"),"data-page-scroll-lock":"true",style:{x:z},"aria-hidden":!d,children:e.jsx(Be,{children:d||k?e.jsx(s.Suspense,{fallback:null,children:e.jsx(_n,{isActive:d})}):null})})]})}),i&&e.jsx("div",{className:"absolute inset-0 z-10 bg-background",style:{paddingTop:"var(--oc-safe-area-top, 0px)"},children:e.jsx(Be,{children:e.jsx(s.Suspense,{fallback:null,children:e.jsx(nl,{onClose:()=>o(!1)})})})})]}):e.jsxs(e.Fragment,{children:[e.jsx(Er,{}),e.jsxs("div",{className:"flex flex-1 overflow-hidden","data-page-scroll-lock":"true",children:[e.jsx(Ho,{isOpen:t,isMobile:c,children:e.jsx(dn,{isVisible:t})}),e.jsxs("div",{className:"relative flex flex-1 min-w-0 flex-col overflow-hidden bg-background","data-page-scroll-lock":"true",children:[e.jsx(an,{}),e.jsxs("div",{className:"relative flex flex-1 min-h-0 overflow-hidden bg-background","data-page-scroll-lock":"true",children:[e.jsx("div",{className:"relative flex flex-1 min-w-0 flex-col overflow-hidden border-t border-border bg-background","data-page-scroll-lock":"true",children:e.jsx("div",{className:"flex flex-1 min-h-0 overflow-hidden","data-page-scroll-lock":"true",children:e.jsxs("div",{className:"relative flex flex-1 min-h-0 min-w-0 overflow-hidden","data-page-scroll-lock":"true","data-chat-area":"true",children:[e.jsxs("main",{className:"flex-1 overflow-hidden bg-background relative","data-page-scroll-lock":"true",children:[e.jsx("div",{className:pe("absolute inset-0",!se&&"invisible"),children:e.jsx(Be,{children:e.jsx(ln,{active:se&&!i})})}),H&&e.jsx("div",{className:"absolute inset-0",children:e.jsx(Be,{children:H})}),e.jsx(Be,{children:e.jsx(cn,{})})]}),e.jsx(Li,{})]})})}),e.jsx("div",{className:"border-t border-border","data-page-scroll-lock":"true",children:e.jsx(Be,{children:e.jsx(Hi,{})})})]})]})]}),u?e.jsx(s.Suspense,{fallback:null,children:e.jsx(sl,{open:i,onOpenChange:o})}):null]})]})]})},ol=()=>(yo(),Dr(),e.jsxs(Ar,{children:[e.jsx(vo,{embeddedBackgroundWorkEnabled:!0}),e.jsx(jo,{}),e.jsx(So,{}),e.jsx(_r,{}),e.jsx(ko,{}),e.jsx(Co,{}),e.jsx(rl,{}),e.jsx(Mr,{}),e.jsx(No,{}),e.jsx(Po,{})]}));function al({apis:t}){const n=t??Vn(),[r,a]=s.useState(0);return s.useEffect(()=>Ys(i=>{if(i.runtimeKey===i.previousRuntimeKey){Gs();return}Tr(i),a(o=>o+1)}),[]),s.useEffect(()=>{let i=!0,o=null,u=null,l=null;return Js().then(()=>{i&&(o=po(),u=mo(),l=go())}),()=>{i=!1,o?.(),u?.(),l?.()}},[r]),s.useEffect(()=>{n&&Qs(n)},[n]),n?e.jsx(Be,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground",children:e.jsx(xo,{apis:n,children:e.jsx(wo,{children:e.jsx(bo,{children:e.jsx(ol,{})})},r)})})}):e.jsx(Be,{children:e.jsx("div",{className:"h-full w-full overflow-hidden bg-background text-foreground"})})}const bs=document.getElementById("root");if(!bs)throw new Error("Root element not found");Ts.createRoot(bs).render(e.jsx(Le.StrictMode,{children:e.jsx(Ro,{children:e.jsx(Eo,{children:e.jsx(al,{apis:Vn()??void 0})})})}));
|