vibelet 1.2.244 → 1.2.245
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/index.cjs +1 -1
- package/dist/inventory-scan-worker.cjs +1 -1
- package/dist/remoteDirect/manifest.json +12 -12
- package/dist/runtime-version.cjs +1 -1
- package/dist/web/assets/App-D4fBMWn7.js +2 -0
- package/dist/web/assets/{BrowserControlPanel-CPoKd7Kw.js → BrowserControlPanel-CX9UdOEA.js} +1 -1
- package/dist/web/assets/{ChatPane-Bja1-mNo.js → ChatPane-wtVFANO0.js} +2 -2
- package/dist/web/assets/{ChipGroup-CBLaaeLz.js → ChipGroup-C16Et4Xc.js} +1 -1
- package/dist/web/assets/{ComposerMenus-DsmaPUcI.js → ComposerMenus-B9EpF3L_.js} +1 -1
- package/dist/web/assets/{DiffDrawer-OzwH-ohL.js → DiffDrawer-DTg5YChv.js} +1 -1
- package/dist/web/assets/{FilesControlPanel-OMKoXFux.js → FilesControlPanel-Bx9RohXk.js} +1 -1
- package/dist/web/assets/{GlobalPendingDialog-C7pEj7Bn.js → GlobalPendingDialog-p1vvgOHs.js} +1 -1
- package/dist/web/assets/{ImageViewer-Cob3hI1x.js → ImageViewer--pLWLE6p.js} +1 -1
- package/dist/web/assets/{LanguageSettingsPanel-CDBK3924.js → LanguageSettingsPanel-COinfVCx.js} +1 -1
- package/dist/web/assets/{MarkdownModePanel-DGwvMtZM.js → MarkdownModePanel-DGxuHxiO.js} +1 -1
- package/dist/web/assets/{MessageImage-Cf2bcj81.js → MessageImage-DyqY_ZJd.js} +1 -1
- package/dist/web/assets/{NewSessionDialog-DUooZQm1.js → NewSessionDialog-CGMida8H.js} +1 -1
- package/dist/web/assets/{NotificationSettingsPanel-CEEZqgwB.js → NotificationSettingsPanel-CrkHAKw9.js} +1 -1
- package/dist/web/assets/{PanelFind-DTUP5y3B.js → PanelFind-Cx5K--7K.js} +1 -1
- package/dist/web/assets/{RemoteLifeOSBlock-BlUqhm3D.js → RemoteLifeOSBlock-CzC-ut2z.js} +2 -2
- package/dist/web/assets/{RemoteWorkspaceSettings--qq9qs_Y.js → RemoteWorkspaceSettings--n8qxL-O.js} +1 -1
- package/dist/web/assets/{SessionTerminalPanel-BaZnSZot.js → SessionTerminalPanel-D59JkdsC.js} +2 -2
- package/dist/web/assets/{SpeechInputSettingsPanel-BK0fKCTr.js → SpeechInputSettingsPanel-rrdMQRnO.js} +1 -1
- package/dist/web/assets/{ThemeSettingsPanel-DI84WGvC.js → ThemeSettingsPanel-JMc98Dpj.js} +1 -1
- package/dist/web/assets/{__vite-browser-external-2447137e-DW3mvo_M.js → __vite-browser-external-2447137e-DYOQzEuf.js} +1 -1
- package/dist/web/assets/{abnfDiagram-VRR7QNED-C3rbCRUQ.js → abnfDiagram-VRR7QNED-CiGRuhk-.js} +1 -1
- package/dist/web/assets/{arc-BMRI7ug0.js → arc-Uf6y3fQG.js} +1 -1
- package/dist/web/assets/{architectureDiagram-ZJ3FMSHR-C6Sppdgd.js → architectureDiagram-ZJ3FMSHR-Cx57d0-g.js} +1 -1
- package/dist/web/assets/{arrow-left-Dn8a_P9r.js → arrow-left-CTbegMaU.js} +1 -1
- package/dist/web/assets/{arrow-right-CD9DUizK.js → arrow-right-BQXADod1.js} +1 -1
- package/dist/web/assets/{blockDiagram-677ZJIJ3-Bm8Ayy1Z.js → blockDiagram-677ZJIJ3-DfDpv9OM.js} +1 -1
- package/dist/web/assets/{c4Diagram-LMCZKHZV-BJzRiX9s.js → c4Diagram-LMCZKHZV-_ILjwxFf.js} +1 -1
- package/dist/web/assets/channel-Dk15gdNy.js +1 -0
- package/dist/web/assets/chevron-up-GZB6oy0t.js +1 -0
- package/dist/web/assets/{chunk-2Q5K7J3B-CQ1-wT5k.js → chunk-2Q5K7J3B-CY59UbU-.js} +1 -1
- package/dist/web/assets/{chunk-32BRIVSS-C9h1MPOY.js → chunk-32BRIVSS-BSCYWxge.js} +1 -1
- package/dist/web/assets/{chunk-5VM5RSS4-676Zf_tM.js → chunk-5VM5RSS4-DAMZXj9y.js} +1 -1
- package/dist/web/assets/{chunk-EX3LRPZG-CN-9cKRq.js → chunk-EX3LRPZG-D2G4irvr.js} +1 -1
- package/dist/web/assets/{chunk-JWPE2WC7-DMSZNrOK.js → chunk-JWPE2WC7-BcR5muoN.js} +1 -1
- package/dist/web/assets/{chunk-MOJQB5TN-CA493fAj.js → chunk-MOJQB5TN-DBf8Vf6T.js} +1 -1
- package/dist/web/assets/{chunk-RYQCIY6F-CuhZfXOr.js → chunk-RYQCIY6F-C3X0k4Wk.js} +1 -1
- package/dist/web/assets/{chunk-V7JOEXUC-BISX05OV.js → chunk-V7JOEXUC-CPO1U4G8.js} +1 -1
- package/dist/web/assets/{chunk-VR4S4FIN-BrxW8t76.js → chunk-VR4S4FIN-D9BlrMdk.js} +1 -1
- package/dist/web/assets/{chunk-XXDRQBXY-B11WukNi.js → chunk-XXDRQBXY-DUhbXvUs.js} +1 -1
- package/dist/web/assets/classDiagram-OUVF2IWQ-CN2WsgwT.js +1 -0
- package/dist/web/assets/classDiagram-v2-EOCWNBFH-CN2WsgwT.js +1 -0
- package/dist/web/assets/{collectMessageImages-ByGEJk4W.js → collectMessageImages-DdrSxaMf.js} +1 -1
- package/dist/web/assets/{cose-bilkent-JH36ORCC-BBct79nj.js → cose-bilkent-JH36ORCC-B3c5J7br.js} +1 -1
- package/dist/web/assets/{cynefin-VYW2F7L2-DkjP8Uvr.js → cynefin-VYW2F7L2-DwrXi0XX.js} +1 -1
- package/dist/web/assets/{cynefinDiagram-TSTJHNR4-BshnTL7c.js → cynefinDiagram-TSTJHNR4-5t6NkjVv.js} +1 -1
- package/dist/web/assets/{dagre-VKFMJZFB-CDJ1LBpz.js → dagre-VKFMJZFB-CE6g1IOo.js} +1 -1
- package/dist/web/assets/{diagram-FQU43EPY-CFT8Dh3F.js → diagram-FQU43EPY-CN3Kybbf.js} +1 -1
- package/dist/web/assets/{diagram-G47NLZAW-FlGvlbBY.js → diagram-G47NLZAW-Djc-xY18.js} +1 -1
- package/dist/web/assets/{diagram-NH7WQ7WH-C3FZqCGr.js → diagram-NH7WQ7WH-dgr5u2-y.js} +1 -1
- package/dist/web/assets/{diagram-OA4YK3LP-CqA8qU8l.js → diagram-OA4YK3LP-Bna9UWZO.js} +1 -1
- package/dist/web/assets/{diagram-WEI45ONY-CWxsHN3a.js → diagram-WEI45ONY-MFmmaGwd.js} +1 -1
- package/dist/web/assets/{ebnfDiagram-CCIWWBDH-D-nwbyZM.js → ebnfDiagram-CCIWWBDH-C4vnTICq.js} +1 -1
- package/dist/web/assets/{erDiagram-Q63AITRT-Cw4QFFdq.js → erDiagram-Q63AITRT-OHs8hKkP.js} +1 -1
- package/dist/web/assets/{file-editor-FileCodeEditor-BTvQY5aN.js → file-editor-FileCodeEditor-CjIOJIPi.js} +1 -1
- package/dist/web/assets/{file-editor-ObsidianCodeEditor-CnBokVUd.js → file-editor-ObsidianCodeEditor-DqGk6x5n.js} +1 -1
- package/dist/web/assets/{file-editor-ObsidianFileEditor-BHqr5Od1.js → file-editor-ObsidianFileEditor-Bw_Rpzie.js} +1 -1
- package/dist/web/assets/{flowDiagram-23GEKE2U-_YtzmK1c.js → flowDiagram-23GEKE2U-CgkejrIU.js} +1 -1
- package/dist/web/assets/{folder-plus-B5Pq2nu3.js → folder-plus-BBvp5bBk.js} +1 -1
- package/dist/web/assets/{ganttDiagram-NO4QXBWP-CooJp1Sy.js → ganttDiagram-NO4QXBWP-C93UiqA8.js} +1 -1
- package/dist/web/assets/{gitGraphDiagram-IHSO6WYX-DLkVxgBO.js → gitGraphDiagram-IHSO6WYX-dNRNMuEa.js} +1 -1
- package/dist/web/assets/highlighted-body-TPN3WLV5-DnHFC22F.js +1 -0
- package/dist/web/assets/{imageViewerCopy-DPlsO9Fq.js → imageViewerCopy-CZ0PxllY.js} +1 -1
- package/dist/web/assets/index-C6NKSiG-.js +2 -0
- package/dist/web/assets/{index-MzY1_GM8.js → index-C_U23Las.js} +1 -1
- package/dist/web/assets/{index-or5MsQ9j.js → index-CvmmrrPC.js} +1 -1
- package/dist/web/assets/{index-CJdSlCST.js → index-D5vqn_ed.js} +1 -1
- package/dist/web/assets/infoDiagram-FWYZ7A6U-CW-qN7ME.js +1 -0
- package/dist/web/assets/{ishikawaDiagram-FXEZZL3T-D49dd8yi.js → ishikawaDiagram-FXEZZL3T-B7qgG7qy.js} +1 -1
- package/dist/web/assets/{journeyDiagram-5HDEW3XC-HCOjLMVz.js → journeyDiagram-5HDEW3XC-fC2VOxfE.js} +1 -1
- package/dist/web/assets/{kanban-definition-HUTT4EX6-C-r1YL8K.js → kanban-definition-HUTT4EX6-CgRDoaWP.js} +1 -1
- package/dist/web/assets/{key-round-CBXf9jso.js → key-round-DZyIHeFg.js} +1 -1
- package/dist/web/assets/{linear-Dieq9bEI.js → linear-B_EbvSwc.js} +1 -1
- package/dist/web/assets/{mermaid-O7DHMXV3-CQ5BQ7KZ.js → mermaid-O7DHMXV3-B-4H0Z-Q.js} +2 -2
- package/dist/web/assets/{mermaid.core-Wy19F3JO.js → mermaid.core-CMBPtXgs.js} +2 -2
- package/dist/web/assets/{mic-D4goCrg5.js → mic-DOgSBjqM.js} +1 -1
- package/dist/web/assets/{mindmap-definition-LN4V7U3C-DjxMFts-.js → mindmap-definition-LN4V7U3C-XM1lxVqO.js} +1 -1
- package/dist/web/assets/{pegDiagram-2B236MQR-BZAyERYc.js → pegDiagram-2B236MQR-DYUFpdXI.js} +1 -1
- package/dist/web/assets/{pieDiagram-ENE6RG2P-CqK22Xww.js → pieDiagram-ENE6RG2P-aBVH0JdT.js} +1 -1
- package/dist/web/assets/{quadrantDiagram-ABIIQ3AL-a7VYXceJ.js → quadrantDiagram-ABIIQ3AL-Bry3howh.js} +1 -1
- package/dist/web/assets/{railroadDiagram-RFXS5EU6-C0Hh-9Vy.js → railroadDiagram-RFXS5EU6-B_X-RKS6.js} +1 -1
- package/dist/web/assets/{requirementDiagram-TGXJPOKE-Dyk0T0Kw.js → requirementDiagram-TGXJPOKE-DSYrODnH.js} +1 -1
- package/dist/web/assets/{sankeyDiagram-HTMAVEWB-OPHtJfE4.js → sankeyDiagram-HTMAVEWB-DgTgUObg.js} +1 -1
- package/dist/web/assets/{sequenceDiagram-DBY2YBRQ-Dy6ExaPH.js → sequenceDiagram-DBY2YBRQ-C0hrYifi.js} +1 -1
- package/dist/web/assets/{shield-check-dTSt1i64.js → shield-check-B5zclKcP.js} +1 -1
- package/dist/web/assets/{sizeCapture-X5ZJPWSS-DISoB4Kg.js → sizeCapture-X5ZJPWSS-KnPlIyQA.js} +1 -1
- package/dist/web/assets/{stateDiagram-2N3HPSRC-BMeAqaRI.js → stateDiagram-2N3HPSRC-DP7NULIr.js} +1 -1
- package/dist/web/assets/stateDiagram-v2-6OUMAXLB-BhpeOEvI.js +1 -0
- package/dist/web/assets/{swimlanes-5IMT3BWC-CLpuLt5m.js → swimlanes-5IMT3BWC-Dg7S6oxH.js} +2 -2
- package/dist/web/assets/swimlanesDiagram-G3AALYLV-DPHGi19a.js +1 -0
- package/dist/web/assets/{timeline-definition-FHXFAJF6-DBVYShyC.js → timeline-definition-FHXFAJF6-CLINYAku.js} +1 -1
- package/dist/web/assets/{useComposerCompletion-BlG5_30j.js → useComposerCompletion-vV_zliKO.js} +1 -1
- package/dist/web/assets/{useMessageImage-DiamlPBI.js → useMessageImage-Bxcjzr5o.js} +1 -1
- package/dist/web/assets/{vennDiagram-L72KCM5P-D17Xr4C3.js → vennDiagram-L72KCM5P-ysQvQnRc.js} +1 -1
- package/dist/web/assets/{wardleyDiagram-EHGQE667-CVEwY56S.js → wardleyDiagram-EHGQE667-DjkDlqix.js} +1 -1
- package/dist/web/assets/{xychartDiagram-FW5EYKEG-J00Holt1.js → xychartDiagram-FW5EYKEG-DHT8vikr.js} +1 -1
- package/dist/web/assets/{zap-NrgCEPGA.js → zap-CGGziZzC.js} +1 -1
- package/dist/web/index.html +1 -1
- package/dist/web/obsidian-editor-assets.json +1 -1
- package/package.json +7 -7
- package/dist/web/assets/App-CtirzFRk.js +0 -2
- package/dist/web/assets/channel-BT2Xr9HW.js +0 -1
- package/dist/web/assets/chevron-up-e3ZkhBY9.js +0 -1
- package/dist/web/assets/classDiagram-OUVF2IWQ-DNNZ5Mwy.js +0 -1
- package/dist/web/assets/classDiagram-v2-EOCWNBFH-DNNZ5Mwy.js +0 -1
- package/dist/web/assets/highlighted-body-TPN3WLV5-rxDgpOLU.js +0 -1
- package/dist/web/assets/index-LydAx7j8.js +0 -2
- package/dist/web/assets/infoDiagram-FWYZ7A6U-CkTGtG4c.js +0 -1
- package/dist/web/assets/stateDiagram-v2-6OUMAXLB-SerPF47v.js +0 -1
- package/dist/web/assets/swimlanesDiagram-G3AALYLV-JC2_r0aG.js +0 -1
- package/dist/web/logo.svg +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ImageViewer-Cob3hI1x.js","assets/index-LydAx7j8.js","assets/index-Df0b_mNb.css","assets/imageViewerCopy-DPlsO9Fq.js","assets/useMessageImage-DiamlPBI.js","assets/arrow-right-CD9DUizK.js","assets/arrow-left-Dn8a_P9r.js","assets/ImageViewer-DilwNKHW.css","assets/DiffDrawer-OzwH-ohL.js","assets/git-actions-DHCQ17VG.js","assets/RemoteWorkspaceSettings--qq9qs_Y.js","assets/ComposerMenus-DsmaPUcI.js","assets/chevron-up-e3ZkhBY9.js","assets/ComposerMenus-8RI97wiO.css","assets/zap-NrgCEPGA.js","assets/key-round-CBXf9jso.js","assets/RemoteWorkspaceSettings-7jz8oX59.css","assets/FilesControlPanel-OMKoXFux.js","assets/folder-plus-B5Pq2nu3.js","assets/__vite-browser-external-2447137e-DW3mvo_M.js","assets/FilesControlPanel-DQpsZVYc.css","assets/LanguageSettingsPanel-CDBK3924.js","assets/ChipGroup-CBLaaeLz.js","assets/ThemeSettingsPanel-DI84WGvC.js","assets/NotificationSettingsPanel-CEEZqgwB.js","assets/SpeechInputSettingsPanel-BK0fKCTr.js","assets/mic-D4goCrg5.js","assets/ChatPane-Bja1-mNo.js","assets/useComposerCompletion-BlG5_30j.js","assets/MessageImage-Cf2bcj81.js","assets/MessageImage-XcPrPLDn.css","assets/shield-check-dTSt1i64.js","assets/useComposerCompletion-B0xUeljY.css","assets/index-CJdSlCST.js","assets/ChatPane-CMZDQ9ZZ.css","assets/InteractionPolish-Nkww8pqM.css","assets/BrowserControlPanel-CPoKd7Kw.js","assets/PanelFind-DTUP5y3B.js","assets/PanelFind-Du02CWMm.css","assets/SessionTerminalPanel-BaZnSZot.js","assets/NewSessionDialog-DUooZQm1.js","assets/NewSessionDialog-eX_6NPbk.css","assets/MarkdownModePanel-DGwvMtZM.js","assets/MarkdownModePanel-D73Xg4At.css","assets/file-editor-FileCodeEditor-BTvQY5aN.js","assets/file-editor-index-C6CU7Fik.js","assets/FileCodeEditor-CW9KijoU.css","assets/file-editor-ObsidianCodeEditor-CnBokVUd.js","assets/file-editor-index-BkRDu8Ih.js","assets/file-editor-index-D5fLCdey.js","assets/file-editor-index-YeA2vzMT.js","assets/file-editor-index-BOi4gj-u.js","assets/file-editor-index-wav2nO7A.js","assets/file-editor-index-BxQDEPaH.js","assets/RemoteLifeOSBlock-BlUqhm3D.js","assets/index-or5MsQ9j.js","assets/RemoteLifeOSBlock-D7P9Ftlh.css","assets/index-BNl2LlC5.js","assets/katex-uyR15voz.js","assets/marked.esm-BBjA1da9.js","assets/ObsidianCodeEditor-eECvmZRy.css","assets/file-editor-ObsidianFileEditor-BHqr5Od1.js","assets/purify.es-BNLkGfTg.js","assets/index-MzY1_GM8.js","assets/isArrayLikeObject-C958pSF-.js","assets/_baseMerge-DBQbsGvS.js","assets/_initCloneObject-BR1zWEqJ.js","assets/ObsidianFileEditor-D2QjjPA3.css","assets/GlobalPendingDialog-C7pEj7Bn.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{c as e,r as t,j as n,h as s,q as r,i,v as o,t as a,b as c,d as l,w as d,x as u,y as h,z as m,A as f,B as p,o as g,C as v,F as y,k as b,G as w,H as S,I as x,f as I,S as k,_ as C,u as R,E,m as M,J as j,K as A}from"./index-LydAx7j8.js";const T=e("activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]),N=e("archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]),P=e("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]),D=e("arrow-left-to-line",[["path",{d:"M3 19V5",key:"rwsyhb"}],["path",{d:"m13 6-6 6 6 6",key:"1yhaz7"}],["path",{d:"M7 12h14",key:"uoisry"}]]),L=e("arrow-right-to-line",[["path",{d:"M17 12H3",key:"8awo09"}],["path",{d:"m11 18 6-6-6-6",key:"8c2y43"}],["path",{d:"M21 5v14",key:"nzette"}]]),F=e("bell",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]]),O=e("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]),q=e("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),_=e("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),$=e("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]),z=e("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]),H=e("ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]),B=e("eye-off",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),U=e("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),W=e("file-question-mark",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]]),K=e("file-text",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]),G=e("flip-horizontal-2",[["path",{d:"m3 7 5 5-5 5V7",key:"couhi7"}],["path",{d:"m21 7-5 5 5 5V7",key:"6ouia7"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 2v2",key:"tus03m"}]]),Q=e("flip-vertical-2",[["path",{d:"m17 3-5 5-5-5h10",key:"1ftt6x"}],["path",{d:"m17 21-5-5-5 5h10",key:"1m0wmu"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]),V=e("folder-open",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]),J=e("folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]),Z=e("funnel",[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]]),X=e("git-compare",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]]),Y=e("globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]),ee=e("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]),te=e("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),ne=e("maximize-2",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]),se=e("maximize",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]),re=e("message-circle",[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719",key:"1sd12s"}]]),ie=e("minimize-2",[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]]),oe=e("minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),ae=e("panel-left",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]),ce=e("panel-right",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]),le=e("pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]),de=e("pin",[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]]),ue=e("plug-zap",[["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m18 3-4 4h6l-4 4",key:"16psg9"}]]),he=e("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),me=e("refresh-cw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]),fe=e("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]),pe=e("rotate-cw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),ge=e("save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]),ve=e("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]),ye=e("settings-2",[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]),be=e("settings",[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),we=e("sliders-horizontal",[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]]),Se=e("square-terminal",[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]]),xe=e("tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]),Ie=e("terminal",[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]]),ke=e("trash-2",[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]]),Ce=e("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),Re=e("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Ee="vibelet:session-workspace-change",Me="vibelet:session-workspace-before-remove",je="vibelet:session-workspace-removing";function Ae(e){window.dispatchEvent(new CustomEvent(Ee,{detail:e}))}function Te(e,t){window.dispatchEvent(new CustomEvent(je,{detail:{...e,removing:t}}))}function Ne(e,t){let n;try{n=JSON.parse(e)}catch{return e}if(!Array.isArray(n)||2!==n.length)return e;if(n[0]===t.daemonId&&n[1]===t.sessionId)return"remove"===t.action?null:JSON.stringify([t.daemonId,t.nextSessionId]);if("string"!=typeof n[0])return e;const s=Ne(n[0],t);return null===s?null:s===n[0]?e:JSON.stringify([s,n[1]])}function Pe(e,t){const{value:n,set:s}=De(e,t);return[n,s]}function De(e,n){const s=t.useRef(new Map),r=t.useRef([]),i=t.useCallback(e=>{let t=e;for(const n of r.current){if(null===t)break;t=Ne(t,n)}return t},[]),o=i(e),a=()=>"function"==typeof n?n():n;null===o||s.current.has(o)||s.current.set(o,a());const[c,l]=t.useState(()=>new Map),d=t.useRef(c),u=t.useCallback(e=>{d.current=e,l(e)},[]),h=null===o?a():c.has(o)?c.get(o):s.current.get(o),m=t.useCallback(t=>{const n=i(e);if(null===n)return;const r=d.current,o=r.has(n)?r.get(n):s.current.get(n),a="function"==typeof t?t(o):t;Object.is(o,a)||u(new Map(r).set(n,a))},[e,i,u]),f=t.useCallback((e,t)=>{const n=i(e);null===n||Object.is(d.current.get(n),t)||u(new Map(d.current).set(n,t))},[i,u]),p=t.useCallback(e=>{const t=i(e);return null===t?void 0:d.current.has(t)?d.current.get(t):s.current.get(t)},[i]),g=t.useCallback(()=>new Map([...s.current,...d.current]),[]),v=t.useCallback(e=>{const t=g();let n=!1;for(const[s,r]of t){const i=e(r,s);i!==r&&(t.set(s,i),n=!0)}n&&u(t)},[g,u]);return t.useEffect(()=>{const e=e=>{const t=e.detail;r.current.push(t);const n=e=>{const n=new Map(e);for(const[s,r]of e){const e=Ne(s,t);e!==s&&(n.delete(s),null!==e&&n.set(e,r))}return n};s.current=n(s.current),u(n(d.current))};return window.addEventListener(Ee,e),()=>window.removeEventListener(Ee,e)},[u]),{value:h,set:m,setForScope:f,getForScope:p,getAll:g,updateAll:v,resolveScope:i}}function Le(e,t){return JSON.stringify([e??null,t??null])}function Fe(e,t){try{const[n,s]=JSON.parse(e),[r,i]=JSON.parse(t);return n===r&&null===s&&"string"==typeof i}catch{return!1}}function Oe(e){try{return new URL(e).href}catch{return e}}const qe=t.createContext(null);function _e({children:e,scopeKey:s}){const r=function(e="default"){const{remember:n,take:s,clear:r}=function(e){const n=t.useRef([]);return t.useEffect(()=>{const e=e=>{const t=e.detail;n.current=n.current.flatMap(e=>{const n=Ne(e.scopeKey??"default",t);return null===n?[]:[{...e,scopeKey:n}]})};return window.addEventListener(Ee,e),()=>window.removeEventListener(Ee,e)},[]),{remember:t.useCallback(e=>{"diff"===e.kind||e.emptyPlaceholder||(n.current=[...n.current.filter(t=>t.id!==e.id),e].slice(-30))},[]),take:t.useCallback(()=>{const t=n.current.findLastIndex(t=>(t.scopeKey??"default")===e);if(t<0)return null;const[s]=n.current.splice(t,1);return{...s,id:crypto.randomUUID(),url:s.currentUrl||s.url,emptyPlaceholder:!1,autoOpenTerminal:!0}},[e]),clear:t.useCallback(()=>{n.current=[]},[])}}(e),i=t.useRef(null),o=t.useRef(null),a=t.useRef({browser:0,terminal:0}),[c,l]=t.useState(0),[d,u]=t.useState([]),h=d.filter(t=>(t.scopeKey??"default")===e),{value:m,set:f,setForScope:p}=De(JSON.stringify([e,c]),null),{value:g,set:v,setForScope:y,getForScope:b}=De(JSON.stringify([e,c]),()=>({}));t.useEffect(()=>{const e=e=>{const t=e.detail;u(e=>e.flatMap(e=>{const n=Ne(e.scopeKey??"default",t);return null===n?[]:n===(e.scopeKey??"default")?[e]:[{...e,scopeKey:n,session:e.session&&"remap"===t.action?{...e.session,sessionId:t.nextSessionId}:e.session}]}))};return window.addEventListener(Ee,e),()=>window.removeEventListener(Ee,e)},[]);const[w,S]=t.useState({}),x=t.useCallback((t,n,s,r,i,o)=>{const c=crypto.randomUUID(),l="diff"===t?"center":"right",d=n;return"diff"!==t&&(n=`${n} ${++a.current[t]}`),u(a=>[...a,{id:c,kind:t,title:n,defaultTitle:d,cwd:s,session:r,scope:i,path:o,location:l,scopeKey:e}]),"center"===l?f(c):v(e=>({...e,[t]:c})),c},[e,f,v]),I=t.useRef(new Set),k=t.useCallback(t=>{const n=d.find(e=>e.id===t);if(!n)return;const s=n.scopeKey??"default",r=JSON.stringify([s,c]);"center"===n.location?p(r,t):(y(r,{...b(r),[n.kind]:t}),i.current?.(n.kind)),s!==e&&window.dispatchEvent(new CustomEvent("vibelet.dock.restore-session",{detail:s}))},[d,c,e,p,y,b]),C=t.useCallback((t,n)=>{const s=h.find(e=>"browser"===e.kind&&"right"===e.location&&Oe(e.currentUrl||e.url||"")===Oe(t));if(s)return v(e=>({...e,browser:s.id})),void i.current?.("browser",!0);const r=h.filter(e=>"browser"===e.kind&&"right"===e.location&&!e.url&&!e.currentUrl&&!I.current.has(e.id)),o=r.find(e=>e.id===g.browser)??r[0],a=o?.id??crypto.randomUUID();o&&I.current.add(a),u(s=>o?s.map(e=>e.id===a?{...e,title:n,url:t,emptyPlaceholder:!1}:e):[...s,{id:a,kind:"browser",location:"right",title:n,defaultTitle:n,url:t,scopeKey:e}]),v(e=>({...e,browser:a})),i.current?.("browser",!0)},[h,g.browser,e,v]),R=t.useCallback((e,t)=>{u(n=>n.map(n=>n.id===e&&n.currentUrl!==t?{...n,currentUrl:t,emptyPlaceholder:!t&&n.emptyPlaceholder}:n))},[]),E=t.useCallback((e,t)=>{const n=h.find(t=>t.id===e);n&&(u(n=>n.map(n=>n.id===e?{...n,location:t}:n)),"center"===t?("right"!==n.location||h.some(t=>t.id!==e&&t.kind===n.kind&&"right"===t.location)||o.current?.(n.kind),f(e),v(t=>({...t,[n.kind]:h.find(t=>t.id!==e&&t.kind===n.kind&&"right"===t.location)?.id}))):(v(t=>({...t,[n.kind]:e})),i.current?.(n.kind),m===e&&f(null)))},[h,m,f,v]),M=t.useCallback(t=>{I.current.delete(t);const s=h.find(e=>e.id===t);if(!s)return;n(s);const r=h.find(e=>e.id!==t&&e.kind===s.kind&&e.location===s.location),i=r||"diff"===s.kind||"right"!==s.location&&h.some(e=>e.id!==t&&e.kind===s.kind)?void 0:{id:crypto.randomUUID(),kind:s.kind,location:"right",title:s.defaultTitle??s.title,defaultTitle:s.defaultTitle,cwd:s.cwd,scopeKey:e,autoOpenTerminal:!0,emptyPlaceholder:!0};u(e=>[...e.filter(e=>e.id!==t),...i?[i]:[]]),r||"right"!==s.location||"diff"===s.kind||o.current?.(s.kind),m===t&&f(null),(i||g[s.kind]===t)&&v(e=>({...e,[s.kind]:i?.id??r?.id}))},[h,m,g,e,f,v,n]),j=t.useCallback(()=>{const t=s();t&&(u(n=>[...n.filter(n=>!("right"===t.location&&n.emptyPlaceholder&&n.kind===t.kind&&(n.scopeKey??"default")===e)),t]),"center"===t.location?f(t.id):(v(e=>({...e,[t.kind]:t.id})),i.current?.(t.kind)))},[s,e,f,v]),A=t.useCallback(e=>{u(t=>t.map(t=>t.id===e&&t.emptyPlaceholder?{...t,emptyPlaceholder:!1}:t))},[]),T=t.useCallback((e,t)=>u(n=>n.map(n=>n.id===e&&n.title!==t?{...n,title:t}:n)),[]),N=t.useCallback((e,t)=>S(n=>{if(n[e]===t||!n[e]&&!t)return n;const s={...n};return t?s[e]=t:delete s[e],s}),[]),P=t.useCallback(()=>{r(),I.current.clear(),u([]),f(null),v({}),l(e=>e+1)},[f,v,r]);return t.useMemo(()=>({scopeKey:e,allItems:d,openRight:i,closeRight:o,openBrowser:C,reveal:k,updateBrowserUrl:R,activate:A,epoch:c,items:h,center:m,right:g,hosts:w,add:x,move:E,close:M,reopenClosed:j,rename:T,register:N,reset:P,setCenter:f,setRight:v}),[e,d,C,k,R,A,c,h,m,g,w,x,E,M,j,T,N,P])}(s);return n.jsx(qe.Provider,{value:r,children:e})}function $e(){const e=t.useContext(qe);if(!e)throw new Error("Dock workspace provider missing");return e}function ze(){return t.useContext(qe)}const He="application/x-vibelet-workspace-tab";function Be(e){return null}function Ue(e){return null}function We(e){return null}function Ke(){return null}const Ge=()=>null;function Qe({children:e}){return n.jsx(n.Fragment,{children:e})}function Ve(e,t,n=!1){const s=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*))?(?:\+[\da-zA-Z-]+(?:\.[\da-zA-Z-]+)*)?$/,r=s.exec(e),i=s.exec(t);if(!r||!i||i[4])return!1;for(let o=1;o<=3;o++){const e=Number(i[o]),t=Number(r[o]);if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t))return!1;if(e!==t)return e>t}return Boolean(r[4])||n}function Je(e="en"){return/^zh/i.test(e)?/tw|hant/i.test(e)?{title:"有更新的正式版",description:(e,t)=>`目前使用 ${e},正式版 ${t} 已發布,建議切換更新。`,action:"切換至正式版"}:{title:"有更新的正式版",description:(e,t)=>`当前使用 ${e},正式版 ${t} 已发布,建议切换更新。`,action:"切换到正式版"}:{title:"A newer stable release is available",description:(e,t)=>`You are using ${e}. Stable ${t} is now available. Switch to stable to update.`,action:"Switch to stable"}}const Ze="pair",Xe="vibelet.web.pairing",Ye="vibelet.web.deviceId";class et extends Error{constructor(e,t){super(t),this.code=e,this.name="PairingCreateError"}}function tt(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function nt(e){const[t,n,s,r,i,o]=e;return!n||!Number.isFinite(s)||s<=0?null:{kind:"relay"===t?"relay":"direct",host:n,port:Math.floor(s),source:r,stability:i,...!0===o?{secure:!0}:{}}}function st(e){if(!tt(e))return null;const{kind:t,host:n,port:s,source:r,stability:i,secure:o}=e;return"direct"!==t&&"relay"!==t||"string"!=typeof n||!n.trim()||"number"!=typeof s||!Number.isFinite(s)||s<=0||"string"!=typeof r||"string"!=typeof i?null:{kind:t,host:n.trim(),port:Math.floor(s),source:r,stability:i,...!0===o?{secure:!0}:{}}}function rt(e){const t=e.trim().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"").toLowerCase();if("localhost"===t||t.endsWith(".localhost"))return!0;if("::1"===t||"0:0:0:0:0:0:0:1"===t)return!0;const n=t.split(".");if(4!==n.length||n.some(e=>!/^\d+$/.test(e)))return!1;const s=n.map(Number);return s.every(e=>e>=0&&e<=255)&&127===s[0]}function it(e,t){return"https:"===t.protocol&&!0!==e.secure?null:`${!0===e.secure?"wss":"ws"}://${function(e){const t=e.trim();return t.includes(":")&&!t.startsWith("[")?`[${t}]`:t}(e.host)}:${e.port}`}function ot(e){return function(e){const t=e.trim().split(".");if(4!==t.length)return!1;const n=t.map(e=>/^\d+$/.test(e)?Number(e):Number.NaN);if(n.some(e=>!Number.isInteger(e)||e<0||e>255))return!1;const[s,r]=n;return 10===s||172===s&&r>=16&&r<=31||192===s&&168===r}(e.host)?0:"local_network"===e.source?1:"configured_host"===e.source?2:3}function at(e,t){const n=t?.port??e.port,s=t?.canonicalHost??e.canonicalHost;if(!s||"number"!=typeof n||!Number.isFinite(n))return[];const r=Math.floor(n);return[{kind:"direct",host:s,port:r,source:"fallback",stability:"stable"},...[...t?.fallbackHosts??[],...e.fallbackHosts??[]].map(e=>({kind:"direct",host:e,port:r,source:"fallback",stability:"stable"}))]}function ct(e,t,n=window.location,s=!0){if(s&&rt(n.hostname))return;const r=[...t?.connections??[],...e.connections??[],...at(e,t)].map(st).filter(e=>Boolean(e)).filter(e=>"direct"===e.kind).sort((e,t)=>ot(e)-ot(t));for(const i of r){const e=it(i,n);if(e)return e}}function lt(e=window.location.hash){const t=e.startsWith("#")?e.slice(1):e,n=new URLSearchParams(t).get(Ze);if(!n)return null;try{const e=JSON.parse(function(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.padEnd(4*Math.ceil(t.length/4),"=");return decodeURIComponent(Array.from(atob(n),e=>`%${e.charCodeAt(0).toString(16).padStart(2,"0")}`).join(""))}(n));if(!tt(e))return null;if("vp"===e.t)return function(e){if(!e.d||!e.c)return null;const t=Array.isArray(e.o)?e.o.map(nt).filter(e=>Boolean(e)):void 0;return{daemonId:e.d,pairNonce:e.c,...e.n?{displayName:e.n}:{},...e.h?{canonicalHost:e.h}:{},...Number.isFinite(e.p)?{port:e.p}:{},...Array.isArray(e.f)?{fallbackHosts:e.f.filter(e=>"string"==typeof e)}:{},...t?.length?{connections:t}:{},...e.e?{expiresAt:e.e}:{}}}(e);if("vibelet-pair"===e.type)return function(e){return e.daemonId&&e.pairNonce?{daemonId:e.daemonId,displayName:e.displayName,canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:e.port,connections:e.connections,pairNonce:e.pairNonce,expiresAt:e.expiresAt}:null}(e)}catch{return null}return null}function dt(e){const t=e.getItem(Xe);if(!t)return null;try{const e=JSON.parse(t);return e.daemonId&&e.deviceId&&e.pairToken?{daemonId:e.daemonId,displayName:e.displayName,deviceId:e.deviceId,pairToken:e.pairToken,pairedAt:e.pairedAt??(new Date).toISOString(),webSocketUrl:"string"==typeof e.webSocketUrl?e.webSocketUrl:void 0}:null}catch{return null}}function ut(e){if("undefined"==typeof window)return null;try{return e===i()?window.sessionStorage:null}catch{return null}}function ht(e=i(),t=ut(e)){const n=dt(e);if(n)return n;const s=t?dt(t):null;return s?(e.setItem(Xe,JSON.stringify(s)),t?.removeItem(Xe),s):null}function mt(e,t=i(),n=ut(t)){t.setItem(Xe,JSON.stringify(e)),n?.removeItem(Xe)}function ft(e=i(),t=ut(e)){e.removeItem(Xe),t?.removeItem(Xe)}async function pt(e,t){try{return await async function(e,t=function(e=i()){const t=e.getItem(Ye);if(t)return t;const n="function"==typeof crypto.randomUUID?crypto.randomUUID():`web_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;return e.setItem(Ye,n),n}()){if(function(e,t=Date.now()){if(!e.expiresAt)return!1;const n=new Date(e.expiresAt).getTime();return Number.isFinite(n)&&n<t}(e))throw new et("pair_window_expired","Pairing link expired.");const n=await fetch("/pair/create",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({daemonId:e.daemonId,pairNonce:e.pairNonce,deviceId:t,deviceName:"Vibelet Web"})});if(!n.ok)throw await async function(e){const t=await e.text().catch(()=>"");try{const e=JSON.parse(t);if(tt(e)&&"pair_window_expired"===e.error)return new et("pair_window_expired","Pairing link expired.")}catch{}return new et("pairing_failed",t||"Pairing failed.")}(n);const s=await n.json();return{daemonId:s.daemonId,displayName:s.displayName||e.displayName,deviceId:s.deviceId,pairToken:s.pairToken,pairedAt:(new Date).toISOString(),webSocketUrl:ct(e,s,window.location,!0)}}(e,t?.deviceId)}catch(n){if(n instanceof et&&"pair_window_expired"===n.code&&t?.daemonId===e.daemonId)return t;throw n}}async function gt(e){const t=s().writeClipboardText;if(t)return t(e);try{if(navigator.clipboard?.writeText)return void(await navigator.clipboard.writeText(e))}catch{}const n=document.activeElement,r=window.getSelection(),i=r?Array.from({length:r.rangeCount},(e,t)=>r.getRangeAt(t).cloneRange()):[],o=n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?[n.selectionStart,n.selectionEnd,n.selectionDirection]:void 0,a=document.createElement("textarea");a.value=e,a.setAttribute("readonly",""),a.style.position="fixed",a.style.opacity="0",document.body.append(a);try{if(a.focus({preventScroll:!0}),a.select(),!document.execCommand("copy"))throw new Error("Clipboard copy was rejected")}finally{if(a.remove(),n instanceof HTMLElement&&n.focus({preventScroll:!0}),o&&(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&null!==o[0]&&null!==o[1]&&n.setSelectionRange(o[0],o[1],o[2]??void 0),r){r.removeAllRanges();for(const e of i)r.addRange(e)}}}function vt(e){return/^[a-zA-Z0-9._/@~-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function yt(e){return Boolean(e.sessionId.trim())&&!e.sessionId.startsWith("pending_")}function bt(e,t={}){return yt(e)?`cd ${vt(e.cwd||".")} && ${function(e,t={}){if(!yt(e))return"";const n=e.approvalMode??e.observedApprovalMode,s="claude"===e.agent?["claude","--resume",e.sessionId]:["codex","resume",e.sessionId],r=t.codexBackend??e.runtime?.codexBackend;return"codex"!==e.agent||"standalone"!==r&&(r||"@vibelet/cli"!==e.originator)||s.push("--no-daemon"),"autoApprove"===n?s.push("claude"===e.agent?"--dangerously-skip-permissions":"--dangerously-bypass-approvals-and-sandbox"):"claude"===e.agent&&"acceptEdits"===n&&s.push("--permission-mode","acceptEdits"),[...t.vibeletChannel?["npx",`vibelet@${t.vibeletChannel}`]:[],...s].map(vt).join(" ")}(e,t)}`:""}const wt="vibelet.web.notificationSettings",St={enabled:!1,approvals:!0,questions:!0,replies:!0,hiddenOnly:!0};function xt(e=i()){try{const t=e.getItem(wt);if(!t)return{...St};const n=JSON.parse(t);return an(n)?{enabled:"boolean"==typeof n.enabled?n.enabled:St.enabled,approvals:"boolean"==typeof n.approvals?n.approvals:St.approvals,questions:"boolean"==typeof n.questions?n.questions:St.questions,replies:"boolean"==typeof n.replies?n.replies:St.replies,hiddenOnly:"boolean"==typeof n.hiddenOnly?n.hiddenOnly:St.hiddenOnly}:{...St}}catch{return{...St}}}function It(e=("undefined"==typeof Notification?void 0:Notification)){return s().notifications?s().notifications.permission():e?.permission??"unsupported"}function kt(e){return Boolean(e.historyKey?.startsWith("client:")&&!e.rewindPoint)}function Ct(e){return JSON.stringify([e.provider,"codex"===e.provider?e.turnId:e.messageId])}function Rt(e,t){const n=e.indexOf(t);if(n>=0)return n;const s=t.historyKey;if(s){const t=e.filter(e=>e.historyKey===s);if(t.length)return 1===t.length?e.indexOf(t[0]):-1}const r=t.rewindPoint;if(r)return function(e){const n=e.flatMap((e,n)=>(e=>e.role===t.role&&Boolean(e.rewindPoint)&&Ct(e.rewindPoint)===Ct(r))(e)?[n]:[]);return 1===n.length?n[0]:-1}(e);if(s)return-1;const i=e.flatMap((e,n)=>e.role===t.role&&e.type===t.type&&e.content===t.content&&e.timestamp===t.timestamp&&JSON.stringify(e.images)===JSON.stringify(t.images)?[n]:[]);return 1===i.length?i[0]:-1}function Et(e){if(Number.isFinite(Date.parse(e.timestamp??"")))return e;const t=e.localClientMessageId??e.historyKey?.match(/^client:(.+)$/)?.[1],n=t?.match(/^(?:msg|cmd_msg)_([0-9a-z]+)_[0-9a-z]+$/)?.[1];if(!n)return e;const s=Number.parseInt(n,36);return!Number.isSafeInteger(s)||s<=0||!Number.isFinite(new Date(s).getTime())?e:{...e,timestamp:new Date(s).toISOString()}}function Mt(e,t){return t?.length?e.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").trim():e}function jt(e,t){const n={...e,...t};return!Number.isFinite(Date.parse(t.timestamp??""))&&Number.isFinite(Date.parse(e.timestamp??""))&&(n.timestamp=e.timestamp),n}function At(e){return"user"===e.role?Mt(e.content,e.images):e.content}function Tt(e,t){return e.role===t.role&&(e.type??"message")===(t.type??"message")&&At(e)===At(t)&&JSON.stringify(e.images??[])===JSON.stringify(t.images??[])&&e.toolName===t.toolName&&JSON.stringify(e.toolInput)===JSON.stringify(t.toolInput)}function Nt(e,t){if(t.historyKey?.startsWith("client:")||!e.historyKey?.startsWith("client:")||!e.localClientMessageId||"user"!==e.role||"user"!==t.role||!Tt(e,t))return!1;const n=Date.parse(e.timestamp??""),s=Date.parse(t.timestamp??"");return Number.isFinite(n)&&Number.isFinite(s)&&s>=n-1e3}function Pt(e,t){if(e.historyKey&&t.historyKey)return e.historyKey===t.historyKey;if(e.rewindPoint&&t.rewindPoint)return Ct(e.rewindPoint)===Ct(t.rewindPoint)&&Tt(e,t);const n=e.timestamp?Date.parse(e.timestamp):NaN;return Number.isFinite(n)&&n>0&&n===Date.parse(t.timestamp??"")&&Tt(e,t)}function Dt(e){for(let t=e.length-1;t>=0;t-=1)if("user"===e[t]?.role)return t;return-1}function Lt(e,t,n){let s=e.map(Et);const r=new Set,i=s.flatMap((e,t)=>e.localClientMessageId&&e.historyKey?.startsWith("client:")?[t]:[]),o=new Map;i.length&&s.forEach((e,t)=>{const n=Date.parse(e.timestamp??"");if(e.historyKey?.startsWith("client:")||!Number.isFinite(n))return;const s=`${e.role}:${n}`,r=o.get(s)??[];r.push(t),o.set(s,r)});for(const d of t){const e=o.get(`${d.role}:${Date.parse(d.timestamp??"")}`)?.find(e=>Pt(s[e],d))??-1;if(e<0||s[e].localClientMessageId)continue;const t=i.find(e=>!r.has(e)&&Nt(s[e],d)&&Date.parse(s[e].timestamp)<=Date.parse(d.timestamp));if(void 0===t)continue;const n=s[e].historyKey;s[e]={...s[t],...s[e],localDelivery:"delivered"},n||delete s[e].historyKey,r.add(t)}r.size&&(s=s.filter((e,t)=>!r.has(t)));const a=new Map,c=[];s.forEach((e,t)=>{e.historyKey&&!a.has(e.historyKey)&&a.set(e.historyKey,t),e.historyKey&&!e.historyKey.startsWith("client:")||c.push(t)});const l=new Set;for(const d of t){const e=d.historyKey?a.get(d.historyKey)??-1:-1;if(e>=0){d.delivery&&(s[e]={...jt(s[e],d),localDelivery:"delivered"}),n?.(d,s[e]);continue}const t=(d.historyKey?c:s.map((e,t)=>t)).find(e=>{const t=s[e];return!l.has(e)&&(!!Pt(t,d)||!!Nt(t,d)||!(t.historyKey&&!t.historyKey.startsWith("client:"))&&(t.liveReply&&(e===s.length-1||s.slice(e+1).every(e=>e.localClientMessageId&&e.historyKey?.startsWith("client:")))&&"assistant"===d.role&&"info"!==d.type?t.content.length>0&&d.content.startsWith(t.content):Boolean(d.historyKey&&!d.historyKey.startsWith("client:")&&t.historyKey?.startsWith("client:")&&"user"===t.role&&e===Dt(s)&&s.slice(e+1).every(e=>"assistant"!==e.role||"info"===e.type||e.liveReply)&&Tt(t,d))))})??-1;if(t<0)d.historyKey&&a.set(d.historyKey,s.length),d.historyKey&&!d.historyKey.startsWith("client:")||c.push(s.length),s.push({...d});else{l.add(t);const e=s[t].historyKey;e&&e!==d.historyKey&&a.delete(e);const r=!d.historyKey&&Nt(s[t],d);s[t]=jt(s[t],d),r&&(delete s[t].historyKey,s[t].localDelivery="delivered"),s[t].historyKey&&a.set(s[t].historyKey,t),s[t].localClientMessageId&&d.historyKey&&!d.historyKey.startsWith("client:")&&(s[t].localDelivery="delivered"),delete s[t].liveReply,n?.(d,s[t])}}return s}function Ft(e){const t=e.at(-1);return"assistant"===t?.role&&"info"!==t.type?[...e.slice(0,-1),{...t,liveReply:!0}]:e.slice()}function Ot(e,t){if(!t?.trim())return e.slice();let n=-1;for(let a=e.length-1;a>=0;a--)if("user"===e[a]?.role){n=a;break}const s=[];for(let a=n+1;a<e.length;a++)"assistant"===e[a]?.role&&"info"!==e[a]?.type&&s.push(a);const r=s.at(-1),i=void 0!==r&&e.slice(r+1).some(e=>"tool"===e.role);let o=t;for(const a of s){if(a===r&&!i)break;const t=e[a].content;if(t.trim().startsWith(o.trim()))return e.slice();if(!t||!o.startsWith(t))break;if(o=o.slice(t.length),!o.trim())return e.slice()}if(void 0!==r&&!i){const t=e[r],n=t.content.trim().startsWith(o.trim())?t.content:o,s=e.slice();return s[r]={...t,content:n},Ft(s)}return Ft([...e,{role:"assistant",content:o,timestamp:(new Date).toISOString()}])}function qt(e){return e&&/^[a-z]:\/+$/i.test(e)?`${e.slice(0,2)}/`:e?.replace(/\/+$/,"")||"/"}function _t(e,t,n){const s=n?.[e.sessionId];return void 0!==s?s:"boolean"==typeof e.pinned?e.pinned:Boolean(t?.[e.sessionId])}function $t(e,t){return!t||e.length<2?e:e.map((e,n)=>({session:e,index:n,regularIndex:t[e.sessionId]})).sort((e,t)=>("number"==typeof e.regularIndex&&Number.isFinite(e.regularIndex)?e.regularIndex:Number.POSITIVE_INFINITY)-("number"==typeof t.regularIndex&&Number.isFinite(t.regularIndex)?t.regularIndex:Number.POSITIVE_INFINITY)||e.index-t.index).map(({session:e})=>e)}function zt(e){return e.length<2?e:e.map((e,t)=>({session:e,index:t,activityAt:Date.parse(e.lastActivityAt)})).sort((e,t)=>{const n=Number.isFinite(e.activityAt),s=Number.isFinite(t.activityAt);return n&&s&&e.activityAt!==t.activityAt?t.activityAt-e.activityAt:n!==s?n?-1:1:(t.session.pinnedAt??0)-(e.session.pinnedAt??0)||e.index-t.index}).map(({session:e})=>e)}function Ht(e,t,n){if(0===t.length)return e;const s=new Set(t),r=[];for(const i of t){const e=n.get(i);e&&r.push(e)}for(const i of e)s.has(i.sessionId)||r.push(i);if(r.length!==e.length)return r;for(let i=0;i<e.length;i+=1)if(r[i]!==e[i])return r;return e}function Bt(e,t=Date.now(),n=o){if(!e)return n.timeUnknown;const s=Date.parse(e);if(!Number.isFinite(s))return n.timeUnknown;const r=t-s,i=36e5,a=24*i;return r<6e4?n.timeNow:r<i?n.timeMinutesAgo(Math.floor(r/6e4)):r<a?n.timeHoursAgo(Math.floor(r/i)):n.timeDaysAgo(Math.floor(r/a))}function Ut(e,t){return"info"===e.type?t.messageInfoRole:{user:t.messageUserRole,assistant:t.messageAssistantRole,tool:t.messageToolRole}[e.role]}const Wt="<oai-mem-citation>";function Kt(e){let t,n=0;for(const s of e.split("\n")){const r=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(s);if(r){const e=r[1][0];t?e===t.marker&&r[1].length>=t.length&&!r[2].trim()&&(t=void 0):t={marker:e,length:r[1].length}}else if(!t){const t=s.replace(/^ {0,3}/,""),r=t.startsWith("<oai-mem")&&Wt.startsWith(t);if(t.startsWith(Wt)||r){const t=e.slice(n).trimStart(),s=t.indexOf("</oai-mem-citation>");if(s<0||!t.slice(s+19).trim())return e.slice(0,n).trimEnd()}}n+=s.length+1}return e}const Gt=e=>e.replace(/\r\n?/g,"\n").trim(),Qt=/^\[Attached image: ([^\n]+)\]$/gm;function Vt(e){return"codex"===e?"Codex":"claude"===e?"Claude":e}function Jt(e){const t=[],n=new Set;for(const s of e.matchAll(Qt)){const e=s[1];e&&0!==e.trim().length&&!n.has(e)&&(n.add(e),t.push(e))}return t}function Zt(e,t){if("assistant"===e.type)return Gt(e.content);const n=Gt(function(e){return e.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").replace(/\n{3,}/g,"\n\n").trim()}(e.content)),s=function(e){const t=new Set,n=[];for(const s of e)0===s.trim().length||t.has(s)||(t.add(s),n.push(s));return n}([...Jt(e.content),...e.images??[]]).map(e=>`- ${t.attachedImage}: \`${e}\``);return n&&s.length>0?`${n}\n\n${s.join("\n")}`:n||s.join("\n")}class Xt{timer=null;sentAt=null;listeners=new Set;value=null;subscribe(e){return this.listeners.add(e),e(this.value),()=>{this.listeners.delete(e)}}start(e,t){this.stop();const n=()=>{if(null!==this.sentAt)return this.stop(),void t();this.sentAt=performance.now(),e()};n(),this.timer=setInterval(n,3e4)}acknowledge(){if(null===this.sentAt)return;const e=Math.max(0,Math.round(performance.now()-this.sentAt));this.sentAt=null,this.publish(e)}stop(){null!==this.timer&&clearInterval(this.timer),this.timer=null,this.sentAt=null,this.publish(null)}publish(e){this.value=e,this.listeners.forEach(t=>t(e))}}class Yt extends Error{name="VibeletRequestRejectedError"}class en extends Error{name="VibeletRequestTimeoutError"}function tn(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}class nn{heartbeat=new Xt;onLatency=e=>this.heartbeat.subscribe(e);capabilities={};socket=null;authenticated=!1;authentication=null;pending=new Map;messageListeners=new Set;closeListeners=new Set;connect(e){this.disconnect();const t=this.openAuthenticatedSocket(e);return this.authentication=t,t}async openAuthenticatedSocket(e){const t=new WebSocket(function(e,t=window.location,n=!0){const s=`${"https:"===t.protocol?"wss:":"ws:"}//${t.host}`;return n&&rt(t.hostname)?s:e?.webSocketUrl?e.webSocketUrl:s}(e));let n;this.socket=t;const s=new Promise((e,s)=>{n=s,t.onopen=()=>e(),t.onerror=()=>s(new Error("WebSocket connection failed."))});if(t.onmessage=e=>{this.socket===t&&this.handleSocketMessage(e.data)},t.onclose=()=>{n(new Error("WebSocket disconnected.")),this.socket===t&&(this.heartbeat.stop(),this.authenticated=!1,this.authentication=null,this.socket=null,this.rejectPending(new Error("WebSocket disconnected.")),this.closeListeners.forEach(e=>e()))},await s,this.socket!==t)throw new Error("WebSocket disconnected.");const r=await this.requestOnSocket({action:"auth.hello",id:tn("auth"),pairToken:e.pairToken,daemonId:e.daemonId,deviceId:e.deviceId,locale:navigator.language});if(this.socket!==t)throw new Error("WebSocket disconnected.");return this.authenticated=!0,this.capabilities=r.capabilities??{},this.heartbeat.start(()=>t.send(JSON.stringify({action:"ping"})),()=>t.close()),r}async request(e,t={}){const n=this.socket;if(!this.authenticated){if(!this.authentication)throw new Error("WebSocket is not connected.");await this.authentication}if(this.socket!==n||!this.isConnected)throw new Error("WebSocket disconnected.");return this.requestOnSocket(e,t)}requestOnSocket(e,t={}){return this.socket&&this.socket.readyState===WebSocket.OPEN?new Promise((n,s)=>{const r={action:e.action,resolve:n,reject:s};t.timeoutMs&&t.timeoutMs>0&&(r.timeoutId=setTimeout(()=>{this.pending.delete(e.id),s(new en(t.timeoutMessage||`Request timed out (${e.action}).`))},t.timeoutMs)),this.pending.set(e.id,r),this.socket?.send(JSON.stringify(e))}):Promise.reject(new Error("WebSocket is not connected."))}send(e){this.isConnected&&this.socket?.send(JSON.stringify(e))}onMessage(e){return this.messageListeners.add(e),()=>this.messageListeners.delete(e)}onClose(e){return this.closeListeners.add(e),()=>this.closeListeners.delete(e)}get supportsSessionSteer(){return this.isConnected&&!0===this.capabilities.sessionSteer}get supportsQueueSendNow(){return this.isConnected&&!0===this.capabilities.queueSendNow}get supportsDirectoryWatch(){return this.isConnected&&!0===this.capabilities.directoryWatch}disconnect(){this.heartbeat.stop(),this.authenticated=!1,this.authentication=null,this.capabilities={},this.rejectPending(new Error("WebSocket disconnected."));const e=this.socket;this.socket=null,e?.close(1e3,"client disconnect")}get isConnected(){return this.authenticated&&this.socket?.readyState===WebSocket.OPEN}makeId(e){return tn(e)}handleSocketMessage(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}if("pong"!==t.type){if("error"===t.type&&!t.sessionId){const e=/unsupported action "([^"]+)"/.exec(t.message)?.[1];if(e){let n=!1;for(const[s,r]of this.pending)r.action===e&&(this.pending.delete(s),r.timeoutId&&clearTimeout(r.timeoutId),r.reject(new Yt(t.message)),n=!0);if(n)return}}if("response"===t.type){const e=this.pending.get(t.id);if(e)return this.pending.delete(t.id),e.timeoutId&&clearTimeout(e.timeoutId),void(t.ok?e.resolve(t.data):e.reject(new Yt(t.error||"Request failed.")))}this.messageListeners.forEach(e=>e(t))}else this.heartbeat.acknowledge()}rejectPending(e){for(const t of this.pending.values())t.timeoutId&&clearTimeout(t.timeoutId),t.reject(e);this.pending.clear()}}function sn(e){if(!e||"object"!=typeof e||Array.isArray(e))return;const t=e;return"string"==typeof t.lastActivityAt&&"string"==typeof t.sessionId?{lastActivityAt:t.lastActivityAt,sessionId:t.sessionId}:void 0}const rn=".",on="normal";function an(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function cn(e){if(!Number.isFinite(e))return"unknown";const t=e??0;return t<1024?`${t} B`:t<1048576?`${(t/1024).toFixed(1)} KB`:`${(t/1048576).toFixed(1)} MB`}function ln(e,t){const n=e[e.length-1];return"assistant"===n?.role&&"info"!==n.type?[...e.slice(0,-1),{...n,content:`${n.content}${t}`}]:[...e,{role:"assistant",content:t,timestamp:(new Date).toISOString()}]}function dn(e){const t=e;return{sessions:Array.isArray(t.sessions)?t.sessions:[],nextCursor:sn(t.nextCursor),inventoryVersion:t.inventoryVersion,inventoryBackfillInFlight:t.inventoryBackfillInFlight,folderCounts:t.folderCounts}}function un(e){return e.split("/").filter(Boolean).at(-1)??e}function hn(e){return 0===Object.entries(e).length?"No structured input.":JSON.stringify(e,null,2)}function mn(e){return Object.fromEntries(e.questions.map(e=>[e.id,e.options[0]?[e.options[0].label]:[]]))}function fn(e){return e.trim()||void 0}function pn(e){const t=864e5;return"7d"===e?Date.now()-7*t:"30d"===e?Date.now()-30*t:"90d"===e?Date.now()-90*t:void 0}function gn(e,t){const n=new Map;for(const s of e)n.set(s.sessionId,s);for(const s of t){const e=n.get(s.sessionId),t=e&&(s.cwd!==e.cwd||Object.hasOwn(s,"branch")&&s.branch!==e.branch);n.set(s.sessionId,{...e,...t?{pullRequest:void 0,branchUrl:void 0,branch:void 0,diffStat:void 0}:{},...s,model:s.model,interruptReason:s.interruptReason,stallWarning:s.stallWarning})}return Array.from(n.values()).sort((e,t)=>{const n=e.pinned?e.pinnedAt??0:0,s=t.pinned?t.pinnedAt??0:0;return n!==s?s-n:Date.parse(t.lastActivityAt)-Date.parse(e.lastActivityAt)})}let vn=0;function yn(e,t,n=(new Date).toISOString()){return{...e,sessionId:t,lastActivityAt:n}}function bn(e,t,n){if(!t||!n||t===n||!Object.hasOwn(e,t))return e;const{[t]:s,...r}=e;return{...r,[n]:s}}function wn(e,t,n){if(!t||!n||t===n||!e.has(t))return e;const s=new Set(e);return s.delete(t),s.add(n),s}function Sn(e,t){const n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n&&"."!==n?`${n}/${t}`:t}function xn(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");if(!t||"/"===t||"~"===t||"."===t)return null;const n=t.lastIndexOf("/");return n<0?".":0===n?"/":t.slice(0,n)}function In(e,t){return t.startsWith("image/")||/\.(png|jpe?g|gif|webp|heic|heif|svg)$/i.test(e)}function kn(e,t,n=window.location.origin){const s=new URL("/file",n);return s.searchParams.set("path",e),t&&s.searchParams.set("cwd",t),s.toString()}function Cn(e,t){return e.get(t)||void 0}function Rn(e,t){if("subscriptionRequired"===e){const e="undefined"==typeof window?"en":c(l().language);return"en"===e?"Computer features are free. Update Vibelet on the paired computer and reconnect.":"zh-TW"===e?"電腦端功能免費。請更新配對電腦上的 Vibelet,再重新連線。":"电脑端功能免费。请更新配对电脑上的 Vibelet,再重新连接。"}return"skillNotFound"===e?"Skill not found on the paired computer.":"skillResolveFailed"===e?"Could not load the skill on the paired computer.":e}const En="vibelet.web.savedTargets";function Mn(e){if(!function(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}(e))return null;if("string"!=typeof e.daemonId||"string"!=typeof e.deviceId||"string"!=typeof e.pairToken||"string"!=typeof e.pairedAt)return null;const t="string"==typeof e.displayName?e.displayName:void 0,n="string"==typeof e.label&&e.label.trim()?e.label.trim():t||e.daemonId.slice(0,10);return{daemonId:e.daemonId,deviceId:e.deviceId,pairToken:e.pairToken,pairedAt:e.pairedAt,displayName:t,webSocketUrl:"string"==typeof e.webSocketUrl?e.webSocketUrl:void 0,label:n,lastConnectedAt:"string"==typeof e.lastConnectedAt?e.lastConnectedAt:void 0}}function jn(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const s of e){const e=Mn(s);if(e&&!t.has(e.daemonId)&&(t.add(e.daemonId),n.push(e),n.length>=12))break}return n}function An(e=i()){const t=e.getItem(En);if(!t)return[];try{return jn(JSON.parse(t))}catch{return[]}}function Tn(e,t=i()){t.setItem(En,JSON.stringify(jn(e)))}const Nn={version:"",latestVersion:"",loading:!1,error:null};function Pn(e){const t=e.match(/^\d+/);return t?Number(t[0]):0}function Dn(e,t){return Ve(e,t)||function(e,t){const n=e.split(/[+-]/,1)[0].split(".").map(Pn),s=t.split(/[+-]/,1)[0].split(".").map(Pn),r=Math.max(n.length,s.length);for(let i=0;i<r;i+=1){const e=n[i]??0,t=s[i]??0;if(e<t)return-1;if(e>t)return 1}return 0}(e,t)<0}const Ln="vibelet.web.sessionListCache";function Fn(e){if(!function(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}(e)||"string"!=typeof e.daemonId||!e.daemonId)return null;const t=dn(e.page);return{daemonId:e.daemonId,page:{...t,sessions:t.sessions.slice(0,120)},cachedAt:"string"==typeof e.cachedAt?e.cachedAt:new Date(0).toISOString()}}function On(e){try{const t=JSON.parse(e.getItem(Ln)||"null");return(Array.isArray(t)?t:[t]).map(Fn).filter(e=>null!==e).slice(0,8)}catch{return[]}}function qn(e){return e instanceof Error&&"auth_failed"===e.message}const _n="vibelet.web.composerDrafts",$n={draftsBySessionId:{},newSessionDraft:""};function zn(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function Hn(e){return zn(e)?{draftsBySessionId:zn(e.draftsBySessionId)?Object.fromEntries(Object.entries(e.draftsBySessionId).filter(e=>"string"==typeof e[1])):{},newSessionDraft:"string"==typeof e.newSessionDraft?e.newSessionDraft:""}:$n}function Bn(e=i()){const t=e.getItem(_n);if(!t)return $n;try{return Hn(JSON.parse(t))}catch{return $n}}function Un(e,t=i()){t.setItem(_n,JSON.stringify(Hn(e)))}function Wn(e,t,n){if(!t)return{...e,newSessionDraft:n};const s={...e.draftsBySessionId};return n.trim()?s[t]=n:delete s[t],{...e,draftsBySessionId:s}}function Kn(e,t){return t?e.draftsBySessionId[t]??"":e.newSessionDraft}function Gn(e){switch(e instanceof Error?e.message:String(e)){case"The active turn changed before guidance was accepted":return"turn-changed";case"Claude turn is no longer active":case"Session has no active turn to guide":return"no-active-turn";case"Session is not ready to send queued messages":case"Codex turn is not ready to accept steering input":return"not-ready";case"Selected queued messages are no longer available":case"Queued message is no longer available for guiding":return"stale-selection";case"Resolve the pending request before guiding this turn":case"Resolve the pending request before sending queued messages":return"pending-request";case"The active driver does not support guiding a running turn":return"unsupported";default:return null}}const Qn=["accountActivationCode","account-activation-code","activationCode","activation-code","apiKey","api_key","api-key","x-api-key","accessKey","access-key","accessKeyId","access-key-id","password","secret","secretAccessKey","secret-access-key","token","access-token","refresh-token","security-token","cookie","set-cookie","authorization","proxy-authorization","x-amz-credential","x-amz-security-token","x-amz-signature"],Vn=["authorization","proxy-authorization"],Jn=["cookie","set-cookie"],Zn=[...Vn,...Jn],Xn=(e,t)=>t.length-e.length,Yn=[...Qn].sort(Xn).join("|"),es=Qn.filter(e=>!Zn.includes(e)).sort(Xn).join("|"),ts=[...Vn].sort(Xn).join("|"),ns=[...Jn].sort(Xn).join("|"),ss=new RegExp(`(?:${Yn}|credential|private[-_ ]?key|session[-_ ]?id|e-?mail|phone|mobile|address)`,"i"),rs=new RegExp(`(["']?(?:${ts})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|(?:Basic|Bearer)\\s+[^\\s,;}]+|AWS4-HMAC-SHA256[^\\r\\n]*(?=\\r?$)|[^\\s,;}]+)`,"gim"),is=new RegExp(`(["']?(?:${ns})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\r\\n]+)`,"gi"),os=new RegExp(`(["']?(?:${es})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\s,;}&]+)`,"gi"),as=new RegExp(`([?&](?:${Yn})=)[^&\\s]+`,"gi");function cs(e,t="[REDACTED]"){const n=(e,n,s)=>{const r='"'===s[0]||"'"===s[0]?s[0]:"";if(!r)return`${n}${t}`;const i=s.slice(1,-1).trim(),o=/^(Basic|Bearer)\b/i.exec(i)?.[1];return`${n}${r}${o?`${o} `:""}${t}${r}`};return e.replace(/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gi,t).replace(rs,n).replace(is,n).replace(os,n).replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/gi,`Bearer ${t}`).replace(/\bBasic\s+[A-Za-z0-9+/=_-]+/gi,`Basic ${t}`).replace(/\bsk(?:-proj)?-[A-Za-z0-9_-]{8,}/g,t).replace(/\bgh[pousr]_[A-Za-z0-9]{16,}\b/gi,t).replace(/\bgithub_pat_[A-Za-z0-9_]{16,}\b/gi,t).replace(/\bglpat-[A-Za-z0-9_-]{16,}\b/gi,t).replace(/\bxox[baprs]-[A-Za-z0-9-]{16,}\b/gi,t).replace(/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{12,}\b/gi,t).replace(/\bAIza[0-9A-Za-z_-]{20,}\b/g,t).replace(/\bAKIA[0-9A-Z]{16}\b/g,t).replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\b/g,t).replace(/(https?:\/\/)[^/\s:@]+:[^@\s/]+@/gi,`$1${t}@`).replace(as,`$1${t}`)}function ls(e){return function(e){return e.replace(/(^|[\s("'=])(?:file:\/\/)?\/(?:Users|home|Volumes|private|var|tmp|storage\/emulated\/\d+|data\/user\/\d+|sdcard)[^\r\n"'<>]*?\.[A-Za-z0-9]{1,12}\b/gim,"$1[LOCAL_PATH]").replace(/(^|[\s("'=])(?:file:\/\/)?\/(?:Users|home|Volumes|private|var|tmp|storage\/emulated\/\d+|data\/user\/\d+|sdcard)(?:\/[^\s"'<>]*)?/gim,"$1[LOCAL_PATH]").replace(/\b[A-Z]:\\(?:Users\\)?[^\r\n"'<>]*?\.[A-Za-z0-9]{1,12}\b/gi,"[LOCAL_PATH]").replace(/\b[A-Z]:\\(?:Users\\)?[^\s"'<>]+/gi,"[LOCAL_PATH]").replace(/\\\\[^\s\\"'<>]+\\[^\r\n"'<>]+/g,"[LOCAL_PATH]").replace(/\bcontent:\/\/[^\s"'<>]+/gi,"[LOCAL_PATH]").replace(/\b(?:[\w.-]+\/)+(?:[\w.-]+\.(?:md|txt|json|ya?ml|pdf|docx?|xlsx?|csv|log|db|sqlite|png|jpe?g|webp|gif))\b/gi,"[RELATIVE_PATH]")}(cs(e)).replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/gi,"[EMAIL]").replace(new RegExp("(?<![\\w])(?:\\+?\\d[\\d\\s().-]{7,}\\d)(?![\\w])","g"),"[PHONE]")}async function ds(e){const t=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body,signal:e.signal});return{status:t.status,statusText:t.statusText,body:await t.text()}}async function us(e,t={}){const n=new AbortController,s=Number.isFinite(t.timeoutMs)&&(t.timeoutMs??0)>0?t.timeoutMs:15e3;let r;try{const i=(t.transport??ds)({url:t.endpoint??"https://service.lifeos.vip/feedback",method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:n.signal}),o=new Promise((e,t)=>{r=setTimeout(()=>{n.abort(),t(new Error("Feedback request timed out"))},s)}),a=await Promise.race([i,o]),c=function(e){try{const t=JSON.parse(e);return t&&"object"==typeof t?t:{}}catch{return{}}}(a.body);if(a.status<200||a.status>=300||0!==c.code)throw new Error(c.message||a.statusText||"Feedback request failed");if("string"!=typeof c.data?.id||!c.data.id||"string"!=typeof c.data.createdAt)throw new Error("Feedback response is invalid");return{id:c.data.id,createdAt:c.data.createdAt,issueFingerprint:"string"==typeof c.data?.issueFingerprint?c.data.issueFingerprint:void 0,issueOccurrence:"number"==typeof c.data?.issueOccurrence?c.data.issueOccurrence:void 0}}finally{r&&clearTimeout(r)}}class hs extends Error{constructor(){super("Feedback submission cancelled"),this.name="FeedbackSubmissionCancelledError"}}const ms={contactTitle:"Stay in touch about this feedback",contactReason:"Leave your email so we can contact you when the issue is fixed and ask you to check that it works. Email is optional; you can send feedback without it.",contactSubmit:"Send with email",contactSkip:"Send without email",contactCancel:"Back",contactInvalidEmail:"Enter a valid email, or choose Send without email.",title:"Feedback",subtitle:"Report a problem or suggest an improvement.",bug:"Problem",feature:"Suggestion",description:"Description",descriptionPlaceholder:"What happened, or what would you like to improve?",email:"Email (optional)",emailPlaceholder:"For a reply from the team",includeDiagnostics:"Include privacy-safe diagnostics",privacyNotice:"Only include diagnostics when needed. Recognized credentials, personal identifiers, and local paths are removed before sending.",submit:"Send feedback",sending:"Sending…",success:"Thank you. Your feedback has been sent.",error:"Could not send feedback. Please try again.",close:"Close"},fs={contactTitle:"留下邮箱,方便联系你验证",contactReason:"问题修复后,我们可以通过邮箱联系你,请你确认是否已经恢复正常。邮箱是选填项,不留也可以提交反馈。",contactSubmit:"留下邮箱并提交",contactSkip:"不留邮箱,继续提交",contactCancel:"返回",contactInvalidEmail:"请输入有效邮箱,或选择不留邮箱继续提交。",title:"意见反馈",subtitle:"报告问题,或告诉我们希望改进的地方。",bug:"问题",feature:"建议",description:"详细说明",descriptionPlaceholder:"发生了什么,或者你希望我们怎样改进?",email:"邮箱(选填)",emailPlaceholder:"便于我们回复你",includeDiagnostics:"附带经过隐私处理的诊断信息",privacyNotice:"仅在需要时附带诊断信息;发送前会移除已识别的凭据、个人标识和本地路径。",submit:"发送反馈",sending:"正在发送…",success:"感谢反馈,已经发送成功。",error:"发送失败,请稍后重试。",close:"关闭"},ps={contactTitle:"留下電子郵件,方便聯絡你驗證",contactReason:"問題修復後,我們可以透過電子郵件聯絡你,請你確認是否已恢復正常。電子郵件為選填,不留也可以提交回饋。",contactSubmit:"留下電子郵件並提交",contactSkip:"不留電子郵件,繼續提交",contactCancel:"返回",contactInvalidEmail:"請輸入有效的電子郵件,或選擇不留電子郵件繼續提交。",title:"意見回饋",subtitle:"回報問題,或告訴我們希望改善的地方。",bug:"問題",feature:"建議",description:"詳細說明",descriptionPlaceholder:"發生了什麼,或你希望我們如何改善?",email:"電子郵件(選填)",emailPlaceholder:"方便我們回覆你",includeDiagnostics:"附上經過隱私處理的診斷資訊",privacyNotice:"僅在需要時附上診斷資訊;傳送前會移除已識別的憑證、個人識別資訊和本機路徑。",submit:"傳送回饋",sending:"正在傳送…",success:"感謝回饋,已成功傳送。",error:"傳送失敗,請稍後再試。",close:"關閉"};function gs(e){const t=e?.trim().toLowerCase().replace(/_/g,"-")??"";return/^zh(?:-(?:tw|hk|mo|hant))(?:-|$)/u.test(t)?ps:t.startsWith("zh")?fs:ms}let vs=!1;const ys=({locale:e,email:t})=>vs?Promise.reject(new hs):"undefined"==typeof document?Promise.reject(new Error("Feedback email dialog requires a UI host")):(vs=!0,new Promise((n,s)=>{const r=gs(e),i=document.activeElement,o=document.createElement("div");o.dataset.feedbackEmailPrompt="";const a=o.attachShadow({mode:"open"}),c=document.createElement("style");c.textContent="\n :host { color-scheme: light dark; }\n dialog { box-sizing:border-box; width:min(440px,calc(100vw - 32px)); max-height:calc(100dvh - 32px);\n overflow:auto; padding:24px; border:1px solid light-dark(#dedee4,#44444c); border-radius:20px;\n background:light-dark(#fff,#24242b); color:light-dark(#252530,#f3f3f7); box-shadow:0 20px 80px #0003;\n font:15px/1.5 system-ui,sans-serif; }\n dialog::backdrop { background:#0006; }\n h2 { margin:0 0 10px; font-size:21px; line-height:1.3; }\n p { margin:0 0 20px; color:light-dark(#60606c,#bdbdc9); }\n label { display:block; margin-bottom:7px; font-weight:600; }\n input { box-sizing:border-box; width:100%; min-height:44px; padding:10px 12px; border-radius:10px;\n border:1px solid light-dark(#cfcfd8,#666672); background:light-dark(#fafafa,#303038); color:inherit; font:inherit; }\n input:focus-visible, button:focus-visible { outline:2px solid #8d70c3; outline-offset:3px; }\n .error { min-height:22px; margin:6px 0; color:light-dark(#b42318,#ff9992); font-size:13px; }\n .actions { display:flex; flex-direction:column; gap:8px; }\n button { min-height:44px; padding:10px 12px; border:1px solid light-dark(#dedee4,#555560);\n border-radius:10px; background:transparent; color:inherit; font:inherit; cursor:pointer; }\n .primary { background:light-dark(#eee6f8,#453653); border-color:transparent; font-weight:600; }\n .cancel { border-color:transparent; font-size:13px; }\n ";const l=document.createElement("dialog");l.setAttribute("aria-labelledby","feedback-contact-title"),l.setAttribute("aria-describedby","feedback-contact-reason");const d=document.createElement("h2");d.id="feedback-contact-title",d.textContent=r.contactTitle;const u=document.createElement("p");u.id="feedback-contact-reason",u.textContent=r.contactReason;const h=document.createElement("label");h.htmlFor="feedback-contact-email",h.textContent=r.email;const m=document.createElement("input");m.id=h.htmlFor,m.type="email",m.inputMode="email",m.autocomplete="email",m.maxLength=320,m.value=t??"",m.placeholder=r.emailPlaceholder;const f=document.createElement("div");f.className="error",f.id="feedback-contact-error",f.setAttribute("role","alert"),m.setAttribute("aria-describedby",f.id);const p=document.createElement("div");p.className="actions";let g=!1;const v=(e,t)=>{g||(g=!0,l.close(),o.remove(),vs=!1,i?.focus(),e?s(new hs):n(t))},y=(e,t,n)=>{const s=document.createElement("button");s.type="button",s.className=t,s.textContent=e,s.onclick=n,p.append(s)},b=()=>{if(!function(e){return e.trim().length<=320&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/u.test(e.trim())}(m.value))return f.textContent=r.contactInvalidEmail,m.setAttribute("aria-invalid","true"),void m.focus();v(!1,m.value.trim())};y(r.contactSubmit,"primary",b),y(r.contactSkip,"skip",()=>v(!1)),y(r.contactCancel,"cancel",()=>v(!0)),m.oninput=()=>{f.textContent="",m.removeAttribute("aria-invalid")},l.addEventListener("keydown",e=>{e.stopPropagation(),"Escape"===e.key&&(e.preventDefault(),v(!0)),"Enter"!==e.key||e.target!==m||e.isComposing||(e.preventDefault(),b())}),l.addEventListener("cancel",e=>{e.preventDefault(),v(!0)}),l.append(d,u,h,m,f,p),a.append(c,l),document.body.append(o);try{l.showModal(),m.focus()}catch(w){o.remove(),vs=!1,s(w)}})),bs=new Set(["action","app","automatic","browser","buildNumber","contextSchemaVersion","correlationId","debugEnabled","deviceFingerprint","diagnosticSchemaVersion","entry","errorCode","errorMessage","module","pagePath","pageTitle","pageUrl","pluginId","privacy","providerPreset","reportKind","resultKind","runtime","screen","storageType","updateChannel","userAgent"]);function ws(e){const t={contextSchemaVersion:1};if(e)for(const[n,s]of Object.entries(e))bs.has(n)&&void 0!==s&&(t[n]=s);return function(e,t={}){if(!e)return{};const n=Math.max(0,t.characterBudget??6e4),s=Math.max(0,t.maxArrayEntries??50),r=Math.max(0,t.maxDepth??8),i=Math.max(0,t.maxObjectEntries??80),o=Math.max(0,t.maxStringLength??4e3),a={remaining:n},c=new WeakSet,l=(e,t)=>{if(a.remaining<=0)return"[TRUNCATED]";if(null===e||"boolean"==typeof e||"number"==typeof e)return e;if("bigint"==typeof e)return e.toString();if("string"==typeof e){const t=ls(e).slice(0,Math.min(o,a.remaining));return a.remaining-=t.length,t}if(t>=r)return"[MAX_DEPTH]";if("object"!=typeof e)return ls(String(e)).slice(0,Math.min(200,a.remaining));if(c.has(e))return"[Circular]";if(c.add(e),Array.isArray(e))return e.slice(0,s).map(e=>l(e,t+1));const n={};for(const[s,r]of Object.entries(e).slice(0,i)){if(a.remaining<=0)break;const e=ls(s).slice(0,Math.min(120,a.remaining));a.remaining-=e.length,n[e]=ss.test(s)?"[REDACTED]":l(r,t+1)}return n};return l(e,0)}(t)}const Ss=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function xs(e){if(!e?.length)return;if(e.length>4)throw new Error("Feedback supports at most 4 images");const t=e.map(e=>{if(!Ss.has(e.mimeType))throw new Error("Feedback image type is not supported");const t=function(e){if(!e||e.length%4!=0||!/^[A-Za-z0-9+/]*={0,2}$/u.test(e))return;const t=e.endsWith("==")?2:e.endsWith("=")?1:0;return e.length/4*3-t}(e.base64);if(!Number.isSafeInteger(e.size)||e.size<=0||t!==e.size)throw new Error("Feedback image size does not match its data");return{name:ls(e.name.trim()||"image").slice(0,255),mimeType:e.mimeType,size:e.size,base64:e.base64}});if(t.reduce((e,t)=>e+t.size,0)>20971520)throw new Error("Feedback images are too large");return t}function Is(e){const t=e.toLowerCase();return/subscription|required|upgrade|billing/u.test(t)?"subscription":/skillnotfound|not found|missing/u.test(t)?"missing-resource":/permission|forbidden|unauthorized|denied/u.test(t)?"permission":/failed to reconnect|startup deadline exceeded/u.test(t)?"reconnect":/timeout|timed out/u.test(t)?"timeout":/process exited|reconnected concurrently/u.test(t)?"reconnect":/websocket|network|disconnect|connection|offline|closed/u.test(t)?"network":"unknown"}const ks=13e4;function Cs(e){return cs(e).trim()}function Rs(e,t,n){const s=new Set(e);return n?s.add(t):s.delete(t),s}async function Es(e){return{[e]:"desktop-free"}}const Ms={en:{mode:"Default send mode",queue:"Queue",queueHelp:"Wait until the current turn finishes.",guide:"Guide",guideHelp:"Guide the active turn; queue when unavailable.",unsupported:"This daemon does not support guidance; the message remains queued."},zh:{mode:"默认发送方式",queue:"排队",queueHelp:"等待当前回合完成后发送。",guide:"引导",guideHelp:"引导当前回合,暂不可用时排队。",unsupported:"此服务不支持引导,消息已保留在队列。"},"zh-TW":{mode:"預設傳送方式",queue:"排隊",queueHelp:"等待目前回合完成後傳送。",guide:"引導",guideHelp:"引導目前回合,暫不可用時排隊。",unsupported:"此服務不支援引導,訊息已保留在佇列。"}};async function js(e,t,n,r){const i=l(),o="desktop"===s().kind&&"guide"===i.composer.sendMode,a=await e.request(t,n);if(!o||!an(a)||!0!==a.queued)return a;const d=Ms[c(l().language)];try{if(!e.supportsSessionSteer)throw new Error(d.unsupported);await e.request({action:"session.steer",id:e.makeId("guide"),sessionId:"string"==typeof a.sessionId?a.sessionId:t.sessionId,clientMessageId:t.clientMessageId,message:t.message,images:t.images},n)}catch(u){r(`${d.guide}: ${u instanceof Error?u.message:String(u)}`)}return a}function As(){let e=[];const t=new Set,n=new Set,s=()=>{e=[...t].map(e=>({...e})),n.forEach(e=>e())};return{getSnapshot:()=>e,has:e=>[...t].some(t=>t.sessionId===e),subscribe:e=>(n.add(e),()=>{n.delete(e)}),start(e){const n={sessionId:e};return t.add(n),s(),{remap(e){t.has(n)&&(n.sessionId=e,s())},finish(){t.delete(n)&&s()}}}}}const Ts=[{name:"clear",commandName:"clear",title:"Clear session",description:"Clear this session in place.",source:"Vibelet",agents:["claude","codex"],argsHint:""},{name:"new",commandName:"new",title:"New session",description:"Start a fresh session with the same assistant and directory.",source:"Vibelet",agents:["claude","codex"],argsHint:""},{name:"exit",commandName:"exit",title:"Archive session",description:"Archive this session and return to the session list.",source:"Vibelet",agents:["claude","codex"],argsHint:""},{name:"quit",commandName:"exit",title:"Archive session",description:"Alias for /exit.",source:"Vibelet",agents:["claude","codex"],argsHint:""},{name:"q",commandName:"exit",title:"Archive session",description:"Alias for /exit.",source:"Vibelet",agents:["claude","codex"],argsHint:""},{name:"compact",commandName:"compact",title:"Compact context",description:"Ask the assistant runtime to compact the current session.",source:"Native",agents:["claude","codex"],argsHint:""},{name:"goal",commandName:"goal",title:"Goal",description:"View, set, pause, resume, or clear the current goal.",source:"Native",agents:["claude","codex"],argsHint:"[objective|status|pause|resume|clear]"}];function Ns(e){return Ts.filter(t=>!e||t.agents.includes(e))}function Ps(e){return e.trim().toLowerCase()}function Ds(e,t,n=8){const s=Ps(t);return(s?e.filter(e=>e.name.includes(s)||e.title.toLowerCase().includes(s)).sort((e,t)=>Ls(e,s)-Ls(t,s)):[...e]).slice(0,n)}function Ls(e,t){return e.name===t?0:e.name.startsWith(t)?1:e.name.includes(t)?2:3}function Fs(e,t){const n=e.trim();if(!n.startsWith("/")||n.startsWith("//"))return null;const s=/^\/([A-Za-z][A-Za-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(n);if(!s)return null;const r=Ps(s[1]??""),i=Ns(t).find(e=>e.name===r);if(!i)return null;const o=s[2]?.trim()??"";switch(i.commandName){case"clear":return{raw:n,command:{name:"clear"}};case"new":return{raw:n,command:{name:"new"}};case"exit":return{raw:n,command:{name:"exit"}};case"compact":return{raw:n,command:{name:"compact"}};case"goal":{const e=o.toLowerCase();return o&&"status"!==e&&"show"!==e&&"usage"!==e&&"help"!==e?"clear"===e||"reset"===e?{raw:n,command:{name:"goal",operation:"clear"}}:"pause"===e||"paused"===e?{raw:n,command:{name:"goal",operation:"pause"}}:"resume"===e||"active"===e?{raw:n,command:{name:"goal",operation:"resume"}}:{raw:n,command:{name:"goal",operation:"set",objective:o}}:{raw:n,command:{name:"goal",operation:"status"}}}}}function Os(e){return"subscriptionRequired"===e?"Error: Agent commands require an active Pro subscription.":`Error: ${e||"Command failed."}`}function qs(e){return e.trim().toLowerCase()}function _s(e){const t=e.trim(),n=/^\$([A-Za-z_][A-Za-z0-9._:-]*)(?:\s+([\s\S]*))?$/.exec(t);return n?{name:qs(n[1]??""),...n[2]?.trim()?{args:n[2].trim()}:{}}:null}function $s(e,t,n=8){const s=qs(t);return(s?e.filter(e=>qs(e.name).includes(s)):e).slice(0,n)}function zs(e,t,n){const s=Kn(e.composerDraftsRef.current,e.activeSessionId),r=s===t?s:[s,t].filter(Boolean).join("\n\n"),i=Wn(e.composerDraftsRef.current,e.activeSessionId,r);e.composerDraftsRef.current=i,e.setComposerDrafts(i),e.activeSessionIdRef.current===e.activeSessionId&&e.setDraft(r);try{Un(i)}catch{}e.setAttachments(e=>[...e,...n.filter(t=>!e.some(e=>e.path===t.path))])}function Hs(e){for(let t=(e?.length??0)-1;t>=0;t-=1){const n=e[t];if("user"===n.role)return"failed"===n.localDelivery?n:void 0}}function Bs(e,t,n=!1){const s="interrupted"===e.delivery?"interrupted":n||"accepted"===e.delivery?"delivered":e.localDelivery;if("user"!==e.role||!s)return null;const r="浏览器"===t.browser?{interrupted:"已中断",sending:"发送中",delivered:"已送达",failed:"未确认送达",hint:"配对电脑已接收,可以退出客户端。任务将由 daemon 继续处理。"}:"瀏覽器"===t.browser?{interrupted:"已中斷",sending:"傳送中",delivered:"已送達",failed:"未確認送達",hint:"配對電腦已接收,可以退出客戶端。任務將由 daemon 繼續處理。"}:{interrupted:"Interrupted",sending:"Sending",delivered:"Delivered",failed:"Delivery unconfirmed",hint:"Received by the paired computer. You can quit the client; the daemon will continue processing."};return{state:s,label:r[s],title:"delivered"===s?r.hint:r[s]}}const Us=e=>e?.trim()?e:void 0,Ws="Session send timed out.";function Ks(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function Gs(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function Qs(e=window.location.search){const t=new URLSearchParams(e),n=Gs(t.get("folder")),s=Gs(t.get("file")),r=Gs(t.get("cwd"));return{...n?{folder:n}:{},...s?{file:s}:{},...r?{cwd:r}:{}}}function Vs(e,t={}){const n=t.history??window.history,s=t.location??window.location,r=[];e.folder&&r.push("file","cwd"),e.file&&r.push("folder");const i=function(e,t,n=[]){const s=new URLSearchParams(e);for(const i of n)s.delete(i);for(const[i,o]of Object.entries(t))o?s.set(i,o):s.delete(i);const r=s.toString();return r?`?${r}`:""}(s.search,e,r),o=`${s.pathname}${i}${s.hash}`;t.replace?n.replaceState(null,"",o):n.pushState(null,"",o)}const Js={en:{rewind:"Rewind to here",rewinding:"Rewinding conversation… The selected message will return to the composer when ready.",confirmRewind:"Continue in a new branch before this message? The original conversation will be archived and preserved. The selected message will become a draft; no message will be sent. Files will not change.",incompleteHistory:"This conversation has older history that is not loaded. Rewinding is unavailable to avoid selecting the wrong turn.",unavailable:"This message is no longer available.",rewindFailed:"Unable to rewind this conversation.",invalidResponse:"Invalid rewind response.",mediaError:"This format cannot be played here. Download the file to open it.",remoteSettings:"Sessions and remote devices",htmlPreview:"HTML preview",pdfPreview:"PDF preview",audioPreview:"Audio preview",videoPreview:"Video preview"},zh:{rewind:"回退到这里",rewinding:"正在回退会话…完成后,所选消息会回到输入框。",confirmRewind:"从这条消息之前建立新分支继续?原会话会归档保留,所选消息会填入草稿,不会自动发送,文件不会改变。",incompleteHistory:"此会话还有未加载的历史,暂时不能回退,以免选错消息位置。",unavailable:"这条消息已不可用。",rewindFailed:"无法回退此会话。",invalidResponse:"回退响应无效。",mediaError:"此格式无法在这里播放,请下载后打开。",remoteSettings:"会话与远程设备",htmlPreview:"HTML 预览",pdfPreview:"PDF 预览",audioPreview:"音频预览",videoPreview:"视频预览"},"zh-TW":{rewind:"回退到這裡",rewinding:"正在回退對話…完成後,所選訊息會回到輸入框。",confirmRewind:"從這則訊息之前建立新分支繼續?原對話會封存保留,所選訊息會填入草稿,不會自動傳送,檔案不會改變。",incompleteHistory:"此對話還有未載入的歷史,暫時不能回退,以免選錯訊息位置。",unavailable:"這則訊息已無法使用。",rewindFailed:"無法回退此對話。",invalidResponse:"回退回應無效。",mediaError:"此格式無法在這裡播放,請下載後開啟。",remoteSettings:"對話與遠端裝置",htmlPreview:"HTML 預覽",pdfPreview:"PDF 預覽",audioPreview:"音訊預覽",videoPreview:"影片預覽"}};function Zs(){return Js[c(l().language)]}const Xs="vibelet.web.sessionSettings";function Ys(e,n){t.useEffect(()=>{e.current=n},[e,n])}async function er(e,t,n){for(let r=0;r<2&&n();r++)try{return await e.request(t(),{timeoutMs:135e3})}catch(s){if(!(s instanceof Error&&/timeout|timed out/i.test(s.message)))return}}class tr{constructor(e,t,n){this.storage=e,this.key=t,this.isReading=n;try{const n=JSON.parse(e?.getItem(t)??"null");if(n&&"object"==typeof n){const e=n,t=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[];if(this.observed=new Set(t(e.observed)),this.unseen=new Set(t(e.unseen)),Array.isArray(e.failed))for(const n of e.failed)Array.isArray(n)&&2===n.length&&n.every(e=>"string"==typeof e)&&this.failed.set(n[0],n[1])}}catch{}this.recovered=new Set(this.observed),this.snapshot=new Set([...this.unseen,...this.failed.values()])}observed=new Set;failed=new Map;unseen=new Set;recovered=new Set;suppressed=new Set;runtime=new Map;listeners=new Set;snapshot=new Set;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;save(){try{this.storage?.setItem(this.key,JSON.stringify({observed:[...this.observed].slice(-256),unseen:[...this.unseen].slice(-256),failed:[...this.failed].slice(-256)}))}catch{}const e=new Set([...this.unseen,...this.failed.values()]);this.snapshot.size===e.size&&[...e].every(e=>this.snapshot.has(e))||(this.snapshot=e,this.listeners.forEach(e=>e()))}deliveryChanged=(e,t,n)=>{if("failed"===n){if(this.failed.get(t)===e)return;this.failed.set(t,e)}else if(!this.failed.delete(t))return;this.save()};reconcileDeliveries=(e,t)=>{for(const[s,r]of this.failed)r===e&&this.failed.delete(s);const n=Hs(t);n?.localClientMessageId&&this.failed.set(n.localClientMessageId,e),this.save()};deliveryRemoved=(e,t)=>{this.failed.delete(t)&&this.save()};observe=e=>{this.suppressed.delete(e),this.observed.has(e)||(this.observed.add(e),this.save())};complete=e=>{this.observed.delete(e)&&(this.suppressed.add(e),this.recovered.delete(e),this.isReading(e)?this.unseen.delete(e):this.unseen.add(e),this.save())};reconcile=(e,t)=>{const n=this.runtime.get(e);this.runtime.set(e,t),t?this.suppressed.has(e)||!0===n||this.observe(e):((!0===n||this.recovered.has(e))&&this.observed.has(e)&&this.complete(e),this.suppressed.delete(e))};acknowledgeOpened=e=>{this.unseen.delete(e)&&this.save()};acknowledgeVisible=()=>{let e=!1;for(const t of this.unseen)this.isReading(t)&&(this.unseen.delete(t),e=!0);e&&this.save()};remap=(e,t)=>{for(const n of[this.observed,this.unseen,this.suppressed,this.recovered])n.delete(e)&&n.add(t);this.runtime.has(e)&&(this.runtime.set(t,this.runtime.get(e)),this.runtime.delete(e));for(const[n,s]of this.failed)s===e&&this.failed.set(n,t);this.save()}}function nr(e){return!("undefined"==typeof document||"visible"!==document.visibilityState||!document.hasFocus())&&[...document.querySelectorAll(".message-scroll")].some(t=>t.dataset.sessionId===e&&t.getClientRects().length>0&&"false"===t.dataset.historyLoading)}const sr=new Set;function rr(e){return sr.add(e),()=>{sr.delete(e)}}const ir="vibelet.workspace.flush",or="vibelet:file-operation-before",ar="vibelet:file-operation-done";function cr(e,t=""){const n=e.replace(/\\/g,"/"),s=/^(\/|[a-z]:\/|~)/i.test(n)?n:`${t.replace(/\\/g,"/")}/${n}`,r=[];for(const i of s.split("/"))i&&"."!==i&&(".."===i?r.pop():r.push(i));return`${s.startsWith("/")?"/":""}${r.join("/")}`}function lr(e,t,n){const s=cr(e,n),r=cr(t,n);return s===r||s.startsWith(`${r}/`)}async function dr(e,t){const n=new CustomEvent(or,{cancelable:!0,detail:{...e,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd}});if(!window.dispatchEvent(n))throw new Error("unsaved_changes");const s=await fetch("/file-operation",{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.pairToken}`},body:JSON.stringify(e)}),r=await s.text();let i;try{i=JSON.parse(r)}catch{throw new Error(404===s.status||/^Vibelet Daemon v/.test(r)?"daemon_update_required":"operation_failed")}if(404===s.status&&"ENOENT"!==i.error)throw new Error("daemon_update_required");if(!s.ok)throw new Error(i.error??"operation_failed");return window.dispatchEvent(new CustomEvent(ar,{detail:{...i,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd,source:e.path}})),i}async function ur(e,t,n,s){const r=AbortSignal.timeout(12e4),i=await fetch(`/upload?name=${encodeURIComponent(e.name)}`,{method:"POST",signal:AbortSignal.any([n,r]),headers:{authorization:`Bearer ${t}`,"content-type":e.type||"application/octet-stream"},body:e});if(!i.ok)throw new Error(await i.text().catch(()=>s.uploadFailed)||s.uploadFailed);const o=function(e){const t=e;return"string"==typeof t.path?t.path:null}(await i.json());if(!o)throw new Error(s.uploadPathMissing);return{path:o,name:e.name,type:e.type||"application/octet-stream",size:e.size}}function hr(e,t,n){const s=t.split(";")[0].trim().toLowerCase();return s.startsWith("image/")?"image":"text/html"===s||/\.html?$/i.test(e)?"html":"application/pdf"===s||/\.pdf$/i.test(e)?"pdf":s.startsWith("audio/")||/\.(mp3|wav|m4a|ogg|flac)$/i.test(e)?"audio":s.startsWith("video/")||/\.(mp4|m4v|webm|mov|ogv)$/i.test(e)?"video":n?"text":"unsupported"}function mr(e){return`<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data: blob:; media-src data: blob:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; base-uri 'none'; form-action 'none'"><script>\n(function() {\n function createStorage() {\n var values = new Map();\n var api = Object.create(null);\n Object.defineProperties(api, {\n length: { configurable: true, get: function() { return values.size; } },\n key: { configurable: true, value: function(index) { return Array.from(values.keys())[Number(index) >>> 0] ?? null; } },\n getItem: { configurable: true, value: function(key) { return values.get(String(key)) ?? null; } },\n setItem: { configurable: true, value: function(key, value) { values.set(String(key), String(value)); } },\n removeItem: { configurable: true, value: function(key) { values.delete(String(key)); } },\n clear: { configurable: true, value: function() { values.clear(); } }\n });\n return new Proxy(api, {\n get: function(target, key) { return Reflect.has(target, key) ? Reflect.get(target, key) : values.get(String(key)); },\n set: function(target, key, value) { values.set(String(key), String(value)); return true; },\n deleteProperty: function(target, key) { values.delete(String(key)); return true; },\n has: function(target, key) { return Reflect.has(target, key) || values.has(String(key)); },\n ownKeys: function() { return Array.from(values.keys()); },\n getOwnPropertyDescriptor: function(target, key) {\n if (values.has(String(key))) return { configurable: true, enumerable: true, writable: true, value: values.get(String(key)) };\n return Reflect.getOwnPropertyDescriptor(target, key);\n }\n });\n }\n ['localStorage', 'sessionStorage'].forEach(function(name) {\n try { if (window[name]) return; } catch (_) {}\n Object.defineProperty(window, name, { configurable: true, value: createStorage() });\n });\n})();\n<\/script>${e}`}const fr=e=>/^(https?:|data:|blob:)/i.test(e.path)?e.path:cr(e.path,e.cwd);function pr(e,t){return Boolean(t)&&Object.hasOwn(e,t)}function gr(e,t,n){return t&&0!==n.length?{...e,[t]:Lt(e[t]??[],n)}:e}function vr(e,t){const n=new Map,s=Lt(e,t,(e,t)=>{t.localClientMessageId&&n.set(e,t)}),r=t.map(e=>{const t=n.get(e);return t?{...e,timestamp:Number.isFinite(Date.parse(e.timestamp??""))?e.timestamp:t.timestamp,localClientMessageId:t.localClientMessageId,localDelivery:t.localDelivery}:{...e}}),i=new Set(r.map(e=>e.localClientMessageId));return function(e,t,n){const s=e.map(e=>{if(e.liveReply){const t=n.slice().reverse().find(t=>t.liveReply&&t.content.length>0&&(e.content.startsWith(t.content)||t.content.startsWith(e.content)));if(t?.timestamp)return{...e,timestamp:t.timestamp}}return e});for(const r of t){const e=Date.parse(r.timestamp??"");let t=Number.isFinite(e)?s.findIndex(t=>{const s=Date.parse(t.timestamp??"");if(s!==e)return s>e;if("assistant"!==t.role)return!1;const i=n.findIndex(e=>t.historyKey&&e.historyKey===t.historyKey||t.liveReply&&e.liveReply&&e.timestamp===t.timestamp);return i<0||n.indexOf(r)<i}):-1;if(!Number.isFinite(e)){const e=n.indexOf(r),i=n.slice(e+1);if(t=s.findIndex(e=>i.some(t=>t===e||t.historyKey&&t.historyKey===e.historyKey)),t<0){const r=n.slice(0,e);t=s.findLastIndex(e=>r.some(t=>t===e||t.historyKey&&t.historyKey===e.historyKey))+1}}s.splice(t<0?s.length:t,0,r)}return s}(r,s.filter(e=>e.localClientMessageId&&e.historyKey?.startsWith("client:")&&!i.has(e.localClientMessageId)),e)}function yr(e){return e.historyKey?`key:${e.historyKey}`:e.rewindPoint?`rewind:${e.role}:${Ct(e.rewindPoint)}`:e.timestamp?JSON.stringify([e.timestamp,e.role,e.type,e.content,e.images,e.toolName,e.toolInput]):void 0}const br="vibelet.web.historyDiskCache.v1";function wr(){try{const e=JSON.parse(i().getItem(br)||"[]");return Array.isArray(e)?e.filter(e=>e&&"string"==typeof e.daemonId&&"string"==typeof e.sessionId&&Array.isArray(e.messages)&&e.messages.every(e=>e&&["user","assistant","tool"].includes(e.role)&&"string"==typeof e.content)).slice(0,40):[]}catch{return[]}}function Sr(e,t){try{const n=wr().filter(n=>n.daemonId!==e||!Object.hasOwn(t,n.sessionId));for(const[r,i]of Object.entries(t)){if(!i)continue;const t={daemonId:e,sessionId:r,messages:i.slice(-1e3)};for(;t.messages.length&&(new TextEncoder).encode(JSON.stringify(t)).length>524288;)t.messages.shift();(t.messages.length||0===i.length)&&n.unshift(t)}const s=n.slice(0,40);for(;s.length&&(new TextEncoder).encode(JSON.stringify(s)).length>2097152;)s.pop();i().setItem(br,JSON.stringify(s))}catch{}}const xr=new Set(["attachmentCount","domNodes","durationMs","errorKind","failureKind","longTaskCount","maxLongTaskMs","online","phase","visibilityState"]);function Ir(e){return e instanceof TypeError?"TypeError":e instanceof RangeError?"RangeError":e instanceof SyntaxError?"SyntaxError":e instanceof Error?"Error":"string"==typeof e?"string":typeof e}function kr(e,t){return t.has(e.sessionId)||!0===e.runtime?.isResponding||"daemonActive"===e.runtime?.state||"externalRunning"===e.runtime?.state}function Cr(e,t,n){return e.replace(/tailcat/gi,t).replace(/(?:https?:\/\/|wss?:\/\/)?\b127\.0\.0\.1\b(?::\d+)?/gi,n)}class Rr{cleared=new Map;live(e,t,n){const s=new Set(n.map(e=>e.clientMessageId)),r=this.cleared.get(t)??new Set;for(const i of e[t]??[])i.clientMessageId&&!s.has(i.clientMessageId)&&r.add(i.clientMessageId);for(const i of s)i&&r.delete(i);return this.cleared.set(t,r),{...e,[t]:n}}confirmRemoval(e,t){const n=this.cleared.get(e)??new Set;t.forEach(e=>n.add(e)),this.cleared.set(e,n)}snapshot(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.filter(t=>!t.clientMessageId||!this.cleared.get(e)?.has(t.clientMessageId))]))}remap(e,t){const n=this.cleared.get(e);n&&(this.cleared.set(t,new Set([...this.cleared.get(t)??[],...n])),this.cleared.delete(e))}}const Er="vibelet.session.command",Mr=[{id:"sessionOpen",zh:"会话:打开",en:"Session: Open",default:""},{id:"sessionRename",zh:"会话:重命名",en:"Session: Rename",default:""},{id:"sessionDetails",zh:"会话:详情",en:"Session: Details",default:""},{id:"sessionCopyResume",zh:"会话:复制恢复命令",en:"Session: Copy resume command",default:""},{id:"sessionResumeTerminal",zh:"会话:在终端恢复",en:"Session: Resume in terminal",default:""},{id:"sessionPin",zh:"会话:置顶 / 取消置顶",en:"Session: Toggle pinned",default:""},{id:"sessionArchive",zh:"会话:归档 / 取消归档",en:"Session: Toggle archived",default:""},{id:"sessionDelete",zh:"会话:删除",en:"Session: Delete",default:""}],jr="vibelet.shortcuts.changed",Ar="vibelet.workspace.command",Tr=[...Mr,{id:"leftSidebar",zh:"显示 / 隐藏左侧栏",en:"Toggle left sidebar",default:"mod+alt+["},{id:"rightSidebar",zh:"显示 / 隐藏右侧栏",en:"Toggle right sidebar",default:"mod+alt+]"},{id:"previousSession",zh:"上一个会话",en:"Previous session",default:""},{id:"nextSession",zh:"下一个会话",en:"Next session",default:""},{id:"searchSessions",zh:"搜索会话",en:"Search sessions",default:"mod+shift+f"},{id:"commandMode",zh:"打开命令模式",en:"Open command mode",default:"mod+p"},{id:"quickSearch",zh:"快速定位会话 / 标签",en:"Quick switch sessions / tabs",default:"mod+k"},{id:"searchMessages",zh:"查找聊天 / 浏览器 / 终端",en:"Find in chat / browser / terminal",default:"mod+f"},{id:"findNext",zh:"下一个匹配项",en:"Next match",default:"mod+g"},{id:"findPrevious",zh:"上一个匹配项",en:"Previous match",default:"mod+shift+g"},{id:"files",zh:"打开文件树",en:"Open files",default:"mod+alt+e"},{id:"terminal",zh:"打开终端",en:"Open terminal",default:"mod+j"},{id:"browser",zh:"打开浏览器",en:"Open browser",default:"mod+alt+b"},{id:"browserAddress",zh:"聚焦浏览器地址栏",en:"Focus browser address",default:"mod+l"},{id:"browserCopyUrl",zh:"复制浏览器地址",en:"Copy browser address",default:"mod+shift+c"},{id:"newTab",zh:"新建终端 / 浏览器标签",en:"New terminal / browser tab",default:"mod+t"},{id:"previousTab",zh:"上一个标签",en:"Previous tab",default:"mod+shift+["},{id:"nextTab",zh:"下一个标签",en:"Next tab",default:"mod+shift+]"},{id:"closeTab",zh:"关闭当前标签",en:"Close current tab",default:"mod+w"},{id:"reopenTab",zh:"恢复已关闭的终端 / 浏览器标签",en:"Reopen closed terminal / browser tab",default:"mod+shift+t"},{id:"moveTab",zh:"在中间区域与右侧栏间移动标签",en:"Move tab between workspace and sidebar",default:"mod+shift+m"},{id:"diff",zh:"查看 Git 变更",en:"View Git changes",default:"mod+alt+g"}];function Nr(){return/Mac|iPhone|iPad/.test(navigator.platform)}function Pr(e,t=Nr()){return t?e.metaKey&&!e.ctrlKey:e.ctrlKey&&!e.metaKey}const Dr={BracketLeft:"[",BracketRight:"]",Comma:",",Period:".",Slash:"/",Backslash:"\\",Minus:"-",Equal:"=",Space:"space"};function Lr(e,t=Nr()){const n=Dr[e.code]||(/^Key[A-Z]$/.test(e.code)?e.code.slice(3).toLowerCase():/^Digit\d$/.test(e.code)?e.code.slice(5):e.key.toLowerCase());return["meta","control","alt","shift","dead"].includes(n)||!(e.metaKey||e.ctrlKey||e.altKey)?null:[t?e.metaKey&&"mod":e.ctrlKey&&"mod",t?e.ctrlKey&&"ctrl":e.metaKey&&"meta",e.altKey&&"alt",e.shiftKey&&"shift",n].filter(Boolean).join("+")}function Fr(e,t=Nr()){const n=t?{mod:"⌘",ctrl:"⌃",meta:"⌘",alt:"⌥",shift:"⇧",space:"Space",enter:"Enter"}:{mod:"Ctrl",ctrl:"Ctrl",meta:/Win/.test(navigator.platform)?"Win":"Super",alt:"Alt",shift:"Shift",space:"Space",enter:"Enter"};return Object.assign(n,{arrowup:"↑",arrowdown:"↓",arrowleft:"←",arrowright:"→"}),e.split("+").map(e=>n[e]||e.toUpperCase()).join(t?"":"+")}function Or(e,t,n,s=Nr()){return t?"mod+w"===t?"closeTab"===e?null:"reserved":!s&&["mod+y","alt+f4"].includes(t)||t===(s?"ctrl+tab":"mod+tab")||t===(s?"ctrl+shift+tab":"mod+shift+tab")||["mod+n","mod+alt+n","mod+,","mod+q","mod+c","mod+v","mod+x","mod+a","mod+z","mod+shift+z","mod+s","mod+r","mod+h","mod+m","mod+-","mod+=","mod+shift+="].includes(t)?"reserved":Tr.find(s=>s.id!==e&&function(e,t={}){return t[e]??Tr.find(t=>t.id===e).default}(s.id,n)===t)?.id??null:null}const qr="vibelet.web.shortcuts";function _r(){try{const e=JSON.parse(i().getItem(qr)||"{}");return Object.fromEntries(Tr.filter(t=>"string"==typeof e?.[t.id]).map(t=>[t.id,e[t.id]]))}catch{return{}}}function $r(e,t=_r()){return t[e]??("closeTab"===e&&"browser"===s().kind?"mod+alt+w":Tr.find(t=>t.id===e).default)}function zr(e,t){const n=$r(t);return n?`${e} (${Fr(n)})`:e}const Hr="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='-3%20-3%2041%2041'%20shape-rendering='crispEdges'%3e%3cpath%20fill='%23ffffff'%20d='M-3%20-3h41v41H-3z'/%3e%3cpath%20stroke='%23000000'%20d='M1%201.5h7m2%200h2m2%200h1m2%200h1m1%200h2m1%200h1m1%200h1m2%200h7M1%202.5h1m5%200h1m2%200h1m3%200h5m3%200h1m2%200h1m1%200h1m5%200h1M1%203.5h1m1%200h3m1%200h1m1%200h1m1%200h1m2%200h1m1%200h2m1%200h6m2%200h1m1%200h3m1%200h1M1%204.5h1m1%200h3m1%200h1m1%200h3m3%200h4m1%200h4m1%200h1m1%200h1m1%200h3m1%200h1M1%205.5h1m1%200h3m1%200h1m1%200h1m2%200h3m1%200h1m1%200h3m1%200h2m3%200h1m1%200h3m1%200h1M1%206.5h1m5%200h1m1%200h2m2%200h6m3%200h2m3%200h1m5%200h1M1%207.5h7m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h7M9%208.5h1m1%200h1m4%200h1m3%200h4M1%209.5h1m1%200h5m2%200h1m1%200h7m1%200h1m2%200h1m1%200h1m1%200h5M3%2010.5h2m1%200h1m2%200h2m1%200h1m3%200h2m1%200h4m1%200h1m2%200h2m1%200h2M1%2011.5h2m1%200h1m2%200h5m4%200h1m4%200h1m1%200h1m1%200h2m2%200h1m1%200h2M1%2012.5h3m1%200h1m2%200h3m2%200h1m1%200h1m3%200h2m1%200h3m1%200h1m2%200h5M2%2013.5h1m1%200h1m2%200h3m1%200h3m2%200h1m2%200h1m3%200h2m1%200h1m1%200h1m1%200h1m1%200h1M2%2014.5h3m1%200h1m3%200h2m3%200h3m1%200h3m2%200h2m6%200h2M1%2015.5h2m1%200h1m1%200h2m4%200h3m3%200h1m2%200h2m2%200h3m1%200h4M1%2016.5h1m1%200h3m2%200h1m2%200h2m1%200h1m2%200h1m1%200h1m1%200h8m1%200h2M3%2017.5h7m1%200h2m1%200h2m1%200h2m4%200h4m1%200h2m1%200h1m1%200h1M2%2018.5h2m4%200h1m1%200h2m1%200h1m2%200h13m1%200h4M1%2019.5h1m2%200h5m1%200h1m1%200h7m7%200h1m1%200h2m1%200h1M1%2020.5h3m5%200h1m1%200h2m1%200h1m2%200h8m2%200h5m1%200h1M1%2021.5h1m1%200h6m1%200h1m1%200h1m1%200h1m2%200h1m2%200h1m1%200h2m1%200h2m1%200h3M1%2022.5h1m1%200h2m1%200h1m1%200h2m1%200h6m1%200h2m1%200h2m1%200h1m2%200h1m2%200h1m2%200h1M1%2023.5h1m2%200h2m1%200h5m2%200h4m1%200h1m1%200h1m3%200h2m2%200h1m2%200h1M1%2024.5h1m2%200h1m5%200h1m1%200h5m3%200h4m1%200h3m1%200h3m1%200h1M1%2025.5h1m3%200h3m4%200h3m1%200h1m1%200h1m4%200h7m1%200h2M9%2026.5h1m1%200h2m1%200h2m3%200h2m1%200h1m1%200h2m3%200h1m1%200h1m1%200h1M1%2027.5h7m2%200h1m1%200h2m1%200h3m1%200h1m1%200h1m2%200h2m1%200h1m1%200h1m1%200h2M1%2028.5h1m5%200h1m1%200h9m3%200h5m3%200h3m1%200h1M1%2029.5h1m1%200h3m1%200h1m1%200h2m2%200h2m1%200h1m2%200h1m1%200h1m3%200h6M1%2030.5h1m1%200h3m1%200h1m1%200h4m1%200h5m2%200h1m1%200h2m1%200h1m2%200h2m1%200h2M1%2031.5h1m1%200h3m1%200h1m1%200h2m1%200h2m7%200h2m1%200h5m1%200h2M1%2032.5h1m5%200h1m2%200h2m2%200h2m1%200h1m1%200h4m1%200h1m2%200h1m1%200h3M1%2033.5h7m1%200h5m4%200h1m2%200h1m1%200h3m1%200h2m3%200h1'/%3e%3c/svg%3e",Br="data:image/svg+xml,%3c?xml%20version='1.0'%20encoding='utf-8'?%3e%3c!DOCTYPE%20svg%20PUBLIC%20'-//W3C//DTD%20SVG%201.1//EN'%20'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'%3e%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%2041%2041'%20shape-rendering='crispEdges'%3e%3cpath%20fill='%23ffffff'%20d='M0%200h41v41H0z'/%3e%3cpath%20stroke='%23000000'%20d='M4%204.5h7m3%200h5m3%200h1m2%200h2m3%200h7M4%205.5h1m5%200h1m1%200h1m2%200h1m4%200h2m2%200h2m2%200h1m1%200h1m5%200h1M4%206.5h1m1%200h3m1%200h1m1%200h1m1%200h1m1%200h1m2%200h1m3%200h3m1%200h1m2%200h1m1%200h3m1%200h1M4%207.5h1m1%200h3m1%200h1m1%200h2m1%200h1m2%200h2m1%200h1m1%200h3m1%200h2m1%200h1m1%200h3m1%200h1M4%208.5h1m1%200h3m1%200h1m3%200h1m6%200h3m1%200h1m1%200h1m2%200h1m1%200h3m1%200h1M4%209.5h1m5%200h1m4%200h1m1%200h1m6%200h1m5%200h1m5%200h1M4%2010.5h7m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h7M12%2011.5h1m3%200h1m3%200h1m2%200h2m1%200h1m1%200h1M4%2012.5h1m5%200h1m1%200h1m1%200h1m1%200h4m1%200h2m3%200h5m2%200h3M6%2013.5h4m4%200h2m1%200h3m1%200h3m3%200h2m3%200h4M4%2014.5h1m2%200h5m1%200h2m2%200h3m2%200h1m1%200h3m2%200h2m1%200h1m1%200h2M5%2015.5h1m1%200h2m2%200h2m2%200h3m1%200h2m2%200h1m2%200h10M5%2016.5h1m4%200h1m1%200h3m2%200h1m1%200h2m2%200h2m2%200h2m1%200h2m4%200h1M6%2017.5h3m2%200h5m3%200h1m1%200h4m2%200h1m1%200h3m1%200h4M7%2018.5h2m1%200h1m3%200h3m1%200h4m3%200h1m2%200h3m3%200h2M5%2019.5h1m1%200h2m3%200h2m5%200h1m3%200h1m2%200h2m1%200h1m1%200h1m2%200h1m1%200h1M4%2020.5h1m4%200h2m3%200h1m1%200h3m1%200h2m1%200h1m2%200h1m2%200h1m1%200h2m3%200h1M6%2021.5h4m1%200h1m2%200h1m1%200h1m1%200h3m1%200h3m1%200h2m2%200h1m2%200h2m1%200h1M5%2022.5h2m3%200h3m2%200h3m1%200h1m1%200h1m1%200h2m1%200h3m1%200h2m1%200h2m1%200h1M5%2023.5h1m1%200h1m3%200h5m2%200h3m1%200h3m1%200h1m1%200h1m3%200h3M6%2024.5h3m1%200h1m1%200h4m2%200h1m1%200h1m1%200h2m2%200h1m2%200h1m1%200h3m1%200h2M4%2025.5h1m7%200h1m3%200h1m3%200h1m2%200h1m2%200h2m3%200h3M4%2026.5h1m2%200h1m2%200h2m1%200h5m1%200h1m2%200h1m1%200h2m7%200h3M4%2027.5h1m3%200h1m4%200h2m5%200h1m8%200h1m1%200h1m1%200h4M4%2028.5h3m1%200h1m1%200h3m5%200h3m3%200h1m3%200h5m3%200h1M12%2029.5h1m1%200h2m3%200h1m3%200h1m1%200h1m1%200h2m3%200h1m1%200h1m1%200h1M4%2030.5h7m7%200h2m2%200h1m1%200h1m1%200h3m1%200h1m1%200h1m1%200h2M4%2031.5h1m5%200h1m2%200h3m4%200h1m1%200h1m4%200h2m3%200h5M4%2032.5h1m1%200h3m1%200h1m2%200h1m3%200h3m1%200h2m3%200h1m1%200h6m1%200h1M4%2033.5h1m1%200h3m1%200h1m2%200h2m4%200h1m2%200h4m2%200h2m1%200h2m1%200h3M4%2034.5h1m1%200h3m1%200h1m4%200h3m2%200h6m1%200h2m2%200h3m1%200h2M4%2035.5h1m5%200h1m2%200h2m1%200h2m1%200h1m2%200h1m1%200h1m4%200h1m1%200h4M4%2036.5h7m1%200h6m2%200h2m4%200h1m1%200h2m1%200h1m3%200h1'/%3e%3c/svg%3e";function Ur(){const e=c(l().language);return"en"===e?{close:"Close",title:"Continue on your phone",free:"Mac and Web are free",description:"Step away from your desk. Check progress, respond to approvals and continue your sessions on your phone.",download:"Scan to install",ios:"Get the iPhone app",android:"Get the Android app",pairing:"Keep your computer running. On Mac, open Settings → Current device, enable phone access and generate a pairing code. Open Vibelet on your phone and scan it. For a CLI daemon, use the pairing code shown by npx vibelet.",pro:"Explore the mobile app first. Upgrade to Vibelet Pro on your phone when you need its advanced features. Existing mobile purchases can be restored there."}:"zh-TW"===e?{close:"關閉",title:"在手機上繼續",free:"Mac 與 Web 免費使用",description:"離開電腦,也能查看任務進度、處理審批,繼續同一段對話。",download:"掃碼安裝",ios:"取得 iPhone 版",android:"取得 Android 版",pairing:"保持電腦運行。在 Mac「設定 → 當前裝置」開啟手機存取並產生配對碼,再用手機 Vibelet 掃碼。使用 CLI 時,掃描 npx vibelet 顯示的配對碼。",pro:"先體驗手機端,需要進階功能時再於手機升級 Vibelet Pro。已有手機端購買可在手機恢復。"}:{close:"关闭",title:"在手机上继续",free:"Mac 与 Web 免费使用",description:"离开电脑,也能查看任务进度、处理审批,继续同一段对话。",download:"扫码安装",ios:"获取 iPhone 版",android:"获取 Android 版",pairing:"保持电脑运行。在 Mac「设置 → 当前设备」开启手机访问并生成配对码,再用手机 Vibelet 扫码。使用 CLI 时,扫描 npx vibelet 显示的配对码。",pro:"先体验手机端,需要高级功能时再在手机升级 Vibelet Pro。已有手机端购买可在手机恢复。"}}function Wr(){const e=Ur();return n.jsxs("section",{className:"mobile-companion-panel control-section",children:[n.jsx("p",{className:"mobile-companion-free",children:e.free}),n.jsx("h2",{children:e.title}),n.jsx("p",{children:e.description}),n.jsx("div",{className:"mobile-companion-downloads",children:[{label:e.ios,qr:Br,url:"https://apps.apple.com/app/id6761245790"},{label:e.android,qr:Hr,url:"https://www.feishu.cn/file/RUnbb7INMocEFjxj5AWcC7WEn6d"}].map(t=>n.jsxs("div",{children:[n.jsx("img",{src:t.qr,alt:`${t.label} · ${e.download}`,width:"140",height:"140"}),n.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",children:t.label})]},t.url))}),n.jsx("p",{children:e.pairing}),n.jsx("p",{className:"mobile-companion-hint",children:e.pro})]})}function Kr({onClose:e}){const s=t.useRef(null);t.useEffect(()=>{const e=document.activeElement,t=document.getElementById("vibelet-workspace"),n=t?.inert;return t&&(t.inert=!0),s.current?.focus(),()=>{t&&(t.inert=Boolean(n)),e?.focus()}},[]);const r=Ur().title;return I.createPortal(n.jsx("div",{className:"mobile-companion-backdrop",onClick:t=>{t.target===t.currentTarget&&e()},children:n.jsxs("section",{ref:s,className:"mobile-companion-dialog",role:"dialog","aria-modal":"true","aria-label":r,tabIndex:-1,onKeyDown:t=>{if("Escape"===t.key&&(t.preventDefault(),t.stopPropagation(),e()),"Tab"!==t.key)return;const n=Array.from(t.currentTarget.querySelectorAll("button,a[href]")),r=n[0],i=n.at(-1);!t.shiftKey||document.activeElement!==r&&document.activeElement!==s.current?t.shiftKey||document.activeElement!==i||(t.preventDefault(),r?.focus()):(t.preventDefault(),i?.focus())},children:[n.jsx("button",{type:"button",className:"icon-button mobile-companion-close","aria-label":Ur().close,title:Ur().close,onClick:e,children:n.jsx(Re,{"aria-hidden":"true"})}),n.jsx(Wr,{})]})}),document.body)}function Gr({activeSession:e,client:r,busy:i,controlsOpen:o,pendingCount:a=0,t:c,onOpenControls:l,onRefreshSessions:d,onRestoreSnapshot:u,onToggleArchived:h,onTogglePinned:m,onViewChanges:f}){const[p,g]=t.useState(!1),[v,y]=t.useState(!1),b=t.useRef(null);t.useEffect(()=>{if(!v)return;const e=e=>{e.target instanceof Node&&!b.current?.contains(e.target)&&y(!1)},t=e=>{"Escape"===e.key&&y(!1)};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[v]);const w=e=>{y(!1),e()},S=s(),x=n.jsxs("div",{className:"header-actions",children:["desktop"!==S.kind&&e&&S.renderSessionShare?.(e,r),("desktop"!==S.kind||a>0)&&n.jsxs("button",{type:"button",className:"icon-button header-pending-button","aria-label":c.pendingActionCount(a),title:c.pendingActionCount(a),onClick:()=>window.dispatchEvent(new Event("vibelet.pending.open")),children:[n.jsx(F,{"aria-hidden":"true"}),a>0&&n.jsx("span",{className:"header-pending-count","aria-hidden":"true",children:a})]}),p&&n.jsx(Kr,{onClose:()=>g(!1)}),e?null:n.jsx("button",{"aria-label":c.refreshSessions,className:"icon-button",onClick:d,title:c.refreshSessions,type:"button",children:n.jsx(me,{"aria-hidden":"true"})}),n.jsx("button",{"aria-expanded":o,"aria-label":o?c.collapseControlsSidebar:c.workspaceTools,title:zr(o?c.collapseControlsSidebar:c.workspaceTools,"rightSidebar"),className:"header-tool-button",onClick:l,type:"button",children:n.jsx(ce,{"aria-hidden":"true"})}),e||S.openSettings?n.jsxs("div",{className:"header-more-wrap",ref:b,children:[n.jsx("button",{"aria-expanded":v,"aria-haspopup":"menu","aria-label":c.moreActions,className:"icon-button",onClick:()=>y(e=>!e),title:c.moreActions,type:"button",children:n.jsx(H,{"aria-hidden":"true"})}),v?n.jsxs("div",{className:"header-action-menu",role:"menu",children:["desktop"===S.kind&&0===a&&n.jsxs("button",{role:"menuitem",type:"button",onClick:()=>w(()=>window.dispatchEvent(new Event("vibelet.pending.open"))),children:[n.jsx(F,{"aria-hidden":"true"}),n.jsx("span",{children:c.pendingActionCount(a)})]}),e&&n.jsxs(n.Fragment,{children:[n.jsxs("button",{onClick:()=>w(()=>f(e.sessionId)),role:"menuitem",type:"button",children:[n.jsx(X,{"aria-hidden":"true"}),n.jsx("span",{children:c.viewChanges})]}),n.jsxs("button",{disabled:i,onClick:()=>w(m),role:"menuitem",type:"button",children:[n.jsx(de,{"aria-hidden":"true"}),n.jsx("span",{children:e.pinned?c.unpin:c.pin})]}),n.jsxs("button",{disabled:i,onClick:()=>w(h),role:"menuitem",type:"button",children:[n.jsx(N,{"aria-hidden":"true"}),n.jsx("span",{children:e.archived?c.unarchive:c.archive})]}),n.jsxs("button",{onClick:()=>w(u),role:"menuitem",type:"button",children:[n.jsx(fe,{"aria-hidden":"true"}),n.jsx("span",{children:c.restoreSnapshot})]})]}),n.jsxs("button",{role:"menuitem",type:"button",onClick:()=>w(()=>g(!0)),children:[n.jsx(k,{"aria-hidden":"true"}),n.jsx("span",{children:Ur().title})]}),n.jsxs("button",{onClick:()=>w(d),role:"menuitem",type:"button",children:[n.jsx(me,{"aria-hidden":"true"}),n.jsx("span",{children:c.refreshSessions})]})]}):null]}):null]}),C=S.toolbarTarget?.("right");return C?I.createPortal(x,C):x}function Qr({language:e,entry:r="web-settings"}){const i=c(e),o=t.useMemo(()=>gs(i),[i]),[a,l]=t.useState("bug"),[d,u]=t.useState(""),[h,m]=t.useState(""),[f,p]=t.useState("idle");return n.jsxs("section",{className:"control-section compact-section",children:[n.jsx("h2",{children:o.title}),n.jsx("p",{className:"empty-copy",children:o.subtitle}),n.jsxs("div",{className:"feedback-type-grid",children:[n.jsx("button",{className:"bug"===a?"primary-button":"",type:"button","aria-pressed":"bug"===a,onClick:()=>l("bug"),children:o.bug}),n.jsx("button",{className:"feature"===a?"primary-button":"",type:"button","aria-pressed":"feature"===a,onClick:()=>l("feature"),children:o.feature})]}),n.jsxs("label",{className:"field",children:[n.jsx("span",{children:o.description}),n.jsx("textarea",{rows:5,maxLength:8e3,value:d,placeholder:o.descriptionPlaceholder,onChange:e=>u(e.target.value)})]}),n.jsxs("label",{className:"field",children:[n.jsx("span",{children:o.email}),n.jsx("input",{type:"email",maxLength:320,value:h,placeholder:o.emailPlaceholder,onChange:e=>m(e.target.value)})]}),n.jsx("button",{className:"primary-button",type:"button",disabled:!d.trim()||"sending"===f,onClick:()=>{(async()=>{if(d.trim()&&"sending"!==f){p("sending");try{await async function(e,t={}){const{requestEmail:n=ys,...s}=t,r=await n({locale:e.locale,email:e.email});return us({...e,email:r},s)}(function(e){const t=function(e){return ls(e.trim()).slice(0,8e3)}(e.description);if(!t)throw new Error("Feedback description is required");const n=!1!==e.includeLogs&&e.logs?function(e,t=6e4){const n=ls(e);return n.length<=t?n:`[truncated ${n.length-t} chars]\n${n.slice(-t)}`}(e.logs):"",s=e.email?.trim().slice(0,320);return{product:e.product,source:e.source,type:e.type,description:t,email:s||void 0,appVersion:e.appVersion?.trim().slice(0,64)||"unknown",locale:e.locale?.trim().slice(0,64)||"unknown",platform:e.platform?.trim().slice(0,128)||"unknown",logsIncluded:Boolean(n),logs:n||void 0,metadata:ws(e.metadata),images:xs(e.images)}}({product:"vibelet",source:"desktop"===s().kind?"desktop":"web",type:a,description:d,email:h,appVersion:s().appVersion||"web",locale:i,platform:navigator.platform||"web",metadata:{app:"desktop"===s().kind?"vibelet-desktop":"vibelet-web",entry:r,screen:"connection-guide"===r?"connection-guide":"settings/language",module:"feedback",action:"manual-submit",userAgent:navigator.userAgent}})),u(""),p("success")}catch(e){p(function(e){return e instanceof Error&&"FeedbackSubmissionCancelledError"===e.name}(e)?"idle":"error")}}})()},children:"sending"===f?o.sending:o.submit}),"success"===f?n.jsx("p",{className:"empty-copy success-copy",children:o.success}):null,"error"===f?n.jsx("p",{className:"empty-copy error-copy",children:o.error}):null]})}const Vr=[[0,.024],[.05,.078],[.25,.157],[.5,.243],[.75,.325],[.9,.4],[.97,.459],[.995,.506],[1,.533]];function Jr(e,t,n){let s=374761393*e+668265263*t+2147483647*n|0;return s=Math.imul(s^s>>>13,1274126177),s^=s>>>16,(s>>>0)/4294967295}function Zr(e,t,n,s){const r=Math.floor(e),i=Math.floor(t),o=e-r,a=t-i,c=o*o*o*(o*(6*o-15)+10),l=a*a*a*(a*(6*a-15)+10),d=e=>(e%n+n)%n,u=Jr(d(r),i,s),h=Jr(d(r+1),i,s),m=Jr(d(r),i+1,s);return u+(h-u)*c+(m-u)*l+(u-h-m+Jr(d(r+1),i+1,s))*c*l}function Xr(e,t,n,s){const r=new Float32Array(e*e);for(let i=0;i<e;i++)for(let o=0;o<e;o++){let a=0,c=1,l=0;for(let r=0;r<n;r++){const n=t<<r;a+=c*Zr(o/e*n,i/e*(n/2),n,s+97*r),l+=c,c*=.5}r[i*e+o]=a/l}return r}function Yr(e,t,n){let s=0;for(const a of e)s+=a;const r=s/e.length;let i=0;for(const a of e)i+=(a-r)**2;const o=Math.sqrt(i/e.length)||1;return e.map(e=>t+(e-r)/o*n)}function ei(e,t,n){const s=Math.floor(6*e),r=6*e-s,i=n*(1-t),o=n*(1-r*t),a=n*(1-(1-r)*t);switch((s%6+6)%6){case 0:return[n,a,i];case 1:return[o,n,i];case 2:return[i,n,a];case 3:return[i,o,n];case 4:return[a,i,n];default:return[n,i,o]}}let ti=null;const ni=["fixed","gradient-2","gradient-3","spectrum"],si=["none","brighten","flow","spotlight"],ri={color:"#b126ff",colorMode:"spectrum",color2:"#ff177c",color3:"#35d3ff",fixedColor:!1,speed:.7,paused:!1,phase:0,feather:95,projectionScale:174,intensity:1.15,grain:.035,seed:7},ii=(e,t,n,s)=>Math.min(s,Math.max(n,Number.isFinite(e)?e:t)),oi=e=>{let t=e.replace(/^#/,"");return/^[\da-f]{3}$/i.test(t)&&(t=Array.from(t,e=>e+e).join("")),/^[\da-f]{6}$/i.test(t)||(t="b126ff"),[0,2,4].map(e=>parseInt(t.slice(e,e+2),16)/255)};function ai({columns:e=1,rows:s=1,gap:r=0,colorSpread:i=0,centerProjectionScale:o,borderRadius:a,hoverEffect:c="none",...l}){const d=t.useRef(null),u=t.useRef(null),h=()=>({...ri,...Object.fromEntries(Object.entries(l).filter(([,e])=>void 0!==e)),colorMode:l.colorMode??(l.fixedColor?"fixed":"spectrum"),columns:e,rows:s,gap:r,colorSpread:i,centerProjectionScale:o,borderRadius:a,hoverEffect:c}),m=t.useRef(h());return t.useEffect(()=>{m.current=h(),u.current?.()}),t.useEffect(()=>{const e=d.current,t=e.parentElement instanceof HTMLButtonElement?e.parentElement:null,n=e.getContext("webgl",{alpha:!0,premultipliedAlpha:!0,antialias:!1});if(!n)return;let s=null,r=null,i=null,o=null,a=null,c=!1,l={},h=0,f=0,p=0,g=0,v=0,y=!1,b=!1,w=[0,0],S=!0,x=!1,I=!1,k=1,C=1;const R=matchMedia("(prefers-reduced-motion: reduce)"),E=(e,t)=>{const s=n.createShader(e);return n.shaderSource(s,t),n.compileShader(s),n.getShaderParameter(s,n.COMPILE_STATUS)?s:(n.deleteShader(s),null)},M=()=>{n.deleteBuffer(r),n.deleteProgram(s),n.deleteShader(i),n.deleteShader(o),n.deleteTexture(a),r=null,s=null,i=null,o=null,a=null},j=()=>{i=E(n.VERTEX_SHADER,"\nattribute vec2 a_position;\nvarying vec2 v_uv;\nvoid main() {\n v_uv = a_position * .5 + .5;\n gl_Position = vec4(a_position, 0., 1.);\n}");const t=!!n.getExtension("OES_standard_derivatives");I=t&&!!n.getExtension("EXT_shader_texture_lod");const d=(t?"#define USE_CHROMATIC_DERIVATIVES\n":"")+(I?"#define USE_CHROMATIC_TEXTURE_LOD\n":"");if(o=E(n.FRAGMENT_SHADER,d+"\n#ifdef USE_CHROMATIC_DERIVATIVES\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef USE_CHROMATIC_TEXTURE_LOD\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\nvarying vec2 v_uv;\nuniform vec2 u_size;\nuniform vec2 u_resolution;\nuniform vec2 u_grid;\nuniform float u_gap;\nuniform float u_time;\nuniform float u_phase;\nuniform float u_feather;\nuniform float u_projectionScale;\nuniform float u_centerProjectionScale;\nuniform float u_borderRadius;\nuniform float u_intensity;\nuniform float u_grain;\nuniform float u_spread;\nuniform float u_seed;\nuniform vec3 u_color;\nuniform float u_colorMode;\nuniform vec3 u_color2;\nuniform vec3 u_color3;\nuniform sampler2D u_field;\nuniform float u_hover;\nuniform float u_hoverEffect;\nuniform vec2 u_hoverPosition;\n\nfloat hash(vec3 p) {\n p = fract(p * .1031);\n p += dot(p, p.yzx + 33.33);\n return fract((p.x + p.y) * p.z);\n}\nvec3 hsv(vec3 c) {\n vec3 p = abs(fract(c.xxx + vec3(0., 2./3., 1./3.)) * 6. - 3.);\n return c.z * mix(vec3(1.), clamp(p - 1., 0., 1.), c.y);\n}\nvec3 rgbToHsv(vec3 c) {\n vec4 k = vec4(0., -1./3., 2./3., -1.);\n vec4 p = mix(vec4(c.bg, k.wz), vec4(c.gb, k.xy), step(c.b, c.g));\n vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n float d = q.x - min(q.w, q.y);\n return vec3(abs(q.z + (q.w - q.y) / (6. * d + 1.e-8)), d / (q.x + 1.e-8), q.x);\n}\nmat2 rotate(float a) { return mat2(cos(a), -sin(a), sin(a), cos(a)); }\n\nvec3 rotatedField(vec2 source, float t, float tile) {\n vec2 uv = source * vec2(3.14159265, 1.57079633);\n vec3 sphere = vec3(cos(uv.y) * sin(uv.x), sin(uv.y), cos(uv.y) * cos(uv.x));\n sphere.xy = rotate(sin(t * .22 + tile * 3.1) * .55) * sphere.xy;\n sphere.yz = rotate(sin(t * .18 + tile * 2.4) * .55) * sphere.yz;\n sphere.xz = rotate(t * .16 + tile * 6.28) * sphere.xz;\n vec2 fieldUv = vec2(atan(sphere.x, sphere.z) / 6.283185 + .5, asin(clamp(sphere.y, -1., 1.)) / 3.141593 + .5);\n#ifdef USE_CHROMATIC_TEXTURE_LOD\n // Longitude wraps from 1 to 0 on the back meridian. Implicit derivatives see\n // that as a full-texture jump and pick the smallest mip, drawing dotted seams,\n // so select the mip from the wrapped (true) longitude change instead.\n vec2 dx = dFdx(fieldUv);\n vec2 dy = dFdy(fieldUv);\n dx.x -= floor(dx.x + .5);\n dy.x -= floor(dy.x + .5);\n return texture2DGradEXT(u_field, fieldUv, dx, dy).rgb;\n#else\n return texture2D(u_field, fieldUv).rgb;\n#endif\n}\nvec3 blurredField(vec2 source, float t, float tile) {\n // Blur the rotated field in the unprojected plane so compressed edges\n // remain soft after projection.\n float b = .045;\n vec3 c = rotatedField(source, t, tile) * .28;\n c += (rotatedField(source + vec2(b,0), t, tile) + rotatedField(source - vec2(b,0), t, tile)\n + rotatedField(source + vec2(0,b), t, tile) + rotatedField(source - vec2(0,b), t, tile)) * .12;\n c += (rotatedField(source + vec2(b,b), t, tile) + rotatedField(source - vec2(b,b), t, tile)\n + rotatedField(source + vec2(b,-b), t, tile) + rotatedField(source + vec2(-b,b), t, tile)) * .06;\n return c;\n}\nvec2 projectedSource(vec2 p, float fov) {\n vec2 angle = p * fov;\n float longitude = clamp(angle.x, -1.565, 1.565);\n float latitude = clamp(angle.y, -1.565, 1.565);\n return vec2(tan(longitude), tan(latitude) / max(.005, cos(longitude))) / tan(fov);\n}\nvec2 contourExtent() {\n vec2 halfSize = max(vec2(2.), (u_size / u_grid - u_gap) * .5);\n return halfSize / min(halfSize.x, halfSize.y);\n}\nfloat contourRadius(vec2 p) {\n // Intersect a ray with circular corners in physical coordinates. A wide\n // button retains straight sides and round end caps instead of becoming an ellipse.\n vec2 direction = abs(p) / max(length(p), .000001);\n vec2 extent = contourExtent();\n vec2 center = extent - u_borderRadius;\n if (direction.y * extent.x <= direction.x * center.y)\n return extent.x / max(direction.x, .000001);\n if (direction.x * extent.y <= direction.y * center.x)\n return extent.y / max(direction.y, .000001);\n float cross = direction.x * center.y - direction.y * center.x;\n return dot(direction, center)\n + sqrt(max(u_borderRadius * u_borderRadius - cross * cross, 0.));\n}\nfloat contourBoundary(vec2 p) {\n if (u_borderRadius < 0.) return max(abs(p.x), abs(p.y));\n vec2 physical = p * contourExtent();\n return length(physical) / max(contourRadius(physical), .000001);\n}\nvec2 materialSource(vec2 p, float fov, float centerFov) {\n if (u_borderRadius >= 0.) {\n // Project from the actual contour instead of clipping a square field.\n // Every point on the rounded/circular edge reaches the same source rim.\n float radius = contourBoundary(p);\n float angle = mix(centerFov, fov, smoothstep(.8, .95, radius));\n float projected = tan(min(radius * angle, 1.565)) / tan(angle);\n return p / max(length(p), .000001) * projected;\n }\n // The face can keep its own projection, which sets how the central gradient\n // moves, while the rim reflections keep the outer projection.\n float rim = smoothstep(.8, .95, max(abs(p.x), abs(p.y)));\n return mix(projectedSource(p, centerFov), projectedSource(p, fov), rim);\n}\nfloat projectedBoundary(vec2 p, float fov, float centerFov) {\n vec2 source = materialSource(p, fov, centerFov);\n return u_borderRadius < 0. ? max(abs(source.x), abs(source.y)) : length(source);\n}\nvoid main() {\n vec2 cellSize = u_size / u_grid;\n vec2 pixel = vec2(v_uv.x, 1. - v_uv.y) * u_size;\n vec2 id = floor(pixel / cellSize);\n vec2 halfSize = max(vec2(2.), (cellSize - u_gap) * .5);\n vec2 p = (mod(pixel, cellSize) - cellSize * .5) / halfSize;\n float tile = fract(dot(id, vec2(.754877666, .569840296)) + u_seed * .1031);\n float t = u_time + u_phase * 6.283185;\n if (u_hoverEffect > 1.5 && u_hoverEffect < 2.5) t += u_hover * 1.25;\n\n // Inverse of AE's Plane to Sphere: a 174 degree flat plane is mapped into\n // an equirectangular 360 x 180 degree frame. Most source pixels compress\n // into the perimeter; the colored rim is the projected field itself.\n float fov = radians(u_projectionScale * .5);\n float centerFov = radians(u_centerProjectionScale * .5);\n vec2 source = materialSource(p, fov, centerFov);\n float boundary = u_borderRadius < 0. ? max(abs(source.x), abs(source.y)) : length(source);\n float boxBoundary = contourBoundary(p);\n float edgeWidth;\n float boxWidth;\n#ifdef USE_CHROMATIC_DERIVATIVES\n edgeWidth = fwidth(boundary);\n boxWidth = fwidth(boxBoundary);\n#else\n // Match one framebuffer pixel even on devices without shader derivatives.\n vec2 dp = u_size / u_resolution / halfSize;\n vec2 dx = vec2(dp.x * .5, 0.);\n vec2 dy = vec2(0., dp.y * .5);\n edgeWidth = abs(projectedBoundary(p + dx, fov, centerFov) - projectedBoundary(p - dx, fov, centerFov))\n + abs(projectedBoundary(p + dy, fov, centerFov) - projectedBoundary(p - dy, fov, centerFov));\n boxWidth = abs(contourBoundary(p + dx) - contourBoundary(p - dx))\n + abs(contourBoundary(p + dy) - contourBoundary(p - dy));\n#endif\n edgeWidth = max(edgeWidth, .0001);\n boxWidth = max(boxWidth, .0001);\n float feather = clamp(u_feather / 360., .001, 1.);\n // Integrate coverage across the pixel footprint instead of cutting a\n // subpixel contour. Feather still controls the material's inner softness.\n float opacity = 1. - smoothstep(1. - feather - edgeWidth * .5, 1. + edgeWidth * .5, boundary);\n opacity *= 1. - smoothstep(1. - boxWidth * .5, 1. + boxWidth * .5, boxBoundary);\n\n // Rotate the already colored, softened source as a panoramic field, just\n // as VR Rotate Sphere precedes the Plane to Sphere adjustment layer.\n vec2 sampleSource = source;\n if (u_hoverEffect > 2.5) sampleSource -= u_hoverPosition * u_hover * .18;\n vec3 sourceColor = blurredField(sampleSource, t, tile);\n float intensity = u_intensity;\n if (u_hoverEffect > .5 && u_hoverEffect < 1.5) intensity *= 1. + u_hover * .3;\n if (u_hoverEffect > 2.5) {\n vec2 light = p - u_hoverPosition;\n intensity *= 1. + u_hover * .4 * exp(-dot(light, light) * 3.);\n }\n vec3 sourceHsv = rgbToHsv(sourceColor);\n vec3 base = rgbToHsv(u_color);\n float hue = sourceHsv.x + base.x - .81 + tile * u_spread + t * .075;\n vec3 color = hsv(vec3(hue, sourceHsv.y * base.y, min(1., sourceHsv.z * 1.75 * intensity * base.z)));\n if (u_colorMode < 2.5) {\n vec3 palette = u_color;\n if (u_colorMode > .5) {\n // Change the whole material's tint over time. Spatial coordinates\n // affect the reflections, never the selected palette's color.\n float flow = .5 - .5 * cos((tile * u_spread + t * .075) * 6.283185);\n palette = mix(u_color, u_color2, flow);\n if (u_colorMode > 1.5) {\n palette = flow < .5\n ? mix(u_color, u_color2, flow * 2.)\n : mix(u_color2, u_color3, flow * 2. - 1.);\n }\n }\n vec3 paletteHsv = rgbToHsv(palette);\n color = hsv(vec3(paletteHsv.xy, min(1., sourceHsv.z * 1.75 * intensity * paletteHsv.z)));\n }\n color += (hash(vec3(floor(pixel * 1.5), u_seed)) - .5) * u_grain * (.1 + length(color) * .15);\n gl_FragColor = vec4(max(color, 0.) * opacity, opacity);\n}"),!i||!o)return void M();if(s=n.createProgram(),n.attachShader(s,i),n.attachShader(s,o),n.linkProgram(s),!n.getProgramParameter(s,n.LINK_STATUS))return void M();n.useProgram(s),r=n.createBuffer(),n.bindBuffer(n.ARRAY_BUFFER,r),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),n.STATIC_DRAW);const u=n.getAttribLocation(s,"a_position");n.enableVertexAttribArray(u),n.vertexAttribPointer(u,2,n.FLOAT,!1,0,0),a=n.createTexture(),n.bindTexture(n.TEXTURE_2D,a),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.REPEAT),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([20,0,35,255])),l=Object.fromEntries(["size","resolution","grid","gap","time","phase","feather","projectionScale","centerProjectionScale","borderRadius","intensity","grain","spread","seed","color","colorMode","color2","color3","field","hover","hoverEffect","hoverPosition"].map(e=>[e,n.getUniformLocation(s,`u_${e}`)])),!c&&!x&&s&&a&&(n.bindTexture(n.TEXTURE_2D,a),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,128,128,0,n.RGBA,n.UNSIGNED_BYTE,function(){if(ti)return ti;const e=function(e,t){const n=Array.from(e.keys()).sort((t,n)=>e[t]-e[n]),s=new Float32Array(e.length);return n.forEach((n,r)=>{const i=r/(e.length-1);let o=1;for(;o<t.length-1&&t[o][0]<i;)o++;const[a,c]=t[o-1],[l,d]=t[o];s[n]=c+(i-a)/Math.max(1e-6,l-a)*(d-c)}),s}(Xr(128,4,4,11),Vr),t=Yr(Xr(128,3,3,29),.83,.05),n=Yr(Xr(128,5,2,53),.988,.03),s=new Uint8Array(65536);for(let r=0;r<16384;r++){const[i,o,a]=ei((t[r]%1+1)%1,Math.min(1,Math.max(.8,n[r])),e[r]);s[4*r]=Math.round(255*i),s[4*r+1]=Math.round(255*o),s[4*r+2]=Math.round(255*a),s[4*r+3]=255}return ti=s,s}()),I&&(n.generateMipmap(n.TEXTURE_2D),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR_MIPMAP_LINEAR)),e.dataset.renderer="webgl",$())},A=()=>!!s&&!x&&S&&!document.hidden&&!R.matches&&(!m.current.paused&&0!==m.current.speed||Math.abs(v-g)>.001),T=()=>{if(!s||x)return;const r=m.current,i=Math.round(ii(r.columns,1,1,24)),o=Math.round(ii(r.rows,1,1,24));n.viewport(0,0,e.width,e.height),n.uniform2f(l.size,k,C),n.uniform2f(l.resolution,e.width,e.height),n.uniform2f(l.grid,i,o),n.uniform1f(l.gap,ii(r.gap,0,0,Math.max(0,Math.min(k/i,C/o)-4))),n.uniform1f(l.time,p),n.uniform1f(l.hover,t?.disabled||"none"===r.hoverEffect?0:g),n.uniform1f(l.hoverEffect,Math.max(0,si.indexOf(r.hoverEffect))),n.uniform2f(l.hoverPosition,...w),n.uniform1f(l.phase,ii(r.phase,0,-1e3,1e3)),n.uniform1f(l.feather,ii(r.feather,95,0,100));const c=ii(r.projectionScale,174,90,179.5);n.uniform1f(l.projectionScale,c),n.uniform1f(l.centerProjectionScale,ii(r.centerProjectionScale??c,c,90,179.5)),n.uniform1f(l.borderRadius,void 0===r.borderRadius?-1:ii(r.borderRadius,50,0,50)/50),n.uniform1f(l.intensity,ii(r.intensity,1.15,0,3)),n.uniform1f(l.grain,ii(r.grain,.035,0,.5)),n.uniform1f(l.spread,ii(r.colorSpread,0,0,2)),n.uniform1f(l.seed,ii(r.seed,7,0,65535)),n.uniform3fv(l.color,oi(r.color)),n.uniform1f(l.colorMode,ni.indexOf(r.colorMode)),n.uniform3fv(l.color2,oi(r.color2)),n.uniform3fv(l.color3,oi(r.color3)),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,a),n.uniform1i(l.field,0),n.drawArrays(n.TRIANGLES,0,6)},N=e=>{if(h=0,A()){if(f){const t=Math.min((e-f)/1e3,.1);m.current.paused||(p+=t*ii(m.current.speed,.7,0,4)),g+=(v-g)*(1-Math.exp(14*-t)),Math.abs(v-g)<=.001&&(g=v)}f=e,T(),A()&&(h=requestAnimationFrame(N))}else f=0},P=()=>{v=t&&!t.disabled&&"none"!==m.current.hoverEffect&&(y||b)?1:0,(R.matches||"none"===m.current.hoverEffect||t?.disabled)&&(g=v)},D=()=>{P(),h||(f=0,T(),A()&&(h=requestAnimationFrame(N)))},L=e=>{"touch"!==e.pointerType&&(y=!0,D())},F=()=>{y=!1,D()},O=()=>{b=!!t?.matches(":focus-visible"),b&&(w=[0,0]),D()},q=()=>{b=!1,D()},_=e=>{if(!t||t.disabled||"touch"===e.pointerType||"spotlight"!==m.current.hoverEffect)return;const n=t.getBoundingClientRect();w=[Math.max(-1,Math.min(1,(e.clientX-n.left)/Math.max(1,n.width)*2-1)),Math.max(-1,Math.min(1,(e.clientY-n.top)/Math.max(1,n.height)*2-1))],h||T()},$=()=>{cancelAnimationFrame(h),h=0,f=0,P(),T(),A()&&(h=requestAnimationFrame(N))},z=()=>{k=Math.max(1,e.clientWidth),C=Math.max(1,e.clientHeight);const t=Math.min(devicePixelRatio||1,2,Math.sqrt(15e5/(k*C)));e.width=Math.max(1,Math.round(k*t)),e.height=Math.max(1,Math.round(C*t)),$()},H=t=>{t.preventDefault(),x=!0,cancelAnimationFrame(h),delete e.dataset.renderer},B=()=>{x=!1,M(),j(),z()};j(),t?.addEventListener("pointerenter",L),t?.addEventListener("pointerleave",F),t?.addEventListener("pointercancel",F),t?.addEventListener("pointermove",_),t?.addEventListener("focus",O),t?.addEventListener("blur",q);const U=new ResizeObserver(z);U.observe(e);const W=new IntersectionObserver(([e])=>{S=e.isIntersecting,$()});return W.observe(e),document.addEventListener("visibilitychange",$),R.addEventListener("change",$),e.addEventListener("webglcontextlost",H),e.addEventListener("webglcontextrestored",B),u.current=$,z(),()=>{c=!0,u.current=null,cancelAnimationFrame(h),U.disconnect(),W.disconnect(),document.removeEventListener("visibilitychange",$),R.removeEventListener("change",$),e.removeEventListener("webglcontextlost",H),e.removeEventListener("webglcontextrestored",B),delete e.dataset.renderer,M(),t?.removeEventListener("pointerenter",L),t?.removeEventListener("pointerleave",F),t?.removeEventListener("pointercancel",F),t?.removeEventListener("pointermove",_),t?.removeEventListener("focus",O),t?.removeEventListener("blur",q)}},[]),n.jsx("canvas",{ref:d,className:"chromatic-surface","aria-hidden":"true",tabIndex:-1})}const ci={...ri,feather:100,projectionScale:174.7,intensity:1.4,grain:.105,borderRadius:50,hoverEffect:"brighten",entrance:"blur-up",entranceSpeed:1,entranceBlur:10,entranceDistance:20,entranceScale:.65},li=t.forwardRef(function({children:e="Get started",className:s="",type:r="button",color:i=ci.color,colorMode:o,color2:a=ci.color2,color3:c=ci.color3,fixedColor:l,speed:d,paused:u,phase:h,feather:m=ci.feather,projectionScale:f=ci.projectionScale,intensity:p=ci.intensity,grain:g=ci.grain,borderRadius:v=ci.borderRadius,hoverEffect:y=ci.hoverEffect,entrance:b=ci.entrance,entranceSpeed:w=ci.entranceSpeed,entranceBlur:S=ci.entranceBlur,entranceDistance:x=ci.entranceDistance,entranceScale:I=ci.entranceScale,seed:k,style:C,...R},E){const M=t.useRef(null);t.useImperativeHandle(E,()=>M.current,[]),t.useEffect(()=>{const e=M.current,t=()=>{e.style.setProperty("--chromatic-button-short-side",`${Math.min(e.clientWidth,e.clientHeight)}px`)};t();const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),t.useEffect(()=>{if("spotlight"!==y||R.disabled)return;const e=M.current,t=matchMedia("(prefers-reduced-motion: reduce)"),n=[0,0],s=[0,0],r=[0,0];let i=0,o=0,a=!1;const c=()=>Math.min(10,.18*Math.min(e.clientWidth,e.clientHeight)),l=()=>{cancelAnimationFrame(i),i=o=0,n.fill(0),s.fill(0),r.fill(0),e.style.removeProperty("--chromatic-pointer-transform")},d=a=>{if(i=0,t.matches||e.disabled||document.hidden)return void l();const u=o?Math.min((a-o)/1e3,1/30):1/60;o=a;const h=Math.max(1,Math.ceil(120*u)),m=u/h;for(let e=0;e<h;e++)for(let t=0;t<2;t++)s[t]+=(220*(r[t]-n[t])-16*s[t])*m,n[t]+=s[t]*m;const f=n.every((e,t)=>Math.abs(e-r[t])<.01&&Math.abs(s[t])<.05);if(f&&(n.splice(0,2,...r),s.fill(0),r.every(e=>0===e)))return void l();const p=Math.max(-1,Math.min(1,(Math.abs(n[0])-Math.abs(n[1]))/Math.max(1,c())));e.style.setProperty("--chromatic-pointer-transform",`translate(${n[0]}px, ${n[1]}px) scale(${1+.025*p}, ${1-.025*p})`),f?o=0:i=requestAnimationFrame(d)},u=()=>{i||(i=requestAnimationFrame(d))},h=e=>{"touch"===e.pointerType||t.matches||(a=!0)},m=s=>{if(!a||"touch"===s.pointerType||t.matches||e.disabled)return;const i=e.getBoundingClientRect(),o=[i.left+i.width/2-n[0],i.top+i.height/2-n[1]];r[0]=Math.max(-1,Math.min(1,(s.clientX-o[0])/Math.max(1,e.clientWidth/2)))*c(),r[1]=Math.max(-1,Math.min(1,(s.clientY-o[1])/Math.max(1,e.clientHeight/2)))*c(),u()},f=()=>{a=!1,r.fill(0),u()},p=()=>{a=!1,l()},g=()=>{document.hidden&&p()};return e.addEventListener("pointerenter",h),e.addEventListener("pointermove",m),e.addEventListener("pointerleave",f),e.addEventListener("pointercancel",f),t.addEventListener("change",p),document.addEventListener("visibilitychange",g),()=>{l(),e.removeEventListener("pointerenter",h),e.removeEventListener("pointermove",m),e.removeEventListener("pointerleave",f),e.removeEventListener("pointercancel",f),t.removeEventListener("change",p),document.removeEventListener("visibilitychange",g)}},[y,R.disabled]);const j=Math.min(50,Math.max(0,Number.isFinite(v)?v:ci.borderRadius)),A=function(e,t,n=!1){const s=e=>Math.SQRT2*(1-e/50)+e/50,r=s(Math.min(50,Math.max(0,Number.isFinite(t)?t:ci.borderRadius)))/s(ci.borderRadius),i=Math.min(179.5,Math.max(90,Number.isFinite(e)?e:174.7))*Math.PI/360;return Math.min(179.5,Math.max(90,360*Math.atan(Math.tan(i)*(n?1/r:r))/Math.PI))}(f,j),T=(e,t,n,s)=>Math.min(s,Math.max(n,Number.isFinite(e)?e:t));return n.jsxs("button",{...R,ref:M,type:r,"data-hover-effect":y,"data-entrance":b,className:`chromatic-button ${s}`.trim(),style:{"--chromatic-button-color":i,"--chromatic-button-radius":j/100,"--chromatic-entrance-speed":T(w,1,.1,4),"--chromatic-entrance-blur":`${T(S,10,0,40)}px`,"--chromatic-entrance-distance":`${T(x,20,0,120)}px`,"--chromatic-entrance-scale":T(I,.65,.05,1),...C},children:[n.jsx(ai,{color:i,colorMode:o,color2:a,color3:c,fixedColor:l,speed:d,paused:u,phase:h,feather:m,projectionScale:A,borderRadius:j,hoverEffect:y,centerProjectionScale:A-(ci.projectionScale-ri.projectionScale),intensity:p,grain:g,seed:k}),n.jsx("span",{className:"chromatic-button-content",children:e})]})}),di=t.forwardRef(function({className:e="",style:s,...r},i){const[o,a]=t.useState(["#a87bb2","#c27ba0"]),[c,l]=t.useState(!1),[d,u]=t.useState(!1),h=t.useRef(null),m=e=>{h.current=e,"function"==typeof i?i(e):i&&(i.current=e)};return t.useEffect(()=>{u("undefined"!=typeof ResizeObserver&&"undefined"!=typeof IntersectionObserver&&"undefined"!=typeof WebGL2RenderingContext);const e=()=>{if(!h.current)return;const e=getComputedStyle(h.current);a([e.getPropertyValue("--accent").trim()||"#a87bb2",e.getPropertyValue("--accent-secondary").trim()||"#c27ba0"])};e();const t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class","style"]}),()=>t.disconnect()},[]),d?n.jsx(li,{...r,ref:m,className:`product-chromatic-action ${e}`,style:s,color:o[0],color2:o[1],colorMode:"gradient-2",intensity:1.2,borderRadius:25,grain:.04,entrance:"none",hoverEffect:"brighten",paused:!c||r.disabled,speed:.25,onPointerEnter:e=>{l(!0),r.onPointerEnter?.(e)},onPointerLeave:e=>{l(!1),r.onPointerLeave?.(e)},onFocus:e=>{l(!0),r.onFocus?.(e)},onBlur:e=>{l(!1),r.onBlur?.(e)}}):n.jsx("button",{...r,ref:m,className:`product-chromatic-action chromatic-button ${e}`,style:s,children:n.jsx("span",{className:"chromatic-button-content",children:r.children})})}),ui={en:{label:"Pairing link",hint:"Paste a Web link from the CLI or the connected mobile app.",connect:"Connect",invalid:"Enter a valid Web pairing link.",expired:"This link has expired. Generate a new link."},zh:{label:"配对链接",hint:"粘贴 CLI 或已连接手机分享的 Web 链接。",connect:"连接",invalid:"请输入有效的 Web 配对链接。",expired:"链接已过期,请重新生成。"},"zh-TW":{label:"配對連結",hint:"貼上 CLI 或已連線手機分享的 Web 連結。",connect:"連線",invalid:"請輸入有效的 Web 配對連結。",expired:"連結已過期,請重新產生。"}};function hi(){const e=ui[c(l().language)],[s,r]=t.useState(""),[i,o]=t.useState("");return n.jsxs("form",{className:"web-pairing-form",onSubmit:t=>{t.preventDefault();try{const e=new URL(function(e){const t=function(e){if(e.length>16384)throw new Error("Pairing link is too long");const t=new URL(e),n="vibelet:"===t.protocol&&"pair"===t.hostname?t.searchParams.get("link"):null,s=n?new URL(n):t,r=s.searchParams.get("data");return r&&!s.hash&&"vibelet:"===s.protocol&&"pair"===s.hostname&&(s.hash=new URLSearchParams({pair:r}).toString(),s.searchParams.delete("data")),s}(e.trim()),n=lt(t.hash);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||!n)throw new Error("invalid");if(n.expiresAt&&(!Number.isFinite(Date.parse(n.expiresAt))||Date.parse(n.expiresAt)<=Date.now()))throw new Error("expired");return t.pathname="/web/",t.search="",t.href}(s)),t=e.origin===window.location.origin&&e.pathname===window.location.pathname&&e.search===window.location.search;window.location.assign(e.href),t&&window.location.reload()}catch(n){o(n instanceof Error&&"expired"===n.message?e.expired:e.invalid)}},children:[n.jsx("label",{htmlFor:"web-pairing-link",children:e.label}),n.jsx("p",{children:e.hint}),n.jsx("input",{id:"web-pairing-link",value:s,onChange:e=>{r(e.target.value),o("")},autoComplete:"off",spellCheck:!1,required:!0}),n.jsx(di,{className:"primary-button",type:"submit",children:e.connect}),i&&n.jsx("p",{role:"alert",className:"connection-guide-error",children:i})]})}const mi="vibelet --access=quick";function fi({errorText:e,t:s}){const[r,i]=t.useState("idle"),[o,a]=t.useState(!1),c=l().language,d=gs(c);return n.jsx("main",{className:"connection-guide",id:"vibelet-main-content",tabIndex:-1,children:n.jsxs("section",{className:"connection-guide-content","aria-labelledby":"connection-guide-title",children:[n.jsx("span",{className:"connection-guide-mark","aria-hidden":"true",children:n.jsx(Se,{})}),n.jsx("span",{className:"connection-guide-eyebrow",children:"Vibelet"}),n.jsx("h1",{id:"connection-guide-title",children:s.openDaemonWebLink}),n.jsx("p",{children:s.openDaemonWebLinkHint}),n.jsx(hi,{}),n.jsxs("div",{className:"connection-command",children:[n.jsx("code",{children:mi}),n.jsxs("button",{className:"primary-button",onClick:()=>{(async()=>{try{await gt(mi),i("success")}catch{i("error")}window.setTimeout(()=>i("idle"),1800)})()},type:"button",children:["success"===r?n.jsx(O,{"aria-hidden":"true"}):n.jsx(z,{"aria-hidden":"true"}),n.jsx("span",{children:"success"===r?s.commandCopied:"error"===r?s.copyFailed:s.copyStartCommand})]})]}),n.jsx("p",{className:"connection-guide-footnote",children:s.connectionGuideFootnote}),e?n.jsx("p",{className:"connection-guide-error",children:e}):null,n.jsxs("button",{className:"connection-feedback-toggle",type:"button","aria-expanded":o,onClick:()=>a(e=>!e),children:[n.jsx(re,{"aria-hidden":"true"}),d.title]}),o?n.jsx("div",{className:"connection-feedback-panel",children:n.jsx(Qr,{language:c,entry:"connection-guide"})}):null]})})}const pi="vibelet:image-gallery";function gi(e){window.dispatchEvent(new CustomEvent(pi,{detail:e}))}const vi=t.lazy(()=>C(()=>import("./ImageViewer-Cob3hI1x.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])));function yi(){const[e,s]=t.useState(null);return t.useEffect(()=>{const e=e=>s(e.detail);return window.addEventListener(pi,e),()=>window.removeEventListener(pi,e)},[]),e?n.jsx(t.Suspense,{fallback:null,children:n.jsx(vi,{request:e,onClose:()=>s(null)},e.images[e.index].src)}):null}const bi=new WeakMap;function wi(e,t,n){let s=bi.get(e);s||bi.set(e,s=new Map);const r=JSON.stringify([t.sessionId,t.cwd,n]);let i=s.get(r);return i||(s.size>=12&&s.delete(s.keys().next().value),s.set(r,i={updated:0,patches:new Map})),i}function Si(e,t,n){return wi(e,t,n)}function xi(e,t,n){const s=wi(e,t,n);return s.pending?s.pending:s.data&&Date.now()-s.updated<5e3?Promise.resolve(s.data):(s.pending=e.request({action:"session.gitDiff.list",id:e.makeId("gitDiffList"),...t,scope:n}).then(e=>(s.data=e,s.updated=Date.now(),s.patches.clear(),e)).finally(()=>{s.pending=void 0}),s.pending)}function Ii(e,t,n,s){const r=wi(e,t,n),i=r.patches.get(s);if(i?.pending)return i.pending;if(i?.data&&Date.now()-r.updated<5e3)return Promise.resolve(i.data);r.patches.size>=12&&r.patches.delete(r.patches.keys().next().value);const o={};return r.patches.set(s,o),o.pending=e.request({action:"session.gitDiff.file",id:e.makeId("gitDiffFile"),...t,scope:n,path:s}).then(e=>(o.data=e,e)).finally(()=>{o.pending=void 0}),o.pending}function ki({t:e}){const s=$e().items.filter(e=>"browser"===e.kind&&"right"===e.location).map(e=>e.currentUrl??e.url??"").filter(e=>e&&"about:blank"!==e).join("\n"),[r,i]=t.useState("idle");t.useEffect(()=>i("idle"),[s]),t.useEffect(()=>{if("idle"===r)return;const e=setTimeout(()=>i("idle"),2e3);return()=>clearTimeout(e)},[r]);const o="浏览器"===e.browser?"复制所有页面网址":"瀏覽器"===e.browser?"複製所有頁面網址":"Copy all page URLs",a="copied"===r?e.browserUrlCopied:"failed"===r?e.browserCopyFailed:o,c="copied"===r?O:"failed"===r?Ce:z;return n.jsxs("button",{type:"button",className:"dock-copy-urls","aria-label":o,title:a,disabled:!s,onClick:()=>{gt(s).then(()=>i("copied"),()=>i("failed"))},children:[n.jsx(c,{"aria-hidden":"true"}),n.jsx("span",{className:"dock-copy-status",role:"status",children:"idle"===r?"":a})]})}const Ci=t.createContext(null),Ri={browser:Y,terminal:Se,diff:X};function Ei(e){return"浏览器"===e.browser?{center:"移到中间区域",right:"移到右侧栏",create:"新建标签页",drop:"拖到这里以移动标签页"}:"瀏覽器"===e.browser?{center:"移到中間區域",right:"移到右側欄",create:"新增標籤頁",drop:"拖到這裡以移動標籤頁"}:{center:"Move to workspace",right:"Move to sidebar",create:"New tab",drop:"Drop here to move tab"}}function Mi({location:e,kind:s,t:r,cwd:i}){const o=$e(),a=Ei(r),c=t.useRef(null),l=t.useRef(null),d=o.items.filter(t=>t.location===e&&(!s||t.kind===s)),u=function(e,n,s,r=""){const i=t.useContext(Ci),o=i?.element;n=n&&i?.kind===s;const[a,c]=t.useState(!1);return t.useLayoutEffect(()=>{const t=e.current,s=o?.querySelector(".control-tabs");if(!(n&&o&&t&&s))return;const r=()=>{const n=(e.current??t).cloneNode(!0);n.setAttribute("aria-hidden","true"),n.inert=!0,Object.assign(n.style,{position:"fixed",visibility:"hidden",width:"max-content",maxWidth:"none",left:"-10000px",font:getComputedStyle(t).font}),document.body.append(n);const r=n.getBoundingClientRect().width;n.remove();const i=o.clientWidth-s.getBoundingClientRect().width-8;c(e=>r>0?r<=i:e)},i=new ResizeObserver(r);return i.observe(o),i.observe(s),r(),()=>i.disconnect()},[n,o,e,r]),n&&a?o:null}(l,"right"===e&&d.length>1,s,d.map(e=>`${e.id}:${e.title}`).join("|"));if(t.useEffect(()=>{"right"===e&&s&&!o.items.some(e=>e.kind===s)&&o.add(s,r["browser"===s?"browser":"terminal"],i)},[e,s,o.epoch,o.scopeKey]),t.useEffect(()=>{if("right"!==e||!c.current)return;const t=c.current.querySelector('.dock-tab[data-active="true"]');t&&(c.current.scrollLeft=Math.max(0,t.offsetLeft-c.current.offsetLeft))},[e,s,o.right,d.map(e=>e.title).join("|")]),"right"===e&&s&&1===d.length)return null;const h=n.jsxs("div",{className:"dock-tabs",ref:l,role:"right"===e?"tablist":"group","aria-label":s?r["browser"===s?"browser":"terminal"]:void 0,children:["right"===e&&s&&o.right[s]&&n.jsx("button",{type:"button",className:"dock-move dock-move-first","aria-label":a.center,title:a.center,onClick:()=>o.move(o.right[s],"center"),children:n.jsx(D,{})}),n.jsx("div",{className:"dock-tab-items",ref:c,children:d.map(t=>{const s="center"===e?o.center===t.id:o.right[t.kind]===t.id,i=Ri[t.kind];return n.jsxs("div",{className:"document-tab dock-tab","data-active":s,"data-dock-id":t.id,draggable:!0,onDragStart:e=>{e.dataTransfer.setData(He,t.id),e.dataTransfer.effectAllowed="move"},children:[n.jsxs("button",{type:"button",role:"tab","aria-selected":s,title:t.title,onClick:()=>"center"===e?o.setCenter(t.id):o.setRight(e=>({...e,[t.kind]:t.id})),children:[n.jsx(i,{}),n.jsx("span",{children:t.title})]}),s&&"center"===e&&n.jsx("button",{type:"button",className:"dock-move","aria-label":a.right,title:a.right,onClick:()=>o.move(t.id,"right"),children:n.jsx(L,{})}),n.jsx("button",{type:"button",className:"document-tab-close","aria-label":`${r.close} ${t.title}`,title:r.close,onClick:()=>o.close(t.id),children:n.jsx(Re,{})})]},t.id)})}),"right"===e&&"browser"===s&&n.jsx(ki,{t:r}),"right"===e&&s&&n.jsx("button",{type:"button",className:"dock-new","aria-label":a.create,title:zr(a.create,"newTab"),onClick:()=>o.add(s,r["browser"===s?"browser":"terminal"],i),children:n.jsx(he,{})})]});return u?I.createPortal(h,u):h}function ji({item:e,t}){const s=$e(),r=Ei(t);return n.jsxs(n.Fragment,{children:[n.jsx("button",{type:"button","aria-label":r.center,title:r.center,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(He,e.id),t.dataTransfer.effectAllowed="move"},onClick:()=>s.move(e.id,"center"),children:n.jsx(D,{})}),"browser"===e.kind&&n.jsx(ki,{t}),n.jsx("button",{type:"button","aria-label":r.create,title:zr(r.create,"newTab"),onClick:()=>s.add(e.kind,t["browser"===e.kind?"browser":"terminal"],e.cwd),children:n.jsx(he,{})})]})}function Ai({location:e,kind:s}){const r=$e(),i="center"===e?"center":`right-${s}`,o=t.useCallback(e=>r.register(i,e),[r.register,i]);return n.jsx("div",{ref:o,className:"dock-slot","data-dock-location":e,"data-dock-kind":s})}function Ti(e,t){const n=ze();return n?{onDragOver:e=>{e.dataTransfer.types.includes(He)&&(e.preventDefault(),e.dataTransfer.dropEffect="move",e.currentTarget.classList.add("dock-drop-target"))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||e.currentTarget.classList.remove("dock-drop-target")},onDrop:s=>{s.currentTarget.classList.remove("dock-drop-target");const r=s.dataTransfer.getData(He),i=n.items.find(e=>e.id===r);i&&(s.preventDefault(),s.stopPropagation(),document.body.classList.remove("dock-dragging"),n.move(r,e),t?.(i.kind))}}:{}}const Ni=t.lazy(()=>C(()=>import("./DiffDrawer-OzwH-ohL.js"),__vite__mapDeps([8,1,2,9])).then(e=>({default:e.DiffDrawer}))),Pi=t.lazy(async()=>C(()=>import("./RemoteWorkspaceSettings--qq9qs_Y.js"),__vite__mapDeps([10,1,2,11,12,13,14,15,16])).then(e=>({default:e.RemoteWorkspaceSettings}))),Di=t.lazy(async()=>C(()=>import("./FilesControlPanel-OMKoXFux.js"),__vite__mapDeps([17,1,2,6,18,19,20])).then(e=>({default:e.FilesControlPanel}))),Li=t.lazy(async()=>C(()=>import("./LanguageSettingsPanel-CDBK3924.js"),__vite__mapDeps([21,1,2,22])).then(e=>({default:e.LanguageSettingsPanel}))),Fi=t.lazy(async()=>C(()=>import("./ThemeSettingsPanel-DI84WGvC.js"),__vite__mapDeps([23,1,2,22])).then(e=>({default:e.ThemeSettingsPanel}))),Oi=t.lazy(async()=>C(()=>import("./NotificationSettingsPanel-CEEZqgwB.js"),__vite__mapDeps([24,1,2])).then(e=>({default:e.NotificationSettingsPanel}))),qi=t.lazy(async()=>C(()=>import("./SpeechInputSettingsPanel-BK0fKCTr.js"),__vite__mapDeps([25,1,2,11,12,13,26])).then(e=>({default:e.SpeechInputSettingsPanel})));function _i({t:e}){return n.jsxs("div",{className:"control-panel-loading","aria-live":"polite","aria-busy":"true",children:[n.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),n.jsx("span",{children:e.loadingControls})]})}function $i({client:e,id:s,activeSession:r,sessions:i,t:o,close:c}){const l=ze(),d=r?.sessionId,u=r?.cwd,h=r?.runtime.isResponding;t.useEffect(()=>{if(!e||!d)return;const t=window.setTimeout(()=>{"hidden"!==document.visibilityState&&async function(e,t){const n=await xi(e,t,"unstaged");n.files[0]&&await Ii(e,t,"unstaged",n.files[0].path)}(e,{sessionId:d,cwd:u}).catch(()=>{})},350);return()=>window.clearTimeout(t)},[e,d,u,h]);const m=i.find(e=>e.sessionId===s);return m&&e?n.jsx(t.Suspense,{fallback:null,children:n.jsx(Ni,{client:e,sessionId:m.sessionId,cwd:m.cwd,sessionTitle:a(m),t:o,onClose:c,dockLabel:Ei(o).center,onDock:l?({scope:e,path:t})=>{l.add("diff",a(m),m.cwd,m,e,t),c()}:void 0},m.sessionId)}):null}const zi=t.lazy(()=>C(()=>import("./ChatPane-Bja1-mNo.js"),__vite__mapDeps([27,1,2,28,4,29,30,31,14,11,12,13,32,33,19,26,3,9,34,35])).then(e=>({default:e.ChatPane})));function Hi(e){return n.jsx(t.Suspense,{fallback:n.jsx(_i,{t:e.t}),children:n.jsx(zi,{...e})})}function Bi(e,t=!1){const n=e.trim();if(!n)return null;let s=n;if(n.startsWith("/")){if(!t||n.startsWith("//")||n.includes("\\"))return null;s=`file://${n.split("/").map(encodeURIComponent).join("/")}`}else if(/^[a-z][a-z\d+.-]*:/i.test(n)&&!/^[^:/\s]+:\d+(?:[/?#]|$)/.test(n)){if(!(/^https?:\/\//i.test(n)||t&&/^file:\/\//i.test(n)))return null}else s=/^(localhost|127\.0\.0\.1|\[::1\])(?::\d+)?(?:[/?#]|$)/i.test(n)?`http://${n}`:!/\s/.test(n)&&/^[^/]+\.[^/]+/.test(n)?`https://${n}`:`https://www.google.com/search?q=${encodeURIComponent(n)}`;try{const e=new URL(s);return!(t&&function(e){return"file:"===e.protocol&&!e.hostname&&!e.username&&!e.password}(e)||/^https?:$/.test(e.protocol))||e.username||e.password?null:e.href}catch{return null}}const Ui=t.lazy(()=>C(()=>import("./BrowserControlPanel-CPoKd7Kw.js"),__vite__mapDeps([36,1,2,37,19,38,6,5]))),Wi=t.lazy(()=>C(()=>import("./SessionTerminalPanel-BaZnSZot.js"),__vite__mapDeps([39,1,2,37,19,38]))),Ki=t.lazy(()=>C(()=>import("./DiffDrawer-OzwH-ohL.js"),__vite__mapDeps([8,1,2,9])).then(e=>({default:e.DiffDrawer})));function Gi({item:e,...s}){const r=$e(),[i]=t.useState(()=>({pairing:s.pairing,deviceName:s.deviceName})),o=t.useRef(s.client);s.daemonId===i.pairing?.daemonId&&(o.current=s.client);const a=Ti(e.location),[c]=t.useState(()=>document.createElement("div")),l="right"===e.location,d=l&&1===r.items.filter(t=>"right"===t.location&&t.kind===e.kind).length,u=d?n.jsx(ji,{item:e,t:s.t}):void 0,h=(e.scopeKey??"default")===r.scopeKey&&(l?"diff"===e.kind?r.right.diff===e.id:s.rightVisible&&s.controlTab===e.kind&&r.right[e.kind]===e.id:r.center===e.id),m=r.hosts[l?`right-${e.kind}`:"center"]??r.hosts.parking,f=r.hosts.parking;t.useLayoutEffect(()=>{f&&c.parentElement!==f&&f.appendChild(c)},[c,f]),t.useLayoutEffect(()=>{c.className="dock-surface",c.dataset.dockId=e.id,c.dataset.location=e.location,c.dataset.kind=e.kind,c.hidden=!h;const t=l&&"diff"===e.kind,n=()=>{const e=m?.getBoundingClientRect();Object.assign(c.style,t?{left:"0px",top:"0px",width:"100vw",height:"100vh"}:{left:`${e?.left??0}px`,top:`${e?.top??0}px`,width:`${e?.width??0}px`,height:`${e?.height??0}px`})};n();const s=new ResizeObserver(n);return m&&s.observe(m),window.addEventListener("resize",n),document.addEventListener("transitionend",n,!0),window.addEventListener("scroll",n,!0),()=>{s.disconnect(),window.removeEventListener("resize",n),document.removeEventListener("transitionend",n,!0),window.removeEventListener("scroll",n,!0)}},[c,m,h,e.id,e.location,e.kind,l]),t.useLayoutEffect(()=>()=>c.remove(),[c]);const p=t.useCallback(t=>r.updateBrowserUrl(e.id,t),[r.updateBrowserUrl,e.id]);return I.createPortal(n.jsx("div",{className:"dock-surface-content",...a,children:n.jsx(t.Suspense,{fallback:n.jsx("p",{className:"control-panel-loading",children:s.t.loading}),children:"browser"===e.kind?n.jsx(Ui,{initialUrl:e.url,visible:h,onUrlChange:p,onRestore:()=>r.reveal(e.id),t:s.t,dockActions:u,onClose:d?()=>r.close(e.id):void 0,onTitleChange:t=>r.rename(e.id,t)}):"terminal"===e.kind?n.jsx(Wi,{pairing:i.pairing,cwd:e.cwd??"",deviceName:i.deviceName,visible:h,autoOpen:!1!==e.autoOpenTerminal,onOpen:()=>r.activate(e.id),onCloseTab:()=>r.close(e.id),t:s.t,dockActions:u}):e.session&&o.current?n.jsx(Ki,{client:o.current,sessionId:e.session.sessionId,cwd:e.session.cwd,sessionTitle:e.title,t:s.t,onClose:()=>r.close(e.id),onDock:()=>r.move(e.id,l?"center":"right"),dockLabel:Ei(s.t).center,presentation:l?"drawer":"workspace",initialScope:e.scope,initialPath:e.path}):null})}),c)}function Qi(e){const r=$e();r.openRight.current=(t,n)=>{"browser"===t&&n&&e.onOpenBrowserLink?.(),"browser"!==t&&"terminal"!==t||e.onOpenRight?.(t)},r.closeRight.current=t=>{e.controlTab===t&&e.onCloseRight?.()},t.useEffect(()=>s().subscribeCommand?.(t=>{if(!t.startsWith("open-link:"))return;const n=t.slice(10);if(!/^(?:https?|file):\/\//i.test(n))return;const i=Bi(n,!!s().mountBrowser);i&&r.openBrowser(i,e.t.browser)}),[r.openBrowser,e.t.browser]);const i=t.useCallback(e=>r.register("parking",e),[r.register]);return n.jsxs(n.Fragment,{children:[n.jsx("div",{className:"dock-parking",ref:i}),n.jsx("div",{className:"dock-overlay-slot",children:n.jsx(Ai,{location:"right",kind:"diff"})}),r.allItems.map(t=>n.jsx(Gi,{item:t,...e},t.id))]})}let Vi;const Ji=C(()=>import("./NewSessionDialog-DUooZQm1.js"),__vite__mapDeps([40,1,2,28,4,29,30,31,14,11,12,13,32,18,19,41])).then(e=>(Vi=e.default,e));Ji.catch(()=>{});const Zi=t.lazy(()=>Ji);function Xi(e){const t=Vi??Zi;return n.jsx(t,{...e})}function Yi(e,n){const[s,r]=t.useState(null),i=t.useRef(null);return t.useEffect(()=>()=>{null!==i.current&&window.clearTimeout(i.current)},[]),{copyText:t.useCallback(async t=>{try{await gt(t),r({message:e,tone:"success"})}catch{r({message:n,tone:"error"})}null!==i.current&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>r(null),2400)},[n,e]),feedback:s}}function eo({feedback:e}){if(!e)return null;const t="success"===e.tone?O:Re;return n.jsxs("div",{className:`copy-feedback ${e.tone}`,role:"status",children:[n.jsx(t,{"aria-hidden":"true"}),e.message]})}function to({message:e,retryLabel:t,onRetry:s,onDismiss:r,closeLabel:i}){return n.jsxs("div",{className:"notice error chat-error-notice",role:"alert",children:[r?n.jsx("button",{type:"button",className:"chat-notice-dismiss","aria-label":i,title:i,onClick:r,children:n.jsx(Re,{"aria-hidden":"true"})}):n.jsx($,{"aria-hidden":"true"}),n.jsx("span",{children:e}),n.jsxs("button",{className:"chat-notice-retry",onClick:s,type:"button",children:[n.jsx(me,{"aria-hidden":"true"}),t]})]})}function no({label:e}){return n.jsxs("div",{className:"history-loading-state","aria-busy":"true","aria-label":e,role:"status",children:[n.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),n.jsxs("div",{className:"history-loading-copy",children:[n.jsx("strong",{children:e}),n.jsx("span",{"aria-hidden":"true"}),n.jsx("span",{"aria-hidden":"true"}),n.jsx("span",{"aria-hidden":"true"})]})]})}function so({failedSend:e,onRetry:t,onDismiss:s,t:r}){const i={network:r.sendFailedNetwork,timeout:r.sendFailedTimeout,reconnect:r.sendFailedReconnect,permission:r.sendFailedPermission,subscription:r.sendFailedSubscription,"missing-resource":r.sendFailedMissingResource,unknown:r.sendFailedUnknown}[e.kind];return n.jsxs("div",{className:"failed-send-notice",role:"alert",children:[n.jsx($,{"aria-hidden":"true"}),n.jsxs("span",{children:[n.jsx("strong",{children:"timeout"===e.kind?r.sendUnconfirmed:r.sendFailed}),i,e.detail&&n.jsx("code",{className:"failed-send-detail",children:e.detail}),e.message&&n.jsx("blockquote",{className:"failed-send-content",children:e.message}),!!e.images?.length&&n.jsx("small",{children:r.failedSendImages(e.images.length)})]}),n.jsxs("button",{disabled:e.retrying,onClick:t,type:"button",children:[n.jsx(me,{"aria-hidden":"true",className:e.retrying?"spin":void 0}),e.retrying?r.retrying:r.retrySend]}),s&&n.jsx("button",{className:"chat-notice-dismiss",onClick:s,type:"button","aria-label":r.close,title:r.close,children:n.jsx(Re,{"aria-hidden":"true"})})]})}function ro({label:e,onClick:t}){return n.jsx("button",{className:"scroll-latest-button",type:"button","aria-label":e,title:e,onClick:t,children:n.jsx(P,{"aria-hidden":"true"})})}const io="vibelet.web.hideDeviceAddresses";function oo({activeDaemonId:e,busy:r,fallbackName:o,phase:a,statusText:c,t:l,targets:d,onConnect:u,onRename:h,onEditConnection:m}){const{hidden:f,toggle:p}=function(){const[e,n]=t.useState(()=>{try{return"true"===i().getItem(io)}catch{return!1}});return{hidden:e,toggle:()=>{const t=!e;n(t);try{i().setItem(io,String(t))}catch{}}}}(),g=e=>f?function(e){return e.replace(/([^\s]+):(\d+)(?=\s|$)/g,(e,t,n)=>{const s=t.split(".");if(4===s.length&&s.every(e=>/^\d{1,3}$/.test(e)))return`${s[0]}.***.${s[3]}:${n}`;const r=Math.min(3,Math.floor((t.length-1)/2));return`${r>0?`${t.slice(0,r)}***${t.slice(-r)}`:"***"}:${n}`})}(e):e,v=f?l.showDeviceAddresses:l.hideDeviceAddresses,[y,b]=t.useState(!1),[w,S]=t.useState(null),[x,I]=t.useState(""),k=t.useRef(null),C=t.useRef(null),R=s().isLocalDaemon??(()=>!1),E=function(e,t,n){const s=e.find(e=>e.daemonId===t&&n(e.daemonId))??e.find(e=>n(e.daemonId));return e.filter(e=>!n(e.daemonId)||e===s)}(d,e,R),M=d.find(t=>t.daemonId===e),j=g(M?.label||o||e?.slice(0,10)||"Vibelet");return t.useEffect(()=>{y||S(null),w&&C.current?.select()},[y,w]),t.useEffect(()=>{if(!y)return;const e=e=>{e.target instanceof Node&&!k.current?.contains(e.target)&&b(!1)},t=e=>{"Escape"===e.key&&b(!1)};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[y]),n.jsxs("div",{className:"device-switcher",ref:k,children:[n.jsxs("button",{"aria-expanded":y,"aria-haspopup":"menu",className:"device-switcher-trigger",onClick:()=>b(e=>!e),title:j,type:"button",children:[n.jsx("strong",{children:j}),n.jsx(q,{"aria-hidden":"true"})]}),n.jsxs("span",{className:`brand-connection ${a}`,children:[n.jsx("i",{"aria-hidden":"true"}),"connected"===a?l.connected:c]}),y?n.jsxs("div",{"aria-label":l.savedDevices,className:"device-switcher-menu",role:"menu",children:[n.jsxs("div",{className:"device-switcher-menu-header",children:[n.jsx("span",{children:l.savedDevices}),n.jsx("button",{type:"button",className:"device-rename-button","aria-label":v,title:v,onClick:p,children:f?n.jsx(B,{"aria-hidden":"true"}):n.jsx(U,{"aria-hidden":"true"})})]}),E.map(t=>{const i=t.daemonId===e,o=(e=>{const t=s();if(!R(e.daemonId))return"desktop"===t.kind?t.connectionEndpoint?.(e.daemonId):e.webSocketUrl?function(e){try{const t=new URL(e);if(!["http:","https:","ws:","wss:"].includes(t.protocol))return;const n=t.port||(["https:","wss:"].includes(t.protocol)?"443":"80");return`${t.hostname}:${n}`}catch{return}}(e.webSocketUrl):void 0})(t),a=g(t.label);return n.jsx("div",{className:"device-switcher-row"+(i?" is-active":""),children:w===t.daemonId?n.jsxs("form",{className:"device-rename-form",onSubmit:e=>{e.preventDefault(),w&&x.trim()&&(h(w,x),S(null))},children:[n.jsx("input",{ref:C,"aria-label":l.rename,autoFocus:!0,onChange:e=>I(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),S(null))},value:x}),n.jsx("button",{"aria-label":l.rename,title:l.rename,disabled:!x.trim(),type:"submit",children:n.jsx(O,{"aria-hidden":"true"})}),n.jsx("button",{"aria-label":l.cancel,title:l.cancel,type:"button",onClick:()=>S(null),children:n.jsx(Re,{"aria-hidden":"true"})})]}):n.jsxs(n.Fragment,{children:[n.jsxs("button",{className:"device-connect-button",disabled:r||i,onClick:()=>{u(t),b(!1)},role:"menuitem","aria-current":i?"true":void 0,type:"button",children:[i?n.jsx(O,{"aria-hidden":"true"}):n.jsx(ue,{"aria-hidden":"true"}),n.jsxs("span",{children:[n.jsxs("strong",{className:"device-target-heading",children:[n.jsx("span",{children:a}),i?n.jsx("em",{className:"device-active-label",children:l.active}):null]}),t.displayName&&t.displayName!==t.label?n.jsx("small",{children:g(t.displayName)}):null,R(t.daemonId)||!t.displayName?n.jsx("small",{children:R(t.daemonId)?l.currentDevice:g(t.daemonId)}):null,o?n.jsx("small",{className:"device-connection-endpoint",children:g(o)}):null]})]}),n.jsx("button",{"aria-label":`${l.rename} ${a}`,title:`${l.rename} ${a}`,className:"device-rename-button",onClick:()=>(e=>{S(e.daemonId),I(e.label)})(t),type:"button",children:n.jsx(le,{"aria-hidden":"true"})}),m&&s().canEditConnection?.(t.daemonId)&&n.jsx("button",{"aria-label":`${l.editConnection} ${a}`,title:`${l.editConnection} ${a}`,className:"device-rename-button",onClick:()=>{m(t),b(!1)},type:"button",children:n.jsx(ye,{"aria-hidden":"true"})})]})},t.daemonId)}),0===d.length?n.jsx("p",{className:"empty-copy",children:l.noSavedDevices}):null]}):null]})}function ao({label:e,value:s,options:r,onChange:i}){const o=t.useId();return n.jsxs("div",{className:"filter-section",children:[n.jsx("span",{className:"filter-section-label",id:o,children:e}),n.jsx("div",{className:"filter-choice-list",role:"radiogroup","aria-labelledby":o,children:r.map(e=>n.jsxs("label",{className:"filter-menu-row",children:[n.jsx("input",{type:"radio",name:o,value:e.value,checked:s===e.value,onChange:()=>i(e.value)}),n.jsx("span",{children:e.label}),n.jsx(O,{className:"filter-menu-check","aria-hidden":"true","data-checked":s===e.value})]},e.value))})]})}function co({folder:e,initialValue:s,t:r,onClose:i,onSave:o}){const[a,c]=t.useState(s),l=t.useRef(null),d=R(i,l);return I.createPortal(n.jsxs("div",{"aria-labelledby":"folder-tag-dialog-title","aria-modal":"true",className:"folder-tag-dialog-layer",ref:d,role:"dialog",tabIndex:-1,children:[n.jsx("div",{"aria-hidden":"true",className:"folder-tag-dialog-backdrop",onClick:i}),n.jsxs("form",{className:"folder-tag-dialog",onSubmit:e=>{e.preventDefault(),o(a)},children:[n.jsxs("header",{children:[n.jsx("span",{className:"folder-tag-dialog-icon","aria-hidden":"true",children:n.jsx(xe,{})}),n.jsxs("div",{children:[n.jsx("strong",{id:"folder-tag-dialog-title",children:r.editDirectoryTags}),n.jsx("span",{title:e,children:e})]}),n.jsx("button",{"aria-label":r.cancel,title:r.cancel,className:"mini-button",onClick:i,type:"button",children:n.jsx(Re,{"aria-hidden":"true"})})]}),n.jsxs("label",{className:"folder-tag-dialog-field",children:[n.jsx("span",{children:r.directoryTags}),n.jsx("textarea",{"aria-describedby":"folder-tag-dialog-help",placeholder:r.directoryTagsPlaceholder,ref:l,rows:3,value:a,onChange:e=>c(e.target.value)})]}),n.jsx("p",{id:"folder-tag-dialog-help",children:r.directoryTagsDescription}),n.jsxs("footer",{children:[n.jsx("button",{className:"icon-text-button",onClick:i,type:"button",children:r.cancel}),n.jsx("button",{className:"primary-button",type:"submit",children:r.saveDirectoryTags})]})]})]}),document.body)}function lo({folderToggle:e,search:s,connected:r,filtersOpen:i,filtersActive:o,t:a,onSearchChange:c,onSearchCommit:l,onToggleFilters:d,onCreate:u}){const[h,m]=t.useState(Boolean(s)),f=h||s.length>0,p=t.useRef(null),g=t.useRef(null),v=t.useRef(!1),y=()=>{v.current=!0,l(),c(""),m(!1),g.current?.focus(),v.current=!1};return t.useEffect(()=>{const e=()=>{m(!0),requestAnimationFrame(()=>p.current?.focus())};return window.addEventListener("vibelet.session-search",e),()=>window.removeEventListener("vibelet.session-search",e)},[]),n.jsxs(n.Fragment,{children:[n.jsxs("div",{className:"rail-list-heading",children:[n.jsx("div",{className:"rail-heading-folders",children:e}),n.jsxs("div",{className:"rail-heading-actions",children:[n.jsx("button",{ref:g,"aria-label":a.searchSessions,"aria-expanded":f,className:"rail-create-button",title:zr(a.searchSessions,"searchSessions"),type:"button",onClick:()=>{m(!0),requestAnimationFrame(()=>p.current?.focus())},children:n.jsx(ve,{"aria-hidden":"true"})}),n.jsx(di,{"aria-label":a.newSession,className:"rail-create-button",disabled:!r,onClick:u,title:a.newSession,type:"button",children:n.jsx(he,{"aria-hidden":"true"})}),n.jsx("button",{"aria-expanded":i,"aria-label":a.sessionFilters,className:"filter-toggle "+(i||o?"selected":""),onClick:d,title:a.sessionFilters,type:"button",children:n.jsx(Z,{"aria-hidden":"true"})})]})]}),f&&n.jsxs("div",{className:"search-box rail-search-overlay",onBlur:e=>{v.current||e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||(l(),m(Boolean(s)))},children:[n.jsx(ve,{"aria-hidden":"true"}),n.jsx("input",{ref:p,"aria-label":a.searchSessions,value:s,onChange:e=>c(e.target.value),placeholder:a.searchSessions,onKeyDown:e=>{"Enter"===e.key&&l(),"Escape"===e.key&&y()}}),n.jsx("button",{className:"search-close","aria-label":a.cancel,title:a.cancel,type:"button",onClick:y,children:n.jsx(Re,{"aria-hidden":"true"})})]})]})}function uo({menu:e,pending:s,t:r,onOpen:i,onDetails:o,onRename:a,onCopyResumeCommand:c,onResumeInTerminal:l,terminalBusy:d,onTogglePinned:u,onToggleArchived:h,onDelete:m}){const f=t.useRef(null),[p,g]=t.useState(_r);t.useEffect(()=>{const e=()=>g(_r());return window.addEventListener(jr,e),()=>window.removeEventListener(jr,e)},[]),t.useLayoutEffect(()=>{const t=f.current;if(!t)return;const n=t.getBoundingClientRect();t.style.left=`${Math.max(10,Math.min(e.x,window.innerWidth-n.width-10))}px`,t.style.top=`${Math.max(10,Math.min(e.y,window.innerHeight-n.height-10))}px`},[e.x,e.y,p]);const v=e=>{const t=$r(e,p);return t?n.jsx("kbd",{children:Fr(t)}):null};return n.jsxs("div",{ref:f,className:"session-context-menu",role:"menu",style:{left:e.x,top:e.y},onPointerDown:e=>e.stopPropagation(),children:[n.jsxs("button",{type:"button",role:"menuitem",onClick:i,children:[n.jsx(E,{"aria-hidden":"true"}),n.jsx("span",{children:r.open}),v("sessionOpen")]}),n.jsxs("button",{type:"button",role:"menuitem",disabled:s,onClick:a,children:[n.jsx(le,{"aria-hidden":"true"}),n.jsx("span",{children:r.rename}),v("sessionRename")]}),n.jsxs("button",{type:"button",role:"menuitem",disabled:s,onClick:o,children:[n.jsx(ee,{"aria-hidden":"true"}),n.jsx("span",{children:r.details}),v("sessionDetails")]}),n.jsxs("button",{type:"button",role:"menuitem",disabled:s,onClick:c,children:[n.jsx(z,{"aria-hidden":"true"}),n.jsx("span",{children:r.copyResumeCommand}),v("sessionCopyResume")]}),l&&n.jsxs("button",{type:"button",role:"menuitem",disabled:s||d,title:d?r.resumeTerminalBusy:r.resumeInTerminal,onClick:l,children:[n.jsx(Ie,{"aria-hidden":"true"}),n.jsx("span",{children:r.resumeInTerminal}),v("sessionResumeTerminal")]}),n.jsx("span",{className:"context-menu-separator"}),n.jsxs("button",{type:"button",role:"menuitem",disabled:s,onClick:u,children:[n.jsx(de,{"aria-hidden":"true"}),n.jsx("span",{children:e.session.pinned?r.unpin:r.pin}),v("sessionPin")]}),n.jsxs("button",{type:"button",role:"menuitem",disabled:s,onClick:h,children:[n.jsx(N,{"aria-hidden":"true"}),n.jsx("span",{children:e.session.archived?r.unarchive:r.archive}),v("sessionArchive")]}),n.jsxs("button",{className:"danger",type:"button",role:"menuitem",onClick:m,children:[n.jsx(ke,{"aria-hidden":"true"}),n.jsx("span",{children:r.delete}),v("sessionDelete")]})]})}function ho({title:e,t:s,onClose:r,onSave:i}){const o=t.useRef(e),a=t.useRef(!1),[c,l]=t.useState(!1),[d,u]=t.useState(!1),h=t.useRef(null),m=t.useRef(!1),f=t.useRef(!1),p=()=>{const e=h.current?.closest(".session-item")?.querySelector(".session-row");r(),f.current&&window.requestAnimationFrame(()=>e?.isConnected&&e.focus())};t.useLayoutEffect(()=>{h.current?.focus(),h.current?.select()},[]);const g=async()=>{if(m.current||a.current)return;const t=(h.current?.value??"").trim();if(t&&t!==e){m.current=!0,u(!0),l(!1);try{if(await i(t))return void p()}catch{}m.current=!1,u(!1),l(!0),h.current?.focus()}else p()};return n.jsxs("form",{className:"session-rename-inline",onSubmit:e=>{e.preventDefault(),g()},children:[n.jsx("input",{ref:h,"aria-label":s.rename,defaultValue:o.current,readOnly:d,onCompositionStart:()=>{a.current=!0},onCompositionEnd:()=>{a.current=!1,document.activeElement!==h.current&&g()},onBlur:()=>{g()},onKeyDown:e=>{e.stopPropagation(),a.current||e.nativeEvent.isComposing||229===e.keyCode?"Enter"===e.key&&e.preventDefault():("Enter"===e.key&&(f.current=!0),"Escape"!==e.key||d||(e.preventDefault(),m.current=!0,f.current=!0,p()))}}),c&&n.jsx("small",{role:"alert",children:s.renameFailed})]})}function mo({session:e,renamingRowId:s,onRename:r,onCloseRename:i,active:o,selected:c=!1,responding:l,pending:d=!1,attentionReason:u,tagLabels:h,showFolder:m=!0,t:f,onSelect:p,onContextMenu:g,onToggleArchived:v,onTogglePinned:y}){const b=e.creationError,w=t.useId(),S=s===w,x=a(e),k=Bt(e.lastActivityAt,Date.now(),f),C=e.cwd?.split(/[\\/]/).filter(Boolean).at(-1)||e.cwd||".",R=e.branchUrl||(e.branch&&e.pullRequest?.url.match(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/)?e.pullRequest.url.replace(/\/pull\/\d+$/,`/tree/${encodeURIComponent(e.branch)}`):void 0),[E,M]=t.useState(!1),j=t.useRef(null),A=t.useRef(null),T=t.useRef({x:0,y:0}),P=t.useRef(null),D=()=>{const e=A.current;if(!e)return;const{x:t,y:n}=T.current,s=e.getBoundingClientRect(),r=n+18+s.height<=window.innerHeight-8?n+18:n-s.height-12;e.style.left=`${Math.max(8,Math.min(t+14,window.innerWidth-s.width-8))}px`,e.style.top=`${Math.max(8,Math.min(r,window.innerHeight-s.height-8))}px`,e.style.visibility="visible"};t.useLayoutEffect(()=>{E&&D()},[E,x]);const L=()=>{null!==j.current&&window.clearTimeout(j.current),j.current=null,null!==P.current&&window.cancelAnimationFrame(P.current),P.current=null,M(!1)};return t.useEffect(()=>()=>{null!==j.current&&window.clearTimeout(j.current),null!==P.current&&window.cancelAnimationFrame(P.current)},[e.sessionId]),t.useEffect(()=>{if(!E)return;const e=()=>M(!1);return document.addEventListener("scroll",e,!0),()=>document.removeEventListener("scroll",e,!0)},[E]),n.jsxs("div",{className:"session-item","data-row-id":w,onContextMenu:e=>{L(),g?.(e)},"data-renaming":S||void 0,"data-active":o||void 0,"data-multi-selected":c||void 0,"data-statuses":Number(Boolean(e.pinned))+Number(Boolean(e.archived)),onMouseEnter:e=>{T.current={x:e.clientX,y:e.clientY},S||(e=>{null!==j.current&&window.clearTimeout(j.current),j.current=window.setTimeout(()=>{j.current=null,e.isConnected&&e.matches(":hover")&&M(!0)},2e3)})(e.currentTarget)},onMouseMove:e=>{T.current={x:e.clientX,y:e.clientY},E&&null===P.current&&(P.current=window.requestAnimationFrame(()=>{P.current=null,D()}))},onMouseLeave:L,onFocusCapture:e=>{if(!S&&e.target instanceof HTMLElement&&e.target.matches(":focus-visible")){null!==j.current&&window.clearTimeout(j.current),j.current=null;const t=e.currentTarget.getBoundingClientRect();T.current={x:t.left+t.width/2,y:t.bottom},M(!0)}},onBlurCapture:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||L()},children:[n.jsxs("button",{className:`session-row ${o?"active":""} ${e.archived?"archived":""} ${l?"responding":""}`,"data-session-id":e.sessionId,"data-row-id":w,disabled:S,"aria-current":o?"true":void 0,"aria-pressed":c,onClick:p,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},type:"button",children:[n.jsxs("span",{className:"session-row-head",children:[n.jsx("strong",{children:x}),n.jsx("span",{className:"session-row-metadata",children:n.jsx("span",{className:"session-row-time",title:k,children:k})}),l?n.jsx("span",{className:"session-running-indicator",role:"img","aria-label":f.agentResponding,title:f.agentResponding}):n.jsx("span",{className:"session-running-placeholder","aria-hidden":"true"})]}),b&&n.jsxs("span",{className:"session-attention-reason",title:b,children:[f.sessionCreateFailed,": ",b]}),u&&n.jsx("span",{className:"session-attention-reason",children:u}),h?.length?n.jsx("span",{className:"directory-tag-row",title:f.directoryTags,children:h.map(e=>n.jsx("em",{children:e},e))}):null,n.jsx("span",{className:"session-row-footer","aria-hidden":"true"})]}),S&&r&&i&&n.jsx(ho,{title:x,t:f,onClose:i,onSave:t=>r(e,t)}),n.jsxs("div",{className:"session-quick-actions",children:[n.jsx("button",{"aria-label":e.pinned?f.unpin:f.pin,className:e.pinned?"is-pinned":void 0,disabled:d,onClick:y,title:e.pinned?f.unpin:f.pin,type:"button",children:n.jsx(de,{"aria-hidden":"true"})}),n.jsx("button",{"aria-label":e.archived?f.unarchive:f.archive,className:e.archived?"is-archived":void 0,disabled:d,onClick:v,title:e.archived?f.unarchive:f.archive,type:"button",children:n.jsx(N,{"aria-hidden":"true"})})]}),n.jsxs("div",{className:"session-git-links",children:[m&&n.jsx("span",{className:"session-git-folder",title:e.cwd,children:C}),e.branch&&(R&&o?n.jsx("a",{className:"session-branch-link",href:R,target:"_blank",rel:"noopener noreferrer",title:e.branch,children:e.branch}):n.jsx("span",{className:"session-branch-link",title:e.branch,children:e.branch})),e.pullRequest&&(o?n.jsxs("a",{className:"session-pr-link",href:e.pullRequest.url,target:"_blank",rel:"noopener noreferrer",title:e.pullRequest.title,children:["PR #",e.pullRequest.number]}):n.jsxs("span",{className:"session-pr-link",title:e.pullRequest.title,children:["PR #",e.pullRequest.number]})),e.pinned?n.jsx("span",{className:"session-row-status",children:f.pinned}):null,e.archived?n.jsx("span",{className:"session-row-status",children:f.archived}):null,n.jsx("span",{className:"session-row-agent",children:"codex"===e.agent?"Codex":"Claude"})]}),E&&I.createPortal(n.jsx("div",{"aria-hidden":"true",className:"session-title-tooltip",ref:A,style:{left:0,top:0,visibility:"hidden"},children:x}),document.body)]})}function fo(e){const s=t.useRef(e);t.useLayoutEffect(()=>{s.current=e});const r=t.useMemo(()=>({onRenameSession:(e,t)=>s.current.onRenameSession?.(e,t)??Promise.resolve(!1),onCloseRename:()=>s.current.onCloseRename?.(),onEditFolderTags:e=>s.current.onEditFolderTags(e),onOpenCreateMenu:(e,t)=>s.current.onOpenCreateMenu(e,t),onOpenSessionMenu:(e,t)=>s.current.onOpenSessionMenu(e,t),onSelectSession:e=>s.current.onSelectSession(e),onToggleSessionArchived:e=>s.current.onToggleSessionArchived(e),onToggleSessionPinned:e=>s.current.onToggleSessionPinned(e),onToggleFolder:e=>s.current.onToggleFolder(e)}),[]);return n.jsx(po,{...e,...r})}const po=t.memo(function({activeSessionId:e,renamingRowId:s,onRenameSession:r,onCloseRename:i,collapsedFolders:o,folderCounts:a,getFolderTags:c,groupFolders:l,groupedSessions:d,phase:u,attentionReasons:h,pendingSessionIds:m,respondingSessionIds:f,t:p,visibleSessions:g,onEditFolderTags:v,onOpenCreateMenu:y,onOpenSessionMenu:b,onSelectSession:w,onToggleSessionArchived:S,onToggleSessionPinned:x,onToggleFolder:I}){const k=t.useId(),[C,R]=t.useState(()=>new Set),E=t.useRef(null),M=t.useMemo(()=>{const e=l?d.flatMap(e=>o[e.folder]?[]:e.sessions):g;return[...new Set(e.map(e=>e.sessionId))]},[o,l,d,g]);t.useEffect(()=>{const e=new Set(M);R(t=>[...t].every(t=>e.has(t))?t:new Set([...t].filter(t=>e.has(t)))),E.current&&!e.has(E.current)&&(E.current=null)},[M]),t.useEffect(()=>{0===C.size&&(E.current=e)},[e,C]);const j=(t,n)=>{if(n.shiftKey){const s=E.current??e??t,r=M.indexOf(s),i=M.indexOf(t),o=M.slice(Math.min(r<0?i:r,i),Math.max(r,i)+1);return R(e=>{const t=Pr(n)?new Set(e):new Set;for(const n of o)t.add(n);return t}),void(E.current=s)}E.current=t,Pr(n)?R(n=>{const s=n.size?new Set(n):new Set(e?[e]:[]);return s.has(t)?s.delete(t):s.add(t),s}):(R(new Set),w(t))};return l?n.jsxs(n.Fragment,{children:[d.map(t=>{const l=!!o[t.folder],d=`${k}-${encodeURIComponent(t.folder)}`,g="folder"===t.kind?a[t.folder]??t.sessions.length:t.sessions.length,w="attention"===t.kind?p.needsAttentionSessionsGroup:"running"===t.kind?p.runningSessionsGroup:"pinned"===t.kind?p.pinnedSessionsGroup:t.folder;return n.jsxs("div",{className:"folder-group "+("folder"!==t.kind?"virtual-session-group":""),"data-group-kind":t.kind,"data-contains-active":t.sessions.some(t=>t.sessionId===e)||void 0,children:[n.jsxs("div",{className:"folder-heading",children:[n.jsxs("div",{className:"folder-header",children:[n.jsxs("button",{"aria-expanded":!l,"aria-controls":d,title:w,onClick:()=>I(t.folder),type:"button",children:[n.jsx(_,{className:"folder-disclosure","aria-hidden":"true"}),"attention"===t.kind?n.jsx(ee,{"aria-hidden":"true"}):"running"===t.kind?n.jsx(T,{"aria-hidden":"true"}):"pinned"===t.kind?n.jsx(de,{"aria-hidden":"true"}):l?n.jsx(J,{"aria-hidden":"true"}):n.jsx(V,{"aria-hidden":"true"}),n.jsx("span",{children:"folder"===t.kind?t.folder.split(/[\\/]/).filter(Boolean).at(-1)||t.folder:w})]}),"folder"===t.kind?n.jsxs(n.Fragment,{children:[n.jsx("button",{"aria-label":c(t.folder).length?p.editDirectoryTags:p.addDirectoryTags,className:"mini-button folder-hover-action",onClick:()=>v(t.folder),title:c(t.folder).length?p.editDirectoryTags:p.addDirectoryTags,type:"button",children:n.jsx(xe,{"aria-hidden":"true"})}),n.jsx("button",{"aria-label":p.newSession,className:"mini-button folder-hover-action",disabled:"connected"!==u,onClick:e=>y(e,t.folder),title:p.newSession,type:"button",children:n.jsx(he,{"aria-hidden":"true"})})]}):null,n.jsx("small",{className:"folder-session-count",title:`${g} ${p.sessions}`,children:g})]}),"folder"===t.kind&&c(t.folder).length?n.jsx("div",{className:"folder-tag-row",children:c(t.folder).map(e=>n.jsx("span",{children:e},e))}):null]}),n.jsx("div",{className:"folder-session-list",id:d,hidden:l,children:l?null:t.sessions.map(o=>n.jsx(mo,{renamingRowId:s,onRename:r,onCloseRename:i,active:o.sessionId===e,selected:C.has(o.sessionId),responding:f.has(o.sessionId),attentionReason:h?.[o.sessionId],pending:m?.has(o.sessionId),session:o,showFolder:"folder"!==t.kind,tagLabels:c(o.cwd),t:p,onContextMenu:e=>b(e,o),onSelect:e=>j(o.sessionId,e),onToggleArchived:()=>S(o),onTogglePinned:()=>x(o)},o.sessionId))})]},t.folder)}),0===g.length?n.jsx("div",{className:"session-empty-state",children:n.jsx("p",{children:p.noSessionsMatch})}):null]}):n.jsxs(n.Fragment,{children:[g.map(t=>n.jsx(mo,{renamingRowId:s,onRename:r,onCloseRename:i,active:t.sessionId===e,selected:C.has(t.sessionId),responding:f.has(t.sessionId),attentionReason:h?.[t.sessionId],pending:m?.has(t.sessionId),session:t,tagLabels:c(t.cwd),t:p,onContextMenu:e=>b(e,t),onSelect:e=>j(t.sessionId,e),onToggleArchived:()=>S(t),onTogglePinned:()=>x(t)},t.sessionId)),0===g.length?n.jsx("div",{className:"session-empty-state",children:n.jsx("p",{children:p.noSessionsMatch})}):null]})});function go({agentFilter:e,t,onAgentFilterChange:s}){return n.jsx(ao,{label:t.agentFilterLabel,value:e,options:[{value:"all",label:t.agentFilterAll},{value:"claude",label:t.agentFilterClaude},{value:"codex",label:t.agentFilterCodex}],onChange:s})}function vo({groupFolders:e,hideArchived:t,separatePinnedGroup:s,showNeedsAttentionGroup:r,showRunningGroup:i,t:o,onToggleGroupFolders:a,onToggleHideArchived:c,onToggleNeedsAttentionGroup:l,onToggleRunningGroup:d,onToggleSeparatePinnedGroup:u}){const h=[[o.showNeedsAttentionGroup,r,l],[o.showRunningGroup,i,d],[o.separatePinnedGroup,s,u]];return n.jsxs("div",{className:"filter-section",children:[n.jsx("span",{className:"filter-section-label",children:o.filterViewOptions}),n.jsxs("div",{className:"filter-view-list",children:[n.jsxs("button",{"aria-pressed":e,className:"filter-menu-row",onClick:a,type:"button",children:[n.jsx("span",{children:o.groupByFolder}),n.jsx(O,{className:"filter-menu-check","aria-hidden":"true","data-checked":e})]}),h.map(([t,s,r])=>n.jsxs("button",{"aria-pressed":e&&s,className:"filter-menu-row nested-filter-option",disabled:!e,onClick:r,type:"button",children:[n.jsx("span",{children:t}),n.jsx(O,{className:"filter-menu-check","aria-hidden":"true","data-checked":e&&s})]},t)),n.jsxs("button",{"aria-pressed":t,className:"filter-menu-row",onClick:c,type:"button",children:[n.jsx("span",{children:o.hideArchived}),n.jsx(O,{className:"filter-menu-check","aria-hidden":"true","data-checked":t})]})]})]})}function yo({connectionIndicators:e,hasDaemonUpdate:r=!1,activeSessionId:i,busy:o,collapsedFolders:a,allFoldersCollapsed:c,currentCwd:l,activeDaemonId:d,displayName:u,savedTargets:h,directoryTags:m,folderCounts:f,groupFolders:p,sessionSort:g,onSessionSortChange:v,groupedSessions:y,hideArchived:b,separatePinnedGroup:w,showNeedsAttentionGroup:S,showRunningGroup:x,inventoryVersion:k,nextCursor:C,phase:R,attentionReasons:E,pendingSessionIds:M,respondingSessionIds:j,search:A,sessionAgentFilter:T,sessionsCount:N,sinceFilter:P,statusText:D,t:L,visibleSessions:F,onLoadMore:O,onCopyResumeCommand:q,onResumeInTerminal:_,onConnectTarget:$,onRequestNewSession:z,onDeleteSession:H,onRenameSession:B,onEditFolderTags:U,onOpenSessionDetails:W,onResetFilters:K,onRenameTarget:G,onEditConnection:Q,onSearchChange:V,onSearchCommit:J,onSelectSession:Z,onToggleSessionArchived:X,onToggleSessionPinned:Y,onSessionAgentFilterChange:ee,onSinceFilterChange:se,onToggleFolder:re,onToggleAllFolders:oe,onToggleGroupFolders:ae,onToggleHideArchived:ce,onToggleNeedsAttentionGroup:le,onToggleRunningGroup:de,onToggleSeparatePinnedGroup:ue}){t.useEffect(()=>(s().onDaemonUpdateChange?.(r),()=>s().onDaemonUpdateChange?.(!1)),[r]);const he=function({activeSessionId:e,activeDaemonId:n,groupFolders:r,groupedSessions:i,collapsedFolders:o,onToggleFolder:a}){const c=t.useRef(null),l=t.useRef({key:"",revealed:!1});return t.useLayoutEffect(()=>{if("desktop"!==s().kind)return;const t=JSON.stringify([n,e]);if(l.current.key!==t&&(l.current={key:t,revealed:!1}),!e||l.current.revealed)return;if(r){const t=i.filter(t=>t.sessions.some(t=>t.sessionId===e)),n=t.find(e=>!o[e.folder])??t[0];if(n&&o[n.folder])return void(l.current.opening!==n.folder&&(l.current.opening=n.folder,a(n.folder)))}const d=c.current?.querySelector('.session-row[aria-current="true"]');if(!d)return;const u=requestAnimationFrame(()=>{d.isConnected&&l.current.key===t&&(d.scrollIntoView({block:"nearest",inline:"nearest",behavior:"instant"}),l.current.revealed=!0)});return()=>cancelAnimationFrame(u)},[n,e,o,r,i,a]),c}({activeSessionId:i,activeDaemonId:d,groupFolders:p,groupedSessions:y,collapsedFolders:a,onToggleFolder:re}),[me,fe]=t.useState(null),[pe,ge]=t.useState(!1),[ve,ye]=t.useState(null);t.useEffect(()=>{if(!ve)return;const e=window.setTimeout(()=>ye(null),2400);return()=>window.clearTimeout(e)},[ve]);const[we,Se]=t.useState(null),[xe,Ie]=t.useState(null),ke=t.useRef(null),Ce=t.useRef(null),[Re,Ee]=t.useState(null),Me="updated"!==g||"all"!==T||"30d"!==P||!p||p&&(S||x||w)||b,je=function(e,n,s=!1){const r=t.useMemo(()=>e,[e?.lastActivityAt,e?.sessionId]),i=t.useRef(null),o=t.useRef(null),a=t.useRef(n),[c,l]=t.useState(null),d=Boolean(e?.lastActivityAt&&e.sessionId),u=d?`${e?.lastActivityAt}:${e?.sessionId}`:null;return t.useEffect(()=>{a.current=n},[n]),t.useEffect(()=>{const e=i.current;if(!e||!r||!u)return o.current=null,void l(null);const t=e.closest(".session-list");if(!(t instanceof HTMLElement))return;let n,c=!0;l(null);const d=()=>{o.current!==u&&(o.current=u,l(u),a.current(r).catch(()=>{c&&(n=window.setTimeout(()=>{c&&(o.current=null,s?d():(h?.unobserve(e),h?.observe(e)))},1500))}).finally(()=>{c&&l(e=>e===u?null:e)}))},h=s?null:new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&d()},{root:t,rootMargin:"0px 0px 240px 0px",threshold:.01});return s?d():h?.observe(e),()=>{c=!1,o.current=null,void 0!==n&&window.clearTimeout(n),h?.disconnect()}},[u,r,s]),{canLoadMore:d,loading:d&&c===u,sentinelRef:i}}(C,O,"updated"!==g||!b),Ae=!!xe&&Boolean(M?.has(xe.session.sessionId)),Te=t.useCallback(e=>m[function(e){return"string"==typeof e&&e.trim().length>0?e:void 0}(e)??"/"]??[],[m]),Ne=`${D} · ${"connected"===R?`${F.length}/${N} sessions · v${k??"-"}`:L.sameOriginAccess}`,Pe=s().toolbarTarget?.("left");t.useLayoutEffect(()=>{if(!pe)return;const e=()=>{const e=ke.current?.getBoundingClientRect();if(!e)return;const t=Math.min(820,window.innerWidth-24);Ee({top:e.bottom+8,left:Math.max(12,Math.min(e.left,window.innerWidth-t-12))})};return e(),window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[pe]),t.useEffect(()=>{if(!pe&&!xe)return;const e=e=>{const t=e.target;t instanceof Node&&(ke.current?.contains(t)||Ce.current?.contains(t))||(ge(!1),Ie(null))},t=e=>{"Escape"===e.key&&(ge(!1),Ie(null))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[xe,pe]);const De=(e,t)=>{Ie(null),ge(!1),z(t)},Le=Boolean(_&&d&&s().resumeInTerminal&&s().isLocalDaemon?.(d)),Fe=(e,t,n)=>{if("sessionOpen"!==e&&"sessionDelete"!==e&&M?.has(t.sessionId))return!1;if("sessionRename"===e&&!n)return!1;if("sessionResumeTerminal"===e&&(!Le||j.has(t.sessionId)))return!1;switch(Ie(null),e){case"sessionOpen":Z(t.sessionId);break;case"sessionRename":fe(n);break;case"sessionDetails":W(t);break;case"sessionCopyResume":Promise.resolve(q(t)).then(()=>ye({message:L.commandCopied,tone:"success"})).catch(()=>ye({message:L.copyResumeFailed,tone:"error"}));break;case"sessionResumeTerminal":_?.(t);break;case"sessionPin":Y(t);break;case"sessionArchive":X(t);break;case"sessionDelete":H(t)}return!0};!function({menu:e,activeSessionId:n,sessions:s,run:r}){const i=t.useRef({menu:e,activeSessionId:n,sessions:s,run:r});i.current={menu:e,activeSessionId:n,sessions:s,run:r},t.useEffect(()=>{const e=e=>{const{command:t,event:n}=e.detail,{menu:s,activeSessionId:r,sessions:o,run:a}=i.current;if(!s&&n.target instanceof Element&&n.target.closest('input, textarea, select, [contenteditable="true"], [role="textbox"], .xterm'))return;const c=Array.from(document.querySelectorAll(".session-rail .session-row")),l=n.target instanceof Element?n.target.closest(".session-item"):null,d=l?.querySelector(".session-row")??c.find(e=>e.dataset.sessionId===r),u=s?.session??o.find(e=>e.sessionId===d?.dataset.sessionId);u&&a(t,u,s?.rowId??d?.dataset.rowId??"")&&(n.preventDefault(),n.stopPropagation())};return window.addEventListener(Er,e),()=>window.removeEventListener(Er,e)},[])}({menu:xe,activeSessionId:i,sessions:F,run:Fe});const Oe=e=>{xe&&Fe(e,xe.session,xe.rowId)},qe=n.jsxs("div",{className:"brand-block",title:Ne,children:[n.jsx("div",{className:"brand-mark","aria-hidden":"true",children:n.jsx("img",{alt:"",className:"brand-logo",height:"40",src:"/web/assets/logo-Caf1Fn81.webp",width:"40"})}),n.jsx(oo,{activeDaemonId:d,busy:o,fallbackName:u,phase:R,statusText:D,t:L,targets:h,onConnect:$,onRename:G,onEditConnection:Q})]});return n.jsxs("aside",{className:"session-rail","aria-label":L.sessions,children:[Pe?I.createPortal(qe,Pe):qe,n.jsxs("div",{className:"search-filter-wrap",ref:ke,children:[n.jsx(lo,{folderToggle:p&&y.length>0&&n.jsx("button",{"aria-label":c?L.expandAllSessions:L.collapseAllSessions,"aria-pressed":c,className:"session-folders-toggle",onClick:oe,title:c?L.expandAllSessions:L.collapseAllSessions,type:"button",children:c?n.jsx(ne,{"aria-hidden":"true"}):n.jsx(ie,{"aria-hidden":"true"})}),search:A,connected:"connected"===R,filtersOpen:pe,filtersActive:Me,t:L,onSearchChange:V,onSearchCommit:J,onToggleFilters:()=>ge(e=>!e),onCreate:De}),pe&&Re?I.createPortal(n.jsxs("div",{className:"filter-popover session-filter-popover",role:"dialog","aria-label":L.sessionFilters,ref:Ce,style:{top:Re.top,left:Re.left},children:[n.jsx(ao,{label:L.sessionSortLabel,value:g,options:[{value:"updated",label:L.sessionSortUpdated},{value:"created",label:L.sessionSortCreated},{value:"title",label:L.sessionSortTitle},{value:"folder",label:L.sessionSortFolder}],onChange:v}),n.jsx(go,{agentFilter:T,t:L,onAgentFilterChange:ee}),n.jsx(ao,{label:L.searchTimeRangeLabel,value:P,options:[{value:"all",label:L.searchTimeRangeAllTime},{value:"7d",label:L.searchTimeRangeLast7Days},{value:"30d",label:L.searchTimeRangeLast30Days},{value:"90d",label:L.searchTimeRangeLast90Days}],onChange:se}),n.jsx(vo,{groupFolders:p,hideArchived:b,separatePinnedGroup:w,showNeedsAttentionGroup:S,showRunningGroup:x,t:L,onToggleGroupFolders:ae,onToggleHideArchived:ce,onToggleNeedsAttentionGroup:le,onToggleRunningGroup:de,onToggleSeparatePinnedGroup:ue}),Me?n.jsx("button",{className:"filter-reset-button",onClick:K,type:"button",children:L.resetFilters}):null]}),document.body):null]}),n.jsxs("div",{className:"session-list",ref:he,children:[n.jsx(fo,{activeSessionId:i,renamingRowId:me,onRenameSession:B,onCloseRename:()=>fe(null),collapsedFolders:a,folderCounts:f,getFolderTags:Te,groupFolders:p,groupedSessions:y,phase:R,attentionReasons:E,pendingSessionIds:M,respondingSessionIds:j,t:L,visibleSessions:F,onEditFolderTags:e=>{ge(!1),Ie(null),Se({folder:e,value:Te(e).join(", ")})},onOpenCreateMenu:De,onOpenSessionMenu:(e,t)=>{e.preventDefault(),Ie({session:t,rowId:e.currentTarget.dataset.rowId??"",x:Math.min(e.clientX,window.innerWidth-224-10),y:Math.min(e.clientY,window.innerHeight-342-10)})},onSelectSession:Z,onToggleSessionArchived:X,onToggleSessionPinned:Y,onToggleFolder:re},d??"unconnected"),je.canLoadMore?n.jsx("div",{"aria-live":"polite",className:"session-load-sentinel "+(je.loading?"loading":""),ref:je.sentinelRef,role:"status",children:je.loading?n.jsxs(n.Fragment,{children:[n.jsx(te,{className:"spin","aria-hidden":"true"}),n.jsx("span",{children:L.loadingMore})]}):null}):null]}),n.jsxs("div",{className:"session-rail-footer",children:[n.jsx("div",{className:"rail-footer-indicators",children:e}),s().openSettings&&n.jsxs("button",{"aria-label":L.settings,className:"icon-button rail-settings-button",onClick:()=>s().openSettings?.(r?"daemon":void 0),title:L.settings,type:"button",children:[n.jsx(be,{"aria-hidden":"true"}),s().settingsBadge?.(r)]})]}),we?n.jsx(co,{folder:we.folder,initialValue:we.value,t:L,onClose:()=>Se(null),onSave:e=>{we&&(U(we.folder,e),Se(null))}}):null,xe?n.jsx(uo,{menu:xe,pending:Ae,t:L,onOpen:()=>Oe("sessionOpen"),onRename:()=>Oe("sessionRename"),onDetails:()=>Oe("sessionDetails"),onCopyResumeCommand:()=>Oe("sessionCopyResume"),onResumeInTerminal:Le?()=>Oe("sessionResumeTerminal"):void 0,terminalBusy:j.has(xe.session.sessionId),onTogglePinned:()=>Oe("sessionPin"),onToggleArchived:()=>Oe("sessionArchive"),onDelete:()=>Oe("sessionDelete")}):null,n.jsx(eo,{feedback:ve})]})}function bo({collapsed:e,children:t,onExpand:r,onResize:i,t:o}){const a=s().toolbarTarget?.("left"),c=n.jsx("button",{"aria-label":e?o.expandSessionSidebar:o.collapseSessionSidebar,className:"sidebar-titlebar-toggle",onClick:r,title:zr(e?o.expandSessionSidebar:o.collapseSessionSidebar,"leftSidebar"),type:"button",children:n.jsx(ae,{"aria-hidden":"true"})});return n.jsxs(n.Fragment,{children:[a?I.createPortal(c,a):c,n.jsx("div",{className:"session-sidebar-motion",inert:e,"aria-hidden":e,children:t}),n.jsx("button",{"aria-label":o.resizeSessionSidebar,"aria-hidden":e,className:"resize-handle",disabled:e,onPointerDown:i,title:o.resizeSessionSidebar,type:"button",children:n.jsx("span",{})})]})}function wo(e){const n=$e(),r=n.items.find(e=>e.id===n.right.browser&&"right"===e.location),i=r?.currentUrl??r?.url,o=t.useRef(null);return t.useEffect(()=>{o.current!==n.scopeKey&&(o.current=n.scopeKey,"desktop"!==s().kind||"browser"!==e.controlTab||i&&"about:blank"!==i||e.setRightSidebarCollapsed(!0))},[n.scopeKey,i,e.controlTab,e.setRightSidebarCollapsed]),()=>{e.rightSidebarCollapsed&&("session"===e.controlTab&&0===e.pendingActionsCount||"desktop"===s().kind&&"browser"===e.controlTab&&(!i||"about:blank"===i))&&e.setControlTab("files"),e.setRightSidebarCollapsed(e=>!e)}}const So={en:{reset:"Reset all session models to CLI defaults",resetHint:"Current connection · Claude and Codex · Keep fast mode unchanged",settings:"Open settings",left:"Toggle left sidebar",right:"Toggle right sidebar",files:"Open file tree",terminal:"Open terminal",browser:"Open browser",diff:"View current session Git changes",working:"Resetting models…",done:"Updated {ok} · Failed {failed}",error:"Reset interrupted. Some sessions may have been updated. Check the connection and retry.",offline:"Connect to a device first",commandHint:"↑ ↓ Select · Enter Run · Esc Close"},"zh-CN":{reset:"将所有会话模型重置为 CLI 默认模型",resetHint:"当前连接 · Claude 和 Codex · 保留快速模式设置",settings:"打开设置",left:"显示 / 隐藏左侧栏",right:"显示 / 隐藏右侧栏",files:"打开文件树",terminal:"打开终端",browser:"打开浏览器",diff:"查看当前会话 Git 变更",working:"正在重置模型…",done:"已更新 {ok} 个 · 失败 {failed} 个",error:"重置中断,部分会话可能已更新。请检查连接后重试。",offline:"请先连接设备",commandHint:"↑ ↓ 选择 · Enter 执行 · Esc 关闭"},"zh-TW":{reset:"將所有會話模型重置為 CLI 預設模型",resetHint:"目前連線 · Claude 和 Codex · 保留快速模式設定",settings:"開啟設定",left:"顯示 / 隱藏左側欄",right:"顯示 / 隱藏右側欄",files:"開啟檔案樹",terminal:"開啟終端機",browser:"開啟瀏覽器",diff:"檢視目前會話 Git 變更",working:"正在重置模型…",done:"已更新 {ok} 個 · 失敗 {failed} 個",error:"重置中斷,部分會話可能已更新。請檢查連線後重試。",offline:"請先連線裝置",commandHint:"↑ ↓ 選擇 · Enter 執行 · Esc 關閉"}};function xo({workspace:e,onSelect:r}){const[i,o]=t.useState(!1),[a,d]=t.useState(""),u=function(e,n){const r=So["zh"===n?"zh-CN":n]??So.en,i=wo(e),o=t.useRef(!1),[a,c]=t.useState(!1),[l,d]=t.useState(null),u="connected"===e.phase;return{commands:[{id:"resetModels",title:r.reset,meta:u?r.resetHint:r.offline,keywords:"reset models cli default auto 重置 模型 默认 預設",disabled:!u||a,keepOpen:!0,select:()=>{(async()=>{if(o.current||!u)return;o.current=!0,c(!0);const t=e.pairing?.daemonId,n=e=>d({scope:t,text:e}),s=e=>r.done.replace("{ok}",String(e.updated)).replace("{failed}",String(e.failed));n(r.working);try{const t=await e.applyToAllSessions({models:{claude:"",codex:""}},e=>n(`${r.working} ${s(e)}`));n(s(t))}catch{n(r.error)}finally{o.current=!1,c(!1)}})()}},{id:"settings",title:r.settings,meta:"",keywords:"settings preferences 设置 設定",select:()=>s().openSettings?.()},{id:"left",title:r.left,meta:"",keywords:"left sidebar 左侧栏 左側欄",select:()=>e.setLeftSidebarCollapsed(e=>!e)},{id:"right",title:r.right,meta:"",keywords:"right sidebar 右侧栏 右側欄",select:i},...["files","terminal","browser"].map(t=>({id:t,title:r[t],meta:"",keywords:t,select:()=>e.setControlTabAndOpen(t)})),{id:"diff",title:r.diff,meta:"",keywords:"git diff changes 差异 差異",disabled:!e.activeSession,select:()=>{e.activeSession&&e.setDiffSessionId(e.activeSession.sessionId)}}].map(e=>({...e,disabled:e.disabled||a})),busy:a,status:l?.scope===e.pairing?.daemonId?l?.text:void 0,hint:r.commandHint}}(e,c(l().language));return t.useEffect(()=>{const e=e=>{d(e.detail?.commandMode?"> ":""),o(!0)};return window.addEventListener("vibelet.quick-search",e),()=>window.removeEventListener("vibelet.quick-search",e)},[]),t.useEffect(()=>o(!1),[e.pairing?.daemonId]),i?n.jsx(Io,{initialQuery:a,workspace:e,onSelect:r,onClose:()=>o(!1),commandState:u},a):null}function Io({workspace:e,onSelect:s,onClose:r,commandState:i,initialQuery:o}){const d=$e(),[u,h]=t.useState(o),[m,f]=t.useState(0),p=u.startsWith(">"),[g,v]=t.useState([]),[y,b]=t.useState(!0),[w,S]=t.useState(!1),x=t.useRef(null),k=R(r,x),C=c(l().language),E="en"===C?{title:"Quick switch",placeholder:"Search tab name, branch, PR title or #number, or > commands…",empty:"No matches",loading:"Loading sessions…",error:"Could not load all sessions. Close and reopen to retry.",hint:"↑ ↓ Select · Enter Open · Esc Close"}:"zh-TW"===C?{title:"快速定位",placeholder:"搜尋標籤名稱、分支、PR 標題或 #編號,或輸入 > 執行命令…",empty:"沒有符合的結果",loading:"正在載入會話…",error:"部分會話載入失敗,請關閉後重新開啟重試。",hint:"↑ ↓ 選擇 · Enter 開啟 · Esc 關閉"}:{title:"快速定位",placeholder:"搜索标签名称、分支、PR 标题或 #编号,或输入 > 执行命令…",empty:"没有匹配的结果",loading:"正在加载会话…",error:"部分会话加载失败,请关闭后重新打开重试。",hint:"↑ ↓ 选择 · Enter 打开 · Esc 关闭"};t.useEffect(()=>{let t=!1;const n=e.clientRef.current;return(async()=>{if(!n?.isConnected)return b(!1),void S(!0);let s;do{const r=await n.request({action:"sessions.list",id:n.makeId("quick_search"),limit:100,cursor:s,hideArchived:!0});if(t||e.clientRef.current!==n)return;v(e=>[...e,...r.sessions]),s=r.nextCursor}while(s);b(!1)})().catch(()=>{t||(S(!0),b(!1))}),()=>{t=!0}},[e.clientRef]);const M=new Map(g.map(e=>[e.sessionId,e]));for(const t of e.displaySessions)M.set(t.sessionId,{...M.get(t.sessionId),...t});const j=p?function(e,t){const n=t.trim().toLocaleLowerCase().split(/\s+/),s=e=>n.filter(t=>e.title.toLocaleLowerCase().includes(t)).length;return e.filter(e=>n.every(t=>`${e.title} ${e.meta} ${e.keywords}`.toLocaleLowerCase().includes(t))).sort((e,t)=>s(t)-s(e))}(i.commands,u.slice(1)):[...d.items.filter(e=>!e.emptyPlaceholder&&e.title.toLocaleLowerCase().includes(u.trim().toLocaleLowerCase())).map(t=>({id:`tab-${t.id}`,title:t.title,meta:t.currentUrl||t.cwd||t.kind,select:()=>{"center"===t.location||"diff"===t.kind?d.setCenter(t.id):(d.setRight(e=>({...e,[t.kind]:t.id})),e.setControlTabAndOpen(t.kind))}})),...[...M.values()].filter(e=>!e.archived&&function(e,t){const n=e.pullRequest,s=[a(e),e.title,...e.titleAliases??[],e.branch,e.cwd,e.agent,n?.title,n?.url,n&&`#${n.number}`].filter(Boolean).join(" ").toLocaleLowerCase();return t.trim().toLocaleLowerCase().split(/\s+/).every(e=>s.includes(e))}(e,u)).map(t=>({id:t.sessionId,title:a(t),meta:[t.branch,t.pullRequest&&`#${t.pullRequest.number} ${t.pullRequest.title}`,t.cwd].filter(Boolean).join(" · "),select:()=>{e.setSessions(e=>e.some(e=>e.sessionId===t.sessionId)?e:[...e,t]),s(t.sessionId)}}))],A=Math.min(m,Math.max(0,j.length-1));t.useEffect(()=>{k.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({block:"nearest"})},[A,u]);const T=e=>{const t=j[e];t&&!t.disabled&&(t.keepOpen||r(),t.select())};return I.createPortal(n.jsx("div",{className:"quick-session-backdrop",onMouseDown:e=>{e.target===e.currentTarget&&r()},children:n.jsxs("div",{className:"quick-session-dialog",ref:k,role:"dialog","aria-modal":"true","aria-label":E.title,onKeyDown:e=>{e.nativeEvent.isComposing||("Enter"===e.key&&(e.preventDefault(),T(A)),"ArrowDown"!==e.key&&"ArrowUp"!==e.key||(e.preventDefault(),f((A+("ArrowDown"===e.key?1:-1)+j.length)%Math.max(1,j.length))))},children:[n.jsx("input",{ref:x,role:"combobox","aria-label":E.title,"aria-expanded":"true","aria-controls":"quick-session-results","aria-activedescendant":j[A]?`quick-result-${A}`:void 0,placeholder:E.placeholder,value:u,onChange:e=>{h(e.target.value),f(0)}}),n.jsxs("div",{className:"quick-session-results",id:"quick-session-results",role:"listbox","aria-label":E.title,children:[j.map((e,t)=>n.jsxs("button",{id:`quick-result-${t}`,type:"button",role:"option",tabIndex:-1,"aria-selected":t===A,"aria-disabled":e.disabled||void 0,onClick:()=>T(t),children:[n.jsx("strong",{children:e.title}),e.meta&&n.jsx("small",{children:e.meta})]},e.id)),!j.length&&(p||!y)&&n.jsx("p",{children:E.empty})]}),n.jsx("footer",{"aria-live":"polite",children:p?i.status||i.hint:w?E.error:y?E.loading:E.hint})]})}),document.body)}function ko({activeSessionId:e,activeSession:s,cwd:r,directoryPath:i,visible:o,t:a}){const[c,l]=t.useState(o);t.useEffect(()=>{o&&l(!0)},[o]);const d=e?s?.sessionId===e?s.cwd:void 0:r===rn?i:r;return c&&d?n.jsxs("div",{hidden:!o,className:"terminal-tab-content",children:[n.jsx(Mi,{location:"right",kind:"terminal",t:a,cwd:d}),n.jsx(Ai,{location:"right",kind:"terminal"})]}):null}function Co(e){const t=e?.fiveHour??e?.weekly,n=Number(t?.usedPercent);return Number.isFinite(n)?{availablePercent:Math.round(Math.max(0,Math.min(100,100-n))),resetsAt:t?.resetsAt??""}:null}function Ro(e){return e?"success":"warning"}function Eo(e,t){return e&&null!==t?t<150?"success":t<500?"warning":"danger":"warning"}function Mo(e,t){if(!e)return t.quotaNotProvided;const n=new Date(e);if(!Number.isFinite(n.getTime()))return t.quotaNotProvided;const s="浏览器"===t.browser?"zh-CN":"瀏覽器"===t.browser?"zh-TW":"en-US";return n.toLocaleString(s,{year:"numeric",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",timeZoneName:"short"})}function jo({limits:e,agent:t="codex",failed:s,connected:r,t:i}){return n.jsxs(n.Fragment,{children:[!r&&n.jsx("p",{className:"quota-details-warning",children:i.latencyDisconnected}),[t].map(t=>{const r=e[t],o=r?.limits,a=[[i.quotaFiveHour,o?.fiveHour],[i.quotaWeekly,o?.weekly],["Opus",o?.weeklyOpus],["Sonnet",o?.weeklySonnet],...(o?.additional??[]).flatMap(e=>[[`${e.name} · ${i.quotaFiveHour}`,e.primary],[`${e.name} · ${i.quotaWeekly}`,e.secondary]])];return n.jsxs("section",{children:[n.jsx("strong",{children:"codex"===t?"Codex":"Claude"}),"codex"===t&&n.jsxs("div",{className:"quota-details-account",children:[n.jsx("span",{children:i.quotaAccount}),n.jsx("b",{children:r?.account?.email||("apiKey"===r?.account?.type?"API Key":i.quotaAccountUnavailable)})]}),n.jsxs("div",{className:"quota-details-line",children:[n.jsx("span",{children:i.quotaPlan}),n.jsx("b",{children:r?.account?.planType||o?.planType||i.quotaNotProvided})]}),s[t]&&n.jsx("p",{className:"quota-details-warning",children:i.quotaUpdateFailed}),!o&&n.jsx("p",{children:i.quotaUnavailable}),a.filter(([,e])=>e&&Number.isFinite(e.usedPercent)).map(([e,t],s)=>{const r=Math.round(Math.max(0,Math.min(100,100-t.usedPercent)));return n.jsxs("div",{className:"quota-details-window",children:[n.jsxs("div",{className:"quota-details-line",children:[n.jsx("span",{children:e}),n.jsxs("b",{children:[i.quotaRemaining," ",r,"%"]})]}),n.jsx("meter",{min:0,max:100,value:r,"aria-label":e}),n.jsxs("small",{children:[i.quotaReset," · ",Mo(t.resetsAt,i)]})]},`${e}-${s}`)}),"codex"===t&&n.jsxs("div",{className:"quota-details-window",children:[n.jsxs("div",{className:"quota-details-line",children:[n.jsx("span",{children:i.quotaResetCards}),n.jsx("b",{children:r?.resetCredits?`${i.quotaCardsAvailable} ${r.resetCredits.availableCount}`:i.quotaNotProvided})]}),r?.resetCredits?.cards.map((e,t)=>n.jsxs("div",{className:"quota-details-window",children:[n.jsxs("div",{className:"quota-details-line",children:[n.jsx("span",{children:e.title}),n.jsx("span",{children:"available"===e.status?i.quotaCardsAvailable:e.status})]}),n.jsxs("small",{children:[i.quotaCardExpires," · ",Mo(e.expiresAt,i)]})]},t))]}),o?.fetchedAt?n.jsxs("small",{children:[i.quotaUpdated," · ",Mo(o.fetchedAt,i)]}):null]},t)})]})}function Ao({connected:e,latencyMs:s,limits:r,t:i,failed:o={},loading:a=!1,onRetry:c}){const l=t.useId(),d=t.useRef(null),u=t.useRef(null),[h,m]=t.useState(null);t.useEffect(()=>{if(!h)return;const e=e=>{e.target instanceof Node&&!d.current?.contains(e.target)&&!u.current?.contains(e.target)&&m(null)},t=e=>{"Escape"===e.key&&(m(null),d.current?.focus())},n=()=>m(null);return document.addEventListener("pointerdown",e),document.addEventListener("focusin",e),document.addEventListener("keydown",t),window.addEventListener("resize",n),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("focusin",e),document.removeEventListener("keydown",t),window.removeEventListener("resize",n)}},[Boolean(h)]);const f=function(e){const t=[],n=Co(e.codex),s=Co(e.claude);return null!==n&&t.push({agent:"codex",label:"Codex",...n}),null!==s&&t.push({agent:"claude",label:"Claude",...s}),t}({codex:r.codex?.limits,claude:r.claude?.limits}),[p,g]=t.useState(0);t.useEffect(()=>{if(f.length<2||h)return;const e=setInterval(()=>g(e=>(e+1)%f.length),4e3);return()=>clearInterval(e)},[f.length,Boolean(h)]);const v=f[p%f.length],y=v?function(e,t=Date.now()){const n=new Date(e);if(!Number.isFinite(n.getTime())||n.getTime()<=t)return null;const s=e=>String(e).padStart(2,"0");return`${n.getFullYear()}-${s(n.getMonth()+1)}-${s(n.getDate())} ${s(n.getHours())}:${s(n.getMinutes())}`}(v.resetsAt):null,b=v?`${v.label} ${v.availablePercent}%`:"",w=!!v&&o[v.agent],S=w?i.quotaUpdateFailed:v?"":a?i.loading:i.quotaUnavailable,x=`${i.remainingQuota}: ${b||S}${w?` · ${S}`:""} · ${y?i.quotaResetsAt.replace("{time}",y):i.quotaResetUnavailable}${e?"":` · ${i.latencyDisconnected}`}`,k=e?null===s?i.latencyMeasuring:`${s} ms`:i.latencyDisconnected;return n.jsxs("div",{className:"connection-indicators",children:[(v||c)&&n.jsxs("span",{children:[n.jsxs("button",{ref:d,type:"button",className:"connection-quota",onClick:()=>{h?m(null):((()=>{const e=d.current?.getBoundingClientRect();e&&m({left:Math.max(12,Math.min(e.left,innerWidth-352)),bottom:innerHeight-e.top+8,maxHeight:Math.max(80,e.top-24)})})(),e&&!a&&c?.())},"aria-haspopup":"dialog","aria-expanded":Boolean(h),"aria-controls":h?l:void 0,"aria-label":`${x}${c?` · ${i.retry}`:""}`,"aria-busy":a,children:[n.jsx("span",{className:"connection-quota-dot",style:{background:`var(--${w||!v?"warning":Ro(e)})`}}),n.jsxs("span",{className:"connection-quota-text",children:[b||S,w?" ↻":""]})]}),h&&I.createPortal(n.jsx("div",{id:l,ref:u,role:"dialog","aria-label":i.remainingQuota,className:"quota-details",style:h,children:n.jsx(jo,{agent:v?.agent,limits:r,failed:o,connected:e,t:i})}),document.body)]}),n.jsxs("span",{role:"img",className:"connection-latency",style:{color:`var(--${Eo(e,s)})`},"aria-label":`${i.connectionLatency}: ${k}`,children:[n.jsx(T,{size:11,"aria-hidden":"true"}),n.jsx("span",{className:"connection-latency-text",children:k})]})]})}function To({workspace:e}){const{phase:s,clientRef:r,pairing:i,t:o}=e,[a,c]=t.useState(null),[l,d]=t.useState({}),[u,h]=t.useState({}),[m,f]=t.useState(!1),p=t.useRef(()=>{});return t.useEffect(()=>{h({}),d({})},[i?.daemonId]),t.useEffect(()=>{const e=r.current;if(c(null),f(!1),"connected"!==s||!e)return;let t=!0;const n=e.onLatency(c),i=new Set,o=new Map,a={codex:0,claude:0},l=()=>t&&r.current===e&&e.isConnected,u=(n,s=!1)=>{l()&&!i.has(n)&&(clearTimeout(o.get(n)),i.add(n),f(!0),er(e,()=>({action:"usage.limits.fetch",id:e.makeId("header-usage"),agent:n,force:s}),l).then(e=>{if(!l())return;const t=Boolean(e?.limits);a[n]=t?0:a[n]+1,h(e=>({...e,[n]:!t})),(e?.limits||e?.account)&&d(t=>{const s=t[n],r=e.account&&s?.account&&e.account.type===s.account.type&&e.account.email===s.account.email;return{...t,[n]:e.limits?e:{...e,limits:r?s.limits:null}}});const s=t?6e4:Math.min(6e4,15e3*2**Math.min(a[n]-1,2));o.set(n,setTimeout(()=>u(n),s))}).finally(()=>{i.delete(n),t&&f(i.size>0)}))},m=()=>{u("codex"),u("claude")};return p.current=()=>{u("codex",!0),u("claude",!0)},m(),window.addEventListener("online",m),window.addEventListener("focus",m),()=>{t=!1,p.current=()=>{},n();for(const e of o.values())clearTimeout(e);window.removeEventListener("online",m),window.removeEventListener("focus",m)}},[s,r,i?.daemonId]),n.jsx(Ao,{connected:"connected"===s,latencyMs:a,limits:l,failed:u,loading:m,onRetry:()=>p.current(),t:o})}function No({value:e,t,showSession:s=!0,onChange:r}){const i=[...s?[{tab:"session",label:t.session,Icon:we}]:[],{tab:"files",label:t.files,Icon:V},{tab:"terminal",label:t.terminal,Icon:Se},{tab:"browser",label:t.browser,Icon:Y}];return n.jsx("div",{className:"control-tabs",children:i.map(({tab:t,label:s,Icon:i})=>n.jsxs("button",{"aria-label":s,"aria-pressed":e===t,className:e===t?"selected":"",onClick:()=>r(t),title:s,type:"button",children:[n.jsx(i,{"aria-hidden":"true"}),n.jsx("span",{children:s})]},t))})}function Po(){const[e,s]=t.useState(null);return t.useEffect(()=>{let e=null,t=null;const n=()=>{e&&null!==t&&e.setAttribute("title",t),e=null,t=null,s(null)},r=e=>{if(!(e instanceof Element))return null;const t=e.closest("button, a");return t?.closest(".control-pane, .control-tabs, .header-actions, .right-resize-handle")?t.textContent?.trim()?null:t:null},i=r=>{if(r===e)return;if(n(),!r)return;const i=r.getAttribute("title")||r.getAttribute("aria-label");if(!i)return;e=r,t=r.getAttribute("title"),null!==t&&r.removeAttribute("title");const o=r.getBoundingClientRect(),a=o.bottom+42>window.innerHeight,c=o.right>window.innerWidth-140?"end":o.left<140?"start":"center";s({label:i,left:"end"===c?o.right:"start"===c?o.left:o.left+o.width/2,top:a?o.top-7:o.bottom+7,above:a,align:c})},o=e=>i(r(e.target)),a=t=>{e&&t.relatedTarget instanceof Node&&e.contains(t.relatedTarget)||r(t.target)===e&&n()},c=e=>i(r(e.target)),l=t=>{r(t.target)===e&&n()};return document.addEventListener("pointerover",o),document.addEventListener("pointerout",a),document.addEventListener("focusin",c),document.addEventListener("focusout",l),()=>{document.removeEventListener("pointerover",o),document.removeEventListener("pointerout",a),document.removeEventListener("focusin",c),document.removeEventListener("focusout",l),n()}},[]),e?I.createPortal(n.jsx("div",{className:"right-sidebar-icon-hint",role:"tooltip",style:{left:e.left,top:e.top,transform:`translate(${"end"===e.align?"-100%":"start"===e.align?"0":"-50%"}, ${e.above?"-100%":"0"})`},children:e.label}),document.body):null}function Do({chinese:e}){const r=Fr("mod+n").replace(/N$/,""),[o,a]=t.useState(_r),[c,l]=t.useState(null),[d,u]=t.useState(""),h=e=>{!function(e){i().setItem(qr,JSON.stringify(e)),window.dispatchEvent(new Event(jr))}(e),a(e),u("")};return n.jsxs("section",{className:"control-section compact-section workspace-shortcut-settings",children:[n.jsx("h2",{children:e?"应用内快捷键":"In-app shortcuts"}),n.jsx("p",{className:"empty-copy",children:e?"会话切换快捷键默认不设置;聚焦左侧会话列表后可按 ↑ / ↓ 切换。点击组合键后直接按键录制。Esc 取消,退格键清除。新建标签会沿用当前终端或浏览器;右侧栏隐藏时不新建标签。":"Session switching is unassigned by default; use ↑ / ↓ while the session list is focused. Click a shortcut to record it. Escape cancels; Backspace clears. New tab follows the current terminal or browser; it does nothing while the right sidebar is hidden."}),Tr.map(t=>n.jsxs("div",{className:"workspace-shortcut-row",children:[n.jsx("span",{children:e?t.zh:t.en}),n.jsx("button",{type:"button","data-shortcut-recording":c===t.id?"true":void 0,"aria-label":`${e?"设置快捷键:":"Set shortcut: "}${e?t.zh:t.en}`,onClick:()=>{l(t.id),u("")},onBlur:()=>l(null),onKeyDown:n=>{if(c!==t.id)return;if(n.preventDefault(),n.stopPropagation(),"Escape"===n.key)return l(null),void u("");if("Backspace"===n.key||"Delete"===n.key)return h({...o,[t.id]:""}),void l(null);const r=Lr(n.nativeEvent);if(!r)return;const i=function(e,t,n){return"browser"===s().kind?"mod+w"===t?"reserved":Or(e,t,{closeTab:"mod+alt+w",...n}):Or(e,t,n)}(t.id,r,o);if(i){const t=Tr.find(e=>e.id===i);return void u("reserved"===i?e?"此组合键用于系统菜单或编辑操作,请换一个组合。":"Reserved for a system menu or editing action. Choose another combination.":`${e?"已用于:":"Already assigned to: "}${e?t?.zh:t?.en}`)}h({...o,[t.id]:r}),l(null)},children:c===t.id?e?"按下快捷键…":"Press shortcut…":Fr($r(t.id,o))||(e?"未设置":"Not set")})]},t.id)),d&&n.jsx("p",{role:"alert",children:d}),n.jsx("div",{className:"attention-actions",children:n.jsx("button",{type:"button",onClick:()=>{h({}),l(null)},children:e?"恢复默认快捷键":"Restore defaults"})}),n.jsx("p",{className:"empty-copy",children:e?`${r}N 新建会话,${r}, 打开设置。关闭标签:${Fr($r("closeTab",o))||"未设置"}。查找作用于当前聚焦的聊天、浏览器或终端;Enter / Shift+Enter 切换匹配,Esc 关闭查找。恢复关闭的标签也支持侧栏隐藏状态。`:`${r}N creates a session; ${r}, opens settings. Close tab: ${Fr($r("closeTab",o))||"Not set"}. Find searches the focused chat, browser or terminal; Enter / Shift+Enter navigates matches and Escape closes find. Reopen closed tab also works when the sidebar is hidden.`})]})}function Lo({children:e,t:s,onClose:r}){const i=t.useRef(null);return t.useEffect(()=>{const e=document.getElementById("vibelet-workspace");return e&&(e.inert=!0),i.current?.focus(),()=>{e&&(e.inert=!1)}},[]),I.createPortal(n.jsxs("section",{className:"browser-settings-page","aria-label":s.settings,onKeyDown:e=>{if("Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),r()),"Tab"!==e.key)return;const t=[...e.currentTarget.querySelectorAll("button:not(:disabled),input:not(:disabled),a[href]")].filter(e=>e.getBoundingClientRect().width>0),n=t[0],s=t.at(-1);e.shiftKey&&document.activeElement===n&&(e.preventDefault(),s?.focus()),e.shiftKey||document.activeElement!==s||(e.preventDefault(),n?.focus())},children:[n.jsxs("button",{ref:i,type:"button",className:"icon-text-button",onClick:r,children:["← ",s.chat]}),n.jsx("h1",{children:s.settings}),n.jsxs("div",{className:"browser-settings-body",children:[n.jsx(Wr,{}),e,n.jsx(Do,{chinese:"Browser"!==s.browser})]})]}),document.body)}function Fo({children:e,collapsed:r,t:i,value:o,showSession:a,onChange:c,onResize:l}){const d=Ti("right",e=>{"terminal"!==e&&"browser"!==e||c(e)}),u=s().toolbarTarget?.("controls"),[h,m]=t.useState(null),f=n.jsx("div",{className:"right-dock-toolbar",ref:m,children:n.jsx(No,{value:o,t:i,showSession:a,onChange:c})});return"admin"===o&&"browser"===s().kind?n.jsx(Lo,{t:i,onClose:()=>c("files"),children:e}):n.jsxs(Ci.Provider,{value:{element:h,kind:o},children:[n.jsx(Po,{}),u&&!r?I.createPortal(f,u):null,n.jsx("button",{"aria-label":i.resizeControlsSidebar,"aria-hidden":r,className:"resize-handle right-resize-handle",disabled:r,onPointerDown:l,title:i.resizeControlsSidebar,type:"button",children:n.jsx("span",{})}),n.jsx("div",{className:"workspace-control-sidebar-motion",inert:r,"aria-hidden":r,children:n.jsxs("aside",{tabIndex:-1,"aria-label":i.controls,className:"control-pane",...d,children:[!u&&n.jsx("div",{className:"control-pane-toolbar",children:f}),e]})})]})}function Oo({path:e,label:t,zh:s,menu:r=!1}){const{copyText:i,feedback:o}=Yi(s?"已复制路径":"Path copied",s?"复制失败,请重试":"Copy failed. Please try again."),a=o?.message??t;return n.jsxs("button",{role:r?"menuitem":void 0,type:"button",title:a,"aria-label":a,onClick:()=>{i(e)},children:[o?"success"===o.tone?n.jsx(O,{}):n.jsx(Re,{}):n.jsx(z,{}),r&&n.jsx("span",{role:o?"status":void 0,children:a})]})}function qo({file:e,daemonId:s,downloadLabel:r,copyPathLabel:i,onDownload:o}){const[a,d]=t.useState(!1),[u,h]=t.useState(!1),[m,f]=t.useState(!1),p=t.useRef(null),g=t.useRef(null),v=t.useId(),y=c(l().language),b="en"===y?"More file actions":"zh-TW"===y?"更多檔案操作":"更多文件操作",w="en"===y?"Download failed. Try again.":"zh-TW"===y?"下載失敗,請重試":"下载失败,请重试",S=()=>{d(!1),p.current?.focus()};return t.useLayoutEffect(()=>{if(!a)return;const e=g.current,t=()=>{const t=p.current.getBoundingClientRect(),n=e.getBoundingClientRect();e.style.left=`${Math.max(8,Math.min(t.right-n.width,innerWidth-n.width-8))}px`,e.style.top=`${Math.max(8,Math.min(t.bottom+6,innerHeight-n.height-8))}px`};t(),e.querySelector("button:not(:disabled)")?.focus();const n=t=>{e.contains(t.target)||p.current?.contains(t.target)||d(!1)},s=new ResizeObserver(t);return s.observe(e),document.addEventListener("pointerdown",n),document.addEventListener("focusin",n),window.addEventListener("resize",t),document.addEventListener("scroll",t,!0),()=>{s.disconnect(),document.removeEventListener("pointerdown",n),document.removeEventListener("focusin",n),window.removeEventListener("resize",t),document.removeEventListener("scroll",t,!0)}},[a]),n.jsxs(n.Fragment,{children:[n.jsx("button",{ref:p,type:"button",title:b,"aria-label":b,"aria-haspopup":"menu","aria-expanded":a,"aria-controls":a?v:void 0,onClick:()=>d(!a),onKeyDown:e=>{"ArrowDown"!==e.key&&"ArrowUp"!==e.key||(e.preventDefault(),e.stopPropagation(),d(!0))},children:n.jsx(H,{"aria-hidden":"true"})}),a&&I.createPortal(n.jsxs("div",{ref:g,id:v,role:"menu","aria-label":b,className:"session-context-menu file-actions-menu",style:{maxWidth:"calc(100vw - 16px)",maxHeight:"calc(100vh - 16px)",overflowY:"auto"},onKeyDown:e=>{const t=Array.from(e.currentTarget.querySelectorAll("button:not(:disabled)")),n=t.indexOf(document.activeElement);["Escape","ArrowDown","ArrowUp","Home","End"].includes(e.key)&&(e.preventDefault(),e.stopPropagation()),"Escape"===e.key&&S(),"Tab"===e.key&&(e.preventDefault(),S()),"ArrowDown"===e.key&&t[(n+1)%t.length]?.focus(),"ArrowUp"===e.key&&t[(n-1+t.length)%t.length]?.focus(),"Home"===e.key&&t[0]?.focus(),"End"===e.key&&t.at(-1)?.focus()},children:[n.jsx(Oo,{path:e.path,label:i,zh:"en"!==y,menu:!0}),n.jsx(Ue,{path:e.path,cwd:e.cwd,daemonId:s,menu:!0,onComplete:S}),n.jsx(Be,{file:e,daemonId:s,menu:!0,onComplete:S}),n.jsx("span",{className:"context-menu-separator"}),n.jsxs("button",{type:"button",role:"menuitem",disabled:u,onClick:async()=>{h(!0),f(!1);try{await o(),S()}catch{f(!0)}finally{h(!1)}},children:[n.jsx(M,{"aria-hidden":"true"}),m?w:r]})]}),document.body)]})}function _o({label:e="Loading…"}){return n.jsxs("div",{className:"markdown-editor-loading",role:"status",children:[n.jsx("span",{className:"markdown-editor-loading-mark","aria-hidden":"true",children:n.jsx("span",{className:"markdown-editor-loading-ring"})}),n.jsx("span",{children:e})]})}function $o(){const e=c(l().language);return"en"===e?{read:"Read",live:"Edit",edit:"Visual",source:"Source",properties:"Properties",loading:"Loading…",unavailable:"Reference unavailable",editorError:"Unable to load the editor. Switch to source mode."}:"zh-TW"===e?{read:"瀏覽",live:"編輯",edit:"視覺化",source:"原始碼",properties:"屬性",loading:"正在載入…",unavailable:"無法讀取引用",editorError:"無法載入編輯器,請切換到原始碼模式。"}:{read:"浏览",live:"编辑",edit:"可视化",source:"源码",properties:"属性",loading:"正在加载…",unavailable:"无法读取引用",editorError:"无法加载编辑器,请切换到源码模式。"}}function zo({loading:e,children:t,className:s,style:r}){return n.jsx("div",{role:"status","aria-busy":e||void 0,className:s,style:r,children:t})}function Ho({title:e,actions:t}){return n.jsxs("header",{children:[n.jsx("span",{children:e}),t]})}function Bo(e){return n.jsx(Uo,{...e},e.source)}function Uo({className:e,style:s,title:r,actions:i,loading:o,loadingLabel:a,errorLabel:c,statusClassName:l,children:d}){const[u,h]=t.useState(!1);return n.jsxs("div",{className:e,style:s??(e?void 0:{display:"contents"}),children:[(null!=r||null!=i)&&n.jsx(Ho,{title:r,actions:i}),u||o?n.jsx(zo,{loading:o&&!u,className:l,children:u?c:a}):d(()=>h(!0))]})}function Wo({kind:e,src:t,label:s,onError:r,fillWidth:i,className:o,preload:a}){const c={src:t,controls:!0,"aria-label":s,onError:r,preload:a,className:o};return"audio"===e?n.jsx("audio",{...c,style:{width:"100%"},children:n.jsx("track",{kind:"captions"})}):n.jsx("video",{...c,playsInline:!0,style:i?{width:"100%",height:"auto",maxHeight:"none"}:{maxWidth:"100%",maxHeight:"100%"},children:n.jsx("track",{kind:"captions"})})}const Ko={zoom:"Image controls",openViewer:"Open image viewer",zoomIn:"Zoom in",zoomOut:"Zoom out",resetZoom:"Reset to fit",actualSize:"Actual size (1:1)",rotateLeft:"Rotate left",rotateRight:"Rotate right",flipHorizontal:"Flip horizontally",flipVertical:"Flip vertically",unavailable:"Image unavailable"},Go={zoom:"图片操作",openViewer:"打开图片查看器",zoomIn:"放大",zoomOut:"缩小",resetZoom:"重置为适应窗口",actualSize:"原始尺寸(1:1)",rotateLeft:"向左旋转",rotateRight:"向右旋转",flipHorizontal:"水平翻转",flipVertical:"垂直翻转",unavailable:"无法加载图片"},Qo={zoom:"圖片操作",openViewer:"開啟圖片檢視器",zoomIn:"放大",zoomOut:"縮小",resetZoom:"重設為適應視窗",actualSize:"原始尺寸(1:1)",rotateLeft:"向左旋轉",rotateRight:"向右旋轉",flipHorizontal:"水平翻轉",flipVertical:"垂直翻轉",unavailable:"無法載入圖片"};function Vo(e="en"){return/zh[-_](TW|HK|Hant)/i.test(e)?Qo:e.startsWith("zh")?Go:Ko}const Jo={actual:!1,scale:1,offset:{x:0,y:0},rotation:0,flip:{x:1,y:1}};function Zo(e){return n.jsx(Xo,{...e},e.src)}function Xo({src:e,alt:s,labels:r=Vo(),imageClassName:i="",onError:o,keyboardRoot:a,toolbarStart:c,toolbarEnd:l}){const d=t.useRef(null),u=t.useRef(null),h=t.useRef(null),[m,f]=t.useState(!1),[p,g]=t.useState(!1),[v,y]=t.useState({width:0,height:0}),[b,w]=t.useState({width:0,height:0}),S=function(e,n){const[s,r]=t.useState(Jo),i=s.rotation%180!=0,o=e.width&&e.height&&n.width&&n.height?Math.min(n.width/(i?e.height:e.width),n.height/(i?e.width:e.height)):1,a=Math.min(.1,1/o),c=Math.max(8,1/o),l=t.useCallback(()=>r(Jo),[]),d=t.useCallback((e,t={x:0,y:0})=>{r(n=>{const s=n.actual?1/o:n.scale,r=Math.min(c,Math.max(a,s*e)),i=r/s;return{...n,actual:!1,scale:r,offset:{x:t.x-(t.x-n.offset.x)*i,y:t.y-(t.y-n.offset.y)*i}}})},[c,a,o]),u=t.useCallback(()=>r(e=>({...e,actual:!0,scale:1/o,offset:{x:0,y:0}})),[o]);return{...s,scale:s.actual?1/o:s.scale,fit:o,min:a,max:c,reset:l,zoom:d,actualSize:u,rotate:e=>r(t=>({...t,rotation:(t.rotation+e+360)%360,offset:{x:0,y:0}})),toggleFlip:e=>r(t=>({...t,flip:{...t.flip,[e]:-t.flip[e]}})),pan:e=>r(t=>({...t,offset:e}))}}(v,b);t.useEffect(()=>{const e=u.current;if(!e)return;const t=new ResizeObserver(e=>{const t=e[0];t&&w({width:t.contentRect.width,height:t.contentRect.height})});return t.observe(e),()=>t.disconnect()},[]);const x=(e,t)=>{const n=u.current.getBoundingClientRect();return{x:e-n.left-n.width/2,y:t-n.top-n.height/2}};t.useEffect(()=>{const e=u.current;if(!e||!m)return;const t=t=>{t.preventDefault(),t.stopPropagation();const n=t.deltaY*(1===t.deltaMode?16:2===t.deltaMode?e.clientHeight:1);S.zoom(Math.exp(.002*-Math.max(-100,Math.min(100,n))),x(t.clientX,t.clientY))};return e.addEventListener("wheel",t,{passive:!1}),()=>e.removeEventListener("wheel",t)},[m,S.zoom]),t.useEffect(()=>{const e=a?.current??d.current;if(!e)return;const t=e=>{e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.target.closest('input,textarea,select,[contenteditable="true"]')||["+","=","-","_","0","1"].includes(e.key)&&(e.preventDefault(),e.stopPropagation(),"0"===e.key?S.reset():"1"===e.key?m&&S.actualSize():S.zoom("+"===e.key||"="===e.key?1.25:.8))};return e.addEventListener("keydown",t),()=>e.removeEventListener("keydown",t)},[a,m,S.zoom,S.reset,S.actualSize]);const I=(e,t,s,r=!m,i,o)=>n.jsx("button",{type:"button",title:e,"aria-label":e,"aria-pressed":i,disabled:r,onClick:s,"data-testid":o,children:t});return n.jsxs("div",{className:"lifeos-image-canvas",role:"region",ref:d,tabIndex:0,"aria-label":s||r.zoom,children:[n.jsx("div",{className:"lifeos-image-viewport",ref:u,onPointerDown:e=>{m&&0===e.button&&(d.current?.focus({preventScroll:!0}),h.current={pointerId:e.pointerId,x:e.clientX,y:e.clientY,left:S.offset.x,top:S.offset.y},e.currentTarget.setPointerCapture(e.pointerId))},onPointerMove:e=>{const t=h.current;t?.pointerId===e.pointerId&&S.pan({x:t.left+e.clientX-t.x,y:t.top+e.clientY-t.y})},onPointerUp:e=>{h.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId)},onLostPointerCapture:()=>{h.current=null},onPointerCancel:()=>{h.current=null},onDoubleClick:e=>{m&&(S.scale>1?S.reset():S.zoom(2.5/S.scale,x(e.clientX,e.clientY)))},children:p?n.jsx("p",{role:"status",children:r.unavailable}):n.jsx("img",{className:i,src:e,alt:s,draggable:!1,onLoad:e=>{y({width:e.currentTarget.naturalWidth,height:e.currentTarget.naturalHeight}),f(!0)},onError:()=>{f(!1),g(!0),o?.()},style:{width:v.width?v.width*S.fit:void 0,height:v.height?v.height*S.fit:void 0,transform:`translate(${S.offset.x}px, ${S.offset.y}px) scale(${S.scale}) scale(${S.flip.x}, ${S.flip.y}) rotate(${S.rotation}deg)`}})}),n.jsxs("div",{className:"lifeos-image-toolbar",role:"toolbar","aria-label":r.zoom,children:[c,I(r.zoomOut,n.jsx(oe,{}),()=>S.zoom(.8),!m||S.scale<=S.min,void 0,"image-viewer-zoom-out"),n.jsxs("output",{className:"lifeos-image-zoom-value","aria-label":r.zoom,children:[Math.round(100*S.scale),"%"]}),I(r.zoomIn,n.jsx(he,{}),()=>S.zoom(1.25),!m||S.scale>=S.max,void 0,"image-viewer-zoom-in"),n.jsx("span",{className:"lifeos-image-divider","aria-hidden":"true"}),I(r.rotateLeft,n.jsx(fe,{}),()=>S.rotate(-90)),I(r.rotateRight,n.jsx(pe,{}),()=>S.rotate(90)),I(r.flipHorizontal,n.jsx(G,{}),()=>S.toggleFlip("x"),!m,-1===S.flip.x),I(r.flipVertical,n.jsx(Q,{}),()=>S.toggleFlip("y"),!m,-1===S.flip.y),n.jsx("span",{className:"lifeos-image-divider","aria-hidden":"true"}),I(r.resetZoom,n.jsx(se,{}),S.reset,!m,void 0,"image-viewer-fit-window"),I(r.actualSize,"1:1",S.actualSize,!m,void 0,"image-viewer-actual-size"),l]})]})}function Yo({className:e,...t}){return n.jsx(Zo,{...t,imageClassName:e,labels:Vo(c(l().language))})}function ea(e,t,n){const s=e.trim();if(s&&!/^(?:#|\/\/)/.test(s)&&(!/^[a-z][\w+.-]*:/i.test(s)||/^[a-z]:[\\/]/i.test(s)))try{return cr(decodeURIComponent(s.split(/[?#]/)[0]),xn(cr(t,n))??n)}catch{return}}function ta({file:e}){const{path:r,cwd:i,text:o}=e,a=ht(),c=a?.pairToken,l=t.useRef(null),[d,u]=t.useState();t.useEffect(()=>{const e=new AbortController;let t=0;return async function(e,t,n,s){const r=(new DOMParser).parseFromString(e,"text/html"),i=Array.from(r.querySelectorAll("img[src]")),o=new Map,a=Object.create(null);let c=0;return await Promise.all(Array.from({length:Math.min(4,i.length)},async()=>{for(;c<i.length;){const e=i[c++],r=ea(e.getAttribute("src")||"",t,n);if(r)try{let t=o.get(r);t||(t=s(r),o.set(r,t));const n=e.getAttribute("src");a[n]=await t,e.setAttribute("src",a[n])}catch{}}})),{html:`<!doctype html>${r.documentElement.outerHTML}`,images:a}}(o,r,i,async n=>{if(!c||e.signal.aborted)throw new Error("Preview unavailable");const s=await fetch(kn(n,i),{headers:{authorization:`Bearer ${c}`},signal:e.signal});if(!s.ok||!s.headers.get("content-type")?.startsWith("image/"))throw new Error("Image unavailable");const r=await s.blob();if(t+=r.size,e.signal.aborted||t>33554432)throw new Error("Preview image limit");return function(e){return new Promise((t,n)=>{const s=new FileReader;s.onload=()=>t(String(s.result)),s.onerror=()=>n(s.error),s.readAsDataURL(e)})}(r)}).then(({html:t,images:n})=>{e.signal.aborted||u({path:r,cwd:i,text:o,token:c,html:mr(t),images:n})}),()=>e.abort()},[r,i,o,c]);const h=d?.path===r&&d.cwd===i&&d.text===o&&d.token===c?d:void 0,m=e.dirty?void 0:s().htmlPreviewUrl?.(r,i),[f,p]=t.useState(),[g,v]=t.useState();t.useEffect(()=>{if(m||!h)return;let e,t=!1;const n=()=>{e&&fetch(e,{method:"DELETE"}).catch(()=>{})};return fetch("/web/html-draft-preview",{method:"POST",headers:{"content-type":"text/html; charset=utf-8"},body:h.html}).then(async s=>{if(!s.ok)throw new Error("Preview unavailable");const r=await s.json();if("string"!=typeof r.url||!r.url.startsWith("/web/html-draft-preview?id="))throw new Error("Invalid preview");e=r.url,t?n():p({html:h.html,url:r.url})}).catch(()=>{t||v(h.html)}),()=>{t=!0,n()}},[h,m]);const y=m??(f?.html===h?.html?f?.url:void 0),b=()=>{h&&m&&l.current?.contentWindow?.postMessage({type:"vibelet:preview-images",images:h.images},"*")};return t.useEffect(b,[h,m]),!m&&h&&g===h.html?n.jsx("p",{role:"alert",className:"empty-copy",children:Zs().mediaError}):n.jsx("iframe",{ref:l,className:"remote-document-preview",sandbox:"allow-scripts",title:Zs().htmlPreview,src:y,srcDoc:y?void 0:"",onLoad:b},y??"preparing")}function na({file:e}){const[r,i]=t.useState(!1),o=R(()=>i(!1),void 0,r),a=Zs(),d=c(l().language),u="en"===d?"Close":"zh-TW"===d?"關閉":"关闭",h=s().pdfPreviewUrl?.(e.path,e.cwd)??e.objectUrl;return n.jsxs(n.Fragment,{children:[n.jsxs("button",{className:"icon-text-button",type:"button",onClick:()=>i(!0),children:[n.jsx(K,{"aria-hidden":"true"}),a.pdfPreview]}),r&&I.createPortal(n.jsx("div",{className:"remote-document-layer",onPointerDown:e=>{e.target===e.currentTarget&&i(!1)},children:n.jsxs("div",{ref:o,className:"remote-document-dialog","aria-label":a.pdfPreview,role:"dialog","aria-modal":"true",tabIndex:-1,children:[n.jsx(Ho,{title:e.path.split("/").pop(),actions:n.jsx("button",{className:"icon-button",type:"button","aria-label":u,title:u,onClick:()=>i(!1),children:n.jsx(Re,{"aria-hidden":"true"})})}),n.jsx("iframe",{title:a.pdfPreview,src:`${h}#toolbar=1&navpanes=0&view=Fit`})]})}),document.body)]})}function sa({file:e,daemonId:r}){const[i,o]=t.useState(!1),[a,d]=t.useState(!1),u=s(),h=c(l().language),m="darwin"===u.platform,f="en"===h?["This file format is not supported","Open with default app",m?"Show in Finder":"Show in file manager","Unable to open the file. Please try again.","Download"]:"zh-TW"===h?["不支援此檔案格式","使用系統預設程式開啟",m?"在 Finder 中顯示":"在檔案管理員中顯示","無法開啟檔案,請重試。","下載"]:["不支持此文件格式","使用系统默认应用打开",m?"在 Finder 中显示":"在文件管理器中显示","无法打开文件,请重试。","下载"],p=async t=>{if(r&&!i){o(!0),d(!1);try{await t({path:e.path,cwd:e.cwd,daemonId:r})}catch{d(!0)}finally{o(!1)}}};return n.jsxs("div",{className:"unsupported-file-preview",children:[n.jsx(W,{className:"unsupported-file-icon","aria-hidden":"true"}),n.jsx("h2",{children:f[0]}),n.jsx("p",{className:"unsupported-file-name",children:e.path.split(/[\\/]/).pop()}),n.jsxs("div",{className:"unsupported-file-actions",children:[u.openFile&&r&&n.jsxs("button",{className:"primary-button",type:"button",disabled:i||e.dirty,onClick:()=>{p(u.openFile)},children:[n.jsx(E,{"aria-hidden":"true"}),f[1]]}),u.revealFile&&r&&n.jsxs("button",{className:"icon-text-button",type:"button",disabled:i,onClick:()=>{p(u.revealFile)},children:[n.jsx(V,{"aria-hidden":"true"}),f[2]]}),"browser"===u.kind&&e.objectUrl&&n.jsx("a",{className:"icon-text-button",href:e.objectUrl,download:e.path.split(/[\\/]/).pop(),children:f[4]})]}),a&&n.jsx("p",{role:"alert",children:f[3]})]})}function ra({file:e,daemonId:t}){const s=Zs(),r=hr(e.path,e.contentType,"text"===e.kind);return"unsupported"===r?n.jsx(sa,{file:e,daemonId:t}):"html"===r?n.jsx(ta,{file:e}):e.objectUrl?"pdf"===r?n.jsx(na,{file:e}):n.jsx(Bo,{source:e.objectUrl,errorLabel:s.mediaError,statusClassName:"empty-copy",className:"image"===r?"remote-media-viewer remote-image-viewer":"video"===r?"remote-media-viewer remote-video-viewer":void 0,children:t=>"image"===r?n.jsx(Yo,{className:"remote-image",src:e.objectUrl,alt:e.path,onError:t}):"video"===r||"audio"===r?n.jsx(Wo,{kind:r,src:e.objectUrl,label:"audio"===r?s.audioPreview:s.videoPreview,preload:"metadata",onError:t}):n.jsx("p",{className:"empty-copy",children:s.mediaError})}):null}function ia(e){const t=e.split("#")[0];return/\.[^/\\.]+$/.test(t)?t:`${t}.md`}function oa(e,t){return xn(cr(e,t))??t??"."}function aa(e,t,n){if(!e)return{path:cr(t,n),cwd:n??oa(t,n)};const s=e.includes("/")&&!/^\.\.?\//.test(e)?n??oa(t,n):oa(t,n);return{path:ia(e||t),cwd:s}}function ca(e,t){if(!t)return;let n=t.replace(/^#/,"");try{n=decodeURIComponent(n)}catch{}const s=n.startsWith("^"),r=e.querySelectorAll(s?".block-id-superscript":"h1,h2,h3,h4,h5,h6"),i=Array.from(r).find(e=>e.textContent?.trim()===n||!s&&e.id===n),o=s?i?.closest(".milkdown-list-item-block, li, p, blockquote")??i:i;o?.scrollIntoView({block:"start"})}const la=new Map;function da(e,t,n){for(const[s,r]of la)Date.now()-r.time>1e4&&la.delete(s);n&&la.set(cr(e,t),{hash:n,time:Date.now()})}function ua(e,t){const n=cr(e,t),s=la.get(n);return la.delete(n),s&&Date.now()-s.time<1e4?s.hash:""}const ha=t.lazy(()=>C(()=>import("./MarkdownModePanel-DGwvMtZM.js"),__vite__mapDeps([42,1,2,43])).then(e=>({default:e.MarkdownModePanel}))),ma=t.lazy(()=>C(()=>import("./file-editor-FileCodeEditor-BTvQY5aN.js"),__vite__mapDeps([44,1,2,45,46])).then(e=>({default:e.FileCodeEditor}))),fa=t.lazy(()=>C(()=>import("./file-editor-ObsidianCodeEditor-CnBokVUd.js"),__vite__mapDeps([47,1,2,44,45,46,48,49,50,51,52,53,54,33,55,12,19,56,57,58,59,60])).then(e=>({default:e.ObsidianCodeEditor}))),pa=t.lazy(()=>C(()=>import("./file-editor-ObsidianFileEditor-BHqr5Od1.js"),__vite__mapDeps([61,1,2,54,33,55,45,12,19,56,62,49,63,64,65,66,29,4,30,67])).then(e=>({default:e.ObsidianFileEditor})));function ga({file:e,client:s,onOpenRemoteFile:r,onTextChange:i}){const o=function(e,n){return t.useMemo(()=>{let t;return async(s,r)=>{const i=aa(s,r,n),o={path:cr(i.path,i.cwd),cwd:n??i.cwd};if(!e?.isConnected||!n||!s||/^([/.]|[a-z]:)/i.test(s))return o;t??=e.request({action:"vault.listMarkdown",id:`editor-vault-${crypto.randomUUID()}`,cwd:n});try{const{entries:e}=await t,i=s.replace(/\.(?:md|markdown)$/i,"").toLowerCase(),a=e.filter(e=>e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase()===i||e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase().endsWith(`/${i}`)||e.basename.toLowerCase()===i||e.aliases?.includes(i)),c=cr(ia(s),oa(r,n)),l=a.find(e=>cr(e.relPath,n)===c)??a.find(e=>e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase()===i)??a.sort((e,t)=>e.relPath.localeCompare(t.relPath))[0];return l?{path:cr(l.relPath,n),cwd:n}:o}catch{return t=void 0,o}}},[e,n])}(s,e.cwd),a=function(e){return/\.(md|mdx|markdown|mdown)$/i.test(e)}(e.path),d=$o(),[u,h]=t.useState("preview"),m="html"===hr(e.path,e.contentType,!0),f="en"!==c(l().language);return n.jsxs(n.Fragment,{children:[m&&n.jsxs("div",{className:"segmented editor-mode-tabs",children:[n.jsx("button",{type:"button",className:"edit"===u?"selected":"",onClick:()=>h("edit"),children:f?"编辑":"Edit"}),n.jsx("button",{type:"button",className:"preview"===u?"selected":"",onClick:()=>h("preview"),children:f?"预览":"Preview"})]}),a?n.jsx(t.Suspense,{fallback:n.jsx(_o,{label:d.loading}),children:n.jsx(ha,{text:e.text,modes:["edit","source"],initialMode:"edit",labels:d,loadingText:d.loading,renderVisual:t=>n.jsx(pa,{client:s,resolveFile:o,path:e.path,cwd:e.cwd,text:e.text,readOnly:t,onChange:i,onOpenFile:r}),renderCode:t=>n.jsx(fa,{client:s,cwd:e.cwd,path:e.path,resolveFile:o,onOpenFile:r,text:e.text,onChange:i,preview:t})})}):m&&"preview"===u?n.jsx(ra,{file:e}):n.jsx(t.Suspense,{fallback:n.jsx("pre",{className:"remote-editor",children:e.text}),children:n.jsx(ma,{path:e.path,text:e.text,onChange:i})})]})}const va=t.createContext(null);function ya({workspace:e,children:r}){const i=$e(),o=Le(e.pairing?.daemonId,e.activeSessionId),a=function(e){const{value:n,setForScope:s}=De(e,!1);return t.useEffect(()=>{const e=e=>{const t=e.detail;s(Le(t.daemonId,t.sessionId),t.removing)};return window.addEventListener(je,e),()=>window.removeEventListener(je,e)},[s]),n}(o),u=Ti("center"),{openFiles:h,setOpenFiles:m}=e,[p,g]=Pe(o,null),[v,y]=Pe(o,()=>[]),[b,w]=t.useState(null),S=t.useRef({files:h,remoteFile:e.remoteFile,scopeKey:o});S.current={files:h,remoteFile:e.remoteFile,scopeKey:o};const x=t.useRef(new Map);t.useEffect(()=>{const e=e=>{const t=e.detail;for(const[n,s]of[...x.current]){const e=Ne(n,t);e!==n&&(x.current.delete(n),null!==e&&x.current.set(e,s))}};return window.addEventListener(Ee,e),()=>window.removeEventListener(Ee,e)},[]);const I="en"!==c(l().language);t.useEffect(()=>{const t=e.remoteFile?fr(e.remoteFile):null;if(x.current.get(o)!==t&&y(e=>[...e.filter(e=>e!==t),t]),!e.remoteFile)return x.current.set(o,null),void g(null);x.current.get(o)!==t&&(g(t),i.setCenter(null)),x.current.set(o,t)},[e.remoteFile,o]);const k=t=>{i.setCenter(null),e.setRemoteFile(h[t]),g(t),Vs({file:h[t].path,cwd:h[t].cwd},{replace:!0})},C=()=>{y(e=>[...e.filter(e=>null!==e),null]),g(null),e.setRemoteFile(null),i.setCenter(null),x.current.set(o,null),Vs({file:void 0},{replace:!0})},R=async e=>{const t=h[e];if(!t)return;const n=d();if(t.dirty&&!(await f({title:n.discard,message:e,confirmLabel:n.discardAction,danger:!0})))return;if(S.current.scopeKey!==o||S.current.files[e]?.text!==t.text)return;m(t=>{const n={...t};return delete n[e],n});const s=v.filter(t=>t!==e&&(null===t||S.current.files[t]));if(y(s),S.current.remoteFile&&fr(S.current.remoteFile)===e){const e=s.at(-1);e?k(e):C()}};t.useEffect(()=>{const e=e=>{const t=e.detail;if(!["closeTab","nextTab","previousTab"].includes(t))return;if("closeTab"===t)return void(i.center?i.close(i.center):p&&R(p));const n=[null,...Object.keys(h),...i.items.filter(e=>"center"===e.location).map(e=>e.id)],s=n.indexOf(i.center||p),r=n[(Math.max(s,0)+("nextTab"===t?1:n.length-1))%n.length];r?h[r]?k(r):i.setCenter(r):C()};return window.addEventListener(Ar,e),()=>window.removeEventListener(Ar,e)},[h,p,i]);const E=p?h[p]:null;!function(e,n,s){const r=t.useRef({enabled:e,busy:n,save:s});r.current={enabled:e,busy:n,save:s},t.useEffect(()=>{const e=e=>{if(!r.current.enabled||e.defaultPrevented||e.isComposing||229===e.keyCode||"mod+s"!==Lr(e)||document.querySelector('[role="dialog"], [role="alertdialog"], .desktop-workspace-container[hidden]'))return;const t=e.target instanceof Element?e.target:document.activeElement;t?.closest(".document-file, .document-file-header")&&(e.preventDefault(),e.stopPropagation(),e.repeat||r.current.busy||r.current.save())};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[])}(!!E&&"text"===E.kind&&!i.center&&!a,e.busy,e.saveRemoteFile);const M=s().toolbarTarget?.("conversation"),j=E&&!i.center&&n.jsxs("header",{className:"document-file-header",role:"toolbar","aria-label":I?"文件操作":"File actions",children:["text"===E.kind&&n.jsx("button",{type:"button",title:e.t.saveFile,"aria-label":e.t.saveFile,disabled:!E.dirty||e.busy,onClick:()=>{e.saveRemoteFile()},children:n.jsx(ge,{})}),n.jsx(qo,{file:E,daemonId:e.pairing?.daemonId,downloadLabel:e.t.download,copyPathLabel:e.t.copyPath,onDownload:e.downloadRemoteFile},E.path)]});return n.jsx(va.Provider,{value:b,children:n.jsxs("div",{className:"workspace-documents",...u,children:[!M&&n.jsx("div",{className:"chat-header document-conversation-header",ref:w}),(Object.keys(h).length>0||i.items.some(e=>"center"===e.location))&&n.jsxs("div",{className:"document-tabs",children:[n.jsxs("div",{className:"document-tab-items",role:"tablist","aria-label":I?"工作区标签页":"Workspace tabs",children:[n.jsx("button",{role:"tab","aria-selected":!p&&!i.center,onClick:C,type:"button",children:e.t.chat}),Object.entries(h).map(([t,s])=>n.jsxs("div",{className:"document-tab","data-active":!i.center&&p===t,children:[n.jsxs("button",{type:"button",role:"tab","aria-selected":!i.center&&p===t,title:fr(s),onClick:()=>k(t),children:[n.jsx(K,{}),n.jsxs("span",{className:"document-tab-label",children:[un(s.path),s.dirty?" ·":""]})]}),n.jsx("button",{type:"button",className:"document-tab-close",title:e.t.close,"aria-label":`${e.t.close} ${un(s.path)}`,onClick:()=>R(t),children:n.jsx(Re,{})})]},t)),n.jsx(Mi,{location:"center",t:e.t})]}),j]}),n.jsx("div",{hidden:!!p||!!i.center,className:"document-chat",children:r}),n.jsx("div",{hidden:!i.center,className:"dock-center-content",children:n.jsx(Ai,{location:"center"})}),E&&!i.center&&n.jsxs("section",{className:"document-file",role:"tabpanel","aria-label":un(E.path),inert:a,"aria-busy":a,children:[e.errorText&&!e.remoteFileConflict&&n.jsx("div",{role:"alert",className:"inline-notice warning",children:n.jsx("span",{children:e.errorText})}),"text"===E.kind?n.jsx(ga,{client:e.clientRef?.current,file:E,onOpenRemoteFile:(t,n)=>{e.openRemoteFile(t,n,{updateRoute:!0})},onTextChange:t=>e.setRemoteFile(e=>e?{...e,text:t,dirty:!0}:e)},E.path):n.jsx(ra,{file:E,daemonId:e.pairing?.daemonId},E.path),e.remoteFileConflict&&n.jsxs("div",{role:"alert",className:"inline-notice warning",children:[n.jsx("span",{children:e.t.remoteFileConflict(E.path)}),n.jsx("button",{type:"button",onClick:()=>{(async()=>{const t=e.remoteFile;t&&await f({message:e.t.confirmOverwrite(un(t.path)),danger:!0})&&S.current.remoteFile===t&&await e.saveRemoteFile({force:!0})})()},children:e.t.forceSave})]})]})]})})}function ba(e,t){const n={read:t.interactionRead,read_file:t.interactionRead,edit:t.interactionEdit,write:t.interactionEdit,apply_patch:t.interactionEdit,grep:t.interactionSearch,glob:t.interactionSearch,bash:t.interactionCommand,exec_command:t.interactionCommand},s=new Map;for(const r of e.filter(e=>"tool"===e.role)){const e=r.toolName||"Tool",t=n[e.toLowerCase()]??e;s.set(t,(s.get(t)??0)+1)}return[...s].map(([e,t])=>t>1?`${e} × ${t}`:e).join(" · ")}function wa(e,t){return JSON.stringify([...Object.values(e),...Object.values(t)].map(e=>JSON.stringify([e.sessionId,e.requestId])).sort())}function Sa(e,t,n){return{quickReplies:j(e.quickReplies,e.quickReplyUsageCounts),onQuickRepliesChange:e=>t(t=>({...t,quickReplies:[...t.quickReplies.filter(t=>e.includes(t)),...e.filter(e=>!t.quickReplies.includes(e))],quickReplyUsageCounts:A(t.quickReplyUsageCounts,e)})),onSendQuickReply:(e,s)=>(t(e=>{const t=A(e.quickReplyUsageCounts,e.quickReplies),n=Object.hasOwn(t,s)?t[s]:0;return{...e,quickReplyUsageCounts:{...t,[s]:Math.min(Number.MAX_SAFE_INTEGER,n+1)}}}),n(e))}}const xa=t.lazy(()=>C(()=>import("./GlobalPendingDialog-C7pEj7Bn.js"),__vite__mapDeps([68,1,2,31,15,35])));function Ia({workspace:e}){const r=function(e){const[n,s]=t.useState(0),[r,i]=t.useState(0);return t.useLayoutEffect(()=>{if(!r)return;const e=requestAnimationFrame(()=>{document.querySelector('[role="dialog"]')||document.querySelector(".document-chat:not([hidden]) .composer textarea")?.focus({preventScroll:!0})});return()=>cancelAnimationFrame(e)},[r]),{selectSession:(t,n=!0)=>{n&&i(e=>e+1),e.activeSessionIdRef.current=t,e.setActiveSessionId(t),e.completionAttention?.acknowledgeOpened(t);const r=e.displaySessions.find(e=>e.sessionId===t);if(!e.pendingApprovals[t]&&!e.pendingQuestions[t]&&!r?.runtime.needsAttention)return;s(e=>e+1);const o=e.clientRef.current;e.requestReconnectSnapshot().catch(n=>{e.clientRef.current===o&&e.activeSessionIdRef.current===t&&e.setErrorText(n instanceof Error?n.message:String(n))})},revealKey:n}}(e);!function(e,n){t.useEffect(()=>{const t=t=>{try{const[s,r]=JSON.parse(t.detail);e.pairing?.daemonId===s&&e.displaySessions.some(e=>e.sessionId===r)&&n(r,!1)}catch{}};return window.addEventListener("vibelet.dock.restore-session",t),()=>window.removeEventListener("vibelet.dock.restore-session",t)},[e.pairing?.daemonId,e.displaySessions,n])}(e,r.selectSession),function(e,n){const{pendingApprovals:r,pendingQuestions:i,displaySessions:o,pairing:c,t:l}=e,d=s(),u=t.useMemo(()=>{const e=new Set([...Object.keys(r),...Object.keys(i)]),t=c?[...e].map(e=>{const t=r[e],n=i[e],s=o.find(t=>t.sessionId===e);return{daemonId:c.daemonId,sessionId:e,title:s?a(s):e,detail:[t&&`${l.interactionWaitingApproval} · ${t.description||t.toolName}`,n&&`${l.interactionWaitingAnswer} · ${n.questions[0]?.question??""}`].filter(Boolean).join(" / "),count:Number(!!t)+Number(!!n)}}):[];return{sessions:t,label:l.pendingActionCount(t.reduce((e,t)=>e+t.count,0)),emptyLabel:l.noPendingActions}},[r,i,o,c,l]),h=JSON.stringify(u);t.useEffect(()=>{d.setPendingSessions?.(JSON.parse(h)).catch(()=>{})},[d,h]),t.useEffect(()=>()=>{d.setPendingSessions?.({sessions:[],label:"",emptyLabel:""}).catch(()=>{})},[d]);const m=t.useRef({state:u,selectSession:n});m.current={state:u,selectSession:n},t.useEffect(()=>d.subscribeCommand?.(e=>{if(e.startsWith("pending-session:"))try{const t=JSON.parse(e.slice(16));if(!m.current.state.sessions.some(e=>e.daemonId===t.daemonId&&e.sessionId===t.sessionId))return;m.current.selectSession(t.sessionId),window.dispatchEvent(new Event("vibelet.pending.open"))}catch{}}),[d])}(e,r.selectSession);const[i,o]=t.useState(!0),[c,l]=t.useState(!1);(function(e){const n=$e(),r=wo(e),[i,o]=t.useState(_r),a=t.useRef({workspace:e,dock:n,shortcuts:i,toggleRightSidebar:r});a.current={workspace:e,dock:n,shortcuts:i,toggleRightSidebar:r},t.useEffect(()=>{const e=()=>o(_r()),t=e=>e instanceof Element&&!!e.closest('.workspace-control-sidebar-motion, .dock-surface[data-location="right"], #desktop-toolbar-controls');let n=!1;const r=e=>{n=t(e.target)},i=(e,s,r=e.target)=>{if(e.defaultPrevented||e.isComposing||e.repeat||document.querySelector('[data-shortcut-recording="true"], [role="dialog"], [role="alertdialog"], .desktop-workspace-container[hidden], .browser-settings-page'))return;const i=Lr(e);if(!i&&!s)return;const{workspace:o,dock:c,shortcuts:l}=a.current,d=s??Tr.find(e=>$r(e.id,l)===i)?.id;if(!d)return;if(["searchMessages","findNext","findPrevious"].includes(d)){let n=r instanceof Element?r.closest(".embedded-browser-panel, .embedded-terminal-panel"):null;if(!n&&!o.rightSidebarCollapsed&&t(r)&&"files"!==o.controlTab){const e=c.right["terminal"===o.controlTab?"terminal":"browser"];n=Array.from(document.querySelectorAll(".dock-surface")).find(t=>t.dataset.dockId===e&&!t.hidden)?.querySelector(".embedded-browser-panel, .embedded-terminal-panel")??null}if(n&&!n.closest(".dock-surface[hidden]"))return e.preventDefault(),e.stopPropagation(),void n.dispatchEvent(new CustomEvent("vibelet.panel.find",{detail:d}));if("searchMessages"!==d){const t=document.querySelector(".message-search-bar"),n=t?.querySelectorAll("button");return void(n?.length&&(e.preventDefault(),e.stopPropagation(),n["findPrevious"===d?0:1]?.click()))}}if("searchMessages"===d&&(t(r)||!document.querySelector(".document-chat:not([hidden]) .chat-pane")))return;if(function(e){return Mr.some(t=>t.id===e)}(d))return void window.dispatchEvent(new CustomEvent(Er,{detail:{command:d,event:e}}));const u="terminal"===o.controlTab?"terminal":"browser",h=c.items.find(e=>e.id===c.center),m=!o.rightSidebarCollapsed&&(t(r)||r===document.body&&n),f=!m&&h?h:c.items.find(e=>e.id===c.right[u]);if("browserAddress"===d||"browserCopyUrl"===d){if("browser"!==f?.kind)return;const t=Array.from(document.querySelectorAll(".dock-surface")).find(e=>e.dataset.dockId===f.id&&!e.hidden)?.querySelector(".embedded-browser-panel");if(!t)return;return e.preventDefault(),e.stopPropagation(),void t.dispatchEvent(new CustomEvent("vibelet.browser.command",{detail:d}))}switch(e.preventDefault(),e.stopPropagation(),d){case"commandMode":window.dispatchEvent(new CustomEvent("vibelet.quick-search",{detail:{commandMode:!0}}));break;case"previousSession":case"nextSession":window.dispatchEvent(new CustomEvent(Ar,{detail:d}));break;case"quickSearch":window.dispatchEvent(new Event("vibelet.quick-search"));break;case"searchMessages":window.dispatchEvent(new Event("vibelet.message-search"));break;case"leftSidebar":o.setLeftSidebarCollapsed(e=>!e);break;case"rightSidebar":a.current.toggleRightSidebar();break;case"files":case"terminal":case"browser":o.setControlTabAndOpen(d);break;case"searchSessions":o.setLeftSidebarCollapsed(!1),window.dispatchEvent(new Event("vibelet.session-search"));break;case"newTab":{if(o.rightSidebarCollapsed)break;const e="terminal"===f?.kind||"browser"===f?.kind?f.kind:u;c.add(e,o.t[e],o.cwd),o.setControlTabAndOpen(e);break}case"moveTab":f&&c.move(f.id,"center"===f.location?"right":"center");break;case"reopenTab":c.reopenClosed();break;case"diff":o.activeSession&&o.setDiffSessionId(o.activeSession.sessionId);break;case"closeTab":case"nextTab":case"previousTab":if(m)if("closeTab"===d)"files"===o.controlTab||!f||f.emptyPlaceholder?o.setRightSidebarCollapsed(!0):(document.querySelector(".control-pane")?.focus(),c.close(f.id));else{const e=c.items.filter(e=>"right"===e.location&&e.kind===u);e.length&&c.setRight(t=>({...t,[u]:e[(Math.max(0,e.findIndex(e=>e.id===f?.id))+("nextTab"===d?1:e.length-1))%e.length].id}))}else window.dispatchEvent(new CustomEvent(Ar,{detail:d}))}},c=e=>i(e),l=s().subscribeCommand?.(e=>{"close-tab"===e&&i(new KeyboardEvent("keydown"),"closeTab",document.activeElement)});return window.addEventListener(jr,e),window.addEventListener("focusin",r,!0),window.addEventListener("pointerdown",r,!0),window.addEventListener("keydown",c,!0),()=>{l?.(),window.removeEventListener(jr,e),window.removeEventListener("focusin",r,!0),window.removeEventListener("pointerdown",r,!0),window.removeEventListener("keydown",c,!0)}},[])})(e),function(e,n){const s=t.useRef(null);t.useLayoutEffect(()=>{const t=s.current;s.current=null,t?.dataset.sessionId===e&&t?.isConnected&&t.focus({preventScroll:!0})},[e]);const r=t.useRef({activeSessionId:e,selectSession:n});r.current={activeSessionId:e,selectSession:n},t.useEffect(()=>{const e=(e,t)=>{if(document.querySelector('[data-shortcut-recording="true"], [role="dialog"], [role="alertdialog"], [role="menu"], .desktop-workspace-container[hidden], .browser-settings-page'))return!1;const n=new Set,i=Array.from(document.querySelectorAll(".session-list .session-row")).filter(e=>{const t=e.dataset.sessionId;return!(!t||e.disabled||e.closest("[hidden]")||n.has(t)||(n.add(t),0))});if(!i.length)return!1;const o=i.findIndex(e=>e.dataset.sessionId===r.current.activeSessionId),a=o<0?e>0?0:i.length-1:Math.max(0,Math.min(i.length-1,o+e)),c=i[a];return s.current=t&&o!==a?c:null,t&&c.focus({preventScroll:!0}),c.scrollIntoView({block:"nearest",inline:"nearest"}),o!==a&&(r.current.activeSessionId=c.dataset.sessionId,r.current.selectSession(c.dataset.sessionId,!t)),!0},t=t=>{if(t.defaultPrevented||t.isComposing||t.metaKey||t.ctrlKey||t.altKey||t.shiftKey)return;if("ArrowUp"!==t.key&&"ArrowDown"!==t.key)return;const n=t.target;n instanceof Element&&n.closest(".session-list")&&!n.closest('input, textarea, select, [contenteditable]:not([contenteditable="false"])')&&e("ArrowDown"===t.key?1:-1,!0)&&(t.preventDefault(),t.stopPropagation())},n=t=>{const n=t.detail;"previousSession"!==n&&"nextSession"!==n||e("nextSession"===n?1:-1,!1)};return window.addEventListener("keydown",t),window.addEventListener(Ar,n),()=>{window.removeEventListener("keydown",t),window.removeEventListener(Ar,n)}},[])}(e.activeSessionId,r.selectSession);const d=wo(e),[u,h]=function(e){const[n,r]=t.useState(null);return t.useEffect(()=>{const t=()=>r(t=>t??{cwd:e}),n=s().subscribeCommand?.(e=>{"new-session"===e&&t()}),i=e=>{"browser"!==s().kind||!Pr(e)||e.altKey||e.shiftKey||"n"!==e.key.toLowerCase()||(e.preventDefault(),t())};return window.addEventListener("keydown",i),()=>{n?.(),window.removeEventListener("keydown",i)}},[e]),[n,r]}(e.cwd);t.useEffect(()=>{"browser"===e.controlTab&&o(!0)},[e.controlTab]),t.useEffect(()=>{("session"===e.controlTab||"desktop"===s().kind&&"admin"===e.controlTab)&&e.setControlTab("files");const t=()=>e.setControlTabAndOpen("admin");return window.addEventListener("vibelet.browser.settings",t),()=>window.removeEventListener("vibelet.browser.settings",t)},[e.controlTab,e.setControlTab,e.setControlTabAndOpen]),t.useEffect(()=>{e.activeQuestion&&e.setQuestionAnswers(mn(e.activeQuestion))},[e.activeQuestion,e.setQuestionAnswers]);const{clientRef:m,phase:f,statusText:p,errorText:g,pairing:v,sessions:y,nextCursor:b,folderCounts:w,inventoryVersion:S,activeSessionId:x,diffSessionId:I,setDiffSessionId:k,respondingSessions:C,questionAnswers:R,agent:E,cwd:M,approvalMode:j,model:A,setModel:T,effort:N,setEffort:P,fastMode:D,setFastMode:L,renameTitle:F,setRenameTitle:O,draft:q,webPreferences:_,sessionSort:$,setSessionSort:z,search:H,setSearch:B,sinceFilter:U,setSinceFilter:W,hideArchived:K,setHideArchived:G,groupFolders:Q,setGroupFolders:V,showNeedsAttentionGroup:J,setShowNeedsAttentionGroup:Z,showRunningGroup:X,setShowRunningGroup:Y,separatePinnedGroup:ee,setSeparatePinnedGroup:te,collapsedFolders:ne,setCollapsedFolders:se,sessionAgentFilter:re,setSessionAgentFilter:ie,directoryTags:oe,composerPreferences:ae,savedTargets:ce,leftSidebarCollapsed:le,setLeftSidebarCollapsed:de,rightSidebarCollapsed:ue,setRightSidebarCollapsed:he,workspaceClassName:me,wideMainClassName:fe,workspaceStyle:pe,beginPaneResize:ge,commitSearch:ve,saveTargets:ye,setLanguagePreference:be,setThemePreference:we,updateComposerPreferences:Se,t:xe,busy:Ie,rewindMessage:ke,rewinding:Ce,controlTab:Re,setControlTab:Ee,detailsOpen:Me,setDetailsOpen:je,setControlTabAndOpen:Ae,skills:Te,admin:Ne,daemonMetadata:Pe,notificationSettings:De,notificationPermission:Le,archiveSyncBusy:Fe,archiveSyncStatus:Oe,attachments:qe,setAttachments:_e,uploadBusy:ze,directory:He,newDirName:Be,setNewDirName:Ue,remoteFile:Ke,uploadFiles:Ge,openRemoteFile:Qe,listDirectory:Ve,listSessionDirectories:Je,listFileTreeDirectory:Ze,createDirectory:Xe,createSessionDirectory:Ye,pendingActionsCount:et,activeQueue:tt,activeModelOptions:nt,activeUsage:st,activeApproval:rt,activeQuestion:it,activeSession:ot,displaySessions:at,groupedSessions:ct,pendingSessionIds:lt,visibleSessions:dt,historyLoading:ut,hasOlderHistory:ht,olderHistoryLoading:mt,requestHistory:ft,messages:pt,messagesSessionIdRef:gt,updateDraft:vt,requestReconnectSnapshot:yt,requestSessions:bt,fetchAgentResources:wt,failedSend:St,dismissFailedSend:xt,retryFailedSend:It,stagePendingSession:kt,listSessionModels:Ct,loadDirectoryGitMetadata:Rt,sendDraft:Et,sendQuickReply:Mt,respondApproval:jt,respondQuestion:At,cancelQuestion:Tt,setQuestionChoice:Nt,requestActiveAction:Pt,interruptActiveSession:Dt,retrySessions:Lt,updateApprovalMode:Ft,cancelQueuedTurn:Ot,setSessionPinned:qt,setSessionArchived:_t,deleteSession:$t,updatePinned:zt,updateArchived:Ht,renameSession:Bt,runArchiveSync:Ut,skipArchiveSync:Wt,runAdminAction:Kt,exportActiveSession:Gt,clearPairing:Qt,setNotificationsEnabled:Vt,connectSavedTarget:Jt,forgetSavedTarget:Zt,openSessionDetails:Xt,editFolderTags:Yt,copyResumeCommand:en,resumeInTerminal:tn,notificationsBlocked:nn,hasDaemonUpdate:sn,archiveSynced:on,archiveSyncDismissed:an}=e,cn=t.useMemo(()=>function(e,t,n){const s={};for(const r of Object.values(e))s[r.sessionId]=`${n.interactionWaitingApproval} · ${r.description||r.toolName}`;for(const r of Object.values(t))s[r.sessionId]=`${n.interactionWaitingAnswer} · ${r.questions[0]?.question??""}`;return s}(e.pendingApprovals,e.pendingQuestions,xe),[e.pendingApprovals,e.pendingQuestions,xe]),ln=t.useMemo(()=>c?Object.fromEntries(ct.map(e=>[e.folder,!1!==ne[e.folder]])):ne,[c,ne,ct]),dn=ct.length>0&&ct.every(e=>ln[e.folder]);return"missing-pair"===f?n.jsxs(n.Fragment,{children:[n.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:xe.skipToConversation}),n.jsx(fi,{errorText:g,t:xe})]}):n.jsxs("main",{className:me,id:"vibelet-workspace",style:pe,children:[n.jsx(We,{workspace:e,onSelect:r.selectSession}),n.jsx(xo,{workspace:e,onSelect:r.selectSession}),u&&n.jsx(t.Suspense,{fallback:null,children:n.jsx(Xi,{client:"connected"===f?m.current:null,onOpenRemoteFile:Qe,pairing:v,onLoadGitMetadata:Rt,cwd:u.cwd,agent:E,device:v?.daemonId??"disconnected",connected:"connected"===f,approvalMode:j,model:A,effort:N,fastMode:D,t:xe,onClose:()=>h(null),onCreate:kt,onListModels:Ct,onListDirectories:Je,onCreateDirectory:Ye},v?.daemonId??"disconnected")}),n.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:xe.skipToConversation}),n.jsx(bo,{collapsed:le,onExpand:()=>de(e=>!e),onResize:ge("left"),t:xe,children:n.jsx(yo,{connectionIndicators:n.jsx(To,{workspace:e}),activeDaemonId:v?.daemonId,activeSessionId:x,busy:Ie,collapsedFolders:ln,allFoldersCollapsed:dn,currentCwd:M,directoryTags:oe,displayName:v?.displayName,savedTargets:ce,folderCounts:w,groupFolders:Q,sessionSort:$,onSessionSortChange:z,groupedSessions:ct,hideArchived:K,separatePinnedGroup:ee,showNeedsAttentionGroup:J,showRunningGroup:X,inventoryVersion:S,nextCursor:b,phase:f,respondingSessionIds:C,search:H,sessionAgentFilter:re,sessionsCount:at.length,sinceFilter:U,statusText:p,t:xe,hasDaemonUpdate:sn,visibleSessions:dt,onLoadMore:e=>bt({append:!0,cursor:e}),onCopyResumeCommand:en,onResumeInTerminal:tn,onConnectTarget:Jt,attentionReasons:cn,pendingSessionIds:lt,onRequestNewSession:e=>h({cwd:e??M}),onRenameSession:Bt,onDeleteSession:e=>{$t(e)},onEditFolderTags:Yt,onOpenSessionDetails:Xt,onResetFilters:()=>{z("updated"),ie("all"),W("30d"),G(!1),V(!0),Z(!1),Y(!1),te(!1)},onRenameTarget:(e,t)=>ye(function(e,t,n){const s=n.trim();return s?e.map(e=>e.daemonId===t?{...e,label:s}:e):e}(ce,e,t)),onEditConnection:s().settingsTarget?e=>window.dispatchEvent(new CustomEvent("vibelet.desktop.edit-connection",{detail:e.pairToken})):void 0,onSearchChange:B,onSearchCommit:ve,onSelectSession:r.selectSession,onToggleSessionArchived:e=>{_t(e,!e.archived)},onToggleSessionPinned:e=>{qt(e,!e.pinned)},onSessionAgentFilterChange:ie,onSinceFilterChange:W,onToggleFolder:e=>se(t=>({...t,[e]:c?!1===t[e]:!t[e]})),onToggleAllFolders:()=>{l(!dn),se({})},onToggleGroupFolders:()=>V(e=>!e),onToggleHideArchived:()=>G(e=>!e),onToggleNeedsAttentionGroup:()=>{e.toggleSessionViewGroup("needsAttention")},onToggleRunningGroup:()=>{e.toggleSessionViewGroup("running")},onToggleSeparatePinnedGroup:()=>{e.toggleSessionViewGroup("pinned")},onToggleCollapse:()=>de(!0)})}),n.jsxs("section",{className:fe,"aria-label":xe.vibeletWorkspace,id:"vibelet-main-content",tabIndex:-1,children:[n.jsx(ya,{workspace:e,children:n.jsx(Hi,{client:"connected"===f?m.current:null,activeSession:ot,activeSessionId:x,activeModelOptions:nt,activeQueue:tt,activeUsage:st,agent:E,approvalMode:j,attachments:qe,busy:Ie,cwd:M,draft:q,effort:N,errorText:g,failedSend:St,onDismissFailedSend:xt,fastMode:D,historyLoading:ut,hasOlderHistory:ht,olderHistoryLoading:mt,onLoadOlderHistory:()=>ot?ft(ot,{older:!0}):Promise.resolve(),messages:pt,messagesSessionId:gt.current,model:A,phase:f,...Sa(ae,Se,Mt),quickRepliesOpen:ae.quickRepliesOpen,onQuickRepliesOpenChange:e=>Se(t=>({...t,quickRepliesOpen:e})),renameTitle:F,respondingSessionIds:C,sendShortcut:ae.sendShortcut,skills:Te,uploadBusy:ze,detailsOpen:Me,t:xe,onApprovalModeChange:e=>{Ft(e)},onBrowseFiles:()=>{const e=ot?.cwd||M||rn;Ae("files"),Ve(e,{updateRoute:!0})},queueControls:e.queueControls,onCancelQueuedTurn:e=>{Ot(e)},onClearInterrupt:()=>{Pt("session.clearInterrupt")},onDraftChange:vt,onDetailsOpenChange:je,onEffortChange:P,onExportActiveSession:()=>{Gt()},rewinding:Ce,onRewindMessage:e=>{ke(e)},onFastModeChange:L,onRetryFailedSend:It,onModelChange:T,onOpenRemoteFile:(e,t)=>{Qe(e,t,{updateRoute:!0})},onInterrupt:Dt,onDismissError:()=>e.setErrorText(null),onRetry:()=>{Lt(),wt(ot?.agent??E,M)},onRenameSession:e=>{Bt(void 0,e)},onRenameTitleChange:O,onRemoveAttachment:e=>_e(t=>t.filter(t=>t.path!==e)),onRefreshSkills:()=>{wt(ot?.agent??E,M)},onSubmit:Et,onToggleArchived:()=>{Ht()},onTogglePinned:()=>{zt()},onUploadFiles:Ge,onViewChanges:k})}),n.jsxs(Fo,{collapsed:ue,t:xe,value:Re,showSession:!1,onChange:Ee,onResize:ge("right"),children:[n.jsx("div",{hidden:"files"!==Re,style:{display:"files"===Re?"contents":"none"},children:n.jsx(t.Suspense,{fallback:n.jsx(_i,{t:xe}),children:n.jsx(Di,{client:"connected"===f?m.current:null,watch:!ue&&"files"===Re,onRefreshDirectory:()=>Ve(He.path,{background:!0}),busy:Ie,cwd:M,canGoBackDirectory:e.canGoBackDirectory,onGoBackDirectory:()=>{e.goBackDirectory()},directory:He,onLoadChildren:Ze,newDirName:Be,remoteFile:Ke,t:xe,onCreateDirectory:()=>{Xe()},onListDirectory:e=>{Ve(e,{updateRoute:!0})},onNewDirNameChange:Ue,onOpenRemoteFile:(e,t)=>{Qe(e,t,{updateRoute:!0})}},v?.daemonId)})}),n.jsx(ko,{activeSessionId:x,activeSession:ot,cwd:M,directoryPath:He.path,visible:"terminal"===Re,t:xe}),i?n.jsxs("div",{hidden:"browser"!==Re,className:"browser-tab-content",children:[n.jsx(Mi,{location:"right",kind:"browser",t:xe}),n.jsx(Ai,{location:"right",kind:"browser"})]}):null,"admin"===Re?n.jsxs(t.Suspense,{fallback:n.jsx(_i,{t:xe}),children:[n.jsx(Li,{language:_.language,t:xe,onLanguageChange:be}),!s().settingsTarget&&n.jsx(qi,{}),n.jsx(Fi,{t:xe,theme:_.theme,onThemeChange:we}),n.jsx(Oi,{notificationsBlocked:nn,permission:Le,settings:De,t:xe,onToggleEnabled:Vt}),!s().settingsTarget&&n.jsx(Pi,{workspace:e})]}):null]})]}),s().settingsTarget&&n.jsx(t.Suspense,{fallback:null,children:n.jsx(Pi,{workspace:e,portalOnly:!0})}),n.jsx("div",{className:"workspace-header-actions",children:n.jsx(Gr,{client:"connected"===f?m.current:null,activeSession:ot,busy:Ie,controlsOpen:!ue,pendingCount:et,t:xe,onOpenControls:d,onRefreshSessions:()=>{bt({force:!0})},onRestoreSnapshot:()=>{yt()},onToggleArchived:()=>{Ht()},onTogglePinned:()=>{zt()},onViewChanges:k})}),n.jsx(t.Suspense,{fallback:null,children:n.jsx(xa,{activeApproval:rt,activeQuestion:it,pendingCount:et,requestKey:wa(e.pendingApprovals,e.pendingQuestions),sessions:y,busy:Ie,errorText:g,questionAnswers:R,t:xe,onCancelQuestion:()=>{Tt()},onQuestionChoice:Nt,onRespondApproval:e=>{jt(e)},onRespondQuestion:()=>{At()},onDismissRequest:(t,n,s)=>{"approval"===t?e.setPendingApprovals(e=>{if(e[n]?.requestId!==s)return e;const t={...e};return delete t[n],t}):e.setPendingQuestions(e=>{if(e[n]?.requestId!==s)return e;const t={...e};return delete t[n],t})},onClearRequests:()=>{e.setPendingApprovals({}),e.setPendingQuestions({})}},r.revealKey)}),n.jsx(yi,{}),n.jsx(Qi,{onOpenBrowserLink:e.applyBrowserDefaultWidth,onOpenRight:Ae,onCloseRight:()=>he(!0),client:"connected"===f?m.current:null,daemonId:v?.daemonId,pairing:v,deviceName:v?.displayName??"",controlTab:Re,rightVisible:!ue,t:xe}),n.jsx($i,{activeSession:ot,client:m.current,close:()=>k(null),id:I,sessions:y,t:xe})]})}const ka=Object.freeze(Object.defineProperty({__proto__:null,App:function(){const e=function(){const e=function(){const e=function(){const e=t.useRef(null),n=t.useRef(async()=>{}),s=t.useRef(null),[r]=t.useState(()=>({permission:It(),notifications:xt(),preferences:l(),drafts:Bn(),targets:An()})),i=t.useRef(r.permission),o=t.useRef(r.notifications),a=t.useRef(r.preferences),d=t.useRef(r.drafts),u=t.useRef(r.targets),h=t.useRef(i.current),m=t.useRef(o.current),f=t.useRef(d.current),p=t.useRef(null),w=t.useRef(null),S=t.useRef(new Set),x=t.useRef(null),I=t.useRef(new Set),k=t.useRef(null),C=t.useRef(0),R=t.useRef(new Set),E=t.useRef({}),M=t.useRef(!1),[j,A]=t.useState("connecting"),[T,N]=t.useState(()=>b[c(a.current.language)].preparingVibeletWeb),[P,D]=t.useState(null),[L,F]=t.useState(null),[O,q]=t.useState([]),[_,$]=t.useState({}),[z,H]=t.useState({}),[B,U]=t.useState(),[W,K]=t.useState({}),[G,Q]=t.useState(),[V,J]=t.useState(null),Z=Le(L?.daemonId,V),[X,Y]=t.useState(null),[ee,te]=t.useState(()=>new Set),[ne,se]=t.useState({}),[re,ie]=t.useState({}),[oe,ae]=t.useState({}),{pendingQueues:ce,setPendingQueues:le,setLivePendingQueue:de,remapPendingQueue:ue,confirmPendingQueueRemoval:he}=function(e){const n=t.useRef(new Rr),s=t.useRef(e);s.current!==e&&(s.current=e,n.current=new Rr);const[r,i]=t.useState({});return{pendingQueues:r,setPendingQueues:t.useCallback(e=>{i(t=>n.current.snapshot("function"==typeof e?e(t):e))},[]),setLivePendingQueue:t.useCallback((e,t)=>{i(s=>n.current.live(s,e,t))},[]),remapPendingQueue:t.useCallback((e,t)=>{n.current.remap(e,t)},[]),confirmPendingQueueRemoval:t.useCallback((e,t)=>{i(s=>(n.current.confirmRemoval(e,t),n.current.snapshot(s)))},[])}}(L?.daemonId),[me,fe]=t.useState("claude"),[pe,ge]=t.useState(rn),[ve,ye]=t.useState(on),[be]=t.useState(!1),[we,Se]=t.useState(""),[xe,Ie]=t.useState(""),[ke,Ce]=t.useState(!1),[Re,Ee]=t.useState(""),[Me,je]=t.useState(d.current),[Ae,Te]=t.useState(()=>Kn(d.current,null)),{webPreferences:Ne,sessionSort:De,setSessionSort:Fe,setRightSidebarCollapsed:Oe,search:qe,setSearch:_e,sinceFilter:$e,setSinceFilter:ze,hideArchived:He,setHideArchived:Be,groupFolders:Ue,setGroupFolders:We,showNeedsAttentionGroup:Ke,setShowNeedsAttentionGroup:Ge,showRunningGroup:Qe,setShowRunningGroup:Ve,separatePinnedGroup:Je,setSeparatePinnedGroup:Ze,collapsedFolders:Xe,setCollapsedFolders:Ye,sessionAgentFilter:et,setSessionAgentFilter:tt,directoryTags:nt,archiveSyncedDaemonIds:st,archiveSyncCardDismissedDaemonIds:rt,composerPreferences:it,savedTargets:ot,setSavedTargets:at,leftSidebarCollapsed:ct,setLeftSidebarCollapsed:lt,rightSidebarCollapsed:dt,workspaceClassName:ut,wideMainClassName:ht,workspaceStyle:mt,beginPaneResize:ft,applyBrowserDefaultWidth:pt,commitSearch:gt,saveTargets:vt,setLanguagePreference:yt,setThemePreference:bt,updateSessionListPreferences:wt,updateComposerPreferences:St}=function(e,n,s="default"){const[r,i]=t.useState(e);t.useEffect(()=>{const e=()=>{const e=l();i(t=>({...t,theme:e.theme,language:e.language,composer:e.composer}))};return window.addEventListener("vibelet.preferences.changed",e),()=>window.removeEventListener("vibelet.preferences.changed",e)},[]);const[o,a]=t.useState(e.sessionList.sortOrder),[c,d]=t.useState(""),[u,h]=t.useState(e.sessionList.searchHistory),[m,f]=t.useState(e.sessionList.sinceFilter),[p,y]=t.useState(e.sessionList.hideArchived),[b,w]=t.useState(e.sessionList.groupFolders),[S,x]=t.useState(e.sessionList.showNeedsAttentionGroup),[I,k]=t.useState(e.sessionList.showRunningGroup),[C,R]=t.useState(e.sessionList.separatePinnedGroup),[E,M]=t.useState(e.sessionList.collapsedFolders),[j,A]=t.useState(e.sessionList.agentFilter),[T,N]=t.useState(n),[P,D]=t.useState(e.layout.leftSidebarCollapsed),[L,F]=t.useState(e.layout.rightSidebarCollapsed),{leftPaneWidth:O,rightPaneWidth:q,beginPaneResize:_,applyBrowserDefaultWidth:$}=function(e,n,s="default"){const[r,i]=t.useState(288),[o,a]=Pe(s,"third"),[c,l]=t.useState(()=>window.innerWidth),[d,u]=t.useState(null);t.useEffect(()=>{const e=document.querySelector(".workspace .wide-main");if(!e||"undefined"==typeof ResizeObserver)return;const t=()=>u(e.getBoundingClientRect().width);t();const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[s]);const h=d??c-(e?0:r+10),m="number"==typeof o?o:Math.round(h/("half"===o?2:3)),f=t.useCallback(()=>{a(e=>"number"==typeof e?e:"half")},[a]),p=t.useRef(null);t.useEffect(()=>()=>p.current?.(),[e,n,s]),t.useEffect(()=>{const e=()=>l(window.innerWidth);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const g=function(e,t){const n=e.leftCollapsed?0:e.leftPaneWidth,s=e.rightCollapsed?0:e.rightPaneWidth,r=n+s,i=r>t?Math.max(0,t)/r:1;return{leftPaneWidth:e.leftCollapsed?e.leftPaneWidth:Math.floor(n*i),rightPaneWidth:e.rightCollapsed?e.rightPaneWidth:Math.floor(s*i)}}({leftCollapsed:e,rightCollapsed:n,leftPaneWidth:r,rightPaneWidth:m},c-96-64),v=t.useCallback(e=>t=>{if(0!==t.button||!1===t.isPrimary)return;t.preventDefault(),p.current?.();const n=t.currentTarget,s=t.pointerId;let r=!0;const o=document.createElement("div");o.dataset.paneResizeShield="",o.setAttribute("aria-hidden","true"),Object.assign(o.style,{position:"fixed",inset:"0",zIndex:"2147483647",cursor:"col-resize",touchAction:"none"}),document.body.append(o);const c=t.clientX,l="left"===e?g.leftPaneWidth:g.rightPaneWidth,d=t.currentTarget.closest(".workspace")?.querySelector(".chat-pane"),u=l+Math.max(0,(d?.getBoundingClientRect().width??0)-96),h=t=>{if(t.pointerId!==s)return;if(!(1&t.buttons))return void m();const n=(t.clientX-c)*("left"===e?1:-1),r=function(e,t,n=1/0){return Math.min(Math.max(Math.round(e),t),n)}(l+n,"left"===e?252:234,u);"left"===e?i(r):a(r)},m=()=>{if(r){r=!1,o.remove(),document.body.classList.remove("pane-resizing"),window.removeEventListener("pointermove",h,!0),window.removeEventListener("pointerup",f,!0),window.removeEventListener("pointercancel",f,!0),window.removeEventListener("blur",m),window.removeEventListener("keydown",v,!0),document.removeEventListener("visibilitychange",y),n.removeEventListener("lostpointercapture",f);try{n.hasPointerCapture?.(s)&&n.releasePointerCapture(s)}catch{}p.current===m&&(p.current=null)}},f=e=>{e.pointerId===s&&m()},v=e=>{"Escape"===e.key&&(e.preventDefault(),m())},y=()=>{"hidden"===document.visibilityState&&m()};p.current=m,document.body.classList.add("pane-resizing"),window.addEventListener("pointermove",h,!0),window.addEventListener("pointerup",f,!0),window.addEventListener("pointercancel",f,!0),window.addEventListener("blur",m),window.addEventListener("keydown",v,!0),document.addEventListener("visibilitychange",y),n.addEventListener("lostpointercapture",f);try{n.setPointerCapture?.(s)}catch{}},[g.leftPaneWidth,g.rightPaneWidth,a]);return{...g,beginPaneResize:v,applyBrowserDefaultWidth:f}}(P,L,s),z=r.sessionList.directoryTags,H=r.sessionList.archiveSyncedDaemonIds,B=r.sessionList.archiveSyncCardDismissedDaemonIds,U=r.composer,W=function(e){return{workspaceClassName:["workspace",e.leftCollapsed&&"left-sidebar-collapsed"].filter(Boolean).join(" "),wideMainClassName:["wide-main",e.rightCollapsed&&"right-sidebar-collapsed"].filter(Boolean).join(" "),style:{"--left-pane-width":`${e.leftPaneWidth}px`,"--right-pane-width":`${e.rightPaneWidth}px`}}}({leftCollapsed:P,rightCollapsed:L,leftPaneWidth:O,rightPaneWidth:q});t.useEffect(()=>{i(e=>{const t={...e,sessionList:{...e.sessionList,searchHistory:u,sortOrder:o,sinceFilter:m,hideArchived:p,groupFolders:b,showNeedsAttentionGroup:S,showRunningGroup:I,separatePinnedGroup:C,collapsedFolders:E,agentFilter:j},layout:{...e.layout,leftSidebarCollapsed:P,rightSidebarCollapsed:L}};return g(t),t})},[E,b,p,P,L,u,C,j,S,I,m,o]);const K=t.useCallback(()=>{h(e=>v(e,c))},[c]),G=t.useCallback(e=>{N(e),Tn(e)},[]),Q=t.useCallback(e=>{i(t=>{const n={...t,language:e};return g(n),n})},[]),V=t.useCallback(e=>{i(t=>{const n={...t,theme:e};return g(n),n})},[]),J=t.useCallback(e=>{i(t=>{const n={...t,sessionList:e(t.sessionList)};return g(n),n})},[]),Z=t.useCallback(e=>{i(t=>{const n={...t,composer:e(t.composer)};return g(n),n})},[]);return{webPreferences:r,sessionSort:o,setSessionSort:a,search:c,setSearch:d,sinceFilter:m,setSinceFilter:f,hideArchived:p,setHideArchived:y,groupFolders:b,setGroupFolders:w,showNeedsAttentionGroup:S,setShowNeedsAttentionGroup:x,showRunningGroup:I,setShowRunningGroup:k,separatePinnedGroup:C,setSeparatePinnedGroup:R,collapsedFolders:E,setCollapsedFolders:M,sessionAgentFilter:j,setSessionAgentFilter:A,directoryTags:z,archiveSyncedDaemonIds:H,archiveSyncCardDismissedDaemonIds:B,composerPreferences:U,savedTargets:T,setSavedTargets:N,leftSidebarCollapsed:P,setLeftSidebarCollapsed:D,rightSidebarCollapsed:L,setRightSidebarCollapsed:F,workspaceClassName:W.workspaceClassName,wideMainClassName:W.wideMainClassName,workspaceStyle:W.style,beginPaneResize:_,applyBrowserDefaultWidth:$,commitSearch:K,saveTargets:G,setLanguagePreference:Q,setThemePreference:V,updateSessionListPreferences:J,updateComposerPreferences:Z}}(a.current,u.current,Z),kt=c(Ne.language),Ct=b[kt],[Rt,Et]=Pe(Z,!1),[Mt,jt]=Pe(Z,!1),[At,Tt]=Pe(Z,"files"),[Nt,Pt]=t.useState(!1);!function(e){t.useEffect(()=>{const t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>y(e,document.documentElement,t.matches);if(n(),"system"===e)return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[e])}(Ne.theme);const Dt=t.useCallback(e=>{Tt(e),Oe(!1)},[Tt,Oe]),[Lt,Ft]=t.useState({}),[Ot,qt]=t.useState({}),[_t,$t]=t.useState([]),[zt,Ht]=t.useState({statusText:"",loading:!1,action:null}),[Bt,Ut]=t.useState(Nn),[Wt,Kt]=t.useState(o.current),[Gt,Qt]=t.useState(i.current),[Vt,Jt]=t.useState(null),[Zt,Xt]=t.useState(null);return{clientRef:e,connectWithPairingRef:n,activeSessionIdRef:s,initialNotificationPermissionRef:i,initialNotificationSettingsRef:o,initialPreferencesRef:a,initialComposerDraftsRef:d,initialSavedTargetsRef:u,notificationPermissionRef:h,notificationSettingsRef:m,composerDraftsRef:f,lastHistorySessionIdRef:p,historyCacheDaemonIdRef:w,historyPrefetchingSessionIdsRef:S,pairingRef:x,notifiedEventsRef:I,reconnectTimerRef:k,connectionAttemptIdRef:C,respondingSessionsRef:R,turnNotificationCountsRef:E,intentionalDisconnectRef:M,phase:j,setPhase:A,statusText:T,setStatusText:N,errorText:P?Cr(P,Ct.remoteDirectConnection,Ct.localConnection):null,setErrorText:D,pairing:L,setPairing:F,sessions:O,setSessions:q,pendingSessions:_,setPendingSessions:$,optimisticSessions:z,setOptimisticSessions:H,nextCursor:B,setNextCursor:U,folderCounts:W,setFolderCounts:K,inventoryVersion:G,setInventoryVersion:Q,activeSessionId:V,setActiveSessionId:J,diffSessionId:X,setDiffSessionId:Y,respondingSessions:ee,setRespondingSessions:te,pendingApprovals:ne,setPendingApprovals:se,pendingQuestions:re,setPendingQuestions:ie,questionAnswers:oe,setQuestionAnswers:ae,pendingQueues:ce,setPendingQueues:le,setLivePendingQueue:de,remapPendingQueue:ue,confirmPendingQueueRemoval:he,agent:me,setAgent:fe,cwd:pe,setCwd:ge,approvalMode:ve,setApprovalMode:ye,continueSession:be,model:we,setModel:Se,effort:xe,setEffort:Ie,fastMode:ke,setFastMode:Ce,renameTitle:Re,setRenameTitle:Ee,composerDrafts:Me,setComposerDrafts:je,draft:Ae,setDraft:Te,webPreferences:Ne,sessionSort:De,setSessionSort:Fe,search:qe,setSearch:_e,sinceFilter:$e,setSinceFilter:ze,hideArchived:He,setHideArchived:Be,groupFolders:Ue,setGroupFolders:We,showNeedsAttentionGroup:Ke,setShowNeedsAttentionGroup:Ge,showRunningGroup:Qe,setShowRunningGroup:Ve,separatePinnedGroup:Je,setSeparatePinnedGroup:Ze,collapsedFolders:Xe,setCollapsedFolders:Ye,sessionAgentFilter:et,setSessionAgentFilter:tt,directoryTags:nt,archiveSyncedDaemonIds:st,archiveSyncCardDismissedDaemonIds:rt,composerPreferences:it,savedTargets:ot,setSavedTargets:at,leftSidebarCollapsed:ct,setLeftSidebarCollapsed:lt,rightSidebarCollapsed:dt,setRightSidebarCollapsed:Oe,workspaceClassName:ut,wideMainClassName:ht,workspaceStyle:mt,beginPaneResize:ft,applyBrowserDefaultWidth:pt,commitSearch:gt,saveTargets:vt,setLanguagePreference:yt,setThemePreference:bt,updateSessionListPreferences:wt,updateComposerPreferences:St,language:kt,t:Ct,busy:Rt,setBusy:Et,rewinding:Mt,setRewinding:jt,controlTab:At,setControlTab:Tt,detailsOpen:Nt,setDetailsOpen:Pt,setControlTabAndOpen:Dt,modelOptions:Lt,setModelOptions:Ft,usageLimits:Ot,setUsageLimits:qt,skills:_t,setSkills:$t,admin:zt,setAdmin:Ht,daemonMetadata:Bt,setDaemonMetadata:Ut,notificationSettings:Wt,setNotificationSettings:Kt,notificationPermission:Gt,setNotificationPermission:Qt,archiveSyncBusy:Vt,setArchiveSyncBusy:Jt,archiveSyncStatus:Zt,setArchiveSyncStatus:Xt}}(),n=function(e){return{showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup,separatePinnedGroup:e.separatePinnedGroup,toggleSessionViewGroup:async t=>{("needsAttention"===t?e.setShowNeedsAttentionGroup:"running"===t?e.setShowRunningGroup:e.setSeparatePinnedGroup)(e=>!e)}}}(e),{clientRef:s,activeSessionIdRef:o,notificationPermissionRef:d,notificationSettingsRef:u,composerDraftsRef:h,lastHistorySessionIdRef:m,historyPrefetchingSessionIdsRef:f,pairingRef:I,reconnectTimerRef:k,respondingSessionsRef:C,phase:R,setStatusText:E,setErrorText:M,pairing:j,setSessions:A,setOptimisticSessions:T,setNextCursor:N,setFolderCounts:P,setInventoryVersion:D,activeSessionId:L,setActiveSessionId:F,respondingSessions:O,setRespondingSessions:q,pendingApprovals:_,setPendingApprovals:$,pendingQuestions:z,setPendingQuestions:H,setQuestionAnswers:B,pendingQueues:U,setPendingQueues:W,agent:K,setAgent:G,cwd:Q,setCwd:V,setApprovalMode:J,composerDrafts:Z,setComposerDrafts:X,search:Y,sinceFilter:ee,hideArchived:te,sessionAgentFilter:ne,setRightSidebarCollapsed:se,t:re,controlTab:ie,setControlTab:oe,setControlTabAndOpen:ae,modelOptions:ce,setModelOptions:le,usageLimits:de,setUsageLimits:ue,setSkills:he,setDaemonMetadata:me,notificationSettings:fe,setNotificationSettings:pe,notificationPermission:ge,setNotificationPermission:ve,sessions:ye,pendingSessions:be,optimisticSessions:we,setDraft:Se,setBusy:xe}=e,Ie=function(e){const{clientRef:n,pairing:s,cwd:r,phase:i,controlTab:o,setControlTab:a,setBusy:c,setErrorText:l,t:d,scopeKey:u="default"}=e,h=t.useRef(!1),m=t.useRef(null),f=m.current&&Fe(m.current.key,u)?m.current:null,{value:p,set:g,setForScope:v,resolveScope:y,getAll:b}=De(u,()=>[]),w=t.useCallback((e,t)=>{v(Le(s?.daemonId,e),t)},[s?.daemonId,v]);t.useEffect(()=>rr(()=>[...b().values()].some(e=>e.length>0)),[b]);const[S,x]=t.useState(!1),I=t.useRef(new Map);t.useEffect(()=>{const e=new Set(p.map(e=>e.path));for(const[t,n]of I.current)(null===y(n.scope)||y(n.scope)===y(u)&&![...n.paths].some(t=>e.has(t)))&&(t.abort(),I.current.delete(t));x(I.current.size>0)},[p,u,y]);const[k,C]=Pe(u,()=>({path:f?.directory.path||!h.current&&(Qs().folder||Qs().cwd)||r||rn,entries:[],loading:!1,loaded:!1})),[R,E]=Pe(u,()=>f?.directoryHistory??[]),[M,j]=Pe(u,""),{remoteFile:A,setRemoteFile:T,openFiles:N,setOpenFiles:P,acknowledgeSave:D}=function(e,n,s){const r=t.useRef(null),i=r.current&&Fe(r.current.scope,e)?r.current:null,{value:o,set:a,getAll:c,updateAll:l}=De(e,()=>i?.value??(s?{current:fr(s),files:{[fr(s)]:s}}:{current:null,files:{}}));r.current={scope:e,value:o},t.useEffect(()=>{i&&l((e,t)=>t===i.scope?{current:null,files:{}}:e)},[e]),t.useEffect(()=>{const e=e=>{const t=e.detail;for(const[n,s]of c())if(null===Ne(n,{...t,action:"remove"})&&Object.values(s.files).some(e=>e.dirty))return void e.preventDefault()};return window.addEventListener(Me,e),()=>window.removeEventListener(Me,e)},[c]),t.useEffect(()=>rr(()=>[...c().values()].some(e=>Object.values(e.files).some(e=>e.dirty))),[c]);const d=t.useRef(new Set);t.useEffect(()=>{const e=new Set([...c().values()].flatMap(e=>Object.values(e.files).flatMap(e=>e.objectUrl?[e.objectUrl]:[])));for(const t of d.current)e.has(t)||URL.revokeObjectURL(t);d.current=e}),t.useEffect(()=>()=>{for(const e of d.current)URL.revokeObjectURL(e)},[]);const u=t.useCallback(e=>{a(t=>{const n=t.current?t.files[t.current]??null:null,s="function"==typeof e?e(n):e;if(!s)return null===t.current?t:{...t,current:null};const r=fr(s),i=t.files[r],o=i?.dirty&&!s.dirty?i:s;return t.current===r&&i===o?t:{current:r,files:{...t.files,[r]:o}}})},[a]),h=t.useCallback(e=>{a(t=>{const n="function"==typeof e?e(t.files):e;return n===t.files?t:{current:t.current&&n[t.current]?t.current:null,files:n}})},[a]),m=t.useCallback((e,t)=>{a(n=>{const s=fr(e),r=n.files[s];if(!r)return n;const i=function(e,t,n){return e&&e.path===t.path&&e.cwd===t.cwd&&e.etag===t.etag?{...e,dirty:e.text!==t.text,etag:"string"==typeof n.etag?n.etag:e.etag,lastModified:"string"==typeof n.lastModified?n.lastModified:e.lastModified,size:"number"==typeof n.size?n.size:e.size}:e}(r,e,t);return i!==r&&i?{...n,files:{...n.files,[s]:i}}:n})},[a]);return t.useEffect(()=>{const t=(t,s)=>{if(t===e)return n===s;try{return JSON.parse(t)[0]===s}catch{return!1}},s=e=>"move"===e.action||"delete"===e.action,r=(e,t)=>lr(fr(e),t.source??t.path,t.cwd),i=e=>{const{detail:n}=e;if(s(n))for(const[s,i]of c())if(t(s,n.daemonId)&&Object.values(i.files).some(e=>e.dirty&&r(e,n)))return void e.preventDefault()},o=e=>{const{detail:i}=e;if(!s(i))return;const o=cr(i.source??i.path,i.cwd),a=e=>`${cr(i.target,i.cwd)}${e.slice(o.length)}`;if(l((e,n)=>{if(!t(n,i.daemonId))return e;let s=e.current,o=!1;const c={};for(const[t,l]of Object.entries(e.files)){if(!r(l,i)){c[t]=l;continue}o=!0;const e="delete"===i.action?null:{...l,path:a(fr(l))},n=e&&fr(e);t===s&&(s=n),e&&n&&(c[n]=e)}return o?{current:s,files:c}:e}),n!==i.daemonId)return;const c=new URL(window.location.href),d=c.searchParams.get("file");d&&lr(d,o,c.searchParams.get("cwd")??i.cwd)&&("delete"===i.action?c.searchParams.delete("file"):c.searchParams.set("file",a(cr(d,c.searchParams.get("cwd")??i.cwd))),window.history.replaceState(null,"",c.href))};return window.addEventListener(or,i),window.addEventListener(ar,o),()=>{window.removeEventListener(or,i),window.removeEventListener(ar,o)}},[e,n,c,l]),{remoteFile:o.current?o.files[o.current]??null:null,setRemoteFile:u,openFiles:o.files,setOpenFiles:h,acknowledgeSave:m}}(u,s?.daemonId,f?.file),[L,F]=Pe(u,()=>new Set);m.current={key:u,file:A,directory:k,directoryHistory:R};const O=e=>JSON.stringify([e.cwd,e.path,e.etag]),q=!!A&&L.has(O(A)),_=t.useRef(new Map),$=t.useRef(null);t.useEffect(()=>{C(e=>({...e,loaded:!1,loading:!1}))},[u]);const z=t.useRef(0),H=t.useRef(k.path);t.useEffect(()=>()=>{if(m.current&&Fe(u,m.current.key)&&!m.current.file&&Qs().file&&(h.current=!1),z.current++,C(e=>e.loading?{...e,loading:!1}:e),y(u)!==y(m.current?.key??"")){$.current?.abort();for(const e of I.current.keys())e.abort();I.current.clear(),x(!1)}},[u]),t.useEffect(()=>{H.current!==k.path&&(z.current++,H.current=k.path)},[k.path]),t.useEffect(()=>(z.current++,C(e=>({...e,loading:!1,loaded:!1})),x(!1),()=>{z.current++;for(const e of I.current.keys())e.abort();I.current.clear(),$.current?.abort();for(const e of _.current.values())e.request.abort(),e.finish()}),[s?.pairToken]),t.useEffect(()=>{k.path!==rn||Qs().folder||(z.current++,C(e=>({...e,entries:[],loaded:!1,loading:!1})))},[r]);const B=t.useCallback(async e=>{if(!e?.length||!s)return;const t=new AbortController;x(!0),l(null);const n=Array.from(e).map(e=>({file:e,path:URL.createObjectURL(e)}));I.current.set(t,{scope:u,paths:new Set(n.map(e=>e.path))}),g(e=>[...e,...n.map(({file:e,path:t})=>({path:t,name:e.name,type:e.type,size:e.size,uploading:!0}))]);try{await async function(e,t,n,s,r){let i=0;const o=[];if(await Promise.all(Array.from({length:Math.min(2,e.length)},async function(){for(;!n.aborted&&i<e.length;){const c=e[i++];try{const e=await ur(c.file,t,n,s);n.aborted||r(c,e)}catch(a){o.push(a)}}})),!n.aborted&&o.length)throw o[0]}(n,s.pairToken,t.signal,d,({path:e},t)=>{g(n=>n.map(n=>n.path===e?t:n))})}catch(r){t.signal.aborted||l(r instanceof Error?r.message:String(r))}finally{const e=new Set(n.map(e=>e.path));g(t=>t.filter(t=>!e.has(t.path)));for(const t of e)URL.revokeObjectURL(t);I.current.delete(t)&&x(I.current.size>0)}},[s,l,d.uploadFailed,d.uploadPathMissing,u]),U=t.useCallback(async e=>{if(!s||!A||"text"!==A.kind||_.current.has(u))return;const t=new AbortController,n={request:t,finish:()=>{_.current.get(u)===n&&(_.current.delete(u),c(!1))}};_.current.set(u,n),c(!0),l(null);try{const n=await fetch(kn(A.path,A.cwd),{method:"PUT",signal:t.signal,headers:{authorization:`Bearer ${s.pairToken}`,"content-type":"text/markdown; charset=utf-8",...A.etag&&!e?.force?{"if-match":A.etag}:{}},body:A.text});if(t.signal.aborted)return;if(!n.ok){if(409===n.status)throw F(e=>new Set(e).add(O(A))),new Error(d.remoteFileConflict(A.path));throw new Error(await n.text().catch(()=>d.fileSaveFailed)||d.fileSaveFailed)}const r=await n.json().catch(()=>null);if(t.signal.aborted)return;if(!r||"object"!=typeof r||!("etag"in r)||"string"!=typeof r.etag||!r.etag.trim())throw new Error(d.fileSaveFailed);F(e=>{const t=new Set(e);return t.delete(O(A)),t}),D(A,r)}catch(r){t.signal.aborted||m.current?.key!==u||l(r instanceof Error?r.message:String(r))}finally{n.finish()}},[s,A,c,l,u,D]),W=t.useCallback(async()=>{if(s&&A)try{const e=/^(?:https?:\/\/|data:image\/|blob:)/i.test(A.path),t=await fetch(e?A.path:kn(A.path,A.cwd),{headers:e?{}:{authorization:`Bearer ${s.pairToken}`}});if(!t.ok)throw new Error(d.downloadFailed);const n=URL.createObjectURL(await t.blob()),r=document.createElement("a");r.href=n,r.download=un(A.path),r.click(),URL.revokeObjectURL(n)}catch(e){l(e instanceof Error?e.message:String(e))}},[s,A,l,u]),K=t.useCallback(async(e=k.path,t)=>{const s=n.current;if(!s?.isConnected)return;if(t?.background&&H.current!==e)return;const i=H.current;t?.background||(t?.back?E(e=>e.slice(0,-1)):cr(i,r)!==cr(e,r)&&E(e=>[...e.slice(-49),i])),H.current=e;const o=++z.current;t?.background||C(t=>({...t,path:e,entries:e===t.path?t.entries:[],loading:!0,loaded:!1,error:void 0}));try{const n=await s.request({action:"dirs.list",id:s.makeId("dirs"),path:e,cwd:r||void 0},{timeoutMs:1e4,timeoutMessage:d.directoryListTimedOut});if(o!==z.current)return;C({path:e,entries:n.entries??[],loading:!1,loaded:!0}),t?.updateRoute&&Vs({folder:e},{replace:t.replaceRoute})}catch(a){if(o!==z.current)return;C(e=>({...e,loading:!1,loaded:!0,error:a instanceof Error?a.message:String(a)}))}},[n,r,k.path,u]),G=t.useCallback(async()=>{const e=R.at(-1);e&&!k.loading&&(a("files"),await K(e,{updateRoute:!0,back:!0}))},[R,k.loading,K,a]),Q=t.useCallback(async(e,t,n)=>{if(!s)return;$.current?.abort();const i=new AbortController;if($.current=i,l(null),/[\\/]$/.test(e)&&!/^[a-z][a-z\d+.-]*:\/\//i.test(e)){const s=t||r,i=/^(?:[/\\]|~[/\\]|[a-z]:[/\\])/i.test(e)||!s?e:Sn(s,e);return a("files"),void(await K(i,n))}try{const r=/^(?:https?:\/\/|data:image\/|blob:)/i.test(e),o=await fetch(r?e:kn(e,t),{headers:r?{}:{authorization:`Bearer ${s.pairToken}`},signal:i.signal});if(!o.ok)throw new Error(404===o.status?d.fileNotFound(e):d.fileOpenFailed);const a=o.headers.get("content-type")??"application/octet-stream";if(r&&!a.startsWith("image/"))throw new Error(d.fileOpenFailed);const c=hr(e,a,!1),l=await o.blob(),u="html"===c||"unsupported"===c&&function(e,t){return!!t.startsWith("text/")||!!(t.includes("json")||t.includes("xml")||t.includes("javascript"))||/\.(md|txt|json|ya?ml|toml|csv|log|ts|tsx|js|jsx|css|html|xml|py|rb|go|rs|java|kt|swift|sh|zsh|bash)$/i.test(e)}(e,a)?await l.text():"unsupported"===c?function(e){const t=new Uint8Array(e);if(!t.some(e=>e<32&&![9,10,12,13].includes(e)||127===e))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{return}}(await l.arrayBuffer()):void 0;if(i.signal.aborted)return;if(void 0!==u)T({path:e,cwd:t,kind:"text",contentType:a,text:u,etag:Cn(o.headers,"etag"),lastModified:Cn(o.headers,"last-modified"),size:Number(o.headers.get("content-length"))||void 0,dirty:!1});else{const n="pdf"===hr(e,a,!1)?new Blob([l],{type:"application/pdf"}):l;T({path:e,cwd:t,kind:In(e,a)?"image":"binary",contentType:a,text:"",objectUrl:URL.createObjectURL(n),etag:Cn(o.headers,"etag"),lastModified:Cn(o.headers,"last-modified"),size:l.size,dirty:!1})}n?.updateRoute&&Vs({file:e,...t?{cwd:t}:{}},{replace:n.replaceRoute})}catch(o){if(i.signal.aborted)return;l(o instanceof Error?o.message:String(o))}},[s,l,u,r,K,a,d]),V=t.useCallback(async e=>{const t=n.current;if(!t?.isConnected)throw new Error(d.webSocketNotConnected);return(await t.request({action:"dirs.list",id:t.makeId("dirs"),path:e,cwd:r||void 0},{timeoutMs:1e4,timeoutMessage:d.directoryListTimedOut})).entries??[]},[n,r,u]),J=t.useCallback(async e=>(await V(e)).filter(e=>e.isDirectory),[V]);t.useEffect(()=>{!h.current||"files"!==o||"connected"!==i||k.loading||k.loaded||K(k.path||r||rn)},[o,r,k.loaded,k.loading,k.path,K,i]),t.useEffect(()=>{if("connected"!==i||h.current)return;const e=Qs();if(e.folder||e.file){if(h.current=!0,e.folder)return a("files"),void K(e.folder,{updateRoute:!1});e.file&&(e.cwd&&C(t=>({...t,path:e.cwd,loaded:!1})),Q(e.file,e.cwd,{updateRoute:!1}))}else h.current=!0},[K,Q,i,a]);const Z=t.useCallback(async()=>{const e=n.current;if(e?.isConnected&&0!==M.trim().length){c(!0),l(null);try{await e.request({action:"dirs.create",id:e.makeId("mkdir"),path:Sn(k.path,M),cwd:r||void 0}),j(""),await K(k.path)}catch(t){l(t instanceof Error?t.message:String(t))}finally{c(!1)}}},[n,r,k.path,K,M,c,l,u]),X=t.useCallback(async e=>{const t=n.current;if(!t?.isConnected)throw new Error(d.webSocketNotConnected);await t.request({action:"dirs.create",id:t.makeId("mkdir"),path:e,cwd:r||void 0},{timeoutMs:1e4,timeoutMessage:d.directoryCreationTimedOut})},[n,r,u]);return{attachments:p,setAttachments:g,setSessionAttachments:w,uploadBusy:S,directory:k,canGoBackDirectory:R.length>0,goBackDirectory:G,setDirectory:C,newDirName:M,setNewDirName:j,remoteFile:A,setRemoteFile:T,openFiles:N,setOpenFiles:P,remoteFileConflict:q,uploadFiles:B,openRemoteFile:Q,saveRemoteFile:U,downloadRemoteFile:W,listDirectory:K,listSessionDirectories:J,listFileTreeDirectory:V,createDirectory:Z,createSessionDirectory:X}}({scopeKey:Le(j?.daemonId,L),clientRef:s,pairing:j,cwd:Q,phase:R,controlTab:ie,setControlTab:ae,setBusy:xe,setErrorText:M,t:re}),ke=Object.keys(_).length+Object.keys(z).length,Ce=function(e,t,n){return"codex"===n&&/^pending_(?:local_)?\d+(?:_\d+)?$/.test(t??"")?e.map(e=>void 0===e.waitingForStartup?{...e,waitingForStartup:!0}:e):e}(L?U[L]??[]:[],L,K),Re=ce[K]??[],Ee=de[K],{completionAttention:je,reviewSessionIds:Te}=function(e,n,s){const r=t.useMemo(()=>{let t;try{t=window.localStorage}catch{}return new tr(t,`vibelet:completion-attention:${e??"disconnected"}`,nr)},[e]),i=t.useSyncExternalStore(r.subscribe,r.getSnapshot),o=t.useRef(new Set);return t.useEffect(()=>{o.current=new Set},[r]),t.useEffect(()=>{for(const e of n)r.reconcile(e.sessionId,Boolean(e.runtime.isResponding))},[r,n]),t.useEffect(()=>{for(const e of s)o.current.has(e)||r.observe(e);o.current=s},[r,s]),t.useEffect(()=>{if(!i.size)return;const e=window.setInterval(r.acknowledgeVisible,250);return window.addEventListener("focus",r.acknowledgeVisible),document.addEventListener("visibilitychange",r.acknowledgeVisible),()=>{window.clearInterval(e),window.removeEventListener("focus",r.acknowledgeVisible),document.removeEventListener("visibilitychange",r.acknowledgeVisible)}},[r,i]),{completionAttention:r,reviewSessionIds:i}}(j?.daemonId,ye,O),{historyCacheRef:Oe,historyPageStartRef:qe,hydrateVisibleHistory:_e,messagesSessionIdRef:$e,remapCachedHistory:ze,appendCachedDelta:He,appendCachedHistory:Be,appendInfoMessage:Ue,clearHistoryLoading:We,ensureCachedHistoryEntry:Ke,setCachedMessageDelivery:Ge,removeCachedMessage:Qe,resolveCachedMessageSession:Ve,historyLoading:Je,hasOlderHistory:Ze,olderHistoryLoading:Xe,messages:Ye,mergeCachedHistoryPage:et,removeCachedHistory:tt,renderCachedHistory:nt,replaceCachedHistory:st,requestHistory:rt,setMessages:it}=function(e){const n=t.useRef({}),s=function(e){return t.useMemo(()=>{const t=new Map,n=t=>JSON.stringify([e?.current??null,t]);return{has:(e,s)=>t.get(n(e))?.has(s)??!1,add:(e,s)=>{const r=t.get(n(e))??new Set;r.add(s),t.set(n(e),r)},filter:(e,s)=>{const r=t.get(n(e));return s.filter(e=>{if("user"!==e.role)return!0;const t=e.localClientMessageId??(e.historyKey?.startsWith("client:")?e.historyKey.slice(7):void 0);return!t||!r?.has(t)})},remap:(e,s)=>{const r=t.get(n(e));r&&(t.set(n(s),new Set([...t.get(n(s))??[],...r])),t.delete(n(e)))}}},[e])}(e.historyCacheDaemonIdRef),r=function(e,n){const s=t.useRef(new Map),r=t.useRef(new Set),i=t.useRef(null),o=e=>JSON.stringify([n?.current,e]),a=t.useCallback(()=>{i.current&&clearTimeout(i.current),i.current=null;for(const[e,t]of s.current)Sr(e,t);s.current.clear()},[]);return t.useEffect(()=>(window.addEventListener("pagehide",a),window.addEventListener("beforeunload",a),()=>{a(),window.removeEventListener("pagehide",a),window.removeEventListener("beforeunload",a)}),[a]),{changed:t=>{const r=n?.current;r&&(s.current.set(r,{...s.current.get(r),[t]:e.current[t]}),i.current||(i.current=setTimeout(a,500)))},fresh:e=>r.current.delete(o(e)),isStale:e=>r.current.has(o(e)),restore:t=>{if(!n?.current||Object.hasOwn(e.current,t))return;const s=function(e,t){return wr().find(n=>n.daemonId===e&&n.sessionId===t)?.messages.map(e=>{const t=Et(e);return"sending"===t.localDelivery?{...t,localDelivery:"failed",localInterruptedSend:!0}:t})}(n.current,t);return s?(e.current={...e.current,[t]:s},r.current.add(o(t)),!0):void 0}}}(n,e.historyCacheDaemonIdRef),i=t.useRef(r);i.current=r;const o=t.useRef(null),a=t.useRef({}),c=t.useRef({}),l=t.useRef(new Map),[d,u]=t.useState(null),h=t.useRef(null),[m,f]=t.useState(!1),[p,g]=t.useState([]),v=t.useCallback(e=>!(e&&o.current&&o.current!==e||(o.current=null,f(!1),0)),[]),y=t.useCallback(t=>(i.current.restore(t)&&(delete a.current[t],delete c.current[t]),!!pr(n.current,t)&&(h.current=t,e.onDeliveryHistoryChanged?.(t,n.current[t]??[]),g(n.current[t]??[]),!0)),[e.onDeliveryHistoryChanged]),b=t.useCallback((t,r,o)=>{n.current=function(e,t,n){return t?{...e,[t]:vr(e[t]??[],n)}:e}(n.current,t,s.filter(t,r)),i.current.changed(t),i.current.fresh(t);const a=n.current[t]??[];for(const n of a)n.localClientMessageId&&n.localDelivery&&e.onDeliveryChanged?.(t,n.localClientMessageId,n.localDelivery);return e.onDeliveryHistoryChanged?.(t,a),!1!==o?.renderActive&&t===e.activeSessionIdRef.current&&(h.current=t,g(a)),a},[e.activeSessionIdRef,e.onDeliveryChanged,e.onDeliveryHistoryChanged,s]),w=t.useCallback((t,s,r,i)=>{const o=e=>b(t,function(e,t){return Ot(e.map(e=>({...e})),t)}(e,i)),d=l.current.get(t);d?.client===e.clientRef.current&&(void 0===d.before||r&&r.start<d.before)&&(d.received=!0),t===e.activeSessionIdRef.current&&e.setErrorText(t=>t===e.historyTimeoutMessage?null:t);const u=pr(n.current,t)?c.current[t]:void 0;if(c.current[t]=r,"byte"===r?.cursorMode){const e=function(e,t,n,s){if(!n||"byte"!==n.cursorMode)return[...t];if(s.start<n.start){const n=new Set(t.map(yr).filter(Boolean));return[...t,...e.filter(e=>{const t=yr(e);return!t||!n.has(t)})]}const r=t[0],i=r?e.findIndex(e=>r.historyKey&&e.historyKey?r.historyKey===e.historyKey:r.rewindPoint&&e.rewindPoint?r.role===e.role&&Ct(r.rewindPoint)===Ct(e.rewindPoint):Boolean(r.timestamp)&&r.timestamp===e.timestamp&&r.role===e.role&&r.type===e.type&&r.content===e.content&&JSON.stringify(r.images)===JSON.stringify(e.images)&&r.toolName===e.toolName&&JSON.stringify(r.toolInput)===JSON.stringify(e.toolInput)):-1;return i>=0?[...e.slice(0,i),...t]:[...t]}(n.current[t]??[],s,u,r);return"byte"===u?.cursorMode&&e.length>s.length&&r.start>=u.start&&(c.current[t]={...r,start:u.start,hasMore:u.hasMore}),a.current[t]=c.current[t]?.start,o(e)}if(!r)return a.current[t]=void 0,o(s);const h=a.current[t],m=n.current[t]??[],f=r.start+s.length;if(void 0===h||f<h||r.start>h+m.length)return a.current[t]=r.start,o(s);a.current[t]=Math.min(h,r.start),c.current[t]={...r,start:Math.min(h,r.start),hasMore:Math.min(h,r.start)>0};const p=m.slice(0,Math.max(0,r.start-h)),g=m.slice(Math.max(0,f-h),Math.max(0,r.total-h));return o([...p,...s,...g])},[b,e.clientRef,e.activeSessionIdRef,e.setErrorText,e.historyTimeoutMessage]),S=t.useCallback((e,t)=>{delete c.current[e],a.current[e]=0;const n=b(e,t,{renderActive:!1});h.current=e,g(n)},[b]),x=t.useCallback((t,r)=>{n.current=gr(n.current,t,s.filter(t,r)),i.current.changed(t),e.onDeliveryHistoryChanged?.(t,n.current[t]??[]),t===e.activeSessionIdRef.current&&(h.current=t,g(n.current[t]??[]))},[e.activeSessionIdRef,e.onDeliveryHistoryChanged,s]),I=t.useCallback((t,r)=>{s.filter(t,[r]).length&&(n.current=function(e,t,n){return n.historyKey&&e[t]?.some(e=>e.historyKey===n.historyKey)?e:gr(e,t,[n])}(n.current,t,r),i.current.changed(t),e.onDeliveryHistoryChanged?.(t,n.current[t]??[]),t===e.activeSessionIdRef.current&&(h.current=t,g(n.current[t]??[])))},[e.activeSessionIdRef,e.onDeliveryHistoryChanged,s]),k=t.useCallback((e,t)=>function(e,t,n){const s=e=>e?.some(e=>e.localClientMessageId===n||e.historyKey===`client:${n}`);return s(e[t])?t:Object.entries(e).find(([,e])=>s(e))?.[0]??t}(n.current,e,t),[]),C=t.useCallback((t,r,o,a)=>{if(t=k(t,r),s.has(t,r))return;if(!a&&!n.current[t]?.some(e=>e.localClientMessageId===r||e.historyKey===`client:${r}`))return;const c=function(e,t,n,s){const r=e.findIndex(e=>e.localClientMessageId===t||e.historyKey===`client:${t}`),i=e.slice();if(r<0)s&&i.push({role:"user",...s,timestamp:(new Date).toISOString(),historyKey:`client:${t}`,localClientMessageId:t,localDelivery:n});else{const s=e[r],o="delivered"===s.localDelivery||"accepted"===s.delivery||s.historyKey&&!s.historyKey.startsWith("client:");i[r]={...s,localClientMessageId:t,localInterruptedSend:void 0,localDelivery:o&&"failed"===n?"delivered":n}}return i}(n.current[t]??[],r,o,a);n.current={...n.current,[t]:c},i.current.changed(t),t!==e.activeSessionIdRef.current&&t!==h.current||(h.current=t,g(n.current[t]??[]));const l=c.find(e=>e.localClientMessageId===r)?.localDelivery;return l&&e.onDeliveryChanged?.(t,r,l),e.onDeliveryHistoryChanged?.(t,c),l},[e.activeSessionIdRef,e.onDeliveryChanged,e.onDeliveryHistoryChanged,s]),R=t.useCallback((t,r)=>{t=k(t,r),s.add(t,r);const o=n.current[t];if(!o)return;const a=o.filter(e=>"user"!==e.role||e.localClientMessageId!==r&&e.historyKey!==`client:${r}`);a.length!==o.length&&(e.onDeliveryRemoved?.(t,r),e.onDeliveryHistoryChanged?.(t,a),n.current={...n.current,[t]:a},i.current.changed(t),t!==e.activeSessionIdRef.current&&t!==h.current||g(a))},[e.activeSessionIdRef,e.onDeliveryRemoved,e.onDeliveryHistoryChanged,k,s]),E=t.useCallback((t,s)=>{n.current=function(e,t,n){return t&&n?{...e,[t]:Ft(ln(e[t]??[],n))}:e}(n.current,t,s),i.current.changed(t),t===e.activeSessionIdRef.current&&(h.current=t,g(n.current[t]??[]))},[e.activeSessionIdRef,s]),M=t.useCallback((e,t)=>{x(e,[{role:"assistant",type:"info",content:t,timestamp:(new Date).toISOString()}])},[x]),j=t.useCallback(e=>{n.current=function(e,t){if(!pr(e,t))return e;const n={...e};return delete n[t],n}(n.current,e),i.current.changed(e),delete a.current[e],delete c.current[e]},[]),A=t.useCallback((e,t)=>{s.remap(e,t),n.current=function(e,t,n){if(!t||!n||t===n||!pr(e,t))return e;const s={...e};return s[n]=e[t],delete s[t],s}(n.current,e,t),i.current.changed(e),i.current.changed(t),a.current[t]=a.current[e],delete a.current[e],c.current[t]=c.current[e],delete c.current[e]},[s]),T=t.useCallback(async(t,{older:n=!1,refresh:s=!1}={})=>{const r=e.clientRef.current;if(!r?.isConnected)return;for(;l.current.get(t.sessionId)?.client===r;){if(!s)return;if(await l.current.get(t.sessionId).settled,e.clientRef.current!==r||!r.isConnected||e.activeSessionIdRef.current!==t.sessionId)return}const d=c.current[t.sessionId];if(n&&(!d?.hasMore||d.start<=0))return;let h;const m={client:r,received:!1,before:n?d?.start:void 0,settled:new Promise(e=>{h=e})};l.current.set(t.sessionId,m),n&&u(t.sessionId);const p=()=>e.clientRef.current===r,g=y(t.sessionId);g?v(t.sessionId):(o.current=t.sessionId,delete a.current[t.sessionId],f(!0),e.setErrorText(null));try{if(!n&&!s&&g&&!i.current.isStale(t.sessionId)){const n=await r.request({action:"reconnect.snapshot",id:r.makeId("snapshot"),activeSessionId:t.sessionId,activeAgent:t.agent,skipActiveSessionHistory:!0,skipGitMetadata:!0});if(!p())return;const s=n.snapshot.activeSession;if(s?.sessionId===t.sessionId){e.setPendingQueues(e=>({...e,[t.sessionId]:s.pendingQueue??[]}));for(const e of s.acceptedClientMessageIds??[])C(t.sessionId,e,"delivered")}return}if(await r.request({action:"session.history",id:r.makeId("history"),sessionId:t.sessionId,agent:t.agent,limit:n?100:20,...n&&"byte"!==d?.cursorMode?{before:d?.start}:{pageMode:"cursor",...n?{beforeCursor:d?.start}:{}}},{timeoutMessage:e.historyTimeoutMessage,timeoutMs:15e3}),!p())return}catch(b){!p()||e.activeSessionIdRef.current!==t.sessionId||b instanceof en&&m.received||e.setErrorText(b instanceof Error?b.message:String(b))}finally{l.current.get(t.sessionId)===m&&l.current.delete(t.sessionId),h(),p()&&(n&&u(e=>e===t.sessionId?null:e),v(t.sessionId))}},[v,e.activeSessionIdRef,e.clientRef,e.historyTimeoutMessage,e.setErrorText,e.setPendingQueues,y,C]);return{hasOlderHistory:Boolean(c.current[e.activeSessionIdRef.current??""]?.hasMore),olderHistoryLoading:d===e.activeSessionIdRef.current&&null!==d,resolveCachedMessageSession:k,setCachedMessageDelivery:C,removeCachedMessage:R,appendCachedDelta:E,appendCachedHistory:x,appendInfoMessage:M,clearHistoryLoading:v,ensureCachedHistoryEntry:I,historyCacheRef:n,historyLoading:m,historyPageStartRef:a,hydrateVisibleHistory:S,messages:p,messagesSessionIdRef:h,mergeCachedHistoryPage:w,remapCachedHistory:A,removeCachedHistory:j,renderCachedHistory:y,replaceCachedHistory:b,requestHistory:T,setMessages:g}}({onDeliveryChanged:je.deliveryChanged,onDeliveryHistoryChanged:je.reconcileDeliveries,onDeliveryRemoved:je.deliveryRemoved,historyCacheDaemonIdRef:e.historyCacheDaemonIdRef,activeSessionIdRef:o,clientRef:s,historyTimeoutMessage:re.historyRequestTimedOut,setPendingQueues:W,setErrorText:M}),ot=t.useMemo(()=>new Set(Object.entries(Oe.current).filter(([,e])=>Hs(e)).map(([e])=>e)),[Oe.current]),{activeSession:at,activeApproval:ct,activeQuestion:lt,displaySessions:dt,groupedSessions:ut,pendingSessionIds:ht,visibleSessions:mt}=function(e){const n=t.useRef({protectedSessionIds:[]}),s=t.useMemo(()=>gn(gn(e.sessions,Object.values(e.optimisticSessions)),Object.values(e.pendingSessions)),[e.optimisticSessions,e.pendingSessions,e.sessions]),i=t.useMemo(()=>new Set(Object.keys(e.pendingSessions)),[e.pendingSessions]),o=t.useRef({scope:"",session:null}),c=JSON.stringify([e.daemonId??null,e.activeSessionId]),l=s.find(t=>t.sessionId===e.activeSessionId)??(o.current.scope===c?o.current.session:null);o.current={scope:c,session:l};const d=(e.activeSessionId?e.pendingApprovals[e.activeSessionId]:null)??Object.values(e.pendingApprovals)[0]??null,u=(e.activeSessionId?e.pendingQuestions[e.activeSessionId]:null)??Object.values(e.pendingQuestions)[0]??null,h=t.useMemo(()=>r(function(e,t){const n=e.filter(e=>("all"===t.agentFilter||e.agent===t.agentFilter)&&function(e,t){const n=t.trim().toLowerCase();return!n||[a(e),e.cwd,e.agent,e.branch??"",...e.titleAliases??[]].some(e=>e.toLowerCase().includes(n))}(e,t.search));if(!t.hideArchived)return n;const s=n.filter(e=>!e.archived);return t.search.trim()&&!s.length?n:s}(s,{search:e.search,hideArchived:e.hideArchived,agentFilter:e.sessionAgentFilter}),e.sessionSort??"updated",!1),[s,e.hideArchived,e.search,e.sessionAgentFilter,e.sessionSort]),m=t.useMemo(()=>new Set([...Object.keys(e.pendingApprovals),...Object.keys(e.pendingQuestions),...e.reviewSessionIds??[],...e.failedSessionIds??[]]),[e.pendingApprovals,e.pendingQuestions,e.reviewSessionIds,e.failedSessionIds]),f=t.useMemo(()=>{if(e.search.trim()||"updated"!==(e.sessionSort??"updated"))return h;const t=function(e,t,n){if(0===e.length)return 0===n.protectedSessionIds.length?{sessions:e,state:n}:{sessions:e,state:{protectedSessionIds:[]}};const s=new Map,r=[];for(const l of e)s.set(l.sessionId,l),(t[l.sessionId]||l.runtime.isResponding)&&r.push(l.sessionId);if(0===r.length)return 0===n.protectedSessionIds.length?{sessions:e,state:n}:{sessions:e,state:{protectedSessionIds:[]}};const i=new Set(r),o=n.protectedSessionIds.filter(e=>s.has(e)&&i.has(e)),a=new Set(o);let c=o.length!==n.protectedSessionIds.length;for(const l of r)a.has(l)||(a.add(l),o.push(l),c=!0);return{sessions:Ht(e,o,s),state:c?{protectedSessionIds:o}:n}}(h,Object.fromEntries([...e.respondingSessionIds].map(e=>[e,!0])),n.current);return n.current=t.state,t.sessions},[h,e.respondingSessionIds,e.search,e.sessionSort]),g=t.useMemo(()=>Object.fromEntries(f.map((e,t)=>[e.sessionId,t])),[f]),v=t.useMemo(()=>[...r(f.filter(e=>e.pinned&&!e.archived),"updated"),...f.filter(e=>!e.pinned||e.archived)],[f]),y=t.useMemo(()=>p(function(e,t={}){const n=e=>Object.fromEntries(Array.from(e??[],e=>[e,!0])),s=function(e,t,n,s={}){const r=new Map,i=[],o=[],a=[];for(const l of e){const e=qt(l.cwd),n=!0!==l.archived;if(Boolean(s.showNeedsAttentionGroup&&n&&(s.needsAttentionSessionIds?.[l.sessionId]||l.interruptReason||l.runtime.needsAttention&&!l.stallWarning))?o.push(l):s.showRunningGroup&&n&&(t?.[l.sessionId]||l.runtime.isResponding)&&a.push(l),s.separatePinnedGroup&&_t(l,s.pinnedSessionIds,s.pendingPinnedSessionIds)&&n){i.push(l);continue}const c=r.get(e);c?c.push(l):r.set(e,[l])}const c=[];o.length&&c.push({folder:"@vibelet/needs-attention",kind:"attention",sessions:$t(o,s.regularSessionOrderById)}),a.length&&c.push({folder:"@vibelet/running",kind:"running",sessions:$t(a,s.regularSessionOrderById)}),i.length&&c.push({folder:"@vibelet/pinned",kind:"pinned",sessions:s.orderPinnedByLastActivity?zt(i):$t(i,s.regularSessionOrderById)});for(const[l,d]of r)c.push({folder:l,kind:"folder",sessions:d});return c}(e,n(t.respondingSessionIds),0,{...t,needsAttentionSessionIds:n(t.needsAttentionSessionIds),orderPinnedByLastActivity:!0}),r=new Map(t.runningSessionOrder?.map((e,t)=>[e,t]));if(r.size){const e=s.find(e=>"running"===e.kind);e?.sessions.sort((e,t)=>(r.get(e.sessionId)??1/0)-(r.get(t.sessionId)??1/0))}return s}(v,{needsAttentionSessionIds:m,regularSessionOrderById:g,respondingSessionIds:e.respondingSessionIds,separatePinnedGroup:e.separatePinnedGroup,showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup}),e.sessionSort??"updated"),[m,g,e.respondingSessionIds,e.separatePinnedGroup,e.showNeedsAttentionGroup,e.showRunningGroup,e.sessionSort,v]);return{activeApproval:d,activeQuestion:u,activeSession:l,displaySessions:s,groupedSessions:y,pendingSessionIds:i,visibleSessions:v}}({daemonId:j?.daemonId,activeSessionId:L,reviewSessionIds:Te,failedSessionIds:ot,hideArchived:te,optimisticSessions:we,pendingApprovals:_,pendingQuestions:z,pendingSessions:be,respondingSessionIds:O,search:Y,separatePinnedGroup:n.separatePinnedGroup,sessionAgentFilter:ne,sessionSort:e.sessionSort,sessions:ye,showNeedsAttentionGroup:n.showNeedsAttentionGroup,showRunningGroup:n.showRunningGroup});Ys(o,L),Ys(I,j),Ys(C,O),Ys(u,fe),Ys(d,ge),Ys(h,Z);const{updateNewSessionDraft:ft,updateDraft:pt,updateSessionDraft:gt}=function({activeSessionIdRef:e,composerDraftsRef:n,setComposerDrafts:s,setDraft:r}){const i=t.useRef(null),o=t.useRef(null),a=t.useRef(!1);t.useEffect(()=>rr(()=>a.current),[]);const c=t.useCallback(()=>{if(i.current&&clearTimeout(i.current),o.current&&clearTimeout(o.current),i.current=o.current=null,a.current){a.current=!1;try{Un(n.current)}catch{a.current=!0}}},[n]),l=t.useCallback(()=>{a.current=!0,i.current&&clearTimeout(i.current),i.current=setTimeout(c,300),o.current||(o.current=setTimeout(c,2e3))},[c]);t.useEffect(()=>{const e=()=>{"hidden"===document.visibilityState&&c()};return window.addEventListener(ir,c),window.addEventListener("pagehide",c),window.addEventListener("beforeunload",c),document.addEventListener("visibilitychange",e),()=>{c(),window.removeEventListener(ir,c),window.removeEventListener("pagehide",c),window.removeEventListener("beforeunload",c),document.removeEventListener("visibilitychange",e)}},[c]);const d=t.useCallback((t,i)=>{const o=Wn(n.current,t,i);n.current=o,s(o),e.current===t&&r(i),l()},[e,n,s,r,l]);return{updateDraft:t.useCallback(t=>d(e.current,t),[e,d]),updateNewSessionDraft:t.useCallback(e=>d(null,e),[d]),updateSessionDraft:d}}({activeSessionIdRef:o,composerDraftsRef:h,setComposerDrafts:X,setDraft:Se});t.useEffect(()=>{w();const e=S();e&&(ft(e),oe("session"),x())},[ft]),t.useEffect(()=>{const e=()=>{pe(xt()),ve(It())};return window.addEventListener("vibelet.notifications.changed",e),()=>window.removeEventListener("vibelet.notifications.changed",e)},[]),t.useEffect(()=>{"admin"===ie&&ve(It())},[ie]),t.useEffect(()=>()=>{k.current&&window.clearTimeout(k.current)},[]);const vt=t.useCallback((e,t=!1)=>{A(n=>function(e,t,n=!1){const s=new Set(t.map(e=>e.sessionId));return gn(n?e:e.filter(e=>s.has(e.sessionId)),t)}(n,e.sessions,t)),T(t=>{const n=new Set(e.sessions.map(e=>e.sessionId)),s=Object.fromEntries(Object.entries(t).filter(([e])=>!n.has(e)));return Object.keys(s).length===Object.keys(t).length?t:s}),N(e.nextCursor),D(e.inventoryVersion),e.folderCounts&&P(e.folderCounts),t||function(e,t,n=i(),s=(new Date).toISOString()){if(!e)return;const r=[{daemonId:e,page:{...t,sessions:t.sessions.slice(0,120)},cachedAt:s},...On(n).filter(t=>t.daemonId!==e)].slice(0,8);try{n.setItem(Ln,JSON.stringify(r))}catch{}}(I.current?.daemonId,e),E(e.inventoryBackfillInFlight?re.connectedIndexing:re.connected)},[re.connected,re.connectedIndexing]),yt=function({clientRef:e,sessions:n,setSessions:s,activeSessionIdRef:r}){const i=t.useRef(new Map),o=t.useRef(n);o.current=n,t.useEffect(()=>()=>i.current.clear(),[]);const a=t.useCallback(async t=>{const n=e.current;if(!n?.isConnected)return;const o=t.find(e=>e.sessionId===r?.current),a=o?[o,...t]:t,c=[...new Set(a.map(e=>e.cwd).filter(Boolean))];if(0===c.length)return;const l={};for(const e of c)i.current.set(e,l);try{const t=await n.request({action:"sessions.gitMetadata",id:n.makeId("git"),cwds:c});if(e.current!==n||!n.isConnected)return;s(s=>s.map(s=>{if(e.current!==n||!n.isConnected||i.current.get(s.cwd)!==l)return s;const r=Object.hasOwn(t.branches,s.cwd),o=r?t.branches[s.cwd]??void 0:s.branch,a=r&&o!==s.branch,c=t.gitLinksCwds?.includes(s.cwd)??r;return{...s,pullRequest:c?t.pullRequests?.[s.cwd]:a?void 0:s.pullRequest,branchUrl:t.branchUrls?.[s.cwd]??(c||a?void 0:s.branchUrl),branch:o,gitSync:t.syncStatuses?t.syncStatuses[s.cwd]??void 0:void 0,diffStat:Object.hasOwn(t.diffStats,s.cwd)?t.diffStats[s.cwd]??void 0:s.diffStat}}))}catch{}},[e,s,r]);return t.useEffect(()=>{let e=!1;const t=()=>{"hidden"===document.visibilityState||e||(e=!0,a(o.current).finally(()=>{e=!1}))},n=window.setInterval(t,15e3);return window.addEventListener("focus",t),document.addEventListener("visibilitychange",t),()=>{window.clearInterval(n),window.removeEventListener("focus",t),document.removeEventListener("visibilitychange",t)}},[a]),a}({clientRef:s,sessions:ye,setSessions:A,activeSessionIdRef:o}),bt=t.useCallback((e,t=C.current)=>{const n=s.current;if(!n?.isConnected||0===e.length)return;const r=function(e,t,n,s,r=6){if(r<=0)return[];const i=[];for(const o of e){if(i.length>=r)break;o.sessionId&&kr(o,n)&&(pr(t,o.sessionId)||s.has(o.sessionId)||i.push(o))}return i}(e.filter(e=>e.sessionId!==o.current),Oe.current,t,f.current);for(const s of r)f.current.add(s.sessionId),n.request({action:"session.history",id:n.makeId("history_prefetch"),pageMode:"cursor",limit:20,sessionId:s.sessionId,agent:s.agent},{timeoutMessage:re.historyPrefetchTimedOut,timeoutMs:15e3}).catch(()=>{}).finally(()=>{f.current.delete(s.sessionId)})},[re.historyPrefetchTimedOut]),St=t.useCallback(e=>{const t=function(e,t={}){const n=new Set,s={},r={},i={};for(const m of e.sessions)m.runtime.isResponding&&n.add(m.sessionId);for(const m of e.pendingApprovals??[])s[m.sessionId]={type:"approval.request",...m};for(const m of e.pendingQuestions??[])r[m.sessionId]={type:"question.request",...m};let o,a,c,l,d,u,h=null;if(e.activeSession){const m=e.activeSession,f=e.sessions.find(e=>e.sessionId===m.sessionId);if(h=m.sessionId,o=m.agent,a=f?.cwd||t.currentCwd||rn,c=m.approvalMode??f?.approvalMode??on,l=m.approvalMode??null,d=Ot(m.messages??[],m.partialReplyText),(m.isResponding||m.externallyResponding)&&n.add(m.sessionId),m.pendingApproval&&(s[m.sessionId]={type:"approval.request",sessionId:m.sessionId,...m.pendingApproval}),m.pendingQuestion){const e={type:"question.request",sessionId:m.sessionId,...m.pendingQuestion};r[m.sessionId]=e,u=mn(e)}m.pendingQueue?.length&&(i[m.sessionId]=m.pendingQueue)}else{const n=t.currentActiveSessionId??null;if(n){const t=e.sessionAliases?.[n];t?h=t:e.sessions.some(e=>e.sessionId===n)&&(h=n)}h=h??e.sessions[0]?.sessionId??null;const s=e.sessions.find(e=>e.sessionId===h);s&&(o=s.agent,a=s.cwd||rn,c=s.approvalMode??on)}return{page:{sessions:e.sessions,nextCursor:sn(e.nextCursor),inventoryVersion:e.inventoryVersion,inventoryBackfillInFlight:e.inventoryBackfillInFlight},activeSessionId:h,activeAgent:o,activeCwd:a,activeApprovalMode:c,activeApprovalOverride:l,messages:d,respondingSessionIds:Array.from(n),pendingApprovals:s,pendingQuestions:r,pendingQueues:i,questionAnswers:u}}(e,{currentActiveSessionId:o.current,currentCwd:Q});vt(t.page,!1),N(t.page.nextCursor),D(t.page.inventoryVersion),void 0!==e.activeSession?.messages&&t.messages&&t.activeSessionId&&_e(t.activeSessionId,t.messages);for(const n of e.activeSession?.acceptedClientMessageIds??[])Ge(e.activeSession.sessionId,n,"delivered");e.activeSession&&void 0===e.activeSession.messages&&rt(e.activeSession,{refresh:!0}),o.current=t.activeSessionId,F(t.activeSessionId),t.activeAgent&&G(t.activeAgent),t.activeCwd&&V(t.activeCwd),t.activeApprovalMode&&J(t.activeApprovalMode),t.questionAnswers&&B(t.questionAnswers),C.current=new Set(t.respondingSessionIds),q(C.current),$(t.pendingApprovals),H(t.pendingQuestions),W(t.pendingQueues),yt(e.sessions),bt(e.sessions,new Set(t.respondingSessionIds))},[Q,yt,_e,bt,rt,vt,Ge]),kt=function(e){const{clientRef:n,activeSessionIdRef:s,search:r,sinceFilter:i,hideArchived:o,sessionAgentFilter:a}=e,c=t.useMemo(()=>({}),[r,i,o,a]),l=t.useRef({scope:c,options:e,request:0});return l.current.scope=c,l.current.options=e,t.useEffect(()=>()=>{l.current.request++},[]),t.useCallback(async()=>{const e=n.current;if(!e?.isConnected)return;const t=++l.current.request,r=()=>n.current===e&&e.isConnected&&l.current.request===t;for(;r();){const t=l.current,n=t.scope,o=t.options,a=s.current,c=()=>l.current.scope===n;try{const t=await e.request({action:"reconnect.snapshot",id:e.makeId("snapshot"),activeSessionId:a??void 0,activeAgent:o.activeAgent,agent:"all"===o.sessionAgentFilter?void 0:o.sessionAgentFilter,search:o.search.trim()||void 0,sinceMs:pn(o.sinceFilter),hideArchived:o.hideArchived,skipGitMetadata:!0,skipActiveSessionHistory:!0});if(!r())return;if(!c())continue;return void l.current.options.apply(s.current===a?t.snapshot:{...t.snapshot,activeSession:void 0})}catch(i){if(!r())return;if(c())throw i}}},[n,s])}({clientRef:s,activeSessionIdRef:o,activeAgent:at?.agent??K,sessionAgentFilter:ne,search:Y,sinceFilter:ee,hideArchived:te,apply:St}),Rt=function(e){const{clientRef:n,search:s,sinceFilter:r,hideArchived:i,sessionAgentFilter:o,viewKey:a}=e,c=t.useMemo(()=>({refresh:0,includeArchived:!1}),[s,r,i,o,a]),l=t.useRef({options:e,scope:c});l.current={options:e,scope:c};const d=t.useRef(c);t.useLayoutEffect(()=>{d.current!==c&&(d.current=c,e.setNextCursor(void 0))},[e.setNextCursor,c]);const u=t.useRef(!0);return t.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]),t.useCallback(async e=>{const t=n.current;if(!u.current||!t?.isConnected||l.current.scope!==c)return;const a=e?.append?c.refresh:++c.refresh,d=()=>u.current&&n.current===t&&t.isConnected&&l.current.scope===c&&(e?.append||a===c.refresh);try{const n={action:"sessions.list",id:t.makeId(e?.append?"sessions_more":"sessions"),limit:e?.preserveLoaded?Math.max(80,l.current.options.loadedCount):80,cursor:e?.cursor,agent:"all"===o?void 0:o,search:s.trim()||void 0,sinceMs:pn(r),hideArchived:i&&!(e?.append&&c.includeArchived),skipGitMetadata:!0,force:e?.force};let a=await t.request(n);if(!d())return;if(!e?.append&&(c.includeArchived=!1,s.trim()&&i&&!a.sessions.length&&!a.nextCursor)){if(a=await t.request({...n,id:t.makeId("sessions_archived"),hideArchived:!1,force:!1}),!d())return;c.includeArchived=!0}if(!d())return;const u=dn(a),h=l.current.options;h.setSessionsFromPage(u,e?.append),h.setActiveSessionId(e=>e??u.sessions[0]?.sessionId??null),h.hydrateGitMetadata(u.sessions),h.prefetchActiveHistories(u.sessions)}catch(h){if(d())throw h}},[n,c,s,r,i,o])}({clientRef:s,search:Y,sinceFilter:ee,hideArchived:te,sessionAgentFilter:ne,viewKey:[e.sessionSort,e.groupFolders,n.showNeedsAttentionGroup,n.showRunningGroup,n.separatePinnedGroup].join(":"),loadedCount:ye.length,setNextCursor:N,setSessionsFromPage:vt,setActiveSessionId:F,hydrateGitMetadata:yt,prefetchActiveHistories:bt}),Mt=function({clientRef:e,setModelOptions:n,setUsageLimits:s,setSkills:r,setErrorText:i,t:o}){const a=t.useRef(0),c=t.useRef(null);return t.useEffect(()=>()=>{a.current++},[]),t.useCallback((t,l)=>{const d=e.current;if(!d?.isConnected)return Promise.resolve();if(c.current?.client===d&&c.current.agent===t&&c.current.cwd===l)return c.current.promise;const u=++a.current,h=()=>a.current===u&&e.current===d&&d.isConnected,m="codex"===t?"Codex":"Claude",f=[],p=Promise.allSettled([d.request({action:"models.list",id:d.makeId("models"),agent:t},{timeoutMs:ks}).then(e=>{h()&&n(n=>({...n,[t]:e.options??[]}))}).catch((e=>t=>{if(!h())return;const n=t instanceof Error?t.message:String(t);f.push(/timeout|timed out/i.test(n)?o.resourceLoadTimedOut(e):o.resourceLoadFailed(e,n)),i(f.join("\n"))})(`${m} · ${o.model}`)),er(d,()=>({action:"usage.limits.fetch",id:d.makeId("usage"),agent:t}),h).then(e=>{e&&h()&&s(n=>({...n,[t]:e}))}),er(d,()=>({action:"skills.list",id:d.makeId("skills"),cwd:l||void 0}),h).then(e=>{e&&h()&&r(Array.isArray(e.skills)?e.skills:[])})]).then(()=>{a.current===u&&(c.current=null)});return c.current={client:d,agent:t,cwd:l,promise:p},p},[e,n,s,r,i,o])}({t:re,clientRef:s,setModelOptions:le,setUsageLimits:ue,setSkills:he,setErrorText:M}),jt=t.useCallback((e,t,n="info")=>{const r=s.current;r?.isConnected&&r.request({action:"log.report",id:r.makeId("log"),entries:[{level:n,event:e,data:t,ts:(new Date).toISOString()}]}).catch(()=>{})},[]);!function(e){t.useEffect(()=>{const t=performance.now(),n=(t,n,s="info")=>e(t,function(e){const t={};for(const[n,s]of Object.entries(e))xr.has(n)&&("string"==typeof s?t[n]=s.slice(0,48):"number"==typeof s&&Number.isFinite(s)?t[n]=Math.round(s):"boolean"==typeof s&&(t[n]=s));return t}(n),s),s=e=>{n("web.telemetry.runtime_error",{errorKind:Ir(e.error)},"error")},r=e=>{n("web.telemetry.unhandled_rejection",{errorKind:Ir(e.reason)},"error")},i=window.setTimeout(()=>{n("web.telemetry.workspace_ready",{durationMs:performance.now()-t,domNodes:document.getElementsByTagName("*").length,online:navigator.onLine,visibilityState:document.visibilityState})},1500);let o=0,a=0,c=null;return"undefined"!=typeof PerformanceObserver&&PerformanceObserver.supportedEntryTypes.includes("longtask")&&(c=new PerformanceObserver(e=>{for(const t of e.getEntries())o+=1,a=Math.max(a,t.duration)}),c.observe({entryTypes:["longtask"]})),window.addEventListener("error",s),window.addEventListener("unhandledrejection",r),()=>{window.clearTimeout(i),window.removeEventListener("error",s),window.removeEventListener("unhandledrejection",r),c?.disconnect(),o>0&&n("web.telemetry.long_tasks",{longTaskCount:o,maxLongTaskMs:a},"warn")}},[e])}(jt);const At=t.useCallback(async(e=I.current)=>{if(e){me(e=>({...e,loading:!0,error:null}));try{const t=await fetch(function(e,t){const n=e?.webSocketUrl?e.webSocketUrl:t.origin;try{const e=new URL(n);return"ws:"===e.protocol&&(e.protocol="http:"),"wss:"===e.protocol&&(e.protocol="https:"),e.pathname="/health",e.search="",e.hash="",e.toString()}catch{return new URL("/health",t.origin).toString()}}(e,window.location),{cache:"no-store",signal:AbortSignal.timeout(8e3)});if(!t.ok)throw new Error(`HTTP ${t.status}`);if(I.current?.daemonId!==e.daemonId)return;const n=function(e){if(!e||"object"!=typeof e)return{version:"",latestVersion:""};const t=e;return{version:"string"==typeof t.version?t.version.trim():"",latestVersion:"string"==typeof t.latestVersion?t.latestVersion.trim():""}}(await t.json().catch(()=>null));me({...n,loading:!1,error:null})}catch{if(I.current?.daemonId!==e.daemonId)return;me(e=>({...e,loading:!1,error:re.connectorVersionFailed}))}}else me(Nn)},[re.connectorVersionFailed]);t.useEffect(()=>{const e=()=>{pe(xt()),ve(It())};return window.addEventListener("vibelet.notifications.changed",e),()=>window.removeEventListener("vibelet.notifications.changed",e)},[]),t.useEffect(()=>{"admin"===ie&&"connected"===R&&At()},[ie,R,At]),t.useEffect(()=>{if("connected"!==R)return;const e=()=>{At()},t=window.setInterval(e,3e4);return window.addEventListener("focus",e),()=>{window.clearInterval(t),window.removeEventListener("focus",e)}},[R,At]);const Tt=t.useCallback(e=>{pe(t=>{const n={...t,...e};return u.current=n,function(e,t=i()){t.setItem(wt,JSON.stringify(e))}(n),n})},[]),Nt=t.useCallback((t,n)=>{t&&n&&t!==n&&(Ae({action:"remap",daemonId:I.current?.daemonId??null,sessionId:t,nextSessionId:n}),o.current===t&&(o.current=n),F(e=>e===t?n:e),m.current===t&&(m.current=n),$e.current===t&&($e.current=n),je.remap(t,n),ze(t,n),C.current=wn(C.current,t,n),q(e=>wn(e,t,n)),$(e=>bn(e,t,n)),H(e=>bn(e,t,n)),e.remapPendingQueue(t,n),W(e=>bn(e,t,n)),T(e=>{const s=e[t];if(!s)return e;const r={...e};return delete r[t],r[n]={...s,sessionId:n},r}),X(e=>{const s=function(e,t,n){if(!t||!n||t===n)return e;const s=e.draftsBySessionId[t];if(void 0===s)return e;const r={...e.draftsBySessionId};return delete r[t],s.trim()&&(r[n]=s),{...e,draftsBySessionId:r}}(e,t,n);if(s!==e){h.current=s;try{Un(s)}catch{}}return s}))},[je]);return{completionAttention:je,...e,...n,...Ie,pendingActionsCount:ke,activeQueue:Ce,activeModelOptions:Re,activeUsage:Ee,activeApproval:ct,activeQuestion:lt,activeSession:at,displaySessions:dt,groupedSessions:ut,pendingSessionIds:ht,visibleSessions:mt,appendCachedDelta:He,appendCachedHistory:Be,appendInfoMessage:Ue,clearHistoryLoading:We,ensureCachedHistoryEntry:Ke,setCachedMessageDelivery:Ge,removeCachedMessage:Qe,resolveCachedMessageSession:Ve,historyCacheRef:Oe,historyLoading:Je,hasOlderHistory:Ze,olderHistoryLoading:Xe,historyPageStartRef:qe,hydrateVisibleHistory:_e,messages:Ye,messagesSessionIdRef:$e,mergeCachedHistoryPage:et,remapCachedHistory:ze,removeCachedHistory:tt,renderCachedHistory:nt,replaceCachedHistory:st,requestHistory:rt,setMessages:it,updateDraft:pt,updateNewSessionDraft:ft,updateSessionDraft:gt,setSessionsFromPage:vt,hydrateGitMetadata:yt,prefetchActiveHistories:bt,applyReconnectSnapshot:St,requestReconnectSnapshot:kt,requestSessions:Rt,fetchAgentResources:Mt,reportLog:jt,refreshDaemonMetadata:At,updateNotificationSettings:Tt,remapLocalSessionState:Nt}}();!function(e){const n=e.admin.pendingUpdate,s=e.pairing?.daemonId,r=e.daemonMetadata.version,{phase:i,setAdmin:o,t:a}=e;t.useEffect(()=>{n&&(s!==n.daemonId?o(e=>({...e,pendingUpdate:void 0,statusText:""})):"connected"===i&&r&&r!==n.version?o(e=>({...e,pendingUpdate:void 0,statusText:a.daemonUpdateCompleted.replace("{version}",r)})):"connected"!==i&&o(e=>({...e,statusText:a.daemonUpdateReconnecting})))},[n,s,r,i,o,a])}(e),function(e){const n=t.useRef({daemonId:"",pending:!0,initial:!0});t.useLayoutEffect(()=>{const t=e.pairing?.daemonId;if("desktop"!==s().kind||"connected"!==e.phase||!t)return;if(n.current.daemonId!==t&&(n.current={daemonId:t,pending:!0,initial:!n.current.daemonId}),!n.current.pending)return;const i=r(e.visibleSessions,"updated",!1)[0];i&&(n.current.initial&&e.activeSessionId||e.setActiveSessionId(i.sessionId),n.current.pending=!1)},[e.pairing?.daemonId,e.phase,e.activeSessionId,e.visibleSessions])}(e),function(e,n,s){const r=Le(e,n?.sessionId),[i,o]=Pe(r,!1),a=t.useRef(null);t.useEffect(()=>{if(!n)return;const t=a.current?.daemonId===e?a.current?.scope:void 0;if(a.current={daemonId:e,scope:r},i)return;o(!0);const c=Qs();s(e=>function(e,t,n,s,r){if(t===n)return e;const i=!t&&r?r:s||rn;return i===e.path?e:{path:i,entries:[],loading:!1,loaded:!1}}(e,t,r,n.cwd||rn,c.folder||c.cwd))},[e,r,n?.sessionId,n?.cwd,i,o,s])}(e.pairing?.daemonId,e.activeSession,e.setDirectory);const n=function(e){const n=t.useRef(!1);return async t=>{const s=e.activeSession,r=e.clientRef.current;if(!s||!r?.isConnected||n.current||e.busy)return;const i=Zs();let o=e.historyCacheRef.current[s.sessionId]??[],a=Rt(o,t);if(a<0||"user"!==t.role||"info"===t.type||kt(t))return void e.setErrorText(i.unavailable);n.current=!0;let c=!1;try{c=await f({message:i.confirmRewind})}finally{n.current=!1}if(c&&e.clientRef.current===r&&r.isConnected&&e.activeSessionIdRef.current===s.sessionId){n.current=!0,e.setBusy(!0),e.setRewinding(!0),e.setErrorText(null);try{const n=await Es("sessionRewind");if(e.clientRef.current!==r||!r.isConnected)return;const c=()=>e.clientRef.current===r&&r.isConnected;if(void 0===e.historyPageStartRef.current[s.sessionId]){if(await e.requestHistory(s,{refresh:!0}),!c())return;if(void 0===e.historyPageStartRef.current[s.sessionId])throw new Error(i.incompleteHistory)}for(;(e.historyPageStartRef.current[s.sessionId]??0)>0;){const t=e.historyPageStartRef.current[s.sessionId];if(await e.requestHistory(s,{older:!0,refresh:!0}),!c())return;const n=e.historyPageStartRef.current[s.sessionId];if(void 0===n||n>=t)throw new Error(i.incompleteHistory)}if(o=(e.historyCacheRef.current[s.sessionId]??[]).filter(e=>!kt(e)),a=Rt(o,t),a<0)throw new Error(i.unavailable);const l=await r.request({action:"session.rewind",id:r.makeId("rewind"),sessionId:s.sessionId,agent:s.agent,targetUserMessageIndex:o.slice(0,a+1).filter(e=>"user"===e.role&&"info"!==e.type).length-1,featureEntitlements:n},{timeoutMs:15e4,timeoutMessage:i.rewindFailed});if(e.clientRef.current!==r)return;if(!l||"string"!=typeof l.sessionId||!l.sessionId||l.sessionId===s.sessionId||l.sourceSessionId!==s.sessionId||!0!==l.archivedSource||!Array.isArray(l.messages)||l.messages.some(e=>!e||"string"!=typeof e.content||!["user","assistant","tool"].includes(e.role)))throw new Error(i.invalidResponse);const d={...s,sessionId:l.sessionId,archived:!1};e.setOptimisticSessions(e=>{const t={...e};return delete t[s.sessionId],t[l.sessionId]=d,t}),e.setSessions(e=>[...e.filter(e=>e.sessionId!==l.sessionId).map(e=>e.sessionId===s.sessionId?{...e,archived:!0,pinned:!1}:e),d]),e.replaceCachedHistory(l.sessionId,l.messages),e.activeSessionIdRef.current===s.sessionId&&(e.lastHistorySessionIdRef.current=l.sessionId,e.activeSessionIdRef.current=l.sessionId,e.setActiveSessionId(l.sessionId),e.renderCachedHistory(l.sessionId)),e.updateSessionDraft(l.sessionId,Mt(t.content,t.images)),e.setSessionAttachments(l.sessionId,(t.images??[]).map(e=>({path:e,name:e.split("/").pop()??e,type:"application/octet-stream",size:0}))),await e.requestSessions({force:!0}).catch(()=>{})}catch(l){e.clientRef.current===r&&e.setErrorText(l instanceof Error?l.message:i.rewindFailed)}finally{n.current=!1,e.setBusy(!1),e.setRewinding(!1)}}}}(e),{initialSavedTargetsRef:o,composerDraftsRef:I,lastHistorySessionIdRef:k,respondingSessionsRef:C,phase:R,setErrorText:E,pairing:M,setSessions:j,pendingSessions:A,activeSessionId:T,setActiveSessionId:N,setRespondingSessions:P,setPendingApprovals:D,setPendingQuestions:L,setPendingQueues:F,setLivePendingQueue:O,agent:q,setAgent:_,cwd:$,setCwd:z,setApprovalMode:H,setEffort:B,setFastMode:U,setRenameTitle:W,setDraft:K,archiveSyncedDaemonIds:G,archiveSyncCardDismissedDaemonIds:Q,setControlTabAndOpen:V,daemonMetadata:J,notificationPermission:Z,displaySessions:X,appendInfoMessage:Y,clearHistoryLoading:ee,messagesSessionIdRef:te,renderCachedHistory:ne,replaceCachedHistory:se,requestHistory:re,setMessages:ie,requestSessions:oe,remapLocalSessionState:ae,attachments:ce,setAttachments:le,listDirectory:de,activeApproval:ue,activeQuestion:he,activeSession:me,appendCachedDelta:fe,appendCachedHistory:pe,ensureCachedHistoryEntry:ge,setCachedMessageDelivery:ve,resolveCachedMessageSession:ye,historyCacheRef:be,messages:we,mergeCachedHistoryPage:Se,removeCachedHistory:xe,updateDraft:Ie,setSessionsFromPage:ke,requestReconnectSnapshot:Ce,fetchAgentResources:Re,reportLog:Ee,refreshDaemonMetadata:je,updateNotificationSettings:Oe,clientRef:qe,connectWithPairingRef:_e,activeSessionIdRef:$e,notificationPermissionRef:ze,notificationSettingsRef:He,historyCacheDaemonIdRef:Be,pairingRef:Ue,notifiedEventsRef:We,reconnectTimerRef:Ke,connectionAttemptIdRef:Ge,turnNotificationCountsRef:Qe,intentionalDisconnectRef:Xe,setPhase:Ye,setStatusText:tt,setPairing:nt,setPendingSessions:st,setOptimisticSessions:rt,questionAnswers:it,setQuestionAnswers:ot,approvalMode:at,continueSession:ct,model:dt,effort:ut,fastMode:vt,renameTitle:yt,setComposerDrafts:St,draft:jt,search:At,sinceFilter:Tt,savedTargets:Nt,setSavedTargets:Pt,saveTargets:Dt,updateSessionListPreferences:Lt,t:Bt,busy:Ut,setBusy:Wt,setDetailsOpen:Qt,setAdmin:Jt,setDaemonMetadata:Xt,setNotificationPermission:tn,archiveSyncBusy:cn,setArchiveSyncBusy:xn,setArchiveSyncStatus:En}=e,Mn=t.useCallback(async(e,t,n)=>{const s="string"==typeof n.sessionId?n.sessionId:e,r="string"==typeof n.oldSessionId?n.oldSessionId:e;r&&s&&r!==s&&ae(r,s),"clear"===t.name?(se(s,[]),F(e=>{const t={...e};return delete t[s],delete t[r],t}),D(e=>{const t={...e};return delete t[s],delete t[r],t}),L(e=>{const t={...e};return delete t[s],delete t[r],t}),N(s)):"new"===t.name?(N(s),te.current=s,ne(s)):"exit"===t.name?(j(e=>e.map(e=>e.sessionId===s?{...e,archived:!0}:e)),N(null),te.current=null,k.current=null,ie([])):"goal"===t.name&&"goal"in n&&Y(s,function(e){const t="string"==typeof e?.objective?e.objective.trim():"";return t?`Goal${"string"==typeof e?.status&&e.status?` (${e.status})`:""}: ${t}`:"Goal: none."}(n.goal)),n.turnStarted&&!n.queued&&(C.current=new Set(C.current).add(s),P(e=>new Set(e).add(s))),await oe({force:!0})},[Y,ae,ne,se,oe]),jn=function(e){const n=t=>{e.setSessions(e=>{const n=e.findIndex(e=>e.sessionId===t&&e.stallWarning);if(n<0)return e;const s=[...e];return s[n]={...e[n],stallWarning:void 0},s})},r=t=>{e.setSessions(e=>e.map(e=>e.sessionId===t&&e.interruptReason?{...e,interruptReason:void 0,runtime:{...e.runtime,needsAttention:!1}}:e))},i=t.useCallback((t,n,r,i,o)=>{const a=e.notificationSettingsRef.current;a[i]&&!e.notifiedEventsRef.current.has(t)&&function(e,t,n={}){const r=n.notificationFactory??("undefined"==typeof Notification?void 0:Notification);if(!r&&!s().notifications)return!1;if(!function(e,t,n=("undefined"==typeof document?"visible":document.visibilityState)){return!(!e.enabled||"granted"!==t||e.hiddenOnly&&"visible"===n)}(n.settings??{enabled:!0,hiddenOnly:!1},n.permission??It(),n.visibilityState??("undefined"==typeof document?"visible":document.visibilityState)))return!1;if(s().notifications)return s().notifications.show(e,t,n.onClick),!0;const i=new r(e,{body:t,tag:n.tag});return n.onClick&&(i.onclick=n.onClick),!0}(n,r,{onClick:()=>{window.focus(),o&&e.setActiveSessionId(o)},permission:e.notificationPermissionRef.current,settings:a,tag:t,visibilityState:document.visibilityState})&&e.notifiedEventsRef.current.add(t)},[e]);return t.useCallback(t=>{switch(t.type){case"daemon.update.progress":return void e.setDaemonUpdateStatus?.(e.t.daemonUpdateAlreadyRunning);case"daemon.update.failed":{const n="timeout"===t.reason?e.t.daemonUpdateTimedOut:t.message;return e.setDaemonUpdateStatus?.(n,!0),void e.setErrorText(n)}case"response":an(t.data)&&"string"==typeof t.data.oldSessionId&&"string"==typeof t.data.sessionId&&e.remapLocalSessionState(t.data.oldSessionId,t.data.sessionId);break;case"sessions.changed":e.requestSessions({force:!0,preserveLoaded:!0}).catch(t=>e.setErrorText(t instanceof Error?t.message:String(t)));break;case"session.history":t.isResponding||t.externallyResponding?e.completionAttention?.observe(t.sessionId):e.completionAttention?.complete(t.sessionId),e.setSessions(e=>{const n=e.findIndex(e=>e.sessionId===t.sessionId&&e.stallWarning!==t.stallWarning);if(n<0)return e;const s=[...e];return s[n]={...e[n],stallWarning:t.stallWarning},s}),e.setPendingQueues(e=>({...e,[t.sessionId]:t.pendingQueue??[]})),e.clearHistoryLoading(t.sessionId),e.mergeCachedHistoryPage(t.sessionId,t.messages,t.historyPage,t.partialReplyText);for(const n of t.acceptedClientMessageIds??[])e.setCachedMessageDelivery(t.sessionId,n,"delivered");t.sessionId===e.activeSessionIdRef.current&&(e.setPendingApprovals(e=>{const n={...e};return t.pendingApproval?n[t.sessionId]={type:"approval.request",sessionId:t.sessionId,...t.pendingApproval}:delete n[t.sessionId],n}),e.setPendingQuestions(n=>{const s={...n};if(t.pendingQuestion){const n={type:"question.request",sessionId:t.sessionId,...t.pendingQuestion};s[t.sessionId]=n,e.setQuestionAnswers(mn(n))}else delete s[t.sessionId];return s})),e.setRespondingSessions(n=>{const s=Rs(n,t.sessionId,Boolean(t.isResponding||t.externallyResponding));return e.respondingSessionsRef.current=s,s});break;case"session.history.append":e.appendCachedHistory(t.sessionId,t.messages);break;case"text.delta":r(t.sessionId),e.completionAttention?.observe(t.sessionId),n(t.sessionId),e.appendCachedDelta(t.sessionId,t.content),e.respondingSessionsRef.current=Rs(e.respondingSessionsRef.current,t.sessionId,!0),e.setRespondingSessions(e=>Rs(e,t.sessionId,!0));break;case"session.background_terminals":e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,runtime:{...e.runtime,backgroundTerminals:t.terminals}}:e));break;case"tool.call":r(t.sessionId),n(t.sessionId),e.appendCachedHistory(t.sessionId,[{role:"tool",type:"info",toolName:t.toolName,toolInput:t.input,content:`${e.t.toolCallLabel}: ${t.toolName}\n\n${hn(t.input)}`,timestamp:(new Date).toISOString()}]);break;case"tool.result":r(t.sessionId),n(t.sessionId),e.appendCachedHistory(t.sessionId,[{role:"tool",type:"info",content:t.output,timestamp:(new Date).toISOString()}]);break;case"approval.request":e.setPendingApprovals(e=>({...e,[t.sessionId]:t})),i(`approval:${t.sessionId}:${t.requestId}`,e.t.notificationApprovalTitle,t.description||t.toolName,"approvals",t.sessionId);break;case"question.request":e.setPendingQuestions(e=>({...e,[t.sessionId]:t})),i(`question:${t.sessionId}:${t.requestId}`,e.t.notificationQuestionTitle,e.t.notificationQuestionCount(t.questions.length),"questions",t.sessionId);break;case"question.cleared":e.setPendingQuestions(e=>{const n={...e};return n[t.sessionId]?.requestId===t.requestId&&delete n[t.sessionId],n});break;case"session.queue":e.setLivePendingQueue(t.sessionId,t.pending);break;case"session.stall_warning":e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,stallWarning:t.warning}:e));break;case"session.interrupted_notice":e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,interruptReason:t.reason,stallWarning:void 0}:e));break;case"session.done":if(e.respondingSessionsRef.current.has(t.sessionId)&&e.completionAttention?.observe(t.sessionId),e.completionAttention?.complete(t.sessionId),n(t.sessionId),e.respondingSessionsRef.current.has(t.sessionId)){const n=(e.turnNotificationCountsRef.current[t.sessionId]??0)+1;e.turnNotificationCountsRef.current[t.sessionId]=n,i(`done:${t.sessionId}:${n}`,e.t.notificationReplyTitle,function(e,t){for(let n=e.length-1;n>=0;n--){const t=e[n];if("user"===t.role)break;if("assistant"!==t.role||"info"===t.type)continue;const s=t.content.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/\[([^\]]+)\]\([^)]*\)/g,"$1").replace(/^\s{0,3}(?:#{1,6}\s+|>\s*|[-*+]\s+)/gm,"").replace(/(\*\*|__|~~)(.+?)\1/g,"$2").replace(/`([^`]+)`/g,"$1").replace(/\*([^*\n]+)\*/g,"$1").replace(/\s+/g," ").trim();if(!s)continue;const r=Array.from(s);return r.length>240?`${r.slice(0,239).join("")}…`:s}return t}(e.historyCacheRef.current[t.sessionId]??[],e.t.notificationReplyBody),"replies",t.sessionId)}e.respondingSessionsRef.current=Rs(e.respondingSessionsRef.current,t.sessionId,!1),e.setRespondingSessions(e=>Rs(e,t.sessionId,!1)),e.setPendingApprovals(e=>{const n={...e};return delete n[t.sessionId],n}),e.setPendingQuestions(e=>{const n={...e};return delete n[t.sessionId],n}),t.usage&&e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,lastUsage:t.usage}:e)),e.requestSessions({force:!0,preserveLoaded:!0}).catch(t=>e.setErrorText(t instanceof Error?t.message:String(t)));break;case"session.interrupted":e.refreshInterruptedHistory?.(t.sessionId),e.respondingSessionsRef.current=Rs(e.respondingSessionsRef.current,t.sessionId,!1),e.setRespondingSessions(e=>Rs(e,t.sessionId,!1)),e.requestSessions({force:!0,preserveLoaded:!0}).catch(t=>e.setErrorText(t instanceof Error?t.message:String(t)));break;case"session.renamed":e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,customTitle:t.title}:e));break;case"error":e.respondingSessionsRef.current=Rs(e.respondingSessionsRef.current,t.sessionId,!1),e.setRespondingSessions(e=>Rs(e,t.sessionId,!1)),n(t.sessionId),e.setPendingApprovals(e=>{const n={...e};return delete n[t.sessionId],n}),e.setPendingQuestions(e=>{const n={...e};return delete n[t.sessionId],n}),e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,runtime:{...e.runtime,isResponding:!1},interruptReason:t.reason??{kind:"driver_error",at:(new Date).toISOString(),humanText:t.message}}:e)),t.sessionId||e.setErrorText(t.message)}},[e,i])}({setDaemonUpdateStatus:(e,t)=>Jt(n=>({...n,statusText:e,...t?{pendingUpdate:void 0}:{}})),historyCacheRef:be,refreshInterruptedHistory:e=>{if(e!==$e.current)return;const t=X.find(t=>t.sessionId===e);t&&re(t,{refresh:!0})},completionAttention:e.completionAttention,notificationSettingsRef:He,notifiedEventsRef:We,notificationPermissionRef:ze,activeSessionIdRef:$e,respondingSessionsRef:C,turnNotificationCountsRef:Qe,t:Bt,setActiveSessionId:N,setErrorText:E,setPendingQueues:F,setLivePendingQueue:O,setPendingApprovals:D,setPendingQuestions:L,setQuestionAnswers:ot,setRespondingSessions:P,setSessions:j,remapLocalSessionState:ae,requestSessions:oe,clearHistoryLoading:ee,replaceCachedHistory:se,setCachedMessageDelivery:ve,mergeCachedHistoryPage:Se,appendCachedHistory:pe,appendCachedDelta:fe});(function(e){const n=t.useRef(null),r=t.useRef(null),o=()=>{null!==r.current&&window.clearTimeout(r.current),r.current=null},a=t.useRef(null),c=t.useRef(e);c.current=e;const l=t.useCallback(e=>{const t=c.current,n=e??t.pairingRef.current;n&&!t.intentionalDisconnectRef.current&&(t.reconnectTimerRef.current&&window.clearTimeout(t.reconnectTimerRef.current),t.reconnectTimerRef.current=window.setTimeout(()=>{t.reconnectTimerRef.current=null,t.connectWithPairingRef.current(n,!0)},1600))},[]),d=t.useCallback(async(e,t=!1)=>{const n=c.current;o(),n.reconnectTimerRef.current&&(window.clearTimeout(n.reconnectTimerRef.current),n.reconnectTimerRef.current=null),n.intentionalDisconnectRef.current=!1,n.setPhase("connecting"),n.setStatusText(t?n.t.reconnectingToDaemon:n.t.connectingToDaemon),n.setErrorText(null);const a=new nn,d=n.connectionAttemptIdRef.current+1;n.connectionAttemptIdRef.current=d;const u=n.clientRef.current;n.clientRef.current=a,u?.disconnect();const h=()=>n.connectionAttemptIdRef.current===d&&n.clientRef.current===a;a.onMessage(e=>{h()&&c.current.handleServerMessage(e)});let m=!1;a.onClose(()=>{h()&&m&&(n.clientRef.current=null,o(),n.intentionalDisconnectRef.current||(n.setPhase("connecting"),n.setStatusText(n.t.reconnectingToDaemon),n.setErrorText(n.t.webSocketClosedRetrying),l(e)))});const f=!!n.pairingRef.current&&n.pairingRef.current.daemonId!==e.daemonId;f&&n.resetDeviceWorkspace(),n.historyCacheDaemonIdRef.current&&n.historyCacheDaemonIdRef.current!==e.daemonId&&(n.historyCacheRef.current={},n.messagesSessionIdRef.current=null,n.lastHistorySessionIdRef.current=null,n.setMessages([])),n.historyCacheDaemonIdRef.current=e.daemonId,n.setPairing(e),n.pairingRef.current=e;const p=function(e,t=i()){return e?On(t).find(t=>t.daemonId===e)?.page??null:null}(e.daemonId);p&&n.setSessionsFromPage(p,!1),n.setStatusText(t?n.t.reconnectingToDaemon:n.t.connectingToDaemon);try{const i=await(s().prepareConnection?.(e))??e;if(!h())return;let o,l=i;try{o=await a.connect(i)}catch(g){if(!h()||!i.webSocketUrl||qn(g))throw g;l={...i,webSocketUrl:void 0},n.setStatusText(n.t.reconnectingToDaemon),o=await a.connect(l)}if(!h())return;m=!0;const d={...l,displayName:o.displayName??l.displayName};n.setPairing(d),n.pairingRef.current=d,mt(d),n.setSavedTargets(e=>{const t=function(e,t,n=(new Date).toISOString()){const s=e.find(e=>e.daemonId===t.daemonId);return[{...t,label:s?.label||t.displayName||t.daemonId.slice(0,10),lastConnectedAt:n},...e.filter(e=>e.daemonId!==t.daemonId)].slice(0,12)}(e,d);return Tn(t),t}),n.setPhase("connected"),n.setStatusText(n.t.connectedTo(o.displayName??e.displayName??"Vibelet Daemon")),n.refreshDaemonMetadata(d);let u=null;const p=async()=>{if(h())try{if(await c.current.requestReconnectSnapshot(),h()&&u){const e=u;n.setErrorText(t=>t===e?null:t)}}catch(g){if(!h())return;u=g instanceof Error?g.message:String(g),n.setErrorText(u),r.current=window.setTimeout(()=>{r.current=null,p()},1600)}};p();const v=c.current;v.fetchAgentResources(v.agent,f?rn:v.cwd).catch(e=>{h()&&n.setErrorText(e instanceof Error?e.message:String(e))}),n.reportLog("web.connected",{reconnecting:t})}catch(g){if(!h())return;n.clientRef.current=null,a.disconnect(),qn(g)&&ht()?.pairToken===e.pairToken&&ft(),n.setPhase("error"),n.setStatusText(n.t.connectionFailed),n.setErrorText(qn(g)?n.t.pairingAuthFailed:g instanceof Error?g.message:String(g)),qn(g)||l(e)}},[l]);t.useEffect(()=>{c.current.connectWithPairingRef.current=d},[d]),t.useEffect(()=>{const e=c.current;let t=!1;return async function(){const n=lt(),s=ht()??e.rememberedTarget;if(!n&&!s)return e.setPhase("missing-pair"),void e.setStatusText(e.t.missingPair);try{e.setPhase("pairing"),n&&a.current?.pairNonce!==n.pairNonce&&(a.current={pairNonce:n.pairNonce,promise:pt(n,s)});const r=n?await(a.current?.promise):s;if(!r||t)return;n&&(mt(r),a.current=null,function(){if(!window.location.hash.includes(`${Ze}=`))return;const e=`${window.location.pathname}${window.location.search}`;window.history.replaceState(null,"",e)}()),await e.connectWithPairingRef.current(r)}catch(r){if(t)return;n&&(a.current=null),e.setPhase("error"),e.setStatusText(e.t.pairingFailed),e.setErrorText(function(e,t){return e instanceof et&&"pair_window_expired"===e.code?t.pairingLinkExpired:e instanceof Error?e.message:String(e)}(r,e.t))}}(),()=>{t=!0,o(),e.intentionalDisconnectRef.current=!0,e.connectionAttemptIdRef.current+=1,e.reconnectTimerRef.current&&window.clearTimeout(e.reconnectTimerRef.current),e.clientRef.current?.disconnect()}},[e.t]),t.useEffect(()=>{const e=c.current;if("connected"!==e.phase)return;const t=n.current;if(n.current={client:e.clientRef.current,request:e.requestSessions},!t||t.client!==e.clientRef.current||t.request===e.requestSessions)return;const s=window.setTimeout(()=>{e.requestSessions().catch(t=>e.setErrorText(t instanceof Error?t.message:String(t)))},260);return()=>window.clearTimeout(s)},[e.phase,e.requestSessions,e.search,e.sinceFilter]),t.useEffect(()=>{const e=c.current;"connected"===e.phase&&e.fetchAgentResources(e.agent,e.cwd)},[e.agent,e.cwd,e.fetchAgentResources,e.phase])})({clientRef:qe,connectWithPairingRef:_e,pairingRef:Ue,reconnectTimerRef:Ke,connectionAttemptIdRef:Ge,intentionalDisconnectRef:Xe,historyCacheRef:be,historyCacheDaemonIdRef:Be,messagesSessionIdRef:te,lastHistorySessionIdRef:k,rememberedTarget:o.current[0]??null,agent:q,cwd:$,phase:R,search:At,sinceFilter:Tt,t:Bt,handleServerMessage:jn,setPhase:Ye,setStatusText:tt,setErrorText:E,setMessages:ie,setPairing:nt,setSavedTargets:Pt,setSessionsFromPage:ke,resetDeviceWorkspace:()=>{$e.current=null,N(null),z(rn),j([]),st({}),rt({}),e.setDiffSessionId(null),D({}),L({}),F({}),C.current=new Set,P(new Set),Vs({folder:void 0,file:void 0,cwd:void 0},{replace:!0})},refreshDaemonMetadata:je,requestReconnectSnapshot:Ce,fetchAgentResources:Re,reportLog:Ee,requestSessions:oe}),t.useLayoutEffect(()=>{K(Kn(I.current,T))},[T,M?.daemonId]),t.useEffect(()=>{const e=me;if(!e)return k.current=null,te.current=null,ee(),void ie([]);if(_(e.agent),z(e.cwd||rn),W(e.customTitle??e.title??""),A[e.sessionId]){if(k.current=e.sessionId,ee(),ne(e.sessionId))return;te.current!==e.sessionId&&(te.current=e.sessionId,ie([]))}else{if(ne(e.sessionId)){const t=k.current!==e.sessionId;return k.current=e.sessionId,ee(e.sessionId),void(t&&re(e,{refresh:!0}))}k.current!==e.sessionId&&(k.current=e.sessionId,te.current!==e.sessionId&&(te.current=e.sessionId,ie([])),re(e,{refresh:!0}))}},[me,T,ee,A,ne,re]);const Pn=function(e){const n=t.useRef(e);n.current=e;const s=t.useRef(!0),r=t.useRef(new Map),[i,o]=t.useState(null),a=JSON.stringify([e.pairing?.daemonId,e.activeSession?.sessionId]),c=t.useRef(a);return c.current=a,t.useEffect(()=>(s.current=!0,()=>{s.current=!1}),[]),t.useLayoutEffect(()=>{e.activeSession&&e.setModel(e.activeSession.model??"")},[a,e.activeSession?.model]),{setModel:t=>{const i=e.activeSession;if(!i)return void e.setModel(t);if(e.pendingSessions[i.sessionId])return e.setPendingSessions(e=>e[i.sessionId]?{...e,[i.sessionId]:{...e[i.sessionId],model:t||void 0}}:e),void e.setModel(t);const l=e.clientRef.current;if(!l?.isConnected)return void e.setErrorText(e.t.webSocketNotConnected);if(r.current.has(a))return;const d=()=>s.current&&n.current.clientRef.current===l&&l.isConnected&&n.current.pairing?.daemonId===e.pairing?.daemonId;e.setErrorText(null),o(a);const u=(async()=>{try{const n=await l.request({action:"session.configure",id:l.makeId("model"),sessionId:i.sessionId,model:t,expectedModel:i.model??""},{timeoutMs:15e3});if(!d())return!1;const s=n.model;return e.setSessions(e=>e.map(e=>e.sessionId===i.sessionId?{...e,model:s}:e)),e.setOptimisticSessions(e=>e[i.sessionId]?{...e,[i.sessionId]:{...e[i.sessionId],model:s}}:e),c.current===a&&e.setModel(s??""),!0}catch(u){return d()&&c.current===a&&e.setErrorText(u instanceof Error&&"session_model_conflict"===u.message?e.t.modelChangedRemotely:e.t.modelSaveFailed),!1}finally{r.current.delete(a),s.current&&o(e=>e===a?null:e),d()&&n.current.requestSessions({force:!0,preserveLoaded:!0}).catch(()=>{})}})();r.current.set(a,u)},saving:i===a,waitForSave:()=>r.current.get(a)??Promise.resolve(!0)}}(e),Fn=function({daemonId:e,session:n,setEffort:s,setFastMode:r,setApprovalMode:o,setPendingSessions:a}){const c=t.useRef(null);c.current||(c.current=function(){try{const e=JSON.parse(i().getItem(Xs)||"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};for(const t of Object.values(e))t&&"object"==typeof t&&delete t.model;return e}catch{return{}}}());const l=JSON.stringify([e??"",n?.sessionId??""]),d={effort:n?.effort??"",fastMode:n?.fastMode??!1,approvalMode:n?.approvalMode??on},u=()=>{try{i().setItem(Xs,JSON.stringify(c.current))}catch{}},h=e=>{const t=c.current[l]?.[e];return void 0===t?d[e]:(d[e]===t&&delete c.current[l][e],t)};t.useLayoutEffect(()=>{n&&(s(h("effort")),r(h("fastMode")),o(h("approvalMode")),u())},[l,d.effort,d.fastMode,d.approvalMode]);const m=(e,t)=>{n&&(c.current[l]={...c.current[l],[e]:t},u(),a(s=>{const r=s[n.sessionId];if(!r)return s;const i="effort"===e?t||void 0:t;return{...s,[n.sessionId]:{...r,[e]:i}}})),"effort"===e&&s(t),"fastMode"===e&&r(t),"approvalMode"===e&&o(t)};return{applyConfirmedSettings:(t,s)=>{const i=JSON.stringify([e??"",t]),o=c.current[i];o&&(void 0!==s.fastMode&&delete o.fastMode,u()),n?.sessionId===t&&void 0!==s.fastMode&&r(s.fastMode)},setEffort:e=>m("effort",e),setFastMode:e=>m("fastMode",e),setApprovalMode:e=>m("approvalMode",e)}}({daemonId:M?.daemonId,session:me,setEffort:B,setFastMode:U,setApprovalMode:H,setPendingSessions:st}),{stagePendingSession:_n,failedSend:$n,dismissFailedSend:zn,retryFailedSend:Hn,sendDraft:Qn,sendQuickReply:Vn}=function(e){const[n]=t.useState(As),[s,r]=function(e,t,n){const s=De(Le(n,e),{}),r=()=>{for(const[r,i]of s.getAll()){const[s,o]=JSON.parse(r);if(s===(n??null)&&o)for(const n of Object.values(i)){const s=t(o,n.clientMessageId);if(s===e)return{scope:r,failure:n.sessionId===s?n:{...n,sessionId:s}}}}return null},i=r();return[i?.failure??null,e=>{const o=i??r(),a=o?s.getForScope(o.scope):void 0,c=o?a?.[o.failure.clientMessageId]??null:null,l=c&&o?.failure.sessionId!==c.sessionId?{...c,sessionId:o.failure.sessionId}:c,d="function"==typeof e?e(l):e;if("function"!=typeof e||d!==l){if((null===e||"function"==typeof e)&&c&&o){if(d?.clientMessageId===c.clientMessageId)return void s.setForScope(o.scope,{...a,[d.clientMessageId]:d});const e={...a};delete e[c.clientMessageId],s.setForScope(o.scope,e)}if(d){const e=Le(n,t(d.sessionId,d.clientMessageId));s.setForScope(e,{...s.getForScope(e),[d.clientMessageId]:d})}}}]}(e.activeSessionId,e.resolveCachedMessageSession,e.daemonId),[i,o]=t.useState(null),a=t.useCallback(t=>{e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current),e.respondingSessionsRef.current.delete(t),e.setRespondingSessions(e=>{const n=new Set(e);return n.delete(t),n})},[e]);!function(e,n,s,r){const i=t.useRef(new Set);t.useEffect(()=>{const t=t=>JSON.stringify([e.daemonId,t]);if(n&&i.current.add(t(n.clientMessageId)),!n){const n=Hs(e.messages),o=e.activeSessionId;if(!o||e.messagesSessionIdRef.current!==o||!n?.localClientMessageId)return;if("accepted"===n.delivery||n.historyKey&&!n.historyKey.startsWith("client:"))return;const a=t(n.localClientMessageId);if(i.current.has(a))return;return i.current.add(a),r(o),void s({sessionId:o,clientMessageId:n.localClientMessageId,historyKey:`client:${n.localClientMessageId}`,message:n.content,images:n.images,agent:e.activeSession?.agent??e.agent,model:e.activeSession?.model,effort:e.activeSession?.effort,fastMode:e.activeSession?.fastMode??!1,skillInvocation:_s(n.content),kind:n.localInterruptedSend?"network":"unknown",retrying:!1})}const o=e.resolveCachedMessageSession(n.sessionId,n.clientMessageId);if(e.messagesSessionIdRef.current!==o)return;const a=e.messages.find(e=>e.localClientMessageId===n.clientMessageId||e.historyKey===n.historyKey);a&&("accepted"===a.delivery||"delivered"===a.localDelivery||a.historyKey&&!a.historyKey.startsWith("client:")?s(null):n.retrying||"sending"!==a.localDelivery||(e.setCachedMessageDelivery(o,n.clientMessageId,"failed"),r(o)))},[e,n,s,r])}(e,s,r,a);const c=t.useCallback((t,n,s)=>{const r=Ks(t)??Ks(e.cwd)??rn,i=n??e.agent,a=function(e=Date.now()){return vn=(vn+1)%1e4,`pending_local_${e}_${vn}`}(),c=function(e){const t=e.now??(new Date).toISOString();return{sessionId:e.sessionId,agent:e.agent,cwd:e.cwd||rn,...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{},fastMode:e.fastMode??!1,...e.title?{title:e.title}:{},createdAt:t,lastActivityAt:t,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver"},managed:!0,approvalMode:e.approvalMode}}({sessionId:a,agent:i,cwd:r,approvalMode:s?.approvalMode??e.approvalMode,model:fn(s?.model??e.model),effort:(s?.effort??e.effort)||void 0,fastMode:s?.fastMode??e.fastMode,title:"codex"===i?e.t.newCodexSession:e.t.newClaudeSession});Object.assign(c,{preparationId:s?.preparationId});const l=s?.draft??(e.activeSessionIdRef.current?"":Kn(e.composerDraftsRef.current,null));return e.setPendingSessions(e=>({...e,[a]:c})),e.revealCreatedSession(r),e.setComposerDrafts(t=>{let n=Wn(t,a,l);return e.activeSessionIdRef.current||(n=Wn(n,null,"")),e.composerDraftsRef.current=n,Un(n),n}),e.setCwd(r),e.setAgent(i),e.activeSessionIdRef.current=a,e.setActiveSessionId(a),e.lastHistorySessionIdRef.current=a,e.messagesSessionIdRef.current=a,e.clearHistoryLoading(),e.setMessages([]),e.setDraft(l),(s?.draft?.trim()||s?.attachments?.length)&&o({sessionId:a,attachments:s.attachments??[]}),e.setErrorText(null),e.reportLog("web.session.pending_create",{sessionId:a,agent:i,cwd:r}),a},[e]),l=function(e){const n=t.useRef(new Map),s=t.useCallback(async(t,n,s)=>{const r=e.clientRef.current;if(!r?.isConnected)return e.setErrorText(e.t.webSocketNotConnected),null;const i=s?e.pendingSessions[s]:void 0,o=Us(t)??Us(i?.cwd)??Us(e.cwd)??rn,a=n??i?.agent??e.agent,c=i?.approvalMode??e.approvalMode,l=i?i.model:fn(e.model),d=i?i.effort:e.effort||void 0,u=i?.fastMode??e.fastMode;e.setErrorText(null),s&&e.setPendingSessions(e=>{const t=e[s];return t?{...e,[s]:{...t,creationError:void 0,creationPending:!0}}:e});try{const t=await r.request({action:"session.create",id:r.makeId("create"),agent:a,cwd:o,approvalMode:c,continueSession:e.continueSession,model:l,effort:d,fastMode:u,...s?{clientSessionId:s}:{},preparationId:i?.preparationId});if(e.clientRef.current!==r)return null;const n=function(e){const t=e;return"string"==typeof t.sessionId?t.sessionId:null}(t);if(!n)throw new Error(e.t.sessionIdMissing);const h=an(t)&&"string"==typeof t.oldSessionId?t.oldSessionId:s;if(e.activeSessionIdRef.current!==(s??null)&&e.activeSessionIdRef.current!==n||(e.setCwd(o),e.setAgent(a),e.activeSessionIdRef.current=n,e.setActiveSessionId(n),e.lastHistorySessionIdRef.current=n,e.messagesSessionIdRef.current=n,e.clearHistoryLoading()),s&&i){e.setPendingSessions(e=>{const t={...e};return delete t[s],h&&h!==s&&delete t[h],t});const{preparationId:t,creationError:r,creationPending:o,...a}=i;e.setOptimisticSessions(e=>({...e,[n]:yn(a,n)})),h&&h!==n&&e.remapLocalSessionState(h,n),s!==n&&e.remapLocalSessionState(s,n)}else await e.requestSessions({force:!0});return e.reportLog("web.session.create",{sessionId:n,clientSessionId:s,agent:a,cwd:o}),n}catch(h){if(e.clientRef.current!==r)return null;const t=h instanceof Error?h.message:String(h);return s&&e.setPendingSessions(e=>{const n=e[s];return n?{...e,[s]:{...n,creationError:t,creationPending:!1}}:e}),e.activeSessionIdRef.current===(s??null)&&e.setErrorText(t),null}},[e]);return t.useCallback((t,r,i)=>{if(!i)return s(t,r);const o=e.clientRef.current,a=n.current.get(i);if(a?.client===o)return a.promise;const c=s(t,r,i),l={client:o,promise:c};return n.current.set(i,l),c.finally(()=>{n.current.get(i)===l&&n.current.delete(i)}),c},[s,e.clientRef])}(e);!function(e,n,s){const r=t.useRef(null);t.useEffect(()=>{const t=e.clientRef.current,n=e.activeSession;if(!t?.isConnected||!n||"codex"!==n.agent||e.pendingSessions[n.sessionId]||!e.draft||e.messages.some(e=>"user"===e.role))return;const s=JSON.stringify([n.sessionId,e.model,e.effort,e.fastMode]),i=r.current;i?.client===t&&i.key===s&&Date.now()-i.at<3e4||(r.current={client:t,key:s,at:Date.now()},t.request({action:"session.prepare",id:t.makeId("prepare"),sessionId:n.sessionId}).catch(()=>{}))},[e.activeSession,e.clientRef,e.draft,e.messages,e.pendingSessions,e.model,e.effort,e.fastMode]);const i=t.useRef(new Set);t.useEffect(()=>{for(const n of i.current)e.pendingSessions[n]||i.current.delete(n);const t=e.activeSessionId,r=t?e.pendingSessions[t]:void 0;!(e.clientRef.current?.isConnected&&t&&r&&"codex"===r.agent)||"creationError"in r&&r.creationError||n===t||i.current.has(t)||(i.current.add(t),s(r.cwd,r.agent,t))},[e.activeSessionId,e.pendingSessions,e.clientRef,n,s])}(e,i?.sessionId,l);const d=t.useCallback(async t=>{const n=e.sessions.find(e=>e.sessionId===t)??(e.activeSession?.sessionId===t?e.activeSession:null);if(!n?.archived)return;const s=e.clientRef.current;if(!s?.isConnected)throw new Error(e.t.webSocketNotConnected);await s.request({action:"session.setArchived",id:s.makeId("unarchive"),sessionId:t,archived:!1}),e.clientRef.current===s&&(e.setSessions(e=>e.map(e=>e.sessionId===t?{...e,archived:!1}:e)),e.setOptimisticSessions(e=>({...e,[t]:{...n,...e[t],archived:!1}})),e.requestSessions({force:!0}).catch(()=>{}))},[e]),u=t.useCallback(async(t,s,i)=>{t?.preventDefault();const o=(i??e.draft).trim(),u=s??e.attachments;if(u.some(e=>e.uploading))return;if(!o&&!u.length||e.busy||n.has(e.activeSessionId))return;const h=e.clientRef.current;if(!h?.isConnected)return void e.setErrorText(e.t.webSocketNotConnected);if(!e.activeSessionId)return void c(void 0,void 0,{draft:o,attachments:u});const m=n.start(e.activeSessionId);try{if(e.waitForModelSave&&!(await e.waitForModelSave()))return;const t=_s(o)?"agentSkills":0===u.length&&Fs(o,e.activeSession?.agent??e.agent)?"agentCommands":void 0;let n;if(t)try{n=await Es(t)}catch(f){if(e.clientRef.current!==h)return;return void e.setErrorText(f instanceof Error?f.message:String(f))}if(e.clientRef.current!==h||e.activeSessionIdRef.current!==e.activeSessionId)return;e.setErrorText(null),void 0===i&&e.updateDraft("");const s=u;void 0===i&&e.setAttachments([]);let c=e.activeSessionId,p=e.pendingSessions[c]?.agent??e.activeSession?.agent??e.agent;const g=c?e.pendingSessions[c]:void 0,v=g?.fastMode??e.fastMode,y=void 0,b=g?g.effort:e.effort||void 0;if(c&&e.pendingSessions[c]&&0===s.length&&Fs(o,p)){const t=await l(e.pendingSessions[c].cwd,e.pendingSessions[c].agent,c);if(e.clientRef.current!==h)return;if(!t)return void(void 0===i&&zs(e,o,s));c=t,p=e.pendingSessions[e.activeSessionId??""]?.agent??p}if(!c)return void(void 0===i&&zs(e,o,s));m.remap(c);const w=0===s.length?Fs(o,p):null;if(w){const t=function(e){return"compact"===e.name?"/compact":"goal"!==e.name?null:"clear"===e.operation?"/goal clear":"pause"===e.operation?"/goal pause":"resume"===e.operation?"/goal resume":"set"===e.operation&&e.objective?.trim()?`/goal ${e.objective.trim()}`:"/goal"}(w.command),s=t?h.makeId("cmd_msg"):void 0;t&&(e.activeSessionIdRef.current===c&&(e.messagesSessionIdRef.current=c),e.appendCachedHistory(c,[{role:"user",content:t,timestamp:(new Date).toISOString()}]),e.activeSessionIdRef.current===c&&e.renderCachedHistory(c));try{if(t&&await d(c),e.clientRef.current!==h)return;const r=await h.request({action:"session.command",id:h.makeId("command"),sessionId:c,agent:p,command:w.command,...s?{clientMessageId:s}:{},featureEntitlements:n});if(e.clientRef.current!==h)return;await e.handleSessionCommandResponse(c,w.command,r)}catch(f){if(e.clientRef.current!==h)return;const t=f instanceof Error?f.message:String(f);e.appendInfoMessage(c,Os(t)),e.activeSessionIdRef.current===c&&e.setErrorText(Os(t))}return}const S=function(e){return e.startsWith("//")?e.slice(1):e}(o),x=s.map(e=>e.path),I=h.makeId("msg"),k=`client:${I}`;e.activeSessionIdRef.current===c&&(e.messagesSessionIdRef.current=c),e.setCachedMessageDelivery(c,I,"sending",{content:S,...x.length?{images:x}:{}}),e.activeSessionIdRef.current===c&&e.renderCachedHistory(c),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(c),e.setRespondingSessions(e=>new Set(e).add(c));const C=_s(S)??void 0,R=C?n:void 0,E={sessionId:c,agent:p,message:S,clientMessageId:I,historyKey:k,kind:"network",retrying:!1,images:x.length?x:void 0,model:y,effort:b,fastMode:v,skillInvocation:C,featureEntitlements:R};try{if(g){const t=await l(g.cwd,g.agent,c);if(e.clientRef.current!==h)return;if(!t)throw new Error(e.t.sessionCreateFailed);c=t,m.remap(c)}if(await d(c),e.clientRef.current!==h)return;const t=await js(h,{action:"session.send",id:h.makeId("send"),sessionId:c,agent:p,message:S,clientMessageId:I,images:x.length?x:void 0,model:y,effort:b,fastMode:v,skillInvocation:C,featureEntitlements:R},{timeoutMs:ks,timeoutMessage:Ws},t=>e.appendInfoMessage(c,t));if(e.clientRef.current!==h)return;an(t)&&"string"==typeof t.oldSessionId&&"string"==typeof t.sessionId&&(m.remap(t.sessionId),e.remapLocalSessionState(t.oldSessionId,t.sessionId)),e.setCachedMessageDelivery(an(t)&&"string"==typeof t.sessionId?t.sessionId:c,I,"delivered"),e.reportLog("web.telemetry.send_accepted",{attachmentCount:x.length}),r(e=>e?.historyKey===k?null:e)}catch(f){if(e.clientRef.current!==h)return;c=e.resolveCachedMessageSession(c,I);const t=f instanceof Error?f.message:String(f),n=Is(Rn(t,Boolean(C)));if("delivered"===e.setCachedMessageDelivery(c,I,"failed"))return;e.activeSessionIdRef.current===c&&e.setErrorText(null),r({sessionId:c,agent:p,message:S,clientMessageId:I,historyKey:k,kind:n,detail:Cs(t),retrying:!1,...x.length?{images:x}:{},model:y,effort:b,fastMode:v,skillInvocation:C,featureEntitlements:R}),e.reportLog("web.telemetry.send_failed",{attachmentCount:x.length,failureKind:n},"warn"),a(c)}finally{e.clientRef.current!==h&&r({...E,sessionId:c})}}finally{m.finish()}},[a,c,l,e,n,d]),h=t.useCallback(async()=>{if(!s||s.retrying||e.busy||n.has(e.activeSessionId))return;const t=e.clientRef.current;if(!t?.isConnected)return void r(e=>e?{...e,kind:"network",detail:void 0}:null);if(e.waitForModelSave&&!(await e.waitForModelSave()))return;if(e.clientRef.current!==t)return;let i=e.resolveCachedMessageSession(s.sessionId,s.clientMessageId);const o=n.start(i);r(e=>e?{...e,retrying:!0}:null),e.ensureCachedHistoryEntry(i,{role:"user",content:s.message,historyKey:s.historyKey,...s.images?.length?{images:s.images}:{}}),e.setCachedMessageDelivery(i,s.clientMessageId,"sending"),e.setErrorText(null),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(i),e.setRespondingSessions(e=>new Set(e).add(i));try{const n=e.pendingSessions[i];if(n){const s=await l(n.cwd,n.agent,i);if(e.clientRef.current!==t)return;if(!s)throw new Error(e.t.sessionCreateFailed);i=s,o.remap(i)}await d(i);const a=s.skillInvocation?await Es("agentSkills"):void 0;if(e.clientRef.current!==t)return;const c=await js(t,{action:"session.send",id:t.makeId("retry_send"),sessionId:i,agent:s.agent,message:s.message,clientMessageId:s.clientMessageId,images:s.images,model:void 0,effort:s.effort,fastMode:s.fastMode,skillInvocation:s.skillInvocation??void 0,featureEntitlements:a},{timeoutMs:ks,timeoutMessage:Ws},t=>e.appendInfoMessage(i,t));if(e.clientRef.current!==t)return;an(c)&&"string"==typeof c.oldSessionId&&"string"==typeof c.sessionId&&(o.remap(c.sessionId),e.remapLocalSessionState(c.oldSessionId,c.sessionId)),e.setCachedMessageDelivery(an(c)&&"string"==typeof c.sessionId?c.sessionId:i,s.clientMessageId,"delivered"),e.reportLog("web.telemetry.retry_accepted",{attachmentCount:s.images?.length??0}),r(null)}catch(c){if(e.clientRef.current!==t)return;i=e.resolveCachedMessageSession(i,s.clientMessageId);const n=c instanceof Error?c.message:String(c),o=Is(Rn(n,Boolean(s.skillInvocation)));if("delivered"===e.setCachedMessageDelivery(i,s.clientMessageId,"failed"))return void r(null);r(e=>e?{...e,sessionId:i,kind:o,detail:Cs(n),retrying:!1}:null),e.reportLog("web.telemetry.retry_failed",{attachmentCount:s.images?.length??0,failureKind:o},"warn"),a(i)}finally{r(e=>e?.clientMessageId===s.clientMessageId&&e.retrying?{...e,retrying:!1}:e),o.finish()}},[a,l,s,e,n,d]);return function(e,n,s,r,i,o){const a=t.useRef({failure:n,retry:o});a.current={failure:n,retry:o};const c=t.useRef(new WeakMap),l=n?.clientMessageId,d=n?.kind,u=n?.retrying;t.useEffect(()=>{if(!s||!r||i||!l||u||!d||!["network","timeout","reconnect"].includes(d))return;let t=c.current.get(s);t||c.current.set(s,t=new Map);const n=JSON.stringify([e,l]),o=t.get(n)??0;if(o>=3)return;const h=window.setTimeout(()=>{s.isConnected&&a.current.failure?.clientMessageId===l&&!a.current.failure.retrying&&(t.set(n,o+1),a.current.retry())},1e3*2**o);return()=>window.clearTimeout(h)},[e,l,d,u,s,r,i])}(e.daemonId,s,e.clientRef.current,e.connectionReady??Boolean(e.clientRef.current?.isConnected),e.busy,h),t.useEffect(()=>{!i||e.busy||n.has(e.activeSessionId)||(e.activeSessionId===i.sessionId&&e.pendingSessions[i.sessionId]?(o(null),u(void 0,i.attachments)):o(null))},[i,e.activeSessionId,e.busy,e.pendingSessions,u]),{failedSend:s,dismissFailedSend:()=>r(null),retryFailedSend:h,stagePendingSession:c,sendDraft:Object.assign(u,{submission:n}),sendQuickReply:e=>u(void 0,[],e)}}({waitForModelSave:Pn.waitForSave,connectionReady:"connected"===R,daemonId:M?.daemonId,revealCreatedSession:t=>{e.setSearch(""),e.setSessionAgentFilter("all"),e.setCollapsedFolders(e=>({...e,[t]:!1}))},messages:we,sessions:X,setSessions:j,clientRef:qe,activeSessionIdRef:$e,composerDraftsRef:I,lastHistorySessionIdRef:k,messagesSessionIdRef:te,respondingSessionsRef:C,agent:q,cwd:$,approvalMode:at,continueSession:ct,model:dt,effort:ut,fastMode:vt,activeSessionId:T,activeSession:me,pendingSessions:A,draft:jt,busy:Ut,attachments:ce,t:Bt,setPendingSessions:st,setOptimisticSessions:rt,setComposerDrafts:St,setCwd:z,setAgent:_,setActiveSessionId:N,setMessages:ie,setDraft:K,setErrorText:E,setBusy:Wt,setAttachments:le,setRespondingSessions:P,clearHistoryLoading:ee,reportLog:Ee,remapLocalSessionState:ae,requestSessions:oe,updateDraft:Ie,appendCachedHistory:pe,ensureCachedHistoryEntry:ge,setCachedMessageDelivery:ve,resolveCachedMessageSession:ye,renderCachedHistory:ne,handleSessionCommandResponse:Mn,appendInfoMessage:Y}),{respondApproval:Jn,respondQuestion:Zn,cancelQuestion:Xn,setQuestionChoice:Yn,requestActiveAction:es,interruptActiveSession:ts,retrySessions:ns,updateApprovalMode:ss,setSessionPinned:rs,setSessionArchived:is,deleteSession:os,updatePinned:as,updateArchived:cs,renameSession:ls}=function(e){const n=function(e){return t.useCallback(async t=>{const n=t.sessionId,s=e.clientRef.current,r=Boolean(e.pendingSessions[n]);if(!r&&!s?.isConnected)return!1;const i={daemonId:e.daemonId,sessionId:n},o=()=>r&&(e.isSessionSubmitting(n)||e.pendingSessions[n]?.creationPending)?(f({message:d().sessionStarting,notice:!0}),!1):!!function(e){return window.dispatchEvent(new CustomEvent(Me,{cancelable:!0,detail:e}))}(i)||(f({message:d().saveSessionFiles,notice:!0}),!1);if(!o())return!1;if(!(await u(d().deleteSession(a(t)))))return!1;if(e.clientRef.current!==s||!r&&!s?.isConnected||!o())return!1;e.setBusy(!0),e.setErrorText(null),Te(i,!0);try{if(r||await s.request({action:"session.delete",id:s.makeId("delete"),sessionId:n}),e.clientRef.current!==s)return!1;Ae({...i,action:"remove"}),e.removeCachedHistory(n);const t=e=>{if(!e[n])return e;const t={...e};return delete t[n],t};return e.setPendingSessions(t),e.setOptimisticSessions(t),e.setPendingQueues(t),e.setPendingApprovals(t),e.setPendingQuestions(t),e.setSessions(e=>e.filter(e=>e.sessionId!==n)),e.updateSessionDraft(n,""),e.respondingSessionsRef.current.delete(n),e.setRespondingSessions(e=>{const t=new Set(e);return t.delete(n),t}),e.activeSessionIdRef.current===n&&(e.activeSessionIdRef.current=null,e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([]),e.setDraft(Kn(e.composerDraftsRef.current,null)),e.setDetailsOpen(!1)),r||await e.requestSessions({force:!0,preserveLoaded:!0}),!0}catch(c){return e.clientRef.current!==s||f({message:c instanceof Error?c.message:String(c),notice:!0}),!1}finally{Te(i,!1),e.setBusy(!1)}},[e])}(e),s=t.useCallback(async t=>{const n=e.clientRef.current,s=e.activeApproval;if(n?.isConnected&&s){e.setBusy(!0),e.setErrorText(null);try{if(await n.request({action:"session.approve",id:n.makeId("approve"),sessionId:s.sessionId,requestId:s.requestId,approved:t}),e.clientRef.current!==n)return;e.setPendingApprovals(e=>{const t={...e};return t[s.sessionId]?.requestId===s.requestId&&delete t[s.sessionId],t})}catch(r){if(e.clientRef.current!==n)return;const t=r instanceof Error?r.message:String(r);/session not found|session .* inactive/i.test(t)&&e.setPendingApprovals(e=>{if(e[s.sessionId]?.requestId!==s.requestId)return e;const t={...e};return delete t[s.sessionId],t}),e.setErrorText(t)}finally{e.setBusy(!1)}}},[e]),r=t.useCallback(async()=>{const t=e.clientRef.current;if(t?.isConnected&&e.activeQuestion){e.setBusy(!0),e.setErrorText(null);try{if(await t.request({action:"session.respondQuestion",id:t.makeId("question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId,answers:e.questionAnswers}),e.clientRef.current!==t)return;e.setPendingQuestions(t=>{const n={...t};return n[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete n[e.activeQuestion.sessionId],n})}catch(n){if(e.clientRef.current!==t)return;e.setErrorText(n instanceof Error?n.message:String(n))}finally{e.setBusy(!1)}}},[e]),i=t.useCallback(async()=>{const t=e.clientRef.current;if(t?.isConnected&&e.activeQuestion){e.setBusy(!0),e.setErrorText(null);try{if(await t.request({action:"session.cancelQuestion",id:t.makeId("cancel_question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId}),e.clientRef.current!==t)return;e.setPendingQuestions(t=>{const n={...t};return n[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete n[e.activeQuestion.sessionId],n})}catch(n){if(e.clientRef.current!==t)return;e.setErrorText(n instanceof Error?n.message:String(n))}finally{e.setBusy(!1)}}},[e]),o=t.useCallback((t,n,s)=>{e.setQuestionAnswers(e=>function(e,t,n,s=!1){if(!s)return{...e,[t]:[n]};const r=e[t]??[],i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,[t]:i}}(e,t,n,Boolean(s)))},[e]),c=t.useCallback(async t=>{const s=e.clientRef.current,r=e.activeSession,i=r?.sessionId??("session.interrupt"===t?e.activeSessionIdRef.current:null);if(!s?.isConnected||!i)return!1;if("session.interrupt"!==t&&!r)return!1;if("session.delete"===t)return n(r);if(e.clientRef.current!==s||!s.isConnected)return!1;e.setBusy(!0),e.setErrorText(null);try{if("session.resume"===t){if(await s.request({action:t,id:s.makeId("resume"),sessionId:i,agent:r.agent}),e.clientRef.current!==s)return!1}else if(await s.request({action:t,id:s.makeId(t.split(".").at(-1)??"session"),sessionId:i}),e.clientRef.current!==s)return!1;return"session.interrupt"!==t&&await e.requestSessions({force:!0,preserveLoaded:!0}),!0}catch(o){return e.clientRef.current!==s||e.setErrorText(o instanceof Error?o.message:String(o)),!1}finally{e.setBusy(!1)}},[e,n]),l=t.useCallback(async t=>{const n=e.clientRef.current;if(e.activeSession){if(n?.isConnected){e.setErrorText(null);try{if(await n.request({action:"session.setApprovalMode",id:n.makeId("approval_mode"),sessionId:e.activeSession.sessionId,approvalMode:t}),e.clientRef.current!==n)return;e.activeSessionIdRef.current===e.activeSession.sessionId&&e.setApprovalMode(t),e.setSessions(n=>n.map(n=>n.sessionId===e.activeSession.sessionId?{...n,approvalMode:t}:n))}catch(s){if(e.clientRef.current!==n)return;e.setErrorText(s instanceof Error?s.message:String(s))}}}else e.setApprovalMode(t)},[e]),h=t.useCallback(async(t,n)=>{if(e.pendingSessions[t.sessionId])return;const s=e.clientRef.current;if(s?.isConnected){e.setBusy(!0),e.setErrorText(null);try{const r=n?Date.now():void 0;if(await s.request({action:"session.setPinned",id:s.makeId("pin"),sessionId:t.sessionId,pinned:n,...r?{pinnedAt:r}:{}}),e.clientRef.current!==s)return;e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,pinned:n,pinnedAt:r}:e)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(r){if(e.clientRef.current!==s)return;e.setErrorText(r instanceof Error?r.message:String(r))}finally{e.setBusy(!1)}}},[e]),m=t.useCallback(async(t,n)=>{if(e.pendingSessions[t.sessionId])return;const s=e.clientRef.current;if(s?.isConnected){e.setBusy(!0),e.setErrorText(null);try{if(await s.request({action:"session.setArchived",id:s.makeId("archive"),sessionId:t.sessionId,archived:n}),e.clientRef.current!==s)return;e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,archived:n}:e)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(r){if(e.clientRef.current!==s)return;e.setErrorText(r instanceof Error?r.message:String(r))}finally{e.setBusy(!1)}}},[e]),p=t.useCallback(async()=>{e.activeSession&&await h(e.activeSession,!e.activeSession.pinned)},[e.activeSession,h]),g=t.useCallback(async()=>{e.activeSession&&await m(e.activeSession,!e.activeSession.archived)},[e.activeSession,m]),v=t.useCallback(()=>{c("session.interrupt")},[c]),y=t.useCallback(()=>{e.setErrorText(null),"connected"===e.phase?e.requestSessions({force:!0,preserveLoaded:!0}):window.location.reload()},[e]),b=t.useCallback(async(t=e.activeSession,n=e.renameTitle)=>{const s=n.trim();if(t&&e.pendingSessions[t.sessionId])return e.setPendingSessions(e=>{const n=e[t.sessionId];return n?{...e,[t.sessionId]:{...n,title:s||n.title,customTitle:s||void 0}}:e}),!0;const r=e.clientRef.current;if(!r?.isConnected||!t)return!1;e.setBusy(!0),e.setErrorText(null);try{return await r.request({action:"session.rename",id:r.makeId("rename"),sessionId:t.sessionId,title:s||void 0}),e.clientRef.current===r&&(e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,customTitle:s||void 0}:e)),!0)}catch(i){return e.clientRef.current!==r||e.setErrorText(i instanceof Error?i.message:String(i)),!1}finally{e.setBusy(!1)}},[e]);return{respondApproval:s,respondQuestion:r,cancelQuestion:i,setQuestionChoice:o,requestActiveAction:c,interruptActiveSession:v,retrySessions:y,updateApprovalMode:l,setSessionPinned:h,setSessionArchived:m,deleteSession:n,updatePinned:p,updateArchived:g,renameSession:b}}({daemonId:M?.daemonId??null,isSessionSubmitting:Qn.submission.has,updateSessionDraft:e.updateSessionDraft,clientRef:qe,activeSessionIdRef:$e,composerDraftsRef:I,lastHistorySessionIdRef:k,messagesSessionIdRef:te,respondingSessionsRef:C,activeApproval:ue,activeQuestion:he,activeSession:me,activeSessionId:T,questionAnswers:it,pendingSessions:A,phase:R,renameTitle:yt,setBusy:Wt,setErrorText:E,setPendingApprovals:D,setPendingQuestions:L,setQuestionAnswers:ot,setPendingQueues:F,setActiveSessionId:N,setMessages:ie,setApprovalMode:H,setSessions:j,setPendingSessions:st,setComposerDrafts:St,setDraft:K,setAttachments:le,setDetailsOpen:Qt,setRespondingSessions:P,setOptimisticSessions:rt,removeCachedHistory:xe,requestSessions:oe,removeCachedMessage:e.removeCachedMessage}),{runArchiveSync:ds,skipArchiveSync:us,runAdminAction:hs,exportActiveSession:ms,clearPairing:fs,setNotificationsEnabled:ps,connectSavedTarget:gs,forgetSavedTarget:vs,openSessionDetails:ys,editFolderTags:bs,browseFolder:ws,copyResumeCommand:Ss,resumeInTerminal:xs}=function(e){const n=t.useCallback((t,n)=>{e.updateSessionListPreferences(e=>({...e,archiveSyncedDaemonIds:"synced"===n?{...e.archiveSyncedDaemonIds,[t]:!0}:e.archiveSyncedDaemonIds,archiveSyncCardDismissedDaemonIds:{...e.archiveSyncCardDismissedDaemonIds,[t]:!0}}))},[e]),r=t.useCallback((t,s)=>{const r="pull"===t?e.t.archiveSyncSuccessPull:"pushMerge"===t?e.t.archiveSyncSuccessMerge:e.t.archiveSyncSuccessPush;if(e.setArchiveSyncStatus(function(e,t,n){return e.ok?{tone:"success",message:t.replace("{n}",String(e.archivedSessionIds.length))}:"timeout"===e.error?{tone:"error",message:n.timeout}:"not_connected"===e.error?{tone:"error",message:n.disconnected}:{tone:"error",message:n.generic.replace("{error}",e.error)}}(s,r,{timeout:e.t.archiveSyncFailedTimeout,disconnected:e.t.archiveSyncFailedDisconnected,generic:e.t.archiveSyncFailedGeneric})),!s.ok)return;const i=new Set(s.archivedSessionIds);e.setSessions(e=>e.map(e=>({...e,archived:i.has(e.sessionId)}))),e.pairingRef.current?.daemonId&&n(e.pairingRef.current.daemonId,"synced"),e.requestSessions({force:!0})},[n,e]),i=t.useCallback(async t=>{if(e.archiveSyncBusy)return;e.setArchiveSyncBusy(t),e.setArchiveSyncStatus(null);const n=await async function(e,t,n){if(!e?.isConnected)return{ok:!1,error:"not_connected"};try{const s=await e.request({action:"sessions.archiveSync",id:e.makeId("archive_sync"),mode:t,..."pull"===t?{}:{archivedSessionIds:n??[]}});return{ok:!0,archivedSessionIds:Array.isArray(s.archivedSessionIds)?s.archivedSessionIds.filter(e=>"string"==typeof e&&e.length>0):[]}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}(e.clientRef.current,t,function(e){return e.filter(e=>!0===e.archived).map(e=>e.sessionId)}(e.displaySessions));r(t,n),e.setArchiveSyncBusy(null)},[r,e]),o=t.useCallback(()=>{e.pairing?.daemonId&&(n(e.pairing.daemonId,"dismissed"),e.setArchiveSyncStatus({tone:"success",message:e.t.archiveSyncSkipped}))},[n,e]),f=t.useCallback(async t=>{const n=e.clientRef.current;if(n?.isConnected){if("update"===t){const{version:t,latestVersion:n}=e.daemonMetadata,s=t.includes("-")&&Ve(t,n)?Je(c(l().language)).description(t,n):d().update;if(!(await u(s)))return}if(("restart"!==t||await u(d().restart))&&e.clientRef.current===n&&n.isConnected){e.setAdmin(e=>({...e,loading:!0,action:t,statusText:""})),e.setErrorText(null);try{if("update"===t){const t=Ve(e.daemonMetadata.version,e.daemonMetadata.latestVersion)?"latest":function(e){const t=e.toLowerCase();return t.includes("alpha")?"alpha":t.includes("beta")?"beta":e.trim()?"latest":void 0}(e.daemonMetadata.version),s=await n.request({action:"daemon.update",id:n.makeId("daemon_update"),...t?{channel:t}:{}});return void e.setAdmin(t=>({...t,loading:!1,action:null,statusText:s.alreadyRunning?e.t.daemonUpdateAlreadyRunning:e.t.daemonUpdateStarted,pendingUpdate:{daemonId:e.pairing?.daemonId??"",version:e.daemonMetadata.version}}))}await n.request({action:"daemon.restart",id:n.makeId("daemon_restart")}),e.setAdmin(t=>({...t,loading:!1,action:null,statusText:e.t.daemonRestartRequested})),e.refreshDaemonMetadata()}catch(s){e.setAdmin(e=>({...e,loading:!1,action:null,statusText:s instanceof Error?s.message:String(s)})),e.setErrorText(s instanceof Error?s.message:String(s))}}}},[e]),p=t.useCallback(async()=>{if(!e.activeSession)return;const t=function(e,t){return function(e,t){const n=a(e),{markdown:s}=function({title:e,session:t,messages:n,labels:s,exportedAt:r=new Date}){const i=[];for(const a of n){if("user"!==a.type&&"assistant"!==a.type)continue;const e=Zt(a,s);e&&i.push(`## ${"user"===a.type?s.userMessage:s.assistantMessage}\n\n${e}`)}const o=[`# ${Gt(e)||t.sessionId}`,"",`- ${s.agent}: ${Vt(t.agent)}`,`- ${s.sessionId}: \`${t.sessionId}\``,`- ${s.workingDirectory}: \`${t.cwd}\``,`- ${s.createdAt}: ${t.createdAt}`,`- ${s.exportedAt}: ${r.toISOString()}`];return{markdown:i.length>0?`${o.join("\n")}\n\n${i.join("\n\n")}`:o.join("\n"),messageCount:i.length}}({title:n,session:e,messages:t.filter(e=>"info"!==e.type).map(e=>({type:e.role,content:"assistant"===e.role?Kt(e.content):e.content,images:e.images})),labels:{agent:"Agent",sessionId:"Session",workingDirectory:"Working directory",createdAt:"Created",exportedAt:"Exported",userMessage:"User",assistantMessage:"Assistant",attachedImage:"Attachment"}});return{title:n,markdown:s}}(e,t).markdown}(e.activeSession,e.messages);!function(e,t){const n=URL.createObjectURL(new Blob([t],{type:"text/plain;charset=utf-8"})),s=document.createElement("a");s.href=n,s.download=e,s.click(),URL.revokeObjectURL(n)}(function(e,t){return`${e.replace(/[<>:"/\\|?*\u0000-\u001F]/g," ").replace(/\s+/g," ").trim().slice(0,80)||t.slice(0,12)||"session"}.txt`}(a(e.activeSession),e.activeSession.sessionId),t),await(navigator.clipboard?.writeText(t).catch(()=>{}))},[e.activeSession,e.messages]),g=t.useCallback(async()=>{if(!("Notification"in window))return e.setNotificationPermission("unsupported"),void e.setErrorText("Browser notifications are not supported.");const t=await Notification.requestPermission();e.notificationPermissionRef.current=t,e.setNotificationPermission(t),"granted"===t&&e.updateNotificationSettings({enabled:!0}),e.setStatusText("granted"===t?"Browser notifications enabled":"Browser notifications not enabled")},[e]),v=t.useCallback(async()=>{const t=e.pairingRef.current;await u(d().forget)&&e.pairingRef.current===t&&(e.intentionalDisconnectRef.current=!0,e.connectionAttemptIdRef.current+=1,ft(),e.clientRef.current?.disconnect(),e.historyCacheRef.current={},e.historyCacheDaemonIdRef.current=null,e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([]),e.setPairing(null),e.setDaemonMetadata(Nn),e.setPhase("missing-pair"),e.setStatusText(e.t.missingPair))},[e]),y=t.useCallback(t=>{t&&"default"===e.notificationPermission?g():e.updateNotificationSettings({enabled:t})},[e,g]),b=t.useCallback(t=>{e.connectWithPairingRef.current(t,!0)},[e]),w=t.useCallback(t=>e.saveTargets(function(e,t){return e.filter(e=>e.daemonId!==t)}(e.savedTargets,t)),[e]),S=t.useCallback(t=>{e.setActiveSessionId(t.sessionId),e.setRenameTitle(t.customTitle??t.title??""),e.setDetailsOpen(!0)},[e]),x=t.useCallback((t,n)=>{const s=h(n);e.updateSessionListPreferences(e=>({...e,directoryTags:m(e.directoryTags,t,s)}))},[e]),I=t.useCallback(t=>{e.setControlTab("files"),e.listDirectory(t,{updateRoute:!0})},[e]),k=t.useCallback(async t=>{try{const n=bt(t);if(!n)return;await gt(n),e.setStatusText(e.t.commandCopied)}catch{throw e.setErrorText(e.t.copyResumeFailed),new Error(e.t.copyResumeFailed)}},[e]),C=t.useRef(!1);return{runArchiveSync:i,skipArchiveSync:o,runAdminAction:f,exportActiveSession:p,clearPairing:v,setNotificationsEnabled:y,connectSavedTarget:b,forgetSavedTarget:w,openSessionDetails:S,editFolderTags:x,browseFolder:I,copyResumeCommand:k,resumeInTerminal:t.useCallback(async t=>{if(C.current)return;const n=s(),r=e.pairingRef.current?.daemonId;if(r&&n.resumeInTerminal&&n.isLocalDaemon?.(r)){C.current=!0;try{const s=e.clientRef.current;if(!s)throw new Error("Not connected");await s.request({action:"session.release",id:s.makeId("release"),sessionId:t.sessionId,agent:t.agent}),await n.resumeInTerminal({...t,daemonId:r,approvalMode:t.approvalMode??t.observedApprovalMode})}catch(i){e.setErrorText(String(i).includes("session_busy")?e.t.resumeTerminalBusy:e.t.resumeTerminalFailed)}finally{C.current=!1}}},[e])}}({clientRef:qe,pairingRef:Ue,connectWithPairingRef:_e,notificationPermissionRef:ze,intentionalDisconnectRef:Xe,connectionAttemptIdRef:Ge,historyCacheRef:be,historyCacheDaemonIdRef:Be,messagesSessionIdRef:te,lastHistorySessionIdRef:k,displaySessions:X,pairing:M,t:Bt,archiveSyncBusy:cn,daemonMetadata:J,activeSession:me,messages:we,notificationPermission:Z,savedTargets:Nt,setArchiveSyncBusy:xn,setArchiveSyncStatus:En,setSessions:j,setAdmin:Jt,setErrorText:E,setNotificationPermission:tn,setStatusText:tt,setMessages:ie,setPairing:nt,setDaemonMetadata:Xt,setPhase:Ye,setActiveSessionId:N,setRenameTitle:W,setDetailsOpen:Qt,setControlTab:V,updateSessionListPreferences:Lt,requestSessions:oe,refreshDaemonMetadata:je,updateNotificationSettings:Oe,saveTargets:Dt,listDirectory:de}),{listSessionModels:Ms,applyToAllSessions:Ts}=function(e,n,s){const r=t.useRef(s);return r.current=s,{listSessionModels:t.useCallback(async t=>{const n=e.current;return n?.isConnected?(await n.request({action:"models.list",id:n.makeId("models"),agent:t})).options??[]:[]},[e]),applyToAllSessions:async(t,s)=>{const i=e.current;if(!i?.isConnected)throw new Error("not_connected");let o=!1;const a=i.onClose(()=>{o=!0});try{return await async function(e,t){const n=new Map,s=new Set;let r;do{if(!t.isCurrentConnection())throw new Error("connection_changed");const e=await t.request({action:"sessions.list",id:t.nextId(),limit:500,cursor:r,skipGitMetadata:!0});if(!Array.isArray(e?.sessions))throw new Error("invalid_session_list");for(const t of e.sessions)t.sessionId.startsWith("pending_")||n.set(t.sessionId,t);if(r=e.nextCursor,r){const e=JSON.stringify(r);if(s.has(e))throw new Error("repeated_cursor");s.add(e)}}while(r);const i={updated:0,failed:0};for(const o of n.values()){const n=e.models[o.agent],s={...void 0!==n?{model:n}:{},...void 0!==e.fastMode?{fastMode:e.fastMode}:{}};try{if(!t.isCurrentConnection())throw new Error("connection_changed");if(await t.request({action:"session.configure",id:t.nextId(),sessionId:o.sessionId,...s}),!t.isCurrentConnection())throw new Error("connection_changed");t.onApplied(o,s),i.updated++}catch{i.failed++}t.onProgress?.({...i})}return i}(t,{nextId:()=>i.makeId("bulkcfg"),request:e=>i.request(e,{timeoutMs:15e3}),isCurrentConnection:()=>!o&&e.current===i&&i.isConnected,onProgress:s,onApplied:(e,t)=>{r.current(e.sessionId,t),n(n=>n.map(n=>n.sessionId===e.sessionId?{...n,...t}:n))}})}finally{a()}}}}(qe,j,Fn.applyConfirmedSettings),Ns=t.useCallback(async e=>{const t=qe.current;if(!t?.isConnected)throw new Error(Bt.webSocketNotConnected);return t.request({action:"sessions.gitMetadata",id:t.makeId("directoryGit"),cwds:[e]})},[qe,Bt.webSocketNotConnected]),Ps="denied"===Z||"unsupported"===Z,Ds=Boolean(J.version&&J.latestVersion&&Dn(J.version,J.latestVersion)),Ls=M?.daemonId,qs=Boolean(Ls&&G[Ls]),$s=Boolean(Ls&&Q[Ls]),Bs=function(e){const[n,s]=t.useState(null),r=e.clientRef.current,i=(t,n,s)=>{const r=n.map(t=>t.content||e.t.failedSendImages(t.images?.length??0)).join(" / ");return function(e,t,n,s){switch(Gn(s)){case"turn-changed":return e.queueGuideTurnChanged;case"no-active-turn":return e.queueGuideNoActiveTurn;case"not-ready":return e.queueSessionNotReady;case"stale-selection":return e.queueSelectionChanged;case"pending-request":return e.queuePendingRequest;case"unsupported":return e.queueGuideUnsupported}const r=s instanceof Error?s.message:String(s);return s instanceof Yt?e.queueRequestRejected(t,n,r):e.queueRequestFailed(t,n,/timeout|timed out/i.test(r)?e.queueRequestTimeout:r)}(e.t,t,r,s)},o=e.activeSessionId,{busy:a,begin:c}=function(e,n){const s=t.useRef(new Set),[r,i]=t.useState([]),o=t=>t.client===e&&t.sessionId===n;return{busy:r.some(o),begin:()=>{if(!e||!n||[...s.current].some(o))return null;const t={client:e,sessionId:n};return s.current.add(t),i([...s.current]),()=>{s.current.delete(t),i([...s.current])}}}}(r,o),l=()=>e.clientRef.current===r,d=async()=>{l()&&await Promise.allSettled([e.requestSessions({force:!0,preserveLoaded:!0}),...e.activeSession?[e.requestHistory(e.activeSession,{refresh:!0})]:[]])},u=t=>n?.sessionId===o&&n.action===t&&n.runtime===e.activeSession?.runtime,h="daemonActive"===e.activeSession?.runtime.state&&!e.activeQueue.some(e=>e.waitingForStartup),m=!o||Boolean(e.pendingApprovals[o]||e.pendingQuestions[o]),p=!m&&!0===r?.supportsSessionSteer&&!!o&&e.respondingSessions.has(o)&&h&&!0===e.activeSession?.runtime.isResponding&&!u("guide"),g=!m&&h&&!u("sendNow")&&!0===r?.supportsQueueSendNow,v=function(e){return t.useCallback(async t=>{const n=e.clientRef.current;if(!n?.isConnected||!e.activeSessionId||!t.clientMessageId)return;const s=e.activeSessionId,r=e.begin();if(r){e.setErrorText(null);try{const r=await n.request({action:"session.queue.cancel",id:n.makeId("queue_cancel"),sessionId:s,clientMessageId:t.clientMessageId},{timeoutMs:ks});if(e.clientRef.current!==n)return;if(e.confirmPendingQueueRemoval(s,[t.clientMessageId]),0===r?.removed&&!r.interrupted)return await e.refreshState(),void(e.clientRef.current===n&&e.activeSessionIdRef.current===s&&f({message:e.t.queueSelectionChanged,notice:!0}));if(r?.interrupted||e.removeCachedMessage(s,t.clientMessageId),e.updateSessionDraft(s,[Kn(e.composerDraftsRef.current,s),t.content].filter(Boolean).join("\n\n")),t.images?.length){const n=[...new Set(t.images)];e.setAttachments(e=>{const t=new Set(e.map(e=>e.path));return[...e,...n.filter(e=>!t.has(e)).map(e=>({path:e,name:un(e),type:"image/*",size:0}))]})}r?.interrupted&&e.activeSessionIdRef.current===s&&f({message:e.t.queueWithdrawalInterrupted,notice:!0})}catch(i){if(e.clientRef.current!==n)return;await e.refreshState(),e.clientRef.current===n&&e.activeSessionIdRef.current===s&&e.setErrorText(i instanceof Error?i.message:String(i))}finally{r()}}},[e])}({...e,begin:c,refreshState:d});return{busy:a,canGuide:p,canSendNow:g,onAction:async(t,n)=>{if(!o||!r?.isConnected||!("guide"===n?p:g))return;const a=new Set(t.map(e=>e.clientMessageId).filter(Boolean)),u=e.activeQueue.filter(e=>e.clientMessageId&&a.has(e.clientMessageId));if(!u.length)return;const h=c();if(!h)return;e.setErrorText(null);const m=new Set;for(const s of u)e.setCachedMessageDelivery(o,s.clientMessageId,"sending",s);const f=t=>{m.add(t.clientMessageId),e.setCachedMessageDelivery(o,t.clientMessageId,"delivered"),e.confirmPendingQueueRemoval(o,[t.clientMessageId])};try{if("sendNow"===n){if(await r.request({action:"session.queue.sendNow",id:r.makeId("queue_now"),sessionId:o,clientMessageIds:u.map(e=>e.clientMessageId)},{timeoutMs:ks}),!l())return;u.forEach(f)}else for(const e of u){if(!l())return;if(await r.request({action:"session.steer",id:r.makeId("queue_guide"),sessionId:o,clientMessageId:e.clientMessageId,message:e.content,images:e.images},{timeoutMs:ks}),!l())return;f(e)}}catch(v){if(!l())return;const t=Gn(v);let r=!1;for(const n of u)m.has(n.clientMessageId)||(r="delivered"!==e.setCachedMessageDelivery(o,n.clientMessageId,"failed")||r);t&&("no-active-turn"===t&&e.setRespondingSessions(e=>{const t=new Set(e);return t.delete(o),t}),e.activeSession&&s({sessionId:o,action:n,runtime:e.activeSession.runtime}),await d()),r&&l()&&e.activeSessionIdRef.current===o&&e.setErrorText(i("guide"===n?e.t.queueGuide:e.t.queueSendNow,u.filter(e=>!m.has(e.clientMessageId)),v))}finally{h()}},onCollect:async t=>{if(!o||!r?.isConnected)return;const n=new Set(t.map(e=>e.clientMessageId).filter(e=>!!e)),s=e.activeQueue.filter(e=>e.clientMessageId&&n.has(e.clientMessageId));if(s.length<2)return;const a=c();if(a){e.setErrorText(null);try{const t=await r.request({action:"session.queue.collect",id:r.makeId("queue_collect"),sessionId:o,clientMessageIds:s.map(e=>e.clientMessageId)},{timeoutMs:ks});if(!l())return;const i=t.entries;if(!Array.isArray(i))throw new Error("Invalid queue collection response");const a=i.map(e=>e.content).filter(e=>e.trim()).join("\n\n"),c=e=>[e,a].filter(e=>e.trim()).join("\n\n");e.updateSessionDraft(o,c(Kn(e.composerDraftsRef.current,o)));const d=[...new Set(i.flatMap(e=>e.images??[]))];e.setAttachments(e=>{const t=new Set(e.map(e=>e.path));return[...e,...d.filter(e=>!t.has(e)).map(e=>({path:e,name:un(e),type:"image/*",size:0}))]}),e.confirmPendingQueueRemoval(o,[...n]);for(const n of i)n.clientMessageId&&e.removeCachedMessage(o,n.clientMessageId)}catch(u){if(!l())return;Gn(u)&&await d(),l()&&e.activeSessionIdRef.current===o&&e.setErrorText(i(e.t.queueCollectAll,s,u))}finally{a()}}},onCancel:v}}(e);return{...e,setModel:Pn.setModel,busy:e.busy||Pn.saving,setEffort:Fn.setEffort,setFastMode:Fn.setFastMode,queueControls:Bs,listSessionModels:Ms,applyToAllSessions:Ts,loadDirectoryGitMetadata:Ns,rewindMessage:n,handleSessionCommandResponse:Mn,handleServerMessage:jn,failedSend:$n,dismissFailedSend:zn,retryFailedSend:Hn,stagePendingSession:_n,sendDraft:Qn,sendQuickReply:Vn,respondApproval:Jn,respondQuestion:Zn,cancelQuestion:Xn,setQuestionChoice:Yn,requestActiveAction:es,interruptActiveSession:ts,retrySessions:ns,updateApprovalMode:async e=>{Fn.setApprovalMode(e),me&&!A[me.sessionId]&&await ss(e)},cancelQueuedTurn:Bs.onCancel,setSessionPinned:rs,setSessionArchived:is,deleteSession:os,updatePinned:as,updateArchived:cs,renameSession:ls,runArchiveSync:ds,skipArchiveSync:us,runAdminAction:hs,exportActiveSession:ms,clearPairing:fs,setNotificationsEnabled:ps,connectSavedTarget:gs,forgetSavedTarget:vs,openSessionDetails:ys,editFolderTags:bs,browseFolder:ws,copyResumeCommand:Ss,resumeInTerminal:xs,notificationsBlocked:Ps,hasDaemonUpdate:Ds,activeDaemonId:Ls,archiveSynced:qs,archiveSyncDismissed:$s}}();return n.jsx(_e,{scopeKey:Le(e.pairing?.daemonId,e.activeSessionId),children:n.jsx(Qe,{workspace:e,children:n.jsx(Ia,{workspace:e})})})}},Symbol.toStringTag,{value:"Module"}));export{Ds as $,P as A,F as B,O as C,Ue as D,_o as E,Qr as F,Y as G,Ge as H,Fr as I,le as J,ze as K,te as L,Pe as M,cr as N,xn as O,he as P,Pr as Q,pe as R,Se as S,ke as T,Nr as U,nn as V,dr as W,Re as X,cn as Y,Yo as Z,we as _,z as a,Ns as a0,$s as a1,Ke as a2,Ie as a3,Zs as a4,fe as a5,Kt as a6,Bs as a7,In as a8,Ut as a9,Mt as aa,ba as ab,kt as ac,so as ad,to as ae,X as af,ve as ag,va as ah,Yi as ai,bt as aj,re as ak,eo as al,de as am,N as an,no as ao,ro as ap,oa as aq,$o as ar,aa as as,ca as at,da as au,ua as av,ye as aw,oe as ax,ka as ay,q as b,_ as c,hn as d,J as e,un as f,Ii as g,D as h,K as i,ht as j,kn as k,xi as l,Ve as m,Je as n,gi as o,Si as p,me as q,Bi as r,zr as s,Bt as t,ue as u,Dn as v,gt as w,V as x,ur as y,Sn as z};
|