vibelet 1.2.233 → 1.2.234
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/runtime-version.cjs +1 -1
- package/dist/web/assets/App-DhealvG9.js +2 -0
- package/dist/web/assets/App-DynBSSrj.css +1 -0
- package/dist/web/assets/BrowserControlPanel-hHGqu9rG.js +1 -0
- package/dist/web/assets/{ChipGroup-Ct9ZVlb4.js → ChipGroup-Bue0n8PM.js} +1 -1
- package/dist/web/assets/FilesControlPanel-D9CJg2LW.js +1 -0
- package/dist/web/assets/{GlobalPendingDialog-YFbtF-Qi.js → GlobalPendingDialog-brYHIW1O.js} +1 -1
- package/dist/web/assets/{ImageViewer-BGEOxuV3.js → ImageViewer-BGZDYUl-.js} +1 -1
- package/dist/web/assets/{LanguageSettingsPanel-BJipWB1x.js → LanguageSettingsPanel-BLfFkm8K.js} +1 -1
- package/dist/web/assets/MarkdownModePanel-D73Xg4At.css +1 -0
- package/dist/web/assets/MarkdownModePanel-vIEhq98H.js +1 -0
- package/dist/web/assets/NewSessionDialog-BMPED8-_.js +1 -0
- package/dist/web/assets/{NewSessionDialog-C4RkGYOJ.css → NewSessionDialog-zLtlfzrw.css} +1 -1
- package/dist/web/assets/{NotificationSettingsPanel-DomEHL_z.js → NotificationSettingsPanel-GendGci0.js} +1 -1
- package/dist/web/assets/{RemoteLifeOSBlock-INrlOM1O.js → RemoteLifeOSBlock-CWCSOeJz.js} +2 -2
- package/dist/web/assets/{TerminalControlPanel-CcDilPZY.js → TerminalControlPanel-D78_YtrT.js} +1 -1
- package/dist/web/assets/ThemeSettingsPanel-C2uyAU3b.js +1 -0
- package/dist/web/assets/{abnfDiagram-VRR7QNED-OQczAdh4.js → abnfDiagram-VRR7QNED-Cjsq0mKx.js} +1 -1
- package/dist/web/assets/{arc-B_7S8PBe.js → arc-B4L9v8p9.js} +1 -1
- package/dist/web/assets/{architectureDiagram-ZJ3FMSHR-0RWvjsWb.js → architectureDiagram-ZJ3FMSHR-BSyKEbIb.js} +1 -1
- package/dist/web/assets/{arrow-right-DNQLufK9.js → arrow-right-C2kpV-wh.js} +1 -1
- package/dist/web/assets/{blockDiagram-677ZJIJ3-BBUl1A67.js → blockDiagram-677ZJIJ3-DVzXY4CR.js} +1 -1
- package/dist/web/assets/{c4Diagram-LMCZKHZV-q98KSF-X.js → c4Diagram-LMCZKHZV-BbAxPsV-.js} +1 -1
- package/dist/web/assets/channel-Cz1GqmQi.js +1 -0
- package/dist/web/assets/{chunk-2Q5K7J3B-CsJ1LsZP.js → chunk-2Q5K7J3B-CMbj6uyZ.js} +1 -1
- package/dist/web/assets/{chunk-32BRIVSS-CcFgBN8P.js → chunk-32BRIVSS-C9idSm3L.js} +1 -1
- package/dist/web/assets/{chunk-5VM5RSS4-BCeKWpkp.js → chunk-5VM5RSS4-DcKiD86C.js} +1 -1
- package/dist/web/assets/{chunk-EX3LRPZG-CkONpXQe.js → chunk-EX3LRPZG-DfkHUbV5.js} +1 -1
- package/dist/web/assets/{chunk-JWPE2WC7-COD3NKSV.js → chunk-JWPE2WC7-CzhsQ9t7.js} +1 -1
- package/dist/web/assets/{chunk-MOJQB5TN-Dq7aeQmI.js → chunk-MOJQB5TN-vouHb5EJ.js} +1 -1
- package/dist/web/assets/{chunk-RYQCIY6F-CmUgPJr0.js → chunk-RYQCIY6F-CJeXJ3Q-.js} +1 -1
- package/dist/web/assets/{chunk-V7JOEXUC-QkD3g50d.js → chunk-V7JOEXUC-C0yXF1v_.js} +1 -1
- package/dist/web/assets/{chunk-VR4S4FIN-bqXmDTmi.js → chunk-VR4S4FIN-dotBlS5o.js} +1 -1
- package/dist/web/assets/{chunk-XXDRQBXY-CylbQ77X.js → chunk-XXDRQBXY-BhynhzmH.js} +1 -1
- package/dist/web/assets/classDiagram-OUVF2IWQ-CA58r1rK.js +1 -0
- package/dist/web/assets/classDiagram-v2-EOCWNBFH-CA58r1rK.js +1 -0
- package/dist/web/assets/clsx-CKCxJTyc.js +1 -0
- package/dist/web/assets/{collectMessageImages-DhGvB-2f.js → collectMessageImages-CyIw_UE5.js} +1 -1
- package/dist/web/assets/{cose-bilkent-JH36ORCC-C9Znh1sN.js → cose-bilkent-JH36ORCC-p70MpNBN.js} +1 -1
- package/dist/web/assets/{cynefin-VYW2F7L2-Bp7Qx0jq.js → cynefin-VYW2F7L2-DeVdCaJW.js} +1 -1
- package/dist/web/assets/{cynefinDiagram-TSTJHNR4-BuCr2MsM.js → cynefinDiagram-TSTJHNR4-DeMwzp6s.js} +1 -1
- package/dist/web/assets/{dagre-VKFMJZFB-Db--wSJy.js → dagre-VKFMJZFB-DEJPTPi0.js} +1 -1
- package/dist/web/assets/{diagram-FQU43EPY-CcDlMM65.js → diagram-FQU43EPY-R2vZE2ct.js} +1 -1
- package/dist/web/assets/{diagram-G47NLZAW-DET75anv.js → diagram-G47NLZAW-DN_xCaXV.js} +1 -1
- package/dist/web/assets/{diagram-NH7WQ7WH-CuSmdJWE.js → diagram-NH7WQ7WH-Crurt3Zc.js} +1 -1
- package/dist/web/assets/{diagram-OA4YK3LP-C4AHJasK.js → diagram-OA4YK3LP-eoATHsv4.js} +1 -1
- package/dist/web/assets/{diagram-WEI45ONY-v2xIwF8y.js → diagram-WEI45ONY-CaFoLg1z.js} +1 -1
- package/dist/web/assets/{ebnfDiagram-CCIWWBDH-wy_kEa8S.js → ebnfDiagram-CCIWWBDH-ft94M3-C.js} +1 -1
- package/dist/web/assets/{erDiagram-Q63AITRT-B2ZADv-r.js → erDiagram-Q63AITRT-CY9h6J4g.js} +1 -1
- package/dist/web/assets/file-editor-FileCodeEditor-C4drlwzi.js +2 -0
- package/dist/web/assets/{file-editor-ObsidianCodeEditor-C4QKDNQs.js → file-editor-ObsidianCodeEditor-BWzRCMya.js} +1 -1
- package/dist/web/assets/file-editor-ObsidianFileEditor-Bo11_LxW.js +2 -0
- package/dist/web/assets/{file-editor-index-BEEbdBdH.js → file-editor-index-BOi4gj-u.js} +1 -1
- package/dist/web/assets/{file-editor-index-Blz54FUZ.js → file-editor-index-BWvEAcHp.js} +1 -1
- package/dist/web/assets/{file-editor-index-BJr7v7bw.js → file-editor-index-Bg9-IMrE.js} +1 -1
- package/dist/web/assets/file-editor-index-BocbUhDf.js +1 -0
- package/dist/web/assets/{file-editor-index-B3d2HyrJ.js → file-editor-index-ByGYwqNf.js} +1 -1
- package/dist/web/assets/{file-editor-index-kJrjg6tD.js → file-editor-index-C-F4L_uP.js} +1 -1
- package/dist/web/assets/{file-editor-index-Cy0cJb2y.js → file-editor-index-C6CU7Fik.js} +1 -1
- package/dist/web/assets/{file-editor-index-BFdT3Mv9.js → file-editor-index-C7QHkk3U.js} +1 -1
- package/dist/web/assets/{file-editor-index-BoV5K7VS.js → file-editor-index-CBJfyhrV.js} +1 -1
- package/dist/web/assets/{file-editor-index-BEOxpefN.js → file-editor-index-CMzVhAnN.js} +1 -1
- package/dist/web/assets/{file-editor-index-Dj7iSTai.js → file-editor-index-CVa9xeL0.js} +1 -1
- package/dist/web/assets/{file-editor-index-C-aRVKEr.js → file-editor-index-Ca7mWpkj.js} +1 -1
- package/dist/web/assets/{file-editor-index-CSaCz3EW.js → file-editor-index-CylY6jN7.js} +1 -1
- package/dist/web/assets/{file-editor-index-C5f7s3Eh.js → file-editor-index-D5fLCdey.js} +1 -1
- package/dist/web/assets/{file-editor-index-DGnKtkr2.js → file-editor-index-DBUZobR-.js} +1 -1
- package/dist/web/assets/{file-editor-index-mYPTZLoA.js → file-editor-index-DH8OZ6dS.js} +1 -1
- package/dist/web/assets/{file-editor-index-DfMO4TI8.js → file-editor-index-DIH2DQ5-.js} +1 -1
- package/dist/web/assets/{file-editor-index-CQsZBAf1.js → file-editor-index-DPwrStxR.js} +1 -1
- package/dist/web/assets/{file-editor-index-Cyo3bdPe.js → file-editor-index-DSJHLC6d.js} +1 -1
- package/dist/web/assets/{file-editor-index-B2I28X4j.js → file-editor-index-Dijmg1Xu.js} +1 -1
- package/dist/web/assets/{file-editor-index-rihVD8wm.js → file-editor-index-EvPD_eNu.js} +1 -1
- package/dist/web/assets/{file-editor-index-WHi3JlW8.js → file-editor-index-WprjWcs8.js} +1 -1
- package/dist/web/assets/{file-editor-index-CKwNSFLk.js → file-editor-index-vyjM9L0w.js} +1 -1
- package/dist/web/assets/{file-editor-index-c2dKCHO8.js → file-editor-index-wav2nO7A.js} +1 -1
- package/dist/web/assets/{flowDiagram-23GEKE2U-CX2RaC4p.js → flowDiagram-23GEKE2U-a19dID2A.js} +1 -1
- package/dist/web/assets/{folder-plus-Cl6NWbNw.js → folder-plus-Bu9QkDgF.js} +1 -1
- package/dist/web/assets/{ganttDiagram-NO4QXBWP-C1fJ323v.js → ganttDiagram-NO4QXBWP-4pJAb1Hw.js} +1 -1
- package/dist/web/assets/{gitGraphDiagram-IHSO6WYX-BLFS-Drr.js → gitGraphDiagram-IHSO6WYX-C0sr7yzB.js} +1 -1
- package/dist/web/assets/highlighted-body-TPN3WLV5-zhoW73ku.js +1 -0
- package/dist/web/assets/{index-8_Am9ShR.js → index-CWLl_NKt.js} +1 -1
- package/dist/web/assets/index-D7uVMBdr.js +2 -0
- package/dist/web/assets/index-DKMeZk9Z.css +1 -0
- package/dist/web/assets/{infoDiagram-FWYZ7A6U-BNpxEHPJ.js → infoDiagram-FWYZ7A6U-CQ_rjtII.js} +1 -1
- package/dist/web/assets/{ishikawaDiagram-FXEZZL3T-CZA4KSjU.js → ishikawaDiagram-FXEZZL3T-HcjvQGn4.js} +1 -1
- package/dist/web/assets/{journeyDiagram-5HDEW3XC-HFqAA_cn.js → journeyDiagram-5HDEW3XC-CYHrlhlu.js} +1 -1
- package/dist/web/assets/{kanban-definition-HUTT4EX6-DD_a9PCM.js → kanban-definition-HUTT4EX6-CZSKwfT5.js} +1 -1
- package/dist/web/assets/{linear-D8Y_m16-.js → linear-DoKSWiVw.js} +1 -1
- package/dist/web/assets/mermaid-O7DHMXV3-DTyL8PSp.js +2 -0
- package/dist/web/assets/{mermaid.core-BOFC-9Zd.js → mermaid.core-SMyy5uul.js} +2 -2
- package/dist/web/assets/{mindmap-definition-LN4V7U3C-D5IUgZ6b.js → mindmap-definition-LN4V7U3C-DS2ffQVR.js} +1 -1
- package/dist/web/assets/{pegDiagram-2B236MQR-CefM8hXa.js → pegDiagram-2B236MQR-Etl5kXs4.js} +1 -1
- package/dist/web/assets/{pieDiagram-ENE6RG2P-BDEGSmj6.js → pieDiagram-ENE6RG2P-BwKVRXTh.js} +1 -1
- package/dist/web/assets/{quadrantDiagram-ABIIQ3AL-CgbzHIM1.js → quadrantDiagram-ABIIQ3AL-DFHey242.js} +1 -1
- package/dist/web/assets/{railroadDiagram-RFXS5EU6-DipKpgnM.js → railroadDiagram-RFXS5EU6-C60Wu2BH.js} +1 -1
- package/dist/web/assets/{requirementDiagram-TGXJPOKE-CJWkBC2T.js → requirementDiagram-TGXJPOKE-YlPVS_9q.js} +1 -1
- package/dist/web/assets/{sankeyDiagram-HTMAVEWB-CJgh1qMP.js → sankeyDiagram-HTMAVEWB-BkJ-Z4ML.js} +1 -1
- package/dist/web/assets/{sequenceDiagram-DBY2YBRQ-oIXo1saQ.js → sequenceDiagram-DBY2YBRQ-TWDsQi8y.js} +1 -1
- package/dist/web/assets/{sizeCapture-X5ZJPWSS-CrToD-n4.js → sizeCapture-X5ZJPWSS-BiFV_D__.js} +1 -1
- package/dist/web/assets/{stateDiagram-2N3HPSRC-PQ_QNKS9.js → stateDiagram-2N3HPSRC-B2NtvIqt.js} +1 -1
- package/dist/web/assets/stateDiagram-v2-6OUMAXLB-BsB_c9dr.js +1 -0
- package/dist/web/assets/{swimlanes-5IMT3BWC-B6jyX_3e.js → swimlanes-5IMT3BWC-BD0rAdln.js} +2 -2
- package/dist/web/assets/swimlanesDiagram-G3AALYLV-TU1AfPIZ.js +1 -0
- package/dist/web/assets/{timeline-definition-FHXFAJF6-CZV40Uiu.js → timeline-definition-FHXFAJF6-B3G3w3c6.js} +1 -1
- package/dist/web/assets/{vennDiagram-L72KCM5P-DfURoA_U.js → vennDiagram-L72KCM5P-CYfww2Cg.js} +1 -1
- package/dist/web/assets/{wardleyDiagram-EHGQE667-BJTuXTfz.js → wardleyDiagram-EHGQE667-DEc4pMwc.js} +1 -1
- package/dist/web/assets/{xychartDiagram-FW5EYKEG-BruFcrd-.js → xychartDiagram-FW5EYKEG-Clep3P8Q.js} +1 -1
- package/dist/web/index.html +2 -2
- package/dist/web/obsidian-editor-assets.json +1 -1
- package/package.json +1 -1
- package/dist/web/assets/App-Bw9Q-kI5.css +0 -1
- package/dist/web/assets/App-DFMRw4Fj.js +0 -2
- package/dist/web/assets/BrowserControlPanel-K-f_KMTt.js +0 -1
- package/dist/web/assets/FilesControlPanel-DlSUh03w.js +0 -1
- package/dist/web/assets/NewSessionDialog-CM5UMy33.js +0 -1
- package/dist/web/assets/ThemeSettingsPanel-DyQIWRlL.js +0 -1
- package/dist/web/assets/channel-CL_-wxGg.js +0 -1
- package/dist/web/assets/classDiagram-OUVF2IWQ-C0QG8J89.js +0 -1
- package/dist/web/assets/classDiagram-v2-EOCWNBFH-C0QG8J89.js +0 -1
- package/dist/web/assets/clsx-BNl54vr7.js +0 -1
- package/dist/web/assets/file-editor-FileCodeEditor-DsxCu0Se.js +0 -2
- package/dist/web/assets/file-editor-ObsidianFileEditor-CHQ4_ygH.js +0 -2
- package/dist/web/assets/file-editor-index-Cubo6rhP.js +0 -1
- package/dist/web/assets/highlighted-body-TPN3WLV5-DeaJXkFu.js +0 -1
- package/dist/web/assets/index-BmushmS_.js +0 -2
- package/dist/web/assets/index-Y4eH8Xel.css +0 -1
- package/dist/web/assets/mermaid-O7DHMXV3-DqNZp9oe.js +0 -2
- package/dist/web/assets/stateDiagram-v2-6OUMAXLB-CTC96jcC.js +0 -1
- package/dist/web/assets/swimlanesDiagram-G3AALYLV-XXos6SqD.js +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid-O7DHMXV3-DTyL8PSp.js","assets/index-D7uVMBdr.js","assets/index-DKMeZk9Z.css","assets/index-CWLl_NKt.js","assets/collectMessageImages-CyIw_UE5.js","assets/clsx-CKCxJTyc.js","assets/index-1M7_HtDu.js","assets/mermaid-O7DHMXV3-CHSBDxzn.css","assets/ImageViewer-BGZDYUl-.js","assets/arrow-right-C2kpV-wh.js","assets/ImageViewer-Fya-Uufq.css","assets/BrowserControlPanel-hHGqu9rG.js","assets/TerminalControlPanel-D78_YtrT.js","assets/FilesControlPanel-D9CJg2LW.js","assets/folder-plus-Bu9QkDgF.js","assets/FilesControlPanel-PdhHw9AQ.css","assets/LanguageSettingsPanel-BLfFkm8K.js","assets/ChipGroup-Bue0n8PM.js","assets/ThemeSettingsPanel-C2uyAU3b.js","assets/NotificationSettingsPanel-GendGci0.js","assets/MarkdownModePanel-vIEhq98H.js","assets/MarkdownModePanel-D73Xg4At.css","assets/file-editor-FileCodeEditor-C4drlwzi.js","assets/file-editor-index-C6CU7Fik.js","assets/FileCodeEditor-CW9KijoU.css","assets/file-editor-ObsidianCodeEditor-BWzRCMya.js","assets/file-editor-index-Bg9-IMrE.js","assets/file-editor-index-D5fLCdey.js","assets/file-editor-index-ByGYwqNf.js","assets/file-editor-index-BOi4gj-u.js","assets/file-editor-index-wav2nO7A.js","assets/file-editor-index-DBUZobR-.js","assets/RemoteLifeOSBlock-CWCSOeJz.js","assets/RemoteLifeOSBlock-BGPY9LfG.css","assets/katex-uyR15voz.js","assets/marked.esm-BBjA1da9.js","assets/ObsidianCodeEditor-eECvmZRy.css","assets/file-editor-ObsidianFileEditor-Bo11_LxW.js","assets/purify.es-BNLkGfTg.js","assets/isArrayLikeObject-C958pSF-.js","assets/_baseMerge-CwDZKfvJ.js","assets/_initCloneObject-C781OlVa.js","assets/ObsidianFileEditor-BM1om3jV.css","assets/NewSessionDialog-BMPED8-_.js","assets/NewSessionDialog-zLtlfzrw.css","assets/GlobalPendingDialog-brYHIW1O.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as e,i as t,h as n,b as s,d as i,j as r,r as o,f as a,S as c,m as l,t as d,n as u,o as h,p,_ as m,u as f,D as g,E as y,q as v,v as b,w as x,x as w,y as S,z as k,A as I,B as C,C as j,F as R,G as M,H as E,I as T}from"./index-D7uVMBdr.js";const A=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-restore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]),P=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"}]]),D=e("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]),F=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"}]]),q=e("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),O=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"}]]),$=e("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]),z=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"}]]),B=e("chevron-up",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]),H=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"}]]),W=e("clipboard",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}]]),K=e("clock-3",[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),Q=e("code-xml",[["path",{d:"m18 16 4-4-4-4",key:"1inbqp"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"m14.5 4-5 16",key:"e7oirm"}]]),U=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"}]]),V=e("corner-up-right",[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M4 20v-7a4 4 0 0 1 4-4h12",key:"1lu4f8"}]]),G=e("cpu",[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]]),J=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"}]]),Z=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"}]]),Y=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"}]]),X=e("file-pen-line",[["path",{d:"m18.226 5.226-2.52-2.52A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-.351",key:"1k2beg"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}],["path",{d:"M8 18h1",key:"13wk12"}]]),ee=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"}]]),te=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"}]]),ne=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"}]]),se=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"}]]),ie=e("gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]),re=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"}]]),oe=e("git-merge",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]]),ae=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"}]]),ce=e("hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]),le=e("image-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]),de=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"}]]),ue=e("key-round",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]),he=e("keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]),pe=e("list-collapse",[["path",{d:"M10 5h11",key:"1hkqpe"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 19h11",key:"14g2nv"}],["path",{d:"m3 10 3-3-3-3",key:"i7pm08"}],["path",{d:"m3 20 3-3-3-3",key:"20gx1n"}]]),me=e("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),fe=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"}]]),ge=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"}]]),ye=e("mic",[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]]),ve=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"}]]),be=e("panel-left",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]),xe=e("panel-right",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]),we=e("paperclip",[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",key:"1miecu"}]]),Se=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"}]]),ke=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"}]]),Ie=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"}]]),Ce=e("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),je=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"}]]),Re=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"}]]),Me=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"}]]),Ee=e("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]),Te=e("send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]),Ae=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"}]]),Ne=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"}]]),Pe=e("shield-check",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),De=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"}]]),Fe=e("sparkles",[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z",key:"1s2grr"}],["path",{d:"M20 2v4",key:"1rf3ol"}],["path",{d:"M22 4h-4",key:"gwowj6"}],["circle",{cx:"4",cy:"20",r:"2",key:"6kqj1y"}]]),Le=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"}]]),qe=e("square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]),Oe=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"}]]),$e=e("terminal",[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]]),ze=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"}]]),_e=e("upload",[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]]),Be=e("wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]]),He=e("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),We=e("zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),Ke="vibelet.shortcuts.changed",Qe="vibelet.workspace.command",Ue=[{id:"leftSidebar",zh:"显示 / 隐藏左侧栏",en:"Toggle left sidebar",default:"mod+alt+["},{id:"rightSidebar",zh:"显示 / 隐藏右侧栏",en:"Toggle right sidebar",default:"mod+alt+]"},{id:"searchSessions",zh:"搜索会话",en:"Search sessions",default:"mod+shift+f"},{id:"searchMessages",zh:"搜索聊天内容",en:"Search conversation",default:"mod+f"},{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:"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:"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 Ve(){return/Mac|iPhone|iPad/.test(navigator.platform)}const Ge={BracketLeft:"[",BracketRight:"]",Comma:",",Period:".",Slash:"/",Backslash:"\\",Minus:"-",Equal:"=",Space:"space"};function Je(e,t=Ve()){const n=Ge[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 Ze(e,t=Ve()){const n=t?{mod:"⌘",ctrl:"⌃",meta:"⌘",alt:"⌥",shift:"⇧",space:"Space"}:{mod:"Ctrl",ctrl:"Ctrl",meta:"Win",alt:"Alt",shift:"Shift",space:"Space"};return e.split("+").map(e=>n[e]||e.toUpperCase()).join(t?"":"+")}function Ye(e,t,n){return t?"mod+w"===t?"closeTab"===e?null:"reserved":["mod+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":Ue.find(s=>s.id!==e&&function(e,t={}){return t[e]??Ue.find(t=>t.id===e).default}(s.id,n)===t)?.id??null:null}const Xe="vibelet.web.shortcuts";function et(){try{const e=JSON.parse(t().getItem(Xe)||"{}");return Object.fromEntries(Ue.filter(t=>"string"==typeof e?.[t.id]).map(t=>[t.id,e[t.id]]))}catch{return{}}}function tt(e,t=et()){return t[e]??("closeTab"===e&&"browser"===n().kind?"mod+alt+w":Ue.find(t=>t.id===e).default)}function nt(e,t){const n=tt(t);return n?`${e} (${Ze(n)})`:e}const st="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",it="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 rt(){const e=s(i().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 ot(){const e=rt();return r.jsxs("section",{className:"mobile-companion-panel control-section",children:[r.jsx("p",{className:"mobile-companion-free",children:e.free}),r.jsx("h2",{children:e.title}),r.jsx("p",{children:e.description}),r.jsx("div",{className:"mobile-companion-downloads",children:[{label:e.ios,qr:it,url:"https://apps.apple.com/app/id6761245790"},{label:e.android,qr:st,url:"https://www.feishu.cn/file/RUnbb7INMocEFjxj5AWcC7WEn6d"}].map(t=>r.jsxs("div",{children:[r.jsx("img",{src:t.qr,alt:`${t.label} · ${e.download}`,width:"140",height:"140"}),r.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",children:t.label})]},t.url))}),r.jsx("p",{children:e.pairing}),r.jsx("p",{className:"mobile-companion-hint",children:e.pro})]})}function at({onClose:e}){const t=o.useRef(null);o.useEffect(()=>{const e=document.activeElement,n=document.getElementById("vibelet-workspace"),s=n?.inert;return n&&(n.inert=!0),t.current?.focus(),()=>{n&&(n.inert=Boolean(s)),e?.focus()}},[]);const n=rt().title;return a.createPortal(r.jsx("div",{className:"mobile-companion-backdrop",onClick:t=>{t.target===t.currentTarget&&e()},children:r.jsxs("section",{ref:t,className:"mobile-companion-dialog",role:"dialog","aria-modal":"true","aria-label":n,tabIndex:-1,onKeyDown:n=>{if("Escape"===n.key&&(n.preventDefault(),n.stopPropagation(),e()),"Tab"!==n.key)return;const s=Array.from(n.currentTarget.querySelectorAll("button,a[href]")),i=s[0],r=s.at(-1);!n.shiftKey||document.activeElement!==i&&document.activeElement!==t.current?n.shiftKey||document.activeElement!==r||(n.preventDefault(),i?.focus()):(n.preventDefault(),r?.focus())},children:[r.jsx("button",{type:"button",className:"icon-button mobile-companion-close","aria-label":rt().close,title:rt().close,onClick:e,children:r.jsx(He,{"aria-hidden":"true"})}),r.jsx(ot,{})]})}),document.body)}function ct({activeSession:e,busy:t,controlsOpen:s,pendingCount:i=0,t:l,onOpenControls:d,onRefreshSessions:u,onRestoreSnapshot:h,onToggleArchived:p,onTogglePinned:m,onViewChanges:f}){const[g,y]=o.useState(!1),[v,b]=o.useState(!1),x=o.useRef(null);o.useEffect(()=>{if(!v)return;const e=e=>{e.target instanceof Node&&!x.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)}},[v]);const w=e=>{b(!1),e()},S=n(),k=r.jsxs("div",{className:"header-actions",children:[r.jsxs("button",{type:"button",className:"icon-button header-pending-button","aria-label":l.pendingActionCount(i),title:l.pendingActionCount(i),onClick:()=>window.dispatchEvent(new Event("vibelet.pending.open")),children:[r.jsx(O,{"aria-hidden":"true"}),i>0&&r.jsx("span",{className:"header-pending-count","aria-hidden":"true",children:i})]}),g&&r.jsx(at,{onClose:()=>y(!1)}),e?null:r.jsx("button",{"aria-label":l.refreshSessions,className:"icon-button",onClick:u,title:l.refreshSessions,type:"button",children:r.jsx(je,{"aria-hidden":"true"})}),r.jsx("button",{"aria-expanded":s,"aria-label":s?l.collapseControlsSidebar:l.workspaceTools,title:nt(s?l.collapseControlsSidebar:l.workspaceTools,"rightSidebar"),className:"header-tool-button",onClick:d,type:"button",children:r.jsx(xe,{"aria-hidden":"true"})}),e||S.openSettings?r.jsxs("div",{className:"header-more-wrap",ref:x,children:[r.jsx("button",{"aria-expanded":v,"aria-haspopup":"menu","aria-label":l.moreActions,className:"icon-button",onClick:()=>b(e=>!e),title:l.moreActions,type:"button",children:r.jsx(J,{"aria-hidden":"true"})}),v?r.jsxs("div",{className:"header-action-menu",role:"menu",children:[e&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:()=>w(()=>f(e.sessionId)),role:"menuitem",type:"button",children:[r.jsx(re,{"aria-hidden":"true"}),r.jsx("span",{children:l.viewChanges})]}),r.jsxs("button",{disabled:t,onClick:()=>w(m),role:"menuitem",type:"button",children:[r.jsx(ke,{"aria-hidden":"true"}),r.jsx("span",{children:e.pinned?l.unpin:l.pin})]}),r.jsxs("button",{disabled:t,onClick:()=>w(p),role:"menuitem",type:"button",children:[r.jsx(P,{"aria-hidden":"true"}),r.jsx("span",{children:e.archived?l.unarchive:l.archive})]}),r.jsxs("button",{onClick:()=>w(h),role:"menuitem",type:"button",children:[r.jsx(Re,{"aria-hidden":"true"}),r.jsx("span",{children:l.restoreSnapshot})]})]}),r.jsxs("button",{role:"menuitem",type:"button",onClick:()=>w(()=>y(!0)),children:[r.jsx(c,{"aria-hidden":"true"}),r.jsx("span",{children:rt().title})]}),r.jsxs("button",{onClick:()=>w(u),role:"menuitem",type:"button",children:[r.jsx(je,{"aria-hidden":"true"}),r.jsx("span",{children:l.refreshSessions})]})]}):null]}):null]}),I=S.toolbarTarget?.("right");return I?a.createPortal(k,I):k}function lt(e,t,n,s,i,r,a){const c=JSON.stringify([t,n,s,i]),[l,d]=o.useState(null);if(o.useEffect(()=>{if("codex"!==t||!e)return;let i=!1,r=0;d({client:e,key:c,state:null,loading:!0});const o=e.onMessage(t=>{"session.model"===t.type&&t.sessionId===s&&(r++,d({client:e,key:c,state:t,loading:!1}))}),a=e.onClose(()=>{i=!0,d({client:e,key:c,state:null,loading:!1})}),l=setTimeout(()=>{if(i)return;const t=r;e.request({action:"model.status",id:e.makeId("model-status"),...s?{sessionId:s}:{cwd:n}},{timeoutMs:15e3}).then(n=>{i||r!==t||d({client:e,key:c,state:n,loading:!1})}).catch(()=>{i||r!==t||d({client:e,key:c,state:null,loading:!1})})},200);return()=>{i=!0,clearTimeout(l),o(),a()}},[e,t,n,s,i,c]),"codex"!==t)return r;const u=l&&l.client===e&&l.key===c?l:null,h={value:"",label:`CLI · ${u?.state?.defaultModel||(!e||u&&!u.loading?a.unknown:a.remoteModelChecking)}`,desc:"config"===u?.state?.defaultSource?a.remoteModelConfig:"recommended"===u?.state?.defaultSource?a.remoteModelRecommended:a.unknown};return r.some(e=>""===e.value)?r.map(e=>""===e.value?{...e,...h}:e):[h,...r]}function dt(e,t){return!t.altKey&&(!(!t.metaKey&&!t.ctrlKey)||("enter"===e?!t.shiftKey:"shiftEnter"===e&&t.shiftKey))}const ut=/^[A-Za-z][A-Za-z0-9_-]*$/,ht=[{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 pt(e){return ht.filter(t=>!e||t.agents.includes(e))}function mt(e){return e.trim().toLowerCase()}function ft(e){if(!e.startsWith("/")||e.startsWith("//"))return null;const t=/^\/([A-Za-z0-9_-]*)$/.exec(e);if(!t)return null;const n=t[1]??"";return n&&!ut.test(n)?null:{start:0,end:e.length,keyword:mt(n)}}function gt(e,t){return e.name===t?0:e.name.startsWith(t)?1:e.name.includes(t)?2:3}function yt(e,t){const n=t.length>0,s=n&&!/^\s/.test(t),i=Boolean(e.argsHint&&!n);return`/${e.name}${i||s?" ":""}`}function vt(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 i=mt(s[1]??""),r=pt(t).find(e=>e.name===i);if(!r)return null;const o=s[2]?.trim()??"";switch(r.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 bt(e){return"subscriptionRequired"===e?"Error: Agent commands require an active Pro subscription.":`Error: ${e||"Command failed."}`}const xt=/^[A-Za-z_][A-Za-z0-9._:-]*$/,wt=/(?:^|\s)\$([A-Za-z_][A-Za-z0-9._:-]*|)$/;function St(e){return e.trim().toLowerCase()}function kt(e){const t=e.trim(),n=/^\$([A-Za-z_][A-Za-z0-9._:-]*)(?:\s+([\s\S]*))?$/.exec(t);return n?{name:St(n[1]??""),...n[2]?.trim()?{args:n[2].trim()}:{}}:null}function It(e){const t=wt.exec(e);if(!t||t.index+t[0].length!==e.length)return null;const n=t[1]??"";if(n&&!xt.test(n))return null;const s=t[0].lastIndexOf("$");return{start:t.index+s,end:e.length,keyword:St(n)}}const Ct=new RegExp("((?:~/|/|\\.{1,2}/|[A-Za-z0-9._-]+/)[^\\n`<>\"')\\]},。!?;:、]*?\\.(?:png|jpg|jpeg|gif|webp|svg|heic|heif)(?::\\d+(?::\\d+)?|#[^\\s`<>\"')\\]},。!?;:、]+)?)","gi"),jt=[".png",".jpg",".jpeg",".gif",".webp",".svg",".heic",".heif"],Rt="\\s`<>\"')\\]},。!?;:、",Mt="`<>\"')\\]},。!?;:、\\n\\r\\t",Et=new RegExp(`(^|[\\s([{>])((?:~\\/|\\/|\\.{1,2}\\/)[^${Rt}]+|[A-Za-z0-9._-]+(?:\\/[A-Za-z0-9._-]+)+(?:\\.[A-Za-z0-9._-]+)?\\/?)`,"g"),Tt=new RegExp(`(^|[\\s([{>])((?=[^${Mt}]*\\/)[^${Mt}]+?\\.[A-Za-z0-9._-]+(?::\\d+(?::\\d+)?|#[^${Rt}]+)?)(?=$|[${Rt}])`,"g");function At(e){let t=e;for(;/[.,!?;:,。!?;:、]+$/.test(t);)t=t.slice(0,-1);return t}function Nt(e,t){return!!e&&!/^[a-z]+:\/\//i.test(e)&&!e.startsWith("streamdown:")&&(!("~"!==e&&!e.startsWith("~/"))||!!(e.startsWith("/")||e.startsWith("./")||e.startsWith("../"))||!(!/^[A-Za-z]:[\\/]/.test(e)&&!e.startsWith("\\\\"))||!(!e.includes("/")&&!e.includes("\\"))||Boolean(t?.allowBareFilename)&&/^[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+$/.test(e))}function Pt(e){let t=At(e.trim());if(!t)return"";const n=t.indexOf("#");if(n>0){const e=t.slice(0,n);Nt(e,{allowBareFilename:!0})&&(t=e)}const s=t.match(/^(.*?)(:\d+(?::\d+)?)$/);if(s){const e=s[1]??"";Nt(e,{allowBareFilename:!0})&&(t=e)}return At(t)}function Dt(e,t){return e.start<t.end&&t.start<e.end}function Ft(e){if(e.startsWith("/")||e.startsWith("~/")||e.startsWith("./")||e.startsWith("../"))return!0;const t=e.indexOf("/");if(t<=0)return!1;const n=e.slice(0,t).trim();return!!/^\d+\s+\S/.test(n)||!/\s/.test(n)&&/[^\p{ASCII}]/u.test(n)}function Lt(e){if(Ft(e.rawCandidate))return e;const t=e.rawCandidate.indexOf("/");if(t<=0)return e;const n=e.rawCandidate.slice(0,t);for(let s=n.indexOf(" ");s>=0;s=n.indexOf(" ",s+1)){const t=s+1,n=e.rawCandidate.slice(t);if(Ft(n))return{start:e.start+t,end:e.end,rawCandidate:n}}return e}function qt(e,t){return Nt(Pt(e),t)}function Ot(e){const t=Pt(e).toLowerCase();return qt(t,{allowBareFilename:!0})&&jt.some(e=>t.endsWith(e))}function $t(e){return/^[a-zA-Z0-9._/@~-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function zt(e){return Boolean(e.sessionId.trim())&&!e.sessionId.startsWith("pending_")}function _t(e,t={}){return zt(e)?`cd ${$t(e.cwd||".")} && ${function(e,t={}){if(!zt(e))return"";const n=e.approvalMode??e.observedApprovalMode,s="claude"===e.agent?["claude","--resume",e.sessionId]:["codex","resume",e.sessionId],i=t.codexBackend??e.runtime?.codexBackend;return"codex"!==e.agent||"standalone"!==i&&(i||"@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($t).join(" ")}(e,t)}`:""}const Bt="vibelet.web.notificationSettings",Ht={enabled:!1,approvals:!0,questions:!0,replies:!0,hiddenOnly:!0};function Wt(e=t()){try{const t=e.getItem(Bt);if(!t)return{...Ht};const n=JSON.parse(t);return dn(n)?{enabled:"boolean"==typeof n.enabled?n.enabled:Ht.enabled,approvals:"boolean"==typeof n.approvals?n.approvals:Ht.approvals,questions:"boolean"==typeof n.questions?n.questions:Ht.questions,replies:"boolean"==typeof n.replies?n.replies:Ht.replies,hiddenOnly:"boolean"==typeof n.hiddenOnly?n.hiddenOnly:Ht.hiddenOnly}:{...Ht}}catch{return{...Ht}}}function Kt(e=("undefined"==typeof Notification?void 0:Notification)){return n().notifications?n().notifications.permission():e?.permission??"unsupported"}function Qt(e){return"user"===e.role&&e.images?.length?e.content.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").trim():e.content}function Ut(e,t){return e.role===t.role&&(e.type??"message")===(t.type??"message")&&Qt(e)===Qt(t)&&JSON.stringify(e.images??[])===JSON.stringify(t.images??[])&&e.toolName===t.toolName&&JSON.stringify(e.toolInput)===JSON.stringify(t.toolInput)}function Vt(e,t){if(t.historyKey?.startsWith("client:")||!e.historyKey?.startsWith("client:")||!e.localClientMessageId||"user"!==e.role||"user"!==t.role||!Ut(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 Gt(e,t){if(e.historyKey&&t.historyKey)return e.historyKey===t.historyKey;const n=e.timestamp?Date.parse(e.timestamp):NaN;return Number.isFinite(n)&&n>0&&n===Date.parse(t.timestamp??"")&&Ut(e,t)}function Jt(e){for(let t=e.length-1;t>=0;t-=1)if("user"===e[t]?.role)return t;return-1}function Zt(e,t,n){let s=e.slice();const i=new Set,r=s.flatMap((e,t)=>e.localClientMessageId&&e.historyKey?.startsWith("client:")?[t]:[]),o=new Map;r.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}`,i=o.get(s)??[];i.push(t),o.set(s,i)});for(const d of t){const e=o.get(`${d.role}:${Date.parse(d.timestamp??"")}`)?.find(e=>Gt(s[e],d))??-1;if(e<0||s[e].localClientMessageId)continue;const t=r.find(e=>!i.has(e)&&Vt(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,i.add(t)}i.size&&(s=s.filter((e,t)=>!i.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]={...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)&&(!!Gt(t,d)||!!Vt(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===Jt(s)&&s.slice(e+1).every(e=>"assistant"!==e.role||"info"===e.type||e.liveReply)&&Ut(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 i=!d.historyKey&&Vt(s[t],d);s[t]={...s[t],...d},i&&(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 Yt(e){const t=e.at(-1);return"assistant"===t?.role&&"info"!==t.type?[...e.slice(0,-1),{...t,liveReply:!0}]:e.slice()}function Xt(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 i=s.at(-1),r=void 0!==i&&e.slice(i+1).some(e=>"tool"===e.role);let o=t;for(const a of s){if(a===i&&!r)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!==i&&!r){const t=e[i],n=t.content.trim().startsWith(o.trim())?t.content:o,s=e.slice();return s[i]={...t,content:n},Yt(s)}return Yt([...e,{role:"assistant",content:o,timestamp:(new Date).toISOString()}])}function en(e,t,n){const s=n?.[e.sessionId];return void 0!==s?s:"boolean"==typeof e.pinned?e.pinned:Boolean(t?.[e.sessionId])}function tn(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 nn(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 sn(e,t,n){if(0===t.length)return e;const s=new Set(t),i=[];for(const r of t){const e=n.get(r);e&&i.push(e)}for(const r of e)s.has(r.sessionId)||i.push(r);if(i.length!==e.length)return i;for(let r=0;r<e.length;r+=1)if(i[r]!==e[r])return i;return e}function rn(e,t=Date.now(),n=l){if(!e)return n.timeUnknown;const s=Date.parse(e);if(!Number.isFinite(s))return n.timeUnknown;const i=t-s,r=36e5,o=24*r;return i<6e4?n.timeNow:i<r?n.timeMinutesAgo(Math.floor(i/6e4)):i<o?n.timeHoursAgo(Math.floor(i/r)):n.timeDaysAgo(Math.floor(i/o))}function on(e,t){return"info"===e.type?t.messageInfoRole:{user:t.messageUserRole,assistant:t.messageAssistantRole,tool:t.messageToolRole}[e.role]}function an(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 cn=".",ln="normal";function dn(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function un(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 hn(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 pn(e){const t=e;return{sessions:Array.isArray(t.sessions)?t.sessions:[],nextCursor:an(t.nextCursor),inventoryVersion:t.inventoryVersion,inventoryBackfillInFlight:t.inventoryBackfillInFlight,folderCounts:t.folderCounts}}function mn(e){return e.split("/").filter(Boolean).at(-1)??e}function fn(e){return 0===Object.entries(e).length?"No structured input.":JSON.stringify(e,null,2)}function gn(e){return Object.fromEntries(e.questions.map(e=>[e.id,e.options[0]?[e.options[0].label]:[]]))}function yn(e){return e.trim()||void 0}function vn(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 bn(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,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 xn=0;function wn(e,t,n=(new Date).toISOString()){return{...e,sessionId:t,lastActivityAt:n}}function Sn(e,t,n){if(!t||!n||t===n||!Object.hasOwn(e,t))return e;const{[t]:s,...i}=e;return{...i,[n]:s}}function kn(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 In(e,t){const n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n&&"."!==n?`${n}/${t}`:t}function Cn(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 jn(e,t){return t.startsWith("image/")||/\.(png|jpe?g|gif|webp|heic|heif|svg)$/i.test(e)}function Rn(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 Mn(e,t){return e.get(t)||void 0}function En(e,t){if("subscriptionRequired"===e){const e="undefined"==typeof window?"en":s(i().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 Tn="vibelet:image-gallery";function An(e){window.dispatchEvent(new CustomEvent(Tn,{detail:e}))}const Nn=/^[a-z][a-z0-9+.-]*:/i,Pn=/^[a-z]:[\\/]/i,Dn=/\.(?:md|markdown)$/i,Fn="https://vibelet.local",Ln="/__vibelet_markdown__",qn=`${Fn}${Ln}`;function On(e){const t=e?.trim()??"";if(!t||t.startsWith("#")||t.startsWith("//"))return null;const n=function(e){let t;try{t=new URL(e)}catch{return null}if(t.origin!==Fn)return null;if(t.pathname!==Ln)return null;const n=t.searchParams.get("path");return n&&Dn.test(n)?n:null}(t);if(n)return n;if(Nn.test(t)&&!Pn.test(t))return null;const s=t.split(/[?#]/,1)[0]??"";return Dn.test(s)?function(e){try{return decodeURIComponent(e)}catch{return e}}(s):null}function $n(e){const t=e.split("\n");let n=null;return t.map(e=>{const t=e.match(/^ {0,3}(`{3,}|~{3,})/);if(t){const s=t[1][0];return n===s?n=null:n||(n=s),e}return n?e:function(e){let t="",n=0;for(;n<e.length;){if("`"===e[n]){const s=zn(e,n);t+=e.slice(n,s),n=s;continue}if("["===e[n]&&"!"!==e[n-1]){const s=_n(e,n);if(s){t+=s.text,n=s.end;continue}}t+=e[n],n+=1}return t}(e)}).join("\n")}function zn(e,t){let n=0;for(;"`"===e[t+n];)n+=1;const s="`".repeat(n),i=e.indexOf(s,t+n);return i<0?e.length:i+n}function _n(e,t){const n=function(e,t){let n=!1;for(let s=t+1;s<e.length;s+=1){const t=e[s];if(n)n=!1;else if("\\"!==t){if("]"===t)return s}else n=!0}return-1}(e,t);if(n<0||"("!==e[n+1])return null;const s=n+2,i=function(e,t){let n=!1;for(let s=t;s<e.length;s+=1){const t=e[s];if(n)n=!1;else if("\\"!==t){if(")"===t)return s}else n=!0}return-1}(e,s);if(i<0)return null;const r=function(e){const t=e.match(/^\s*/)?.[0]??"",n=e.match(/\s*$/)?.[0]??"",s=e.slice(t.length,e.length-n.length);if(s.startsWith("<")){const e=s.indexOf(">");if(e<0)return null;const i=Bn(s.slice(1,e));return i?`${t}<${i}>${s.slice(e+1)}${n}`:null}const i=s.match(/^(\S+)([\s\S]*)$/);if(!i)return null;const r=Bn(i[1]);return r?`${t}${r}${i[2]}${n}`:null}(e.slice(s,i));return r?{text:`${e.slice(t,s)}${r})`,end:i+1}:null}function Bn(e){const t=On(e);return t?`${qn}?path=${encodeURIComponent(t)}`:null}const Hn="https://vibelet.local/__vibelet_file__";function Wn(e){if(!e)return null;const t=On(e);if(t)return t;let n=e.trim();if(n.startsWith(Hn))try{const e=new URL(n);if("https://vibelet.local"!==e.origin||"/__vibelet_file__"!==e.pathname)return null;n=e.searchParams.get("path")??""}catch{return null}else if(/^file:\/\//i.test(n))try{const e=new URL(n);if(e.hostname&&"localhost"!==e.hostname)return null;n=e.pathname}catch{return null}else if(/^(?:[a-z][a-z\d+.-]*:|\/\/|#)/i.test(n)&&!/^[a-z]:[\\/]/i.test(n))return null;try{n=decodeURIComponent(n.split("?")[0])}catch{}return n=Pt(n),qt(n,{allowBareFilename:!0})?n:null}const Kn=e=>`${Hn}?path=${encodeURIComponent(e)}`;function Qn(e){return e.value??e.children?.map(Qn).join("")??""}function Un(){return e=>{const t=e=>{if("link"===e.type||"image"===e.type){const t=Wn(e.url);return void(t&&(e.url=Kn(t),Ot(t)&&(e.alt=e.alt||Qn(e)||t.split(/[\\/]/).at(-1),e.type="image",delete e.children)))}e.children&&!["code","inlineCode","html"].includes(e.type)&&(e.children=e.children.flatMap(e=>"text"===e.type?function(e){const t=[],n=new RegExp(`(?:file://(?:localhost)?(?=/))?${Ct.source}`,Ct.flags);let s=0;const i=e=>{for(const n of function(e){if(!e)return[];const t=[];let n=0;for(const s of function(e){const t=[];for(const n of e.matchAll(Et)){const e=n[1]??"",s=n[2]??"",i=(n.index??0)+e.length;t.push({start:i,end:i+s.length,rawCandidate:s})}for(const n of e.matchAll(Tt)){const e=n[1]??"",s=n[2]??"",i=(n.index??0)+e.length,r=Lt({start:i,end:i+s.length,rawCandidate:s}),o=t.filter(e=>Dt(e,r));if(0!==o.length){if(Ft(r.rawCandidate)){for(const e of o){const n=t.indexOf(e);n>=0&&t.splice(n,1)}t.push(r)}}else t.push(r)}return t.sort((e,t)=>e.start-t.start||e.end-t.end)}(e)){s.start>n&&t.push({type:"text",value:e.slice(n,s.start)});const i=At(s.rawCandidate),r=Pt(i),o=s.rawCandidate.slice(i.length);qt(i)&&!Ot(i)?(t.push({type:"path",value:i,target:r||i}),o&&t.push({type:"text",value:o})):t.push({type:"text",value:s.rawCandidate}),n=s.end}return n<e.length&&t.push({type:"text",value:e.slice(n)}),t.length>0?t:[{type:"text",value:e}]}(e))t.push("path"===n.type?{type:"link",url:Kn(n.target??n.value),children:[{type:"text",value:n.value}]}:{type:"text",value:n.value})};for(const r of e.matchAll(n)){const n=Wn(r[0]);n&&Ot(n)&&(i(e.slice(s,r.index)),t.push({type:"image",url:Kn(n),alt:n.split(/[\\/]/).at(-1)}),s=r.index+r[0].length)}return i(e.slice(s)),t}(e.value??""):(t(e),[e])))};t(e)}}const Vn="pair",Gn="vibelet.web.pairing",Jn="vibelet.web.deviceId";class Zn extends Error{constructor(e,t){super(t),this.code=e,this.name="PairingCreateError"}}function Yn(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function Xn(e){const[t,n,s,i,r,o]=e;return!n||!Number.isFinite(s)||s<=0?null:{kind:"relay"===t?"relay":"direct",host:n,port:Math.floor(s),source:i,stability:r,...!0===o?{secure:!0}:{}}}function es(e){if(!Yn(e))return null;const{kind:t,host:n,port:s,source:i,stability:r,secure:o}=e;return"direct"!==t&&"relay"!==t||"string"!=typeof n||!n.trim()||"number"!=typeof s||!Number.isFinite(s)||s<=0||"string"!=typeof i||"string"!=typeof r?null:{kind:t,host:n.trim(),port:Math.floor(s),source:i,stability:r,...!0===o?{secure:!0}:{}}}function ts(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 ns(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 ss(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,i]=n;return 10===s||172===s&&i>=16&&i<=31||192===s&&168===i}(e.host)?0:"local_network"===e.source?1:"configured_host"===e.source?2:3}function is(e,t){const n=t?.port??e.port,s=t?.canonicalHost??e.canonicalHost;if(!s||"number"!=typeof n||!Number.isFinite(n))return[];const i=Math.floor(n);return[{kind:"direct",host:s,port:i,source:"fallback",stability:"stable"},...[...t?.fallbackHosts??[],...e.fallbackHosts??[]].map(e=>({kind:"direct",host:e,port:i,source:"fallback",stability:"stable"}))]}function rs(e,t,n=window.location,s=!0){if(s&&ts(n.hostname))return;const i=[...t?.connections??[],...e.connections??[],...is(e,t)].map(es).filter(e=>Boolean(e)).filter(e=>"direct"===e.kind).sort((e,t)=>ss(e)-ss(t));for(const r of i){const e=ns(r,n);if(e)return e}}function os(e=window.location.hash){const t=e.startsWith("#")?e.slice(1):e,n=new URLSearchParams(t).get(Vn);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(!Yn(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(Xn).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 as(e){const t=e.getItem(Gn);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 cs(e){if("undefined"==typeof window)return null;try{return e===t()?window.sessionStorage:null}catch{return null}}function ls(e=t(),n=cs(e)){const s=as(e);if(s)return s;const i=n?as(n):null;return i?(e.setItem(Gn,JSON.stringify(i)),n?.removeItem(Gn),i):null}function ds(e,n=t(),s=cs(n)){n.setItem(Gn,JSON.stringify(e)),s?.removeItem(Gn)}function us(e=t(),n=cs(e)){e.removeItem(Gn),n?.removeItem(Gn)}async function hs(e,n){try{return await async function(e,n=function(e=t()){const n=e.getItem(Jn);if(n)return n;const s="function"==typeof crypto.randomUUID?crypto.randomUUID():`web_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;return e.setItem(Jn,s),s}()){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 Zn("pair_window_expired","Pairing link expired.");const s=await fetch("/pair/create",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({daemonId:e.daemonId,pairNonce:e.pairNonce,deviceId:n,deviceName:"Vibelet Web"})});if(!s.ok)throw await async function(e){const t=await e.text().catch(()=>"");try{const e=JSON.parse(t);if(Yn(e)&&"pair_window_expired"===e.error)return new Zn("pair_window_expired","Pairing link expired.")}catch{}return new Zn("pairing_failed",t||"Pairing failed.")}(s);const i=await s.json();return{daemonId:i.daemonId,displayName:i.displayName||e.displayName,deviceId:i.deviceId,pairToken:i.pairToken,pairedAt:(new Date).toISOString(),webSocketUrl:rs(e,i,window.location,!0)}}(e,n?.deviceId)}catch(s){if(s instanceof Zn&&"pair_window_expired"===s.code&&n?.daemonId===e.daemonId)return n;throw s}}const ps=20971520,ms=new class{constructor(e=128,t=67108864,n=3e4){this.maxEntries=e,this.maxBytes=t,this.ttl=n}scope="";bytes=0;entries=new Map;get(e,t,n){this.scope!==e&&(this.entries.clear(),this.bytes=0,this.scope=e);for(const[r,o]of this.entries)o.expires<=Date.now()&&this.remove(r,o);const s=this.entries.get(t);if(s)return this.entries.delete(t),this.entries.set(t,s),s.promise;const i={promise:Promise.resolve(new Blob),bytes:0,expires:1/0};return i.promise=Promise.resolve().then(n).then(e=>(this.entries.get(t)===i&&(i.bytes=e.size,i.expires=Date.now()+this.ttl,this.bytes+=e.size,this.trim()),e),e=>{throw this.remove(t,i),e}),this.entries.set(t,i),this.trim(),i.promise}remove(e,t){this.entries.get(e)===t&&(this.entries.delete(e),this.bytes-=t.bytes)}trim(){for(;this.entries.size>this.maxEntries||this.bytes>this.maxBytes;){const e=this.entries.entries().next().value;if(!e)return;this.remove(...e)}}};function fs(e,t,n=1600){const s=Wn(e),i=ls(),[r,a]=o.useState(null),[c,l]=o.useState(null);return o.useEffect(()=>{if(!s)return;const r=new AbortController;let o;return a(null),l(null),(async()=>{try{if(!i)throw new Error("No pairing");const c=new URL(Rn(s,t));null!==n&&c.searchParams.set("w",String(n));const l=await function(e,t){return ms.get(t,e,async()=>{const n=await fetch(e,{headers:{authorization:`Bearer ${t}`}});if(!n.ok||Number(n.headers.get("content-length"))>ps)throw new Error("Image unavailable");const s=await n.blob();if(!s.type.startsWith("image/")||s.size>ps)throw new Error("Unsupported image");return s})}(c.toString(),i.pairToken);if(r.signal.aborted)return;o=URL.createObjectURL(l),a({src:e,url:o})}catch{r.signal.aborted||l(e)}})(),()=>{r.abort(),o&&URL.revokeObjectURL(o)}},[e,s,t,n,i?.pairToken,i?.webSocketUrl]),{url:s?r?.src===e?r.url:void 0:e,error:c===e,fail:()=>l(e)}}function gs({src:e,alt:t,cwd:n,onOpen:o,gallery:a}){const c=Wn(e),{url:l,error:d,fail:h}=fs(e,n),p=u[s(i().language)],m=t||mn(c??e);return r.jsx("button",{className:"message-image-preview",type:"button",title:c??e,"aria-label":`${p.preview}: ${m}`,onClick:async t=>{t.preventDefault(),t.stopPropagation();const s=await(a?.())??[{src:e,alt:m,cwd:n}],i=s.findIndex(t=>t.src===e||c&&Wn(t.src)===c);An({images:i<0?[{src:e,alt:m,cwd:n}]:s,index:Math.max(0,i),onOpen:o})},children:d?r.jsxs("span",{className:"message-image-placeholder",children:[r.jsx(le,{"aria-hidden":"true"}),m," · ",p.fileOpenFailed]}):l?r.jsx("img",{src:l,alt:m,loading:"lazy",onError:h}):r.jsxs("span",{className:"message-image-placeholder",children:[r.jsx(me,{className:"session-running-icon","aria-hidden":"true"}),m]})})}function ys({attachments:e,uploadBusy:t,onRemove:n,onOpen:s,t:i}){if(!e.length&&!t)return null;const o=e.filter(e=>e.type.startsWith("image/")||Ot(e.path)||Ot(e.name)),a=()=>o.map(e=>({src:e.path,alt:e.name||mn(e.path)}));return r.jsxs("div",{className:"attachment-row composer-attachments",children:[e.length>0&&r.jsx("div",{className:"composer-attachment-images",children:e.map(e=>{const t=e.name||mn(e.path),c=o.includes(e);return r.jsxs("div",{className:"composer-attachment-card "+(c?"composer-image-card":"composer-file-card"),children:[c?r.jsx(gs,{src:e.path,alt:t,onOpen:s,gallery:a}):r.jsxs("button",{className:"composer-file-preview",type:"button",title:`${t} · ${un(e.size)}`,"aria-label":`${i.preview}: ${t}`,onClick:()=>s(e.path),children:[r.jsx(we,{"aria-hidden":"true"}),r.jsx("span",{children:t}),r.jsx("small",{children:un(e.size)})]}),r.jsx("button",{className:"composer-image-remove",type:"button",title:`${i.removeAttachment}: ${t}`,"aria-label":`${i.removeAttachment}: ${t}`,onClick:()=>n(e.path),children:r.jsx(He,{"aria-hidden":"true"})})]},e.path)})}),t&&r.jsxs("span",{className:"attachment-empty",role:"status",children:[r.jsx("span",{className:"loading-spinner small","aria-hidden":"true"}),i.uploading]})]})}function vs({icon:e,label:t,menuLabel:n,options:s,value:i,onSelect:c,align:l="left",disabled:d,selected:u,wide:h,blendBackground:p,portal:m=!1,tooltipHoverDelay:f}){const[g,y]=o.useState(!1),v=o.useRef(null),b=o.useRef(null),x=o.useRef(null),w=function(e,t,n,s){const[i,r]=o.useState({left:16,top:16,maxHeight:240});return o.useLayoutEffect(()=>{if(!e)return;const i=()=>{const e=t.current?.getBoundingClientRect(),i=n.current;if(!e||!i)return;const o=i.getBoundingClientRect().width,a=Math.max(80,e.top-24),c=Math.min(i.scrollHeight,a);r({left:Math.max(16,Math.min("right"===s?e.right-o:e.left,innerWidth-o-16)),top:Math.max(16,e.top-c-8),maxHeight:a})};return i(),window.addEventListener("resize",i),document.addEventListener("scroll",i,!0),()=>{window.removeEventListener("resize",i),document.removeEventListener("scroll",i,!0)}},[e,t,n,s]),i}(g&&m,x,b,l),S=s.some(e=>e.icon);o.useEffect(()=>{if(!g)return;const e=b.current?.querySelectorAll('[role="menuitemradio"]:not(:disabled)'),t=[...e??[]].find(e=>"true"===e.getAttribute("aria-checked"));(t??e?.[0])?.focus();const n=e=>{e.target instanceof Node&&!v.current?.contains(e.target)&&!b.current?.contains(e.target)&&y(!1)};return document.addEventListener("pointerdown",n),()=>document.removeEventListener("pointerdown",n)},[g]);const k=g?r.jsx("div",{ref:b,style:m?w:void 0,"aria-label":n,className:`composer-option-popover ${m?"portal":""} ${p?"blend-background":""} ${S?"":"without-icons"} ${h?"wide":""} ${"right"===l?"align-right":""}`,role:"menu",children:s.map(e=>{const t=e.icon,n=e.value===i;return r.jsxs("button",{"aria-checked":n,className:n?"selected":"",disabled:e.disabled,onClick:()=>{c(e.value),y(!1),x.current?.focus()},role:"menuitemradio","data-tooltip-delay":f,title:e.description??e.label,type:"button",children:[S&&r.jsx("span",{className:"composer-menu-icon",children:t?r.jsx(t,{"aria-hidden":"true"}):null}),r.jsxs("span",{className:"composer-menu-copy",children:[r.jsx("strong",{children:e.label}),e.description?r.jsx("small",{children:e.description}):null]}),r.jsx("span",{className:"composer-menu-indicator","aria-hidden":"true",children:n?r.jsx($,{className:"composer-menu-check"}):null})]},e.value)})}):null;return r.jsxs("div",{className:"composer-menu",ref:v,onBlur:e=>{const t=e.relatedTarget;t&&(e.currentTarget.contains(t)||b.current?.contains(t))||y(!1)},onKeyDown:e=>{if("Escape"===e.key&&g&&(e.stopPropagation(),e.preventDefault(),y(!1),x.current?.focus()),!["ArrowDown","ArrowUp","Home","End"].includes(e.key))return;if(e.preventDefault(),!g)return void y(!0);const t=[...b.current?.querySelectorAll('[role="menuitemradio"]:not(:disabled)')??[]];if(!t.length)return;const n=t.indexOf(document.activeElement),s="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key?1:-1)+t.length)%t.length;t[s]?.focus()},children:[r.jsxs("button",{ref:x,"aria-expanded":g,"aria-haspopup":"menu",className:"composer-option-button "+(g||u?"selected":""),disabled:d,onClick:()=>y(e=>!e),title:n,type:"button",children:[r.jsx(e,{"aria-hidden":"true"}),r.jsx("span",{children:t}),g?r.jsx(B,{"aria-hidden":"true"}):r.jsx(z,{"aria-hidden":"true"})]}),k&&m?a.createPortal(k,document.body):k]})}function bs(e,t,n){const s=o.useRef(null);return o.useEffect(()=>{n&&document.getElementById(`${e}-${t}`)?.scrollIntoView({block:"nearest"})},[e,t,n]),s}function xs({visible:e,listId:t,selectedIndex:n,onHighlight:s,skills:i,onClose:o,onSelect:a,t:c}){const l=bs(t,n,e);return e?r.jsxs("div",{className:"skill-suggestion-popover",children:[r.jsxs("header",{children:[r.jsx("strong",{children:c.skills}),r.jsx("button",{type:"button",className:"icon-button",onClick:o,title:c.closeSkills,children:r.jsx(He,{"aria-hidden":"true"})})]}),i.length?r.jsx("div",{className:"skill-suggestion-list",id:t,role:"listbox",ref:l,children:i.map((e,i)=>r.jsxs("button",{id:`${t}-${i}`,role:"option","aria-selected":n===i,onMouseEnter:()=>s(i),onClick:()=>a(e),title:e.description??e.name,type:"button",children:[r.jsxs("span",{children:[r.jsxs("strong",{children:["$",e.name]}),e.description?r.jsx("small",{children:e.description}):null]}),r.jsx("em",{children:e.source})]},`${e.source}:${e.name}`))}):r.jsx("p",{children:c.noSkillsFound})]}):null}function ws({visible:e,listId:t,selectedIndex:n,onHighlight:s,commands:i,onClose:o,onSelect:a,t:c}){const l=bs(t,n,e);return e?r.jsxs("div",{className:"skill-suggestion-popover command-suggestion-popover",children:[r.jsxs("header",{children:[r.jsx("strong",{children:c.commands}),r.jsx("button",{type:"button",className:"icon-button",onClick:o,title:c.closeCommands,children:r.jsx(He,{"aria-hidden":"true"})})]}),i.length?r.jsx("div",{className:"skill-suggestion-list",id:t,role:"listbox",ref:l,children:i.map((e,i)=>r.jsxs("button",{id:`${t}-${i}`,role:"option","aria-selected":n===i,onMouseEnter:()=>s(i),onClick:()=>a(e),title:e.description,type:"button",children:[r.jsxs("span",{children:[r.jsxs("strong",{children:["/",e.name]}),r.jsx("small",{children:e.argsHint?`${e.title} ${e.argsHint}`:e.title})]}),r.jsx("em",{children:e.source})]},e.name))}):r.jsx("p",{children:c.noCommandsFound})]}):null}function Ss({queue:e,controls:t,busy:n,t:s,onCancel:i}){const[c,l]=o.useState(new Set),[d,u]=o.useState(!1),h=o.useId(),p=o.useRef(null),m=o.useRef(0),f=o.useRef(!1),[g,y]=o.useState(null),v=o.useRef(null),b=()=>{v.current=null,y(null)},x=e=>{if(v.current===e)return;const t=e.getBoundingClientRect(),n=Math.min(280,window.innerWidth-16);v.current=e,y({label:e.dataset.queueLabel||"",help:e.dataset.queueHelp||"",left:Math.max(8,Math.min(t.left,window.innerWidth-n-8)),top:t.top<76?t.bottom+7:t.top-7,below:t.top<76})},w=e.length>0&&e.every(e=>e.waitingForStartup),S=w?s.sessionStartingMessage:s.queuedTurns(e.length),k=e.filter(e=>e.clientMessageId),I=k.filter(e=>c.has(e.clientMessageId)),C=n||t.busy,j=I.length?I:k;return o.useLayoutEffect(()=>{e.length>m.current&&(f.current=!0,d&&u(!1)),m.current=e.length,!d&&f.current&&p.current&&(p.current.scrollTop=p.current.scrollHeight,f.current=!1)},[d,e.length]),e.length?r.jsxs("section",{className:"composer-queue-banner","aria-label":S,onPointerMove:e=>{const t=e.target instanceof Element?e.target.closest("button[data-queue-help]"):null;t?x(t):v.current&&b()},onPointerLeave:b,onFocusCapture:e=>{e.target instanceof HTMLButtonElement&&e.target.dataset.queueHelp&&x(e.target)},onBlurCapture:b,onScrollCapture:b,onClickCapture:b,children:[r.jsxs("header",{className:"composer-queue-heading",children:[r.jsx("strong",{"aria-live":"polite",children:S}),r.jsxs("div",{className:"composer-queue-heading-actions",children:[!d&&r.jsx("button",{type:"button","data-queue-label":k.length>0&&I.length===k.length?s.queueClearSelection:s.queueSelectAll,"data-queue-help":s.queueSelectionHelp,disabled:C||!k.length,onClick:()=>l(k.length>0&&I.length===k.length?new Set:new Set(k.map(e=>e.clientMessageId))),children:k.length>0&&I.length===k.length?s.queueClearSelection:s.queueSelectAll}),r.jsx("button",{type:"button",className:"composer-queue-collapse","aria-controls":h,"aria-expanded":!d,"aria-label":d?s.queueExpand:s.queueCollapse,"data-queue-label":d?s.queueExpand:s.queueCollapse,"data-queue-help":d?s.queueExpandHelp:s.queueCollapseHelp,onClick:()=>u(e=>!e),children:d?r.jsx(z,{"aria-hidden":"true"}):r.jsx(B,{"aria-hidden":"true"})})]})]}),r.jsxs("div",{className:"composer-queue-details",id:h,hidden:d,children:[r.jsx("div",{className:"composer-queue-list",ref:p,children:e.map((e,n)=>r.jsxs("div",{className:"composer-queue-item","data-selected":!!e.clientMessageId&&c.has(e.clientMessageId)||void 0,children:[r.jsx("button",{type:"button",className:"queue-select-button","aria-label":s.selectQueuedTurn(n+1),"aria-pressed":!!e.clientMessageId&&c.has(e.clientMessageId),disabled:C||!e.clientMessageId,"data-queue-label":s.selectQueuedTurn(n+1),"data-queue-help":e.content?`${s.queueSelectionHelp}\n${e.content}`:s.queueSelectionHelp,onClick:()=>l(t=>{const n=new Set(t),s=e.clientMessageId;return n.has(s)?n.delete(s):n.add(s),n}),children:r.jsx("span",{children:e.content||s.queuedTurnFallback})}),r.jsxs("div",{className:"queue-row-actions",children:[r.jsx("button",{type:"button","data-queue-label":s.queueGuide,"data-queue-help":s.queueGuideHelp,"aria-label":s.guideQueuedTurn(n+1),disabled:C||!e.clientMessageId||!t.canGuide||w,onClick:()=>{t.onAction([e],"guide")},children:r.jsx(V,{"aria-hidden":"true"})}),r.jsx("button",{type:"button","data-queue-label":s.queueSendNow,"data-queue-help":s.queueSendNowHelp,"aria-label":s.sendQueuedTurnNow(n+1),disabled:C||!e.clientMessageId||!t.canSendNow||w,onClick:()=>{t.onAction([e],"sendNow")},children:r.jsx(Te,{"aria-hidden":"true"})}),r.jsx("button",{type:"button",className:"queue-withdraw-button","data-queue-label":s.withdraw,"data-queue-help":s.queueWithdrawHelp,"aria-label":s.withdrawQueuedTurn(n+1),disabled:C||!e.clientMessageId,onClick:()=>i(e),children:r.jsx(He,{"aria-hidden":"true"})})]})]},e.clientMessageId||`${e.enqueuedAt}:${n}`))}),r.jsxs("footer",{className:"queue-batch-actions",children:[I.length>0&&r.jsx("span",{children:s.queueSelectedCount(I.length)}),r.jsxs("button",{type:"button","data-queue-label":I.length?s.queueCollectSelected:s.queueCollectAll,"aria-label":I.length?s.queueCollectSelected:s.queueCollectAll,"data-queue-help":s.queueCollectHelp,disabled:C||j.length<2,onClick:()=>{t.onCollect(j)},children:[r.jsx(pe,{"aria-hidden":"true"}),s.queueCollect]}),r.jsx("button",{type:"button","data-queue-label":I.length?s.queueGuideSelected:s.queueGuideAll,"aria-label":I.length?s.queueGuideSelected:s.queueGuideAll,"data-queue-help":s.queueGuideHelp,disabled:C||!j.length||!t.canGuide||w,onClick:()=>{t.onAction(j,"guide")},children:s.queueGuide}),r.jsx("button",{type:"button","data-queue-label":I.length?s.queueSendSelected:s.queueSendAll,"aria-label":I.length?s.queueSendSelected:s.queueSendAll,"data-queue-help":s.queueSendNowHelp,disabled:C||!j.length||!t.canSendNow||w,onClick:()=>{t.onAction(j,"sendNow")},children:s.queueSendNow})]})]}),g&&a.createPortal(r.jsxs("div",{className:"composer-queue-tooltip",role:"tooltip",style:{left:g.left,top:g.top,transform:g.below?void 0:"translateY(-100%)"},children:[r.jsx("strong",{children:g.label}),r.jsx("span",{children:g.help})]}),document.body)]}):null}function ks({replies:e,disabled:t,onSend:n,onChange:s,t:i}){const[a,c]=o.useState(!1),[l,d]=o.useState(""),u=()=>{const t=l.trim();!t||e.length>=20||(e.some(e=>h(e,i)===t)||s?.([...e,t]),d(""),c(!1))};return r.jsxs("div",{className:"quick-reply-row",children:[e.map(o=>{const a=h(o,i);return r.jsxs("span",{className:"quick-reply-item",children:[r.jsx("button",{type:"button",disabled:t||!n,onClick:()=>{n?.(a)},children:a}),s&&r.jsx("button",{className:"quick-reply-remove",type:"button","aria-label":`${i.delete}: ${a}`,title:`${i.delete}: ${a}`,onClick:()=>s(e.filter(e=>e!==o)),children:r.jsx(He,{"aria-hidden":"true"})})]},o)}),s&&(a?r.jsxs("div",{className:"quick-reply-add-form",children:[r.jsx("input",{autoFocus:!0,"aria-label":i.quickReplyAdd,placeholder:i.quickReplyAdd,value:l,maxLength:1e3,onChange:e=>d(e.target.value),onKeyDown:e=>{e.nativeEvent.isComposing||("Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),u()),"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),c(!1)))}}),r.jsx("button",{type:"button","aria-label":i.quickReplyAdd,disabled:!l.trim(),onClick:u,children:r.jsx(Ce,{"aria-hidden":"true"})}),r.jsx("button",{type:"button","aria-label":i.cancel,onClick:()=>c(!1),children:r.jsx(He,{"aria-hidden":"true"})})]}):r.jsx("button",{type:"button",className:"quick-reply-add","aria-label":i.quickReplyAdd,title:i.quickReplyAdd,disabled:e.length>=20,onClick:()=>c(!0),children:r.jsx(Ce,{"aria-hidden":"true"})}))]})}function Is({shortcut:e,onChange:t,action:n,t:s}){const i="New session"!==s.newSession,o="傳送快捷鍵"===s.sendShortcut,a="enter"===e?"Enter":"shiftEnter"===e?"Shift+Enter":"Cmd/Ctrl+Enter",c="enter"===e?"shiftEnter":"enter",l="enter"===c?"Enter":"Shift+Enter",d="create"===n?i?"建立":"create":i?s.send:"send",u="create"===n&&i&&!o?"创建":d,h="enter"===e?"Shift+Enter":"Enter",p=i?`${a} ${u};${h} ${o?"換行":"换行"}。${o?"點擊切換為":"点击切换为"} ${l} ${u}`:`${a} to ${d}; ${h} for a newline. Click to switch to ${l} to ${d}`;return r.jsxs("button",{type:"button",className:"submit-shortcut-toggle","data-shortcut":e,"aria-label":p,"aria-pressed":"enter"!==e,onMouseDown:e=>e.preventDefault(),onClick:()=>t(c),children:[r.jsx(he,{"aria-hidden":"true"}),r.jsx("span",{className:"submit-shortcut-tooltip","aria-hidden":"true",children:p})]})}function Cs({connected:e,busy:t,sending:n,responding:s,hasDraft:o,shortcut:a,onStop:c,t:l}){const d=n?"sending":s?"replying":"ready",u=s&&!n&&!o,h=n?l.sendingMessage:u?l.stopGenerating:l.send,m=n?l.sendingMessage:s?l.replyingMessage:l.send,f=n?me:u?qe:q;return r.jsxs("div",{className:"submit-button-group",children:[r.jsx(Is,{shortcut:a,action:"send",t:l,onChange:e=>{const t=i();p({...t,composer:{...t.composer,sendShortcut:e}}),window.dispatchEvent(new Event("vibelet.preferences.changed"))}}),r.jsxs("button",{type:u?"button":"submit",className:"send-button submit-action-button","data-state":d,"data-action":u?"stop":"send",disabled:!e||t||n||!u&&!o,"aria-label":h,"aria-description":m,title:u?`${m} · ${l.stopGenerating}`:n?m:`${s?`${m} · `:""}${l.send} · ${"enter"===a?l.sendShortcutEnter:"shiftEnter"===a?l.sendShortcutShiftEnter:l.sendShortcutModEnter}`,onClick:u?c:void 0,children:[s&&!n&&r.jsx("span",{className:"composer-send-progress","aria-hidden":"true"}),r.jsx(f,{className:n?"composer-send-spinner":u?"composer-send-stop":void 0,"aria-hidden":"true"}),r.jsx("span",{className:"composer-send-status",role:"status","aria-live":"polite",children:m})]})]})}function js({value:e,textareaRef:t,onValueChange:n,onKeyDown:s,autoFocus:i,disabled:a,...c}){const l=o.useRef(!1),d=o.useRef(!1);o.useEffect(()=>{if(!i||a||d.current)return;let e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{const e=t.current;if(!e)return;d.current=!0;const n=document.activeElement;n&&n!==document.body&&n!==e||(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length),d.current=!0)})});return()=>cancelAnimationFrame(e)},[i,a,t]);const u=o.useMemo(()=>function(e){let t=0;for(let n=0;n<e.length;n++){const s=e.charCodeAt(n);if(t=s>32&&s<127?t+1:0,t>=4096)return"off"}return"soft"}(e),[e]);return o.useLayoutEffect(()=>{const n=t.current;n&&!l.current&&n.value!==e&&(n.value=e)},[e,t]),r.jsx("textarea",{...c,ref:t,disabled:a,wrap:l.current?t.current?.wrap:u,onCompositionStart:()=>{l.current=!0},onCompositionEnd:e=>{l.current=!1,n(e.currentTarget.value)},onChange:e=>n(e.currentTarget.value),onKeyDown:e=>{l.current||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||s?.(e)}})}function Rs({onTranscript:e}){const a=n(),[c,l]=o.useState("idle"),[d,u]=o.useState("");o.useEffect(()=>{if(!d||"idle"!==c)return;const e=setTimeout(()=>u(""),5e3);return()=>clearTimeout(e)},[d,c]);const[h,p]=o.useState(0),m=o.useRef(!1);o.useEffect(()=>{if("recording"!==c)return;const e=Date.now();p(0);const t=setInterval(()=>p(Math.floor((Date.now()-e)/1e3)),1e3);return()=>clearInterval(t)},[c]);const[f,g]=o.useState(!1);o.useEffect(()=>{let e=!0;const t=()=>{a.speechSettings?.status().then(t=>{e&&g(t.configured)}).catch(()=>{e&&g(!1)})};return t(),window.addEventListener("vibelet.speech.changed",t),()=>{e=!1,window.removeEventListener("vibelet.speech.changed",t)}},[]);const y=o.useRef(null),v=o.useRef(!0),b=o.useRef(e);b.current=e;const x=s(i().language),w="en"!==x;return o.useEffect(()=>(v.current=!0,()=>{v.current=!1,y.current?.stream.getTracks().forEach(e=>e.stop()),"recording"===y.current?.state&&y.current.stop()}),[]),f&&a.transcribeAudio&&"true"===t().getItem("vibelet.web.voice.enabled")?r.jsxs("span",{className:"voice-input-control","data-voice-state":c,children:[r.jsx("button",{className:"icon-button",type:"button",disabled:"idle"!==c&&"recording"!==c,"aria-label":w?"recording"===c?"停止录音":"语音输入":"recording"===c?"Stop recording":"Voice input",title:"recording"===c?w?"停止录音":"Stop recording":w?"语音输入(最长 60 秒)":"Voice input (up to 60 seconds)",onClick:()=>{"recording"===c?"recording"===y.current?.state&&y.current.stop():(async()=>{if(!m.current){m.current=!0,u(""),l("starting");try{const t=await navigator.mediaDevices.getUserMedia({audio:!0});if(!v.current)return void t.getTracks().forEach(e=>e.stop());let n;try{n=new MediaRecorder(t,{mimeType:"audio/webm"})}catch(e){throw t.getTracks().forEach(e=>e.stop()),e}y.current=n;const s=[];let i=0;n.ondataavailable=e=>{s.push(e.data),i+=e.data.size,i>9437184&&"recording"===n.state&&n.stop()};const r=setTimeout(()=>{"recording"===n.state&&n.stop()},6e4);n.onstop=async()=>{if(clearTimeout(r),t.getTracks().forEach(e=>e.stop()),y.current=null,v.current){l("transcribing");try{const e=new Blob(s,{type:"audio/webm"}),t=await(a.speechSettings?.status()),n="system"===t?.engine||"volcengine"===t?.engine?await async function(e){const t=new AudioContext;try{const n=await t.decodeAudioData(await e.arrayBuffer());if(n.duration>61||n.duration<=0)throw new Error("Invalid recording duration");const s=new Uint8Array(44+2*n.length),i=new DataView(s.buffer),r=(e,t)=>[...t].forEach((t,n)=>i.setUint8(e+n,t.charCodeAt(0)));r(0,"RIFF"),i.setUint32(4,s.length-8,!0),r(8,"WAVEfmt "),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,n.sampleRate,!0),i.setUint32(28,2*n.sampleRate,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),r(36,"data"),i.setUint32(40,s.length-44,!0);const o=Array.from({length:n.numberOfChannels},(e,t)=>n.getChannelData(t));for(let e=0;e<n.length;e++){const t=Math.max(-1,Math.min(1,o.reduce((t,n)=>t+n[e],0)/o.length));i.setInt16(44+2*e,t*(t<0?32768:32767),!0)}return s}finally{await t.close()}}(e):new Uint8Array(await e.arrayBuffer()),i=await a.transcribeAudio(n,"zh-TW"===x?"zh-TW":w?"zh":"en");if(v.current)if(i.trim()){u("");let e=i;const t=await(a.polishSettings?.status().catch(()=>{}));if(!v.current)return;if(t?.settings.enabled&&a.polishTranscript){l("polishing");try{const t=await a.polishTranscript(i);e=t.text,v.current&&"fallback"===t.status&&u(w?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}catch{v.current&&u(w?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}}v.current&&b.current(e)}else u(w?"没有识别到语音,请靠近麦克风重试。":"No speech detected. Try speaking closer to the microphone.")}catch{v.current&&u(w?"语音识别失败,请检查麦克风权限、语音设置和网络。":"Speech failed. Check microphone access, speech settings and connection.")}finally{m.current=!1,v.current&&l("idle")}}};try{n.start(1e3)}catch(e){throw clearTimeout(r),t.getTracks().forEach(e=>e.stop()),y.current=null,e}l("recording")}catch{m.current=!1,v.current&&(l("idle"),u(w?"无法开启麦克风,请检查系统权限。":"Microphone unavailable. Check system permissions."))}}})()},children:"recording"===c?r.jsx(qe,{"aria-hidden":"true"}):"idle"===c?r.jsx(ye,{"aria-hidden":"true"}):r.jsx(me,{className:"voice-input-spinner","aria-hidden":"true"})}),"idle"!==c&&r.jsxs("span",{className:"voice-input-progress",children:["recording"===c&&r.jsxs("span",{className:"voice-input-wave","aria-hidden":"true",children:[r.jsx("i",{}),r.jsx("i",{}),r.jsx("i",{})]}),r.jsx("span",{role:"status","aria-live":"polite",children:"recording"===c?w?"录音中":"Recording":"polishing"===c?w?"润色中":"Polishing":"transcribing"===c?w?"识别中":"Transcribing":w?"开启麦克风":"Opening microphone"}),"recording"===c&&r.jsxs("span",{className:"voice-input-time","aria-hidden":"true",children:["00:",String(h).padStart(2,"0")]})]}),"idle"===c&&d&&r.jsx("span",{className:"voice-input-error",role:"alert",children:d})]}):null}function Ms({activeQueue:e,queueControls:t,agent:s,attachments:i,approvalMode:a,activeModelOptions:c,busy:l,sending:d,responding:u,onStop:h,draft:p,effort:m,fastMode:f,model:g,phase:y,quickReplies:v,onQuickRepliesChange:b,quickRepliesOpen:x=!1,onQuickRepliesOpenChange:w,onSendQuickReply:S,sendShortcut:k,skills:I,uploadBusy:C,t:j,onApprovalModeChange:R,onCancelQueuedTurn:M,onDraftChange:E,onEffortChange:T,onFastModeChange:A,onModelChange:N,onRefreshSkills:P,onRemoveAttachment:D,onOpenRemoteFile:F,onSubmit:L,onUploadFiles:q}){const O=o.useRef(null),$=o.useRef(null),[z]=o.useState(()=>"desktop"===n().kind||(window.matchMedia?.("(pointer: fine)").matches??!1)),[_,B]=o.useState(!1),[H,W]=o.useState(!1),[K,Q]=o.useState(!1),[U,V]=o.useState(""),[J,Z]=o.useState(""),Y=o.useRef(null),ee=o.useRef(null),te="connected"===y,ne=o.useMemo(()=>pt(s),[s]),se=o.useMemo(()=>ft(p),[p]),re=se?`${se.start}:${se.end}:${se.keyword}`:"",oe=Boolean(K||se&&J!==re),ae=o.useMemo(()=>function(e,t,n=8){const s=mt(t);return(s?e.filter(e=>e.name.includes(s)||e.title.toLowerCase().includes(s)).sort((e,t)=>gt(e,s)-gt(t,s)):[...e]).slice(0,n)}(ne,se?.keyword??"",8),[ne,se?.keyword]),ce=o.useMemo(()=>It(p),[p]),le=ce?`${ce.start}:${ce.end}:${ce.keyword}`:"",de=Boolean(!oe&&(H||ce&&U!==le)),ue=o.useMemo(()=>function(e,t,n=8){const s=St(t);return(s?e.filter(e=>St(e.name).includes(s)):e).slice(0,n)}(I,ce?.keyword??"",8),[ce?.keyword,I]),he=o.useMemo(()=>function(e){return[{value:"normal",label:e.approvalNormal,description:e.approvalNormalDescription,icon:Pe},{value:"plan",label:e.approvalPlan,description:e.approvalPlanDescription,icon:De},{value:"acceptEdits",label:e.approvalEdits,description:e.approvalEditsDescription,icon:X},{value:"autoApprove",label:e.approvalAuto,description:e.approvalAutoDescription,icon:We}]}(j),[j]),pe=o.useMemo(()=>function(e){return[{value:"",label:e.effort,description:e.useDaemonDefault,icon:ie},{value:"minimal",label:e.effortMinimal,icon:ie},{value:"low",label:e.effortLow,icon:ie},{value:"medium",label:e.effortMedium,icon:ie},{value:"high",label:e.effortHigh,icon:ie},{value:"xhigh",label:e.effortXHigh,icon:ie},{value:"max",label:e.effortMax,icon:ie},{value:"ultra",label:e.effortUltra,icon:ie}]}(j),[j]),me=c.find(e=>e.value===g),fe=me?.label??(g||j.defaultOption),ge=he.find(e=>e.value===a)?.label??a,ye=pe.find(e=>e.value===m)?.label??m,ve=c.map(e=>({value:e.value,label:e.label,description:e.desc,icon:G}));ve.some(e=>""===e.value)||ve.unshift({value:"",label:j.defaultOption,description:j.useDaemonDefaultModel,icon:G}),o.useEffect(()=>{ce||(Y.current=null,V(""),W(!1))},[ce]),o.useEffect(()=>{se||(ee.current=null,Z(""),Q(!1))},[se]);const be=()=>{const e=function(e,t){if(!t)return e;const n=It(e);if(!n||n.start!==t.triggerStart)return e;const s=n.start>t.draftBeforeInsertion.length?" ":"";return e.slice(0,n.start)!==`${t.draftBeforeInsertion}${s}`?e:t.draftBeforeInsertion}(p,Y.current);Y.current=null,e!==p&&E(e),le&&V(le),W(!1),$.current?.focus()},xe=()=>{const e=function(e,t){return t&&ft(e)?t.draftBeforeInsertion:e}(p,ee.current);ee.current=null,e!==p&&E(e),re&&Z(re),Q(!1),$.current?.focus()},we=e=>{const t=ft(p),n=function(e,t,n){return t?function(e,t,n){return`${e.slice(0,t.start)}${yt(n,"")}${e.slice(t.end)}`}(e,t,n):`${yt(n,e)}${e}`}(p,t,e);E(n),ee.current=null,Q(!1),Z(""),$.current?.focus()},Se=e=>{const t=It(p),n=t?function(e,t,n){return`${e.slice(0,t.start)}$${St(n)} ${e.slice(t.end)}`}(p,t,e.name):p.trim().length?`${p}${/\s$/.test(p)?"":" "}$${e.name} `:`$${e.name} `;E(n),Y.current=null,W(!1),V(""),$.current?.focus()},ke=function({context:e,count:t,onSelect:n,onClose:s}){const i=o.useId(),[r,a]=o.useState({context:"",index:0}),c=r.context===e?Math.min(r.index,Math.max(0,t-1)):0,l=t=>a({context:e,index:t});return{listId:i,selectedIndex:c,selectIndex:l,handleKeyDown:i=>!(!e||i.nativeEvent.isComposing||229===i.nativeEvent.keyCode||i.metaKey||i.ctrlKey||i.altKey||i.shiftKey||("Escape"===i.key?(i.preventDefault(),i.stopPropagation(),s(),0):!t||("ArrowDown"===i.key||"ArrowUp"===i.key?(i.preventDefault(),i.stopPropagation(),l((c+("ArrowDown"===i.key?1:-1)+t)%t),0):"Enter"!==i.key&&"Tab"!==i.key||(i.preventDefault(),i.stopPropagation(),n(c),0))))}}({context:oe?`command:${re}:${ae.map(e=>e.name).join(",")}`:de?`skill:${le}:${ue.map(e=>`${e.source}:${e.name}`).join(",")}`:"",count:oe?ae.length:de?ue.length:0,onSelect:e=>oe?we(ae[e]):Se(ue[e]),onClose:oe?xe:be});return r.jsxs("form",{className:"composer "+(_?"dragging":""),onDragEnter:e=>{e.preventDefault(),B(!0)},onDragLeave:()=>B(!1),onDragOver:e=>e.preventDefault(),onDrop:e=>{(async e=>{e.preventDefault(),B(!1),te&&await q(e.dataTransfer.files)})(e)},onSubmit:e=>{L(e)},children:[r.jsx(Ss,{queue:e,controls:t,busy:l,t:j,onCancel:M}),x&&r.jsx(ks,{replies:v,disabled:!te||l||d||C,onSend:S,onChange:b,t:j}),r.jsx(xs,{visible:de,skills:ue,listId:ke.listId,selectedIndex:ke.selectedIndex,onHighlight:ke.selectIndex,onClose:be,onSelect:Se,t:j}),r.jsx(ws,{visible:oe,commands:ae,listId:ke.listId,selectedIndex:ke.selectedIndex,onHighlight:ke.selectIndex,onClose:xe,onSelect:we,t:j}),r.jsx(js,{textareaRef:$,autoFocus:z,"aria-controls":oe||de?ke.listId:void 0,"aria-activedescendant":oe&&ae.length||de&&ue.length?`${ke.listId}-${ke.selectedIndex}`:void 0,"aria-autocomplete":"list",value:p,onValueChange:E,onPaste:e=>{(async e=>{te&&e.clipboardData.files.length&&await q(e.clipboardData.files)})(e)},onKeyDown:e=>{ke.handleKeyDown(e)||"Enter"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||dt(k,e)&&(e.preventDefault(),e.repeat||L())},placeholder:j.messagePlaceholder,rows:3,disabled:!te}),r.jsx(ys,{attachments:i,uploadBusy:C,onRemove:D,onOpen:F,t:j}),r.jsxs("div",{className:"composer-toolbar",children:[r.jsxs("div",{className:"composer-scroll-controls",children:[r.jsxs("div",{className:"composer-leading-controls",children:[r.jsx(Rs,{onTranscript:e=>E(p?`${p} ${e}`:e)}),r.jsx("button",{type:"button",className:"icon-button",onClick:()=>O.current?.click(),title:j.uploadFiles,"aria-label":j.uploadFiles,disabled:!te||C,children:r.jsx(Ce,{"aria-hidden":"true"})}),v.length>0||b?r.jsx("button",{className:"icon-button quick-replies-toggle "+(x?"selected":""),type:"button",title:x?j.hideQuickReplies:j.showQuickReplies,"aria-label":x?j.hideQuickReplies:j.showQuickReplies,"aria-pressed":x,onClick:()=>w?.(!x),children:r.jsx(Fe,{"aria-hidden":"true"})}):null,r.jsx("button",{className:"icon-button "+(de?"selected":""),type:"button",title:j.skills,"aria-label":j.skills,onClick:()=>{if(de)be();else{if(P(),V(""),!It(p)){const e=0===p.length||/\s$/.test(p)?"":" ";Y.current={draftBeforeInsertion:p,triggerStart:p.length+e.length},E(`${p}${e}$`)}W(!0),$.current?.focus()}},disabled:!te||C,children:r.jsx(We,{"aria-hidden":"true"})}),r.jsx("button",{className:"icon-button "+(oe?"selected":""),type:"button",title:j.commands,"aria-label":j.commands,onClick:()=>{oe?xe():(Z(""),ft(p)||0!==p.length||(ee.current={draftBeforeInsertion:p},E("/")),Q(!0),$.current?.focus())},disabled:!te||C,children:r.jsx(Le,{"aria-hidden":"true"})})]}),r.jsx("input",{ref:O,type:"file",multiple:!0,hidden:!0,onChange:e=>{(async(e,t)=>{await q(e),t.value=""})(e.currentTarget.files,e.currentTarget)}}),r.jsxs("div",{className:"composer-control-strip",children:[r.jsx(vs,{portal:!0,icon:"autoApprove"===a?We:Pe,label:ge,menuLabel:j.approvalMode,blendBackground:!0,options:he,value:a,onSelect:R,wide:!0}),r.jsx(vs,{portal:!0,icon:G,label:fe,menuLabel:j.model,tooltipHoverDelay:1500,options:ve,value:g,onSelect:N,align:"right",wide:!0}),r.jsx(vs,{portal:!0,icon:ie,label:ye||j.effort,menuLabel:j.effort,options:pe,value:m,onSelect:T,align:"right"}),r.jsx(vs,{portal:!0,icon:We,label:f?j.fast:j.normal,menuLabel:j.fastMode,options:[{value:"off",label:j.normal,description:j.standardExecution,icon:ie},{value:"on",label:j.fast,description:j.preferFasterResponses,icon:We}],value:f?"on":"off",onSelect:e=>A("on"===e),align:"right",selected:f,wide:!0})]})]}),r.jsx(Cs,{connected:te,busy:l,sending:d,responding:u,hasDraft:!!p.trim(),shortcut:k,onStop:h,t:j})]})]})}function Es({terminals:e,t}){const[n,s]=o.useState(Date.now),i=e?.length??0;return o.useEffect(()=>{if(!i)return;s(Date.now());const e=window.setInterval(()=>s(Date.now()),1e3);return()=>window.clearInterval(e)},[i]),i?r.jsxs("details",{className:"background-terminals",children:[r.jsxs("summary",{children:[r.jsx($e,{"aria-hidden":"true"}),r.jsx("span",{role:"status",children:t.backgroundTerminalsRunning(i)}),r.jsx(z,{className:"background-terminal-chevron","aria-hidden":"true"})]}),r.jsx("p",{children:t.backgroundTerminalsHint}),r.jsx("ul",{children:e.map(e=>{const s=Date.parse(e.startedAt),i=Number.isFinite(s)?Math.max(0,Math.floor((n-s)/1e3)):0;return r.jsxs("li",{children:[r.jsxs("span",{children:[t.backgroundTerminalLabel," #",e.id]}),r.jsxs("time",{children:[Math.floor(i/60),":",String(i%60).padStart(2,"0")]})]},e.id)})})]}):null}async function Ts(e){const t=n().writeClipboardText;if(t)return t(e);try{if(navigator.clipboard?.writeText)return void(await navigator.clipboard.writeText(e))}catch{}const s=document.activeElement,i=window.getSelection(),r=i?Array.from({length:i.rangeCount},(e,t)=>i.getRangeAt(t).cloneRange()):[],o=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement?[s.selectionStart,s.selectionEnd,s.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(),s instanceof HTMLElement&&s.focus({preventScroll:!0}),o&&(s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement)&&null!==o[0]&&null!==o[1]&&s.setSelectionRange(o[0],o[1],o[2]??void 0),i){i.removeAllRanges();for(const e of r)i.addRange(e)}}}function As(e,t){const[n,s]=o.useState(null),i=o.useRef(null);return o.useEffect(()=>()=>{null!==i.current&&window.clearTimeout(i.current)},[]),{copyText:o.useCallback(async n=>{try{await Ts(n),s({message:e,tone:"success"})}catch{s({message:t,tone:"error"})}null!==i.current&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>s(null),2400)},[t,e]),feedback:n}}function Ns({feedback:e}){if(!e)return null;const t="success"===e.tone?$:He;return r.jsxs("div",{className:`copy-feedback ${e.tone}`,role:"status",children:[r.jsx(t,{"aria-hidden":"true"}),e.message]})}function Ps({message:e,retryLabel:t,onRetry:n,onDismiss:s,closeLabel:i}){return r.jsxs("div",{className:"notice error chat-error-notice",role:"alert",children:[s?r.jsx("button",{type:"button",className:"chat-notice-dismiss","aria-label":i,title:i,onClick:s,children:r.jsx(He,{"aria-hidden":"true"})}):r.jsx(H,{"aria-hidden":"true"}),r.jsx("span",{children:e}),r.jsxs("button",{className:"chat-notice-retry",onClick:n,type:"button",children:[r.jsx(je,{"aria-hidden":"true"}),t]})]})}function Ds({label:e}){return r.jsxs("div",{className:"history-loading-state","aria-busy":"true","aria-label":e,role:"status",children:[r.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),r.jsxs("div",{className:"history-loading-copy",children:[r.jsx("strong",{children:e}),r.jsx("span",{"aria-hidden":"true"}),r.jsx("span",{"aria-hidden":"true"}),r.jsx("span",{"aria-hidden":"true"})]})]})}function Fs({failedSend:e,onRetry:t,onDismiss:n,t:s}){const i={network:s.sendFailedNetwork,timeout:s.sendFailedTimeout,reconnect:s.sendFailedReconnect,permission:s.sendFailedPermission,subscription:s.sendFailedSubscription,"missing-resource":s.sendFailedMissingResource,unknown:s.sendFailedUnknown}[e.kind];return r.jsxs("div",{className:"failed-send-notice",role:"alert",children:[r.jsx(H,{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:"timeout"===e.kind?s.sendUnconfirmed:s.sendFailed}),i,e.message&&r.jsx("blockquote",{className:"failed-send-content",children:e.message}),!!e.images?.length&&r.jsx("small",{children:s.failedSendImages(e.images.length)})]}),r.jsxs("button",{disabled:e.retrying,onClick:t,type:"button",children:[r.jsx(je,{"aria-hidden":"true",className:e.retrying?"spin":void 0}),e.retrying?s.retrying:s.retrySend]}),n&&r.jsx("button",{className:"chat-notice-dismiss",onClick:n,type:"button","aria-label":s.close,title:s.close,children:r.jsx(He,{"aria-hidden":"true"})})]})}function Ls({label:e,onClick:t}){return r.jsx("button",{className:"scroll-latest-button",type:"button","aria-label":e,title:e,onClick:t,children:r.jsx(D,{"aria-hidden":"true"})})}const qs=/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,Os=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\u00AD\u061C\u180E\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g,$s=new Set(["","{}","[]","null","undefined",'""']);function zs(e){return e.replace(/\s+/g," ").trim()}function _s(e,t){return"string"==typeof e[t]?e[t]:""}function Bs(e,t){return"number"==typeof e[t]?e[t]:void 0}function Hs(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function Ws(e){const t=[],n=_s(e,"file_path")||_s(e,"filePath");n&&t.push({label:"Path",value:n,isFilePath:!0});const s=Bs(e,"offset"),i=Bs(e,"limit");if(void 0!==s||void 0!==i){const e=[];void 0!==s&&e.push(`line ${s+1}`),void 0!==i&&e.push(`to ${void 0!==s?s+i:i}`),t.push({label:"Range",value:e.join(" ")})}return t}function Ks(e){const t=function(e){return"string"!=typeof e?"":e.replace(/\r\n?/g,"\n").replace(qs,"").replace(Os,"").trim()}(e);return $s.has(t)?"":t}function Qs(e){const t=Ks(e);if(!t)return"";try{const e=JSON.parse(t);if(e&&"object"==typeof e&&!Array.isArray(e)){const t="string"==typeof e.query?zs(e.query):"";if(t)return t;const n="string"==typeof e.command?zs(e.command):"";if(n)return n;const s="string"==typeof e.description?zs(e.description):"";if(s)return s}}catch{}return zs(t)}function Us(e){return"tool"===e.role||"info"===e.type&&!/^Error:/i.test(e.content.trim())}function Vs(e){const t=[];for(const n of e){const e=n.toolName?.trim();e&&!t.includes(e)&&t.push(e)}return t.length?t.join(", "):e.map(e=>Qs(e.content)).find(Boolean)??""}function Gs(e,t){return e.historyKey?e.historyKey:`${e.timestamp??e.toolName??e.content.slice(0,24)??"message"}:${t}`}const Js="<oai-mem-citation>",Zs={en:{rewind:"Rewind to here",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:"回退到这里",confirmRewind:"从这条消息之前建立新分支继续?原会话会归档保留,所选消息会填入草稿,不会自动发送,文件不会改变。",incompleteHistory:"此会话还有未加载的历史,暂时不能回退,以免选错消息位置。",unavailable:"这条消息已不可用。",rewindFailed:"无法回退此会话。",invalidResponse:"回退响应无效。",mediaError:"此格式无法在这里播放,请下载后打开。",remoteSettings:"会话与远程设备",htmlPreview:"HTML 预览",pdfPreview:"PDF 预览",audioPreview:"音频预览",videoPreview:"视频预览"},"zh-TW":{rewind:"回退到這裡",confirmRewind:"從這則訊息之前建立新分支繼續?原對話會封存保留,所選訊息會填入草稿,不會自動傳送,檔案不會改變。",incompleteHistory:"此對話還有未載入的歷史,暫時不能回退,以免選錯訊息位置。",unavailable:"這則訊息已無法使用。",rewindFailed:"無法回退此對話。",invalidResponse:"回退回應無效。",mediaError:"此格式無法在這裡播放,請下載後開啟。",remoteSettings:"對話與遠端裝置",htmlPreview:"HTML 預覽",pdfPreview:"PDF 預覽",audioPreview:"音訊預覽",videoPreview:"影片預覽"}};function Ys(){return Zs[s(i().language)]}function Xs({position:e,onClose:t,onCopy:n,onRewind:s,onToggleSource:i,sourceOpen:c,t:l}){const d=o.useRef(null),u=o.useRef(t);u.current=t,o.useLayoutEffect(()=>{const t=d.current,n=document.activeElement,s=t.getBoundingClientRect();t.style.left=`${Math.max(8,Math.min(e.x,innerWidth-s.width-8))}px`,t.style.top=`${Math.max(8,Math.min(e.y,innerHeight-s.height-8))}px`,t.querySelector("button")?.focus({preventScroll:!0});const i=()=>u.current(),r=e=>{t.contains(e.target)||i()};return document.addEventListener("pointerdown",r),document.addEventListener("scroll",i,!0),window.addEventListener("resize",i),window.addEventListener("blur",i),()=>{document.removeEventListener("pointerdown",r),document.removeEventListener("scroll",i,!0),window.removeEventListener("resize",i),window.removeEventListener("blur",i),t.contains(document.activeElement)&&n?.focus({preventScroll:!0})}},[e]);const h=e=>{t(),e()};return a.createPortal(r.jsxs("div",{ref:d,role:"menu","aria-label":l.messageActions,className:"session-context-menu message-context-menu",style:{left:e.x,top:e.y},onPointerDown:e=>e.stopPropagation(),onContextMenu:e=>{e.preventDefault(),e.stopPropagation()},onKeyDown:e=>{e.stopPropagation();const n=Array.from(d.current.querySelectorAll("button:not(:disabled)")),s=n.indexOf(document.activeElement);["Escape","Tab","ArrowDown","ArrowUp","Home","End"].includes(e.key)&&e.preventDefault(),"Escape"!==e.key&&"Tab"!==e.key||t(),"ArrowDown"===e.key&&n[(s+1)%n.length]?.focus(),"ArrowUp"===e.key&&n[(s-1+n.length)%n.length]?.focus(),"Home"===e.key&&n[0]?.focus(),"End"===e.key&&n.at(-1)?.focus()},children:[s&&r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>h(s),children:[r.jsx(Re,{"aria-hidden":"true"}),Ys().rewind]}),r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>h(n),children:[r.jsx(U,{"aria-hidden":"true"}),l.copyMessage]}),r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>h(i),children:[r.jsx(Q,{"aria-hidden":"true"}),c?l.hideMarkdownSource:l.viewMarkdownSource]})]}),document.body)}function ei({message:e,t}){return r.jsx("pre",{className:"message-markdown-source",role:"region","aria-label":t.markdownSource,children:e.content})}function ti({field:e}){return e.isDiff?r.jsxs("div",{className:"tool-field diff",children:[r.jsx("span",{children:e.label}),e.diffOld?r.jsxs("pre",{className:"tool-diff old",children:[r.jsx("b",{children:"-"}),e.diffOld]}):null,e.diffNew?r.jsxs("pre",{className:"tool-diff new",children:[r.jsx("b",{children:"+"}),e.diffNew]}):null]}):r.jsxs("div",{className:`tool-field ${e.isCode?"code":""} ${e.isFilePath?"path":""}`,children:[r.jsx("span",{children:e.label}),r.jsx("pre",{children:e.value})]})}function ni({message:e,onCopy:t,t:n}){const s=function(e,t){if(!t)return[];switch((e??"").toLowerCase()){case"read":return Ws(t);case"write":{const e=Ws(t),n=_s(t,"content");return n&&e.push({label:"Content",isDiff:!0,value:"",diffNew:Hs(n,500)}),e}case"edit":{const e=Ws(t),n=_s(t,"old_string")||_s(t,"oldString"),s=_s(t,"new_string")||_s(t,"newString");return(n||s)&&e.push({label:"Change",isDiff:!0,value:"",diffOld:Hs(n,300),diffNew:Hs(s,300)}),e}case"bash":{const e=_s(t,"command");return e?[{label:"Command",value:e,isCode:!0}]:[]}case"websearch":{const e=_s(t,"query");return e?[{label:"Query",value:e}]:[]}case"webfetch":{const e=[],n=_s(t,"url");n&&e.push({label:"URL",value:n});const s=_s(t,"prompt");return s&&e.push({label:"Prompt",value:Hs(s,200)}),e}case"glob":{const e=_s(t,"pattern");return e?[{label:"Pattern",value:e}]:[]}case"grep":{const e=[],n=_s(t,"pattern");n&&e.push({label:"Pattern",value:n,isCode:!0});const s=_s(t,"path");return s&&e.push({label:"In",value:s,isFilePath:!0}),e}default:{const e=[],n=_s(t,"command");if(n)return[{label:"Command",value:n,isCode:!0}];const s=_s(t,"file_path")||_s(t,"filePath");s&&e.push({label:"Path",value:s,isFilePath:!0});const i=_s(t,"description");i&&e.push({label:"Description",value:Hs(i,200)});const r=_s(t,"query");r&&e.push({label:"Query",value:r});const o=_s(t,"url");return o&&e.push({label:"URL",value:o}),e}}}(e.toolName,e.toolInput),i=Qs(e.content),o=Ks(e.content),a=function(e){return Ks(e).length>0}(e.content)&&!s.length,c=e.toolName??n.tool;return r.jsxs("section",{className:"tool-detail-card",children:[r.jsxs("header",{children:[r.jsx("span",{className:"tool-detail-icon",children:r.jsx($e,{"aria-hidden":"true"})}),r.jsxs("div",{children:[r.jsx("strong",{children:c}),i?r.jsx("small",{title:i,children:i}):null]}),r.jsx("button",{className:"icon-button",onClick:()=>t(e.content),type:"button",title:n.copyOutput,children:r.jsx(U,{"aria-hidden":"true"})})]}),s.length?r.jsx("div",{className:"tool-fields",children:s.map((e,t)=>r.jsx(ti,{field:e},`${e.label}:${t}`))}):null,a?r.jsx("pre",{className:"json-box compact",children:o}):null]})}function si({messages:e,showHeader:t=!0,onClose:n,onCopy:s,t:i}){if(!e.length)return null;const o=e.filter(e=>"tool"===e.role).length||e.length,a=i.toolCallCount(o),c=Vs(e),l=e.map(e=>e.content).join("\n\n");return r.jsxs("section",{className:"tool-inline-panel","aria-label":i.toolDetails,children:[t?r.jsxs("header",{className:"inline-detail-header",children:[r.jsxs("div",{className:"inline-detail-title",children:[r.jsx("strong",{children:a}),r.jsx("span",{title:c,children:c||i.toolDetail})]}),r.jsxs("div",{className:"row-actions",children:[r.jsx("button",{className:"icon-button",onClick:()=>s(l),type:"button",title:i.copyOutput,children:r.jsx(U,{"aria-hidden":"true"})}),r.jsx("button",{className:"icon-button",onClick:n,type:"button",title:i.closeToolDetails,children:r.jsx(He,{"aria-hidden":"true"})})]})]}):null,r.jsx("div",{className:"tool-detail-list",children:e.map((e,t)=>r.jsx(ni,{message:e,onCopy:s,t:i},`${e.historyKey??e.timestamp??e.toolName??"tool"}:${t}`))})]})}const ii=o.lazy(async()=>m(()=>import("./mermaid-O7DHMXV3-DTyL8PSp.js").then(e=>e.a),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.MessageMarkdown})));function ri({label:e}){return r.jsxs("span",{className:"message-replying-indicator","aria-label":e,role:"status",children:[r.jsxs("span",{"aria-hidden":"true",className:"message-replying-dots",children:[r.jsx("i",{}),r.jsx("i",{}),r.jsx("i",{})]}),r.jsx("span",{children:e})]})}function oi({activeMatch:e,baseCwd:t,message:n,onCopy:s,onRewind:i,onCloseTool:a,onOpenRemoteFile:c,onToggleSource:l,onToggleTool:d,sourceOpen:u,toolOpen:h,replying:p,queued:f,t:g}){const y="assistant"===n.role?function(e){let t,n=0;for(const s of e.split("\n")){const i=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(s);if(i){const e=i[1][0];t?e===t.marker&&i[1].length>=t.length&&!i[2].trim()&&(t=void 0):t={marker:e,length:i[1].length}}else if(!t){const t=s.replace(/^ {0,3}/,""),i=t.startsWith("<oai-mem")&&Js.startsWith(t);if(t.startsWith(Js)||i){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}(n.content):n.content,[v,b]=o.useState(null),x="user"===n.role&&"info"!==n.type?i:void 0,w=function(e,t,n=!1){const s="interrupted"===e.delivery?"interrupted":n?"queued":"accepted"===e.delivery?"delivered":e.localDelivery;if("user"!==e.role||!s)return null;const i="浏览器"===t.browser?{queued:"排队中",interrupted:"已中断",sending:"发送中",delivered:"已送达",failed:"未确认送达",hint:"配对电脑已接收,可能仍在等待处理。"}:"瀏覽器"===t.browser?{queued:"排隊中",interrupted:"已中斷",sending:"傳送中",delivered:"已送達",failed:"未確認送達",hint:"配對電腦已接收,可能仍在等待處理。"}:{queued:"Queued",interrupted:"Interrupted",sending:"Sending",delivered:"Delivered",failed:"Delivery unconfirmed",hint:"Received by the paired computer; processing may still be pending."};return{state:s,label:i[s],title:"delivered"===s?i.hint:i[s]}}(n,g,f),S=(n.images??[]).filter(e=>jn(e,"")||/^(?:data:image\/|https?:\/\/|blob:)/i.test(e)),k="tool"===n.role?Qs(n.content):"";return r.jsxs("article",{className:`message ${n.role} ${"info"===n.type?"info":""} ${e?"match":""}`,onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),b({x:e.clientX,y:e.clientY})},onKeyDown:e=>{if("ContextMenu"!==e.key&&(!e.shiftKey||"F10"!==e.key))return;e.preventDefault(),e.stopPropagation();const t=e.currentTarget.getBoundingClientRect();b({x:t.left+16,y:t.top+16})},children:[v&&r.jsx(Xs,{position:v,onClose:()=>b(null),onCopy:()=>s(n.content),onRewind:x,onToggleSource:l,sourceOpen:u,t:g}),r.jsxs("div",{className:"message-meta",children:[r.jsx("span",{children:on(n,g)}),r.jsxs("div",{className:"message-meta-side",children:[w&&r.jsx("span",{className:"message-delivery","data-state":w.state,role:"status",title:w.title,children:w.label}),r.jsx("time",{children:rn(n.timestamp,Date.now(),g)})]})]}),u?r.jsx(ei,{message:n,t:g}):"tool"===n.role?r.jsxs("button",{className:"tool-inline-summary","aria-expanded":h,onClick:d,type:"button",children:[r.jsxs("span",{children:[r.jsx(Be,{"aria-hidden":"true"}),n.toolName??g.tool]}),k?r.jsx("small",{children:k}):null]}):"assistant"===n.role||"user"===n.role?r.jsx(o.Suspense,{fallback:r.jsx("pre",{children:y}),children:r.jsx(ii,{baseCwd:t,content:n.images?.length?y.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").trim():y,onOpenRemoteFile:c,additionalImages:S})}):r.jsx("pre",{children:n.content}),n.images?.length?r.jsx("div",{className:"message-image-attachments",children:n.images.map(e=>S.includes(e)?r.jsx(gs,{src:e,cwd:t,onOpen:c,gallery:async()=>[...(await m(async()=>{const{collectMessageImages:e}=await import("./collectMessageImages-CyIw_UE5.js");return{collectMessageImages:e}},__vite__mapDeps([4,1,2]))).collectMessageImages(n.content,t),...S.map(e=>({src:e,cwd:t}))]},e):r.jsxs("button",{type:"button",className:"message-file-attachment",title:e,onClick:()=>c(e,t),children:[r.jsx(we,{size:16,"aria-hidden":"true"}),mn(e)]},e))}):null,"tool"===n.role&&h?r.jsx(si,{messages:[n],onClose:a,onCopy:s,t:g}):null,p&&r.jsx(ri,{label:g.replyingMessage}),r.jsxs("div",{className:"message-actions","aria-label":g.messageActions,role:"group",children:[x&&r.jsx("button",{type:"button",onClick:x,title:Ys().rewind,"aria-label":Ys().rewind,children:r.jsx(Re,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":g.copyMessage,onClick:()=>s(u?n.content:y),title:g.copyMessage,type:"button",children:r.jsx(U,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":g.viewMarkdownSource,"aria-expanded":u,onClick:l,title:u?g.hideMarkdownSource:g.viewMarkdownSource,type:"button",children:r.jsx(Q,{"aria-hidden":"true"})})]})]})}function ai(e,t){return JSON.stringify([...Object.values(e),...Object.values(t)].map(e=>JSON.stringify([e.sessionId,e.requestId])).sort())}function ci({activeMatch:e,expanded:t,messages:n,onToggle:s,t:i}){const o=Vs(n),a=function(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 i of e.filter(e=>"tool"===e.role)){const e=i.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(" · ")}(n,i)||o;return r.jsx("button",{className:`tool-group-bubble ${e?"match":""} ${t?"expanded":""}`,type:"button",onClick:s,"aria-expanded":t,"aria-label":o?`${a}: ${o}`:a,children:r.jsxs("span",{className:"tool-group-header",children:[r.jsxs("span",{className:"tool-group-title",children:[r.jsx(_,{className:"tool-group-chevron","aria-hidden":"true"}),r.jsx("strong",{children:a})]}),o?r.jsx("span",{className:"tool-group-summary",children:o}):null]})})}const li=o.memo(function({message:e,index:t,actions:n,messageRefs:s,baseCwd:i,canRewind:o,activeMatch:a,replying:c,queued:l,sourceOpen:d,toolOpen:u,setOpenSourceKey:h,setOpenToolKey:p,copyText:m,failedSend:f,t:g}){const y=Gs(e,t);return r.jsxs("div",{className:`message-frame ${e.role} ${"info"===e.type?"info":""}`,"data-message-index":t,ref:e=>{s.current[t]=e},children:[r.jsx(oi,{activeMatch:a,baseCwd:i,message:e,replying:c,queued:l,onCopy:m,onRewind:o?()=>n.current.onRewindMessage(e):void 0,onCloseTool:()=>p(null),onOpenRemoteFile:(e,t)=>n.current.onOpenRemoteFile(e,t),onToggleSource:()=>h(e=>e===y?null:y),onToggleTool:()=>p(e=>e===y?null:y),sourceOpen:d,toolOpen:u,t:g}),f?r.jsx(Fs,{failedSend:f,onRetry:()=>{n.current.retry()},onDismiss:()=>n.current.onDismissFailedSend?.(),t:g}):null]},y)}),di=o.memo(function({items:e,activeQueue:t,actions:n,messageRefs:s,activeMatchedMessageIndex:i,baseCwd:o,canRewind:a,hiddenLaterItemCount:c,replyingMessageIndex:l,openSourceKey:d,openToolKey:u,setOpenSourceKey:h,setOpenToolKey:p,copyText:m,failedSend:f,t:g}){return r.jsx(r.Fragment,{children:e.map(e=>{if("toolGroup"===e.type){const t=e.entries.map(e=>e.message),n=e.entries.some(e=>i===e.index),o=u===e.id;return r.jsx("div",{className:"message-frame tool info",ref:t=>{for(const n of e.entries)s.current[n.index]=t},children:r.jsxs("div",{className:"inline-message-stack",children:[r.jsx(ci,{t:g,activeMatch:n,expanded:o,messages:t,onToggle:()=>p(t=>t===e.id?null:e.id)}),o?r.jsx(si,{messages:t,showHeader:!1,onClose:()=>p(null),onCopy:m,t:g}):null]})},e.id)}const{index:y,message:v}=e,b=Gs(v,y),x=d===b,w=u===b,S=f?.historyKey===v.historyKey?f:null;return r.jsx(li,{message:v,queued:!!t?.some(e=>!!e.clientMessageId&&(v.historyKey===`client:${e.clientMessageId}`||v.localClientMessageId===e.clientMessageId)),index:y,actions:n,messageRefs:s,baseCwd:o,canRewind:a,activeMatch:i===y,replying:0===c&&y===l,sourceOpen:x,toolOpen:w,setOpenSourceKey:h,setOpenToolKey:p,copyText:m,failedSend:S,t:g},b)})})});function ui({activeSession:e,busy:t,errorText:n,failedSend:s,failedSendVisibleInConversation:i,onClearInterrupt:o,onDismissError:a,onDismissFailedSend:c,onRetry:l,onRetryFailedSend:d,t:u}){return r.jsxs("div",{className:"chat-notices","aria-live":"polite",children:[n?r.jsx(Ps,{message:n,retryLabel:u.retry,onRetry:l,closeLabel:u.close,onDismiss:a}):null,s&&!i?r.jsx(Fs,{failedSend:s,onRetry:d,onDismiss:c,t:u}):null,e?.interruptReason?r.jsxs("div",{className:"notice error",role:"alert",children:[r.jsx(We,{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:u.replyStopped})," ",e.interruptReason.humanText||e.interruptReason.kind]}),r.jsx("button",{className:"icon-text-button",disabled:t,onClick:o,type:"button",children:u.clear})]}):null,e?.stallWarning?r.jsxs("div",{className:"notice warning",children:[r.jsx(K,{"aria-hidden":"true"}),r.jsx("span",{children:e.stallWarning.humanText||u.agentMayBeStalled}),r.jsx("button",{className:"chat-notice-dismiss",type:"button","aria-label":u.close,title:u.close,onClick:o,children:r.jsx(He,{"aria-hidden":"true"})})]}):null]})}function hi({title:e,draft:t,label:n,disabled:s,onDraftChange:i,onCommit:a}){const[c,l]=o.useState(!1),[d,u]=o.useState(t),h=o.useRef(null),p=o.useRef(null),m=o.useRef(!1),f=o.useRef(!1);o.useLayoutEffect(()=>{c?(h.current?.focus(),h.current?.select()):m.current&&(m.current=!1,p.current?.focus()),c||(f.current=!1)},[c]);const g=()=>{m.current=!0,l(!1)};return c?r.jsx("input",{ref:h,className:"inline-session-title-input","aria-label":n,value:d,onChange:e=>{u(e.target.value),i(e.target.value)},onBlur:()=>{f.current||(d.trim()&&d.trim()!==e&&a(d),l(!1))},onKeyDown:t=>{t.nativeEvent.isComposing||229===t.keyCode||("Enter"===t.key?(t.preventDefault(),f.current=!0,d.trim()&&d.trim()!==e&&a(d),g()):"Escape"===t.key&&(t.preventDefault(),t.stopPropagation(),f.current=!0,g()))}}):r.jsx("button",{ref:p,type:"button",className:"inline-session-title-button",title:e,"aria-label":`${n}: ${e}`,disabled:s,onClick:()=>{u(e),i(e),l(!0)},children:e})}const pi=o.createContext(null);function mi({matchCount:e,activeMatchIndex:t,query:n,onChange:s,onNext:i,onPrevious:o,onClose:a,t:c}){const l="浏览器"===c.browser?"上一个匹配项":"瀏覽器"===c.browser?"上一個匹配項":"Previous match",d="浏览器"===c.browser?"下一个匹配项":"瀏覽器"===c.browser?"下一個匹配項":"Next match";return r.jsxs("div",{className:"message-search-bar",id:"conversation-message-search",children:[r.jsx(Ee,{"aria-hidden":"true"}),r.jsx("input",{autoFocus:!0,"aria-label":c.searchThisSession,value:n,onChange:e=>s(e.target.value),onKeyDown:e=>{e.nativeEvent.isComposing||(["Enter","ArrowUp","ArrowDown"].includes(e.key)&&(e.preventDefault(),"ArrowUp"===e.key||"Enter"===e.key&&e.shiftKey?o():i()),"Escape"===e.key&&(e.preventDefault(),a()))},placeholder:c.searchThisSession}),r.jsx("span",{className:"message-search-position","aria-live":"polite",title:c.messageSearchMatches(e),children:n.trim()?`${t} / ${e}`:c.allMessages}),r.jsx("button",{type:"button",className:"icon-button mini-button","aria-label":l,title:l,disabled:!e,onClick:o,children:r.jsx(q,{"aria-hidden":"true"})}),r.jsx("button",{type:"button",className:"icon-button mini-button","aria-label":d,title:d,disabled:!e,onClick:i,children:r.jsx(D,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":c.clearMessageSearch,title:c.clearMessageSearch,className:"icon-button mini-button",onClick:a,type:"button",children:r.jsx(He,{"aria-hidden":"true"})})]})}function fi({activeSession:e,agent:t,cwd:s,t:i,onOpenDetails:c,onScrollToStart:l,renameTitle:u,busy:h,onRename:p,onRenameTitleChange:m,onViewChanges:f,search:g}){const[y,v]=o.useState(!1),b=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{const e=()=>{v(!0),requestAnimationFrame(()=>{const e=document.querySelector("#conversation-message-search input");e?.focus(),e?.select()})};return window.addEventListener("vibelet.message-search",e),()=>window.removeEventListener("vibelet.message-search",e)},[]),o.useEffect(()=>{g.query&&v(!0)},[g.query]),o.useLayoutEffect(()=>{!y&&x.current&&(x.current=!1,b.current?.focus())},[y]);const w=e?d(e):i.newSession,S=e?.cwd??(s.trim().length>0&&"."!==s?s:""),k=e?.agent??t,I=o.useContext(pi),C=n().toolbarTarget?.("conversation")??I,j=r.jsxs("div",{className:"chat-header-title-row",onClick:e=>{e.target instanceof Element&&e.target.closest('button,a,input,textarea,[contenteditable="true"],.message-search-bar')||l()},children:[r.jsxs("div",{className:"chat-title-block",children:[r.jsxs("span",{className:"chat-title-line",children:[r.jsx("button",{className:`agent-status-pill chat-session-details-button ${k}`,type:"button",onClick:c,"aria-label":i.details,title:i.details,disabled:!e,children:"codex"===k?"Codex":"Claude"}),r.jsx("h1",{children:e?r.jsx(hi,{title:w,draft:u,label:i.rename,disabled:h,onDraftChange:m,onCommit:p},e.sessionId):w})]}),S?r.jsx("p",{title:S,children:S}):null,e?.branch||e?.diffStat?r.jsxs("div",{className:"header-metadata",children:[e.branch?r.jsx("span",{children:e.branch}):null,e.runtime.state?r.jsx("span",{children:i.runtimeState(e.runtime.state)}):null,e.terminal?.mode?r.jsx("span",{children:e.terminal.mode}):null]}):null]}),r.jsx("button",{"aria-label":i.scrollToConversationStart,className:"chat-scroll-start-target",onClick:l,title:i.scrollToConversationStart,type:"button"}),e&&!y?r.jsxs("button",{className:"chat-changes-button",type:"button","aria-label":i.viewChanges,title:i.viewChanges,onClick:()=>f(e.sessionId),children:[r.jsx(re,{"aria-hidden":"true"}),e.diffStat&&(e.diffStat.additions>0||e.diffStat.deletions>0)?r.jsxs("span",{className:"chat-changes-summary","aria-hidden":"true",children:[r.jsxs("span",{className:"diff-add",children:["+",e.diffStat.additions]}),r.jsxs("span",{className:"diff-del",children:["−",e.diffStat.deletions]})]}):null]}):null,y?r.jsx(mi,{...g,t:i,onClose:()=>{x.current=!0,g.onChange(""),v(!1)}}):r.jsx("button",{ref:b,className:"icon-button chat-search-toggle",type:"button","aria-label":i.searchThisSession,title:nt(i.searchThisSession,"searchMessages"),"aria-expanded":!1,"aria-controls":"conversation-message-search",onClick:()=>v(!0),children:r.jsx(Ee,{"aria-hidden":"true"})})]});return r.jsx("header",{className:"chat-header chat-search-header "+(C?"chat-header-in-titlebar":""),children:C?a.createPortal(j,C):j})}const gi={};function yi(e,t){return vi(e,"boolean"!=typeof gi.includeImageAlt||gi.includeImageAlt,"boolean"!=typeof gi.includeHtml||gi.includeHtml)}function vi(e,t,n){if(function(e){return Boolean(e&&"object"==typeof e)}(e)){if("value"in e)return"html"!==e.type||n?e.value:"";if(t&&"alt"in e&&e.alt)return e.alt;if("children"in e)return bi(e.children,t,n)}return Array.isArray(e)?bi(e,t,n):""}function bi(e,t,n){const s=[];let i=-1;for(;++i<e.length;)s[i]=vi(e[i],t,n);return s.join("")}const xi=document.createElement("i");function wi(e){const t="&"+e+";";xi.innerHTML=t;const n=xi.textContent;return(59!==n.charCodeAt(n.length-1)||"semi"===e)&&n!==t&&n}function Si(e,t,n,s){const i=e.length;let r,o=0;if(t=t<0?-t>i?0:i+t:t>i?i:t,n=n>0?n:0,s.length<1e4)r=Array.from(s),r.unshift(t,n),e.splice(...r);else for(n&&e.splice(t,n);o<s.length;)r=s.slice(o,o+1e4),r.unshift(t,0),e.splice(...r),o+=1e4,t+=1e4}function ki(e,t){return e.length>0?(Si(e,e.length,0,t),e):t}const Ii={}.hasOwnProperty;function Ci(e){const t={};let n=-1;for(;++n<e.length;)ji(t,e[n]);return t}function ji(e,t){let n;for(n in t){const s=(Ii.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let r;if(i)for(r in i){Ii.call(s,r)||(s[r]=[]);const e=i[r];Ri(s[r],Array.isArray(e)?e:e?[e]:[])}}}function Ri(e,t){let n=-1;const s=[];for(;++n<t.length;)("after"===t[n].add?e:s).push(t[n]);Si(e,0,0,s)}function Mi(e,t){const n=Number.parseInt(e,t);return n<9||11===n||n>13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||!(65535&~n)||65534==(65535&n)||n>1114111?"�":String.fromCodePoint(n)}function Ei(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Ti=Bi(/[A-Za-z]/),Ai=Bi(/[\dA-Za-z]/),Ni=Bi(/[#-'*+\--9=?A-Z^-~]/);function Pi(e){return null!==e&&(e<32||127===e)}const Di=Bi(/\d/),Fi=Bi(/[\dA-Fa-f]/),Li=Bi(/[!-/:-@[-`{-~]/);function qi(e){return null!==e&&e<-2}function Oi(e){return null!==e&&(e<0||32===e)}function $i(e){return-2===e||-1===e||32===e}const zi=Bi(new RegExp("\\p{P}|\\p{S}","u")),_i=Bi(/\s/);function Bi(e){return function(t){return null!==t&&t>-1&&e.test(String.fromCharCode(t))}}function Hi(e,t,n,s){const i=s?s-1:Number.POSITIVE_INFINITY;let r=0;return function(s){return $i(s)?(e.enter(n),o(s)):t(s)};function o(s){return $i(s)&&r++<i?(e.consume(s),o):(e.exit(n),t(s))}}const Wi={tokenize:function(e){const t=e.attempt(this.parser.constructs.contentInitial,function(n){if(null!==n)return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),Hi(e,t,"linePrefix");e.consume(n)},function(t){return e.enter("paragraph"),s(t)});let n;return t;function s(t){const s=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=s),n=s,i(t)}function i(t){return null===t?(e.exit("chunkText"),e.exit("paragraph"),void e.consume(t)):qi(t)?(e.consume(t),e.exit("chunkText"),s):(e.consume(t),i)}}},Ki={tokenize:function(e){const t=this,n=[];let s,i,r,o=0;return a;function a(s){if(o<n.length){const i=n[o];return t.containerState=i[1],e.attempt(i[0].continuation,c,l)(s)}return l(s)}function c(e){if(o++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,s&&v();const n=t.events.length;let i,r=n;for(;r--;)if("exit"===t.events[r][0]&&"chunkFlow"===t.events[r][1].type){i=t.events[r][1].end;break}y(o);let a=n;for(;a<t.events.length;)t.events[a][1].end={...i},a++;return Si(t.events,r+1,0,t.events.slice(n)),t.events.length=a,l(e)}return a(e)}function l(i){if(o===n.length){if(!s)return h(i);if(s.currentConstruct&&s.currentConstruct.concrete)return m(i);t.interrupt=Boolean(s.currentConstruct&&!s._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Qi,d,u)(i)}function d(e){return s&&v(),y(o),h(e)}function u(e){return t.parser.lazy[t.now().line]=o!==n.length,r=t.now().offset,m(e)}function h(n){return t.containerState={},e.attempt(Qi,p,m)(n)}function p(e){return o++,n.push([t.currentConstruct,t.containerState]),h(e)}function m(n){return null===n?(s&&v(),y(0),void e.consume(n)):(s=s||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:s,contentType:"flow",previous:i}),f(n))}function f(n){return null===n?(g(e.exit("chunkFlow"),!0),y(0),void e.consume(n)):qi(n)?(e.consume(n),g(e.exit("chunkFlow")),o=0,t.interrupt=void 0,a):(e.consume(n),f)}function g(e,n){const a=t.sliceStream(e);if(n&&a.push(null),e.previous=i,i&&(i.next=e),i=e,s.defineSkip(e.start),s.write(a),t.parser.lazy[e.start.line]){let e=s.events.length;for(;e--;)if(s.events[e][1].start.offset<r&&(!s.events[e][1].end||s.events[e][1].end.offset>r))return;const n=t.events.length;let i,a,c=n;for(;c--;)if("exit"===t.events[c][0]&&"chunkFlow"===t.events[c][1].type){if(i){a=t.events[c][1].end;break}i=!0}for(y(o),e=n;e<t.events.length;)t.events[e][1].end={...a},e++;Si(t.events,c+1,0,t.events.slice(n)),t.events.length=e}}function y(s){let i=n.length;for(;i-- >s;){const s=n[i];t.containerState=s[1],s[0].exit.call(t,e)}n.length=s}function v(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}},Qi={tokenize:function(e,t,n){return Hi(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}};function Ui(e){return null===e||Oi(e)||_i(e)?1:zi(e)?2:void 0}function Vi(e,t,n){const s=[];let i=-1;for(;++i<e.length;){const r=e[i].resolveAll;r&&!s.includes(r)&&(t=r(t,n),s.push(r))}return t}const Gi={name:"attention",resolveAll:function(e,t){let n,s,i,r,o,a,c,l,d=-1;for(;++d<e.length;)if("enter"===e[d][0]&&"attentionSequence"===e[d][1].type&&e[d][1]._close)for(n=d;n--;)if("exit"===e[n][0]&&"attentionSequence"===e[n][1].type&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[d][1]).charCodeAt(0)){if((e[n][1]._close||e[d][1]._open)&&(e[d][1].end.offset-e[d][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[d][1].end.offset-e[d][1].start.offset)%3))continue;a=e[n][1].end.offset-e[n][1].start.offset>1&&e[d][1].end.offset-e[d][1].start.offset>1?2:1;const u={...e[n][1].end},h={...e[d][1].start};Ji(u,-a),Ji(h,a),r={type:a>1?"strongSequence":"emphasisSequence",start:u,end:{...e[n][1].end}},o={type:a>1?"strongSequence":"emphasisSequence",start:{...e[d][1].start},end:h},i={type:a>1?"strongText":"emphasisText",start:{...e[n][1].end},end:{...e[d][1].start}},s={type:a>1?"strong":"emphasis",start:{...r.start},end:{...o.end}},e[n][1].end={...r.start},e[d][1].start={...o.end},c=[],e[n][1].end.offset-e[n][1].start.offset&&(c=ki(c,[["enter",e[n][1],t],["exit",e[n][1],t]])),c=ki(c,[["enter",s,t],["enter",r,t],["exit",r,t],["enter",i,t]]),c=ki(c,Vi(t.parser.constructs.insideSpan.null,e.slice(n+1,d),t)),c=ki(c,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",s,t]]),e[d][1].end.offset-e[d][1].start.offset?(l=2,c=ki(c,[["enter",e[d][1],t],["exit",e[d][1],t]])):l=0,Si(e,n-1,d-n+3,c),d=n+c.length-l-2;break}for(d=-1;++d<e.length;)"attentionSequence"===e[d][1].type&&(e[d][1].type="data");return e},tokenize:function(e,t){const n=this.parser.constructs.attentionMarkers.null,s=this.previous,i=Ui(s);let r;return function(t){return r=t,e.enter("attentionSequence"),o(t)};function o(a){if(a===r)return e.consume(a),o;const c=e.exit("attentionSequence"),l=Ui(a),d=!l||2===l&&i||n.includes(a),u=!i||2===i&&l||n.includes(s);return c._open=Boolean(42===r?d:d&&(i||!u)),c._close=Boolean(42===r?u:u&&(l||!d)),t(a)}}};function Ji(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const Zi={name:"autolink",tokenize:function(e,t,n){let s=0;return function(t){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(t),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i};function i(t){return Ti(t)?(e.consume(t),r):64===t?n(t):c(t)}function r(e){return 43===e||45===e||46===e||Ai(e)?(s=1,o(e)):c(e)}function o(t){return 58===t?(e.consume(t),s=0,a):(43===t||45===t||46===t||Ai(t))&&s++<32?(e.consume(t),o):(s=0,c(t))}function a(s){return 62===s?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(s),e.exit("autolinkMarker"),e.exit("autolink"),t):null===s||32===s||60===s||Pi(s)?n(s):(e.consume(s),a)}function c(t){return 64===t?(e.consume(t),l):Ni(t)?(e.consume(t),c):n(t)}function l(e){return Ai(e)?d(e):n(e)}function d(n){return 46===n?(e.consume(n),s=0,l):62===n?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(n),e.exit("autolinkMarker"),e.exit("autolink"),t):u(n)}function u(t){if((45===t||Ai(t))&&s++<63){const n=45===t?u:d;return e.consume(t),n}return n(t)}}},Yi={partial:!0,tokenize:function(e,t,n){return function(t){return $i(t)?Hi(e,s,"linePrefix")(t):s(t)};function s(e){return null===e||qi(e)?t(e):n(e)}}},Xi={continuation:{tokenize:function(e,t,n){const s=this;return function(t){return $i(t)?Hi(e,i,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):i(t)};function i(s){return e.attempt(Xi,t,n)(s)}}},exit:function(e){e.exit("blockQuote")},name:"blockQuote",tokenize:function(e,t,n){const s=this;return function(t){if(62===t){const n=s.containerState;return n.open||(e.enter("blockQuote",{_container:!0}),n.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(t),e.exit("blockQuoteMarker"),i}return n(t)};function i(n){return $i(n)?(e.enter("blockQuotePrefixWhitespace"),e.consume(n),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(n))}}},er={name:"characterEscape",tokenize:function(e,t,n){return function(t){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(t),e.exit("escapeMarker"),s};function s(s){return Li(s)?(e.enter("characterEscapeValue"),e.consume(s),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(s)}}},tr={name:"characterReference",tokenize:function(e,t,n){const s=this;let i,r,o=0;return function(t){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(t),e.exit("characterReferenceMarker"),a};function a(t){return 35===t?(e.enter("characterReferenceMarkerNumeric"),e.consume(t),e.exit("characterReferenceMarkerNumeric"),c):(e.enter("characterReferenceValue"),i=31,r=Ai,l(t))}function c(t){return 88===t||120===t?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(t),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,r=Fi,l):(e.enter("characterReferenceValue"),i=7,r=Di,l(t))}function l(a){if(59===a&&o){const i=e.exit("characterReferenceValue");return r!==Ai||wi(s.sliceSerialize(i))?(e.enter("characterReferenceMarker"),e.consume(a),e.exit("characterReferenceMarker"),e.exit("characterReference"),t):n(a)}return r(a)&&o++<i?(e.consume(a),l):n(a)}}},nr={partial:!0,tokenize:function(e,t,n){const s=this;return function(t){return null===t?n(t):(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),i)};function i(e){return s.parser.lazy[s.now().line]?n(e):t(e)}}},sr={concrete:!0,name:"codeFenced",tokenize:function(e,t,n){const s=this,i={partial:!0,tokenize:function(e,t,n){let i=0;return function(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),o};function o(t){return e.enter("codeFencedFence"),$i(t)?Hi(e,c,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):c(t)}function c(t){return t===r?(e.enter("codeFencedFenceSequence"),l(t)):n(t)}function l(t){return t===r?(i++,e.consume(t),l):i>=a?(e.exit("codeFencedFenceSequence"),$i(t)?Hi(e,d,"whitespace")(t):d(t)):n(t)}function d(s){return null===s||qi(s)?(e.exit("codeFencedFence"),t(s)):n(s)}}};let r,o=0,a=0;return function(t){return function(t){const n=s.events[s.events.length-1];return o=n&&"linePrefix"===n[1].type?n[2].sliceSerialize(n[1],!0).length:0,r=t,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(t)}(t)};function c(t){return t===r?(a++,e.consume(t),c):a<3?n(t):(e.exit("codeFencedFenceSequence"),$i(t)?Hi(e,l,"whitespace")(t):l(t))}function l(n){return null===n||qi(n)?(e.exit("codeFencedFence"),s.interrupt?t(n):e.check(nr,p,v)(n)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),d(n))}function d(t){return null===t||qi(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),l(t)):$i(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Hi(e,u,"whitespace")(t)):96===t&&t===r?n(t):(e.consume(t),d)}function u(t){return null===t||qi(t)?l(t):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),h(t))}function h(t){return null===t||qi(t)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),l(t)):96===t&&t===r?n(t):(e.consume(t),h)}function p(t){return e.attempt(i,v,m)(t)}function m(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),f}function f(t){return o>0&&$i(t)?Hi(e,g,"linePrefix",o+1)(t):g(t)}function g(t){return null===t||qi(t)?e.check(nr,p,v)(t):(e.enter("codeFlowValue"),y(t))}function y(t){return null===t||qi(t)?(e.exit("codeFlowValue"),g(t)):(e.consume(t),y)}function v(n){return e.exit("codeFenced"),t(n)}}},ir={name:"codeIndented",tokenize:function(e,t,n){const s=this;return function(t){return e.enter("codeIndented"),Hi(e,i,"linePrefix",5)(t)};function i(e){const t=s.events[s.events.length-1];return t&&"linePrefix"===t[1].type&&t[2].sliceSerialize(t[1],!0).length>=4?r(e):n(e)}function r(t){return null===t?a(t):qi(t)?e.attempt(rr,r,a)(t):(e.enter("codeFlowValue"),o(t))}function o(t){return null===t||qi(t)?(e.exit("codeFlowValue"),r(t)):(e.consume(t),o)}function a(n){return e.exit("codeIndented"),t(n)}}},rr={partial:!0,tokenize:function(e,t,n){const s=this;return i;function i(t){return s.parser.lazy[s.now().line]?n(t):qi(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),i):Hi(e,r,"linePrefix",5)(t)}function r(e){const r=s.events[s.events.length-1];return r&&"linePrefix"===r[1].type&&r[2].sliceSerialize(r[1],!0).length>=4?t(e):qi(e)?i(e):n(e)}}},or={name:"codeText",previous:function(e){return 96!==e||"characterEscape"===this.events[this.events.length-1][1].type},resolve:function(e){let t,n,s=e.length-4,i=3;if(!("lineEnding"!==e[i][1].type&&"space"!==e[i][1].type||"lineEnding"!==e[s][1].type&&"space"!==e[s][1].type))for(t=i;++t<s;)if("codeTextData"===e[t][1].type){e[i][1].type="codeTextPadding",e[s][1].type="codeTextPadding",i+=2,s-=2;break}for(t=i-1,s++;++t<=s;)void 0===n?t!==s&&"lineEnding"!==e[t][1].type&&(n=t):t!==s&&"lineEnding"!==e[t][1].type||(e[n][1].type="codeTextData",t!==n+2&&(e[n][1].end=e[t-1][1].end,e.splice(n+2,t-n-2),s-=t-n-2,t=n+2),n=void 0);return e},tokenize:function(e,t,n){let s,i,r=0;return function(t){return e.enter("codeText"),e.enter("codeTextSequence"),o(t)};function o(t){return 96===t?(e.consume(t),r++,o):(e.exit("codeTextSequence"),a(t))}function a(t){return null===t?n(t):32===t?(e.enter("space"),e.consume(t),e.exit("space"),a):96===t?(i=e.enter("codeTextSequence"),s=0,l(t)):qi(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),a):(e.enter("codeTextData"),c(t))}function c(t){return null===t||32===t||96===t||qi(t)?(e.exit("codeTextData"),a(t)):(e.consume(t),c)}function l(n){return 96===n?(e.consume(n),s++,l):s===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(n)):(i.type="codeTextData",c(n))}}};class ar{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,t){const n=t??Number.POSITIVE_INFINITY;return n<this.left.length?this.left.slice(e,n):e>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){const s=t||0;this.setCursor(Math.trunc(e));const i=this.right.splice(this.right.length-s,Number.POSITIVE_INFINITY);return n&&cr(this.left,n),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),cr(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),cr(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&0===this.right.length||e<0&&0===this.left.length))if(e<this.left.length){const t=this.left.splice(e,Number.POSITIVE_INFINITY);cr(this.right,t.reverse())}else{const t=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);cr(this.left,t.reverse())}}}function cr(e,t){let n=0;if(t.length<1e4)e.push(...t);else for(;n<t.length;)e.push(...t.slice(n,n+1e4)),n+=1e4}function lr(e){const t={};let n,s,i,r,o,a,c,l=-1;const d=new ar(e);for(;++l<d.length;){for(;l in t;)l=t[l];if(n=d.get(l),l&&"chunkFlow"===n[1].type&&"listItemPrefix"===d.get(l-1)[1].type&&(a=n[1]._tokenizer.events,i=0,i<a.length&&"lineEndingBlank"===a[i][1].type&&(i+=2),i<a.length&&"content"===a[i][1].type))for(;++i<a.length&&"content"!==a[i][1].type;)"chunkText"===a[i][1].type&&(a[i][1]._isInFirstContentOfListItem=!0,i++);if("enter"===n[0])n[1].contentType&&(Object.assign(t,dr(d,l)),l=t[l],c=!0);else if(n[1]._container){for(i=l,s=void 0;i--;)if(r=d.get(i),"lineEnding"===r[1].type||"lineEndingBlank"===r[1].type)"enter"===r[0]&&(s&&(d.get(s)[1].type="lineEndingBlank"),r[1].type="lineEnding",s=i);else if("linePrefix"!==r[1].type&&"listItemIndent"!==r[1].type)break;s&&(n[1].end={...d.get(s)[1].start},o=d.slice(s,l),o.unshift(n),d.splice(s,l-s+1,o))}}return Si(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!c}function dr(e,t){const n=e.get(t)[1],s=e.get(t)[2];let i=t-1;const r=[];let o=n._tokenizer;o||(o=s.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const a=o.events,c=[],l={};let d,u,h=-1,p=n,m=0,f=0;const g=[f];for(;p;){for(;e.get(++i)[1]!==p;);r.push(i),p._tokenizer||(d=s.sliceStream(p),p.next||d.push(null),u&&o.defineSkip(p.start),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(d),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),u=p,p=p.next}for(p=n;++h<a.length;)"exit"===a[h][0]&&"enter"===a[h-1][0]&&a[h][1].type===a[h-1][1].type&&a[h][1].start.line!==a[h][1].end.line&&(f=h+1,g.push(f),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(o.events=[],p?(p._tokenizer=void 0,p.previous=void 0):g.pop(),h=g.length;h--;){const t=a.slice(g[h],g[h+1]),n=r.pop();c.push([n,n+t.length-1]),e.splice(n,2,t)}for(c.reverse(),h=-1;++h<c.length;)l[m+c[h][0]]=m+c[h][1],m+=c[h][1]-c[h][0]-1;return l}const ur={resolve:function(e){return lr(e),e},tokenize:function(e,t){let n;return function(t){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),s(t)};function s(t){return null===t?i(t):qi(t)?e.check(hr,r,i)(t):(e.consume(t),s)}function i(n){return e.exit("chunkContent"),e.exit("content"),t(n)}function r(t){return e.consume(t),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,s}}},hr={partial:!0,tokenize:function(e,t,n){const s=this;return function(t){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),Hi(e,i,"linePrefix")};function i(i){if(null===i||qi(i))return n(i);const r=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&r&&"linePrefix"===r[1].type&&r[2].sliceSerialize(r[1],!0).length>=4?t(i):e.interrupt(s.parser.constructs.flow,n,t)(i)}}};function pr(e,t,n,s,i,r,o,a,c){const l=c||Number.POSITIVE_INFINITY;let d=0;return function(t){return 60===t?(e.enter(s),e.enter(i),e.enter(r),e.consume(t),e.exit(r),u):null===t||32===t||41===t||Pi(t)?n(t):(e.enter(s),e.enter(o),e.enter(a),e.enter("chunkString",{contentType:"string"}),m(t))};function u(n){return 62===n?(e.enter(r),e.consume(n),e.exit(r),e.exit(i),e.exit(s),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),h(n))}function h(t){return 62===t?(e.exit("chunkString"),e.exit(a),u(t)):null===t||60===t||qi(t)?n(t):(e.consume(t),92===t?p:h)}function p(t){return 60===t||62===t||92===t?(e.consume(t),h):h(t)}function m(i){return d||null!==i&&41!==i&&!Oi(i)?d<l&&40===i?(e.consume(i),d++,m):41===i?(e.consume(i),d--,m):null===i||32===i||40===i||Pi(i)?n(i):(e.consume(i),92===i?f:m):(e.exit("chunkString"),e.exit(a),e.exit(o),e.exit(s),t(i))}function f(t){return 40===t||41===t||92===t?(e.consume(t),m):m(t)}}function mr(e,t,n,s,i,r){const o=this;let a,c=0;return function(t){return e.enter(s),e.enter(i),e.consume(t),e.exit(i),e.enter(r),l};function l(u){return c>999||null===u||91===u||93===u&&!a||94===u&&!c&&"_hiddenFootnoteSupport"in o.parser.constructs?n(u):93===u?(e.exit(r),e.enter(i),e.consume(u),e.exit(i),e.exit(s),t):qi(u)?(e.enter("lineEnding"),e.consume(u),e.exit("lineEnding"),l):(e.enter("chunkString",{contentType:"string"}),d(u))}function d(t){return null===t||91===t||93===t||qi(t)||c++>999?(e.exit("chunkString"),l(t)):(e.consume(t),a||(a=!$i(t)),92===t?u:d)}function u(t){return 91===t||92===t||93===t?(e.consume(t),c++,d):d(t)}}function fr(e,t,n,s,i,r){let o;return function(t){return 34===t||39===t||40===t?(e.enter(s),e.enter(i),e.consume(t),e.exit(i),o=40===t?41:t,a):n(t)};function a(n){return n===o?(e.enter(i),e.consume(n),e.exit(i),e.exit(s),t):(e.enter(r),c(n))}function c(t){return t===o?(e.exit(r),a(o)):null===t?n(t):qi(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),Hi(e,c,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),l(t))}function l(t){return t===o||null===t||qi(t)?(e.exit("chunkString"),c(t)):(e.consume(t),92===t?d:l)}function d(t){return t===o||92===t?(e.consume(t),l):l(t)}}function gr(e,t){let n;return function s(i){return qi(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,s):$i(i)?Hi(e,s,n?"linePrefix":"lineSuffix")(i):t(i)}}const yr={name:"definition",tokenize:function(e,t,n){const s=this;let i;return function(t){return e.enter("definition"),function(t){return mr.call(s,e,r,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(t)}(t)};function r(t){return i=Ei(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)),58===t?(e.enter("definitionMarker"),e.consume(t),e.exit("definitionMarker"),o):n(t)}function o(t){return Oi(t)?gr(e,a)(t):a(t)}function a(t){return pr(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(t)}function c(t){return e.attempt(vr,l,l)(t)}function l(t){return $i(t)?Hi(e,d,"whitespace")(t):d(t)}function d(r){return null===r||qi(r)?(e.exit("definition"),s.parser.defined.push(i),t(r)):n(r)}}},vr={partial:!0,tokenize:function(e,t,n){return function(t){return Oi(t)?gr(e,s)(t):n(t)};function s(t){return fr(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(t)}function i(t){return $i(t)?Hi(e,r,"whitespace")(t):r(t)}function r(e){return null===e||qi(e)?t(e):n(e)}}},br={name:"hardBreakEscape",tokenize:function(e,t,n){return function(t){return e.enter("hardBreakEscape"),e.consume(t),s};function s(s){return qi(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}},xr={name:"headingAtx",resolve:function(e,t){let n,s,i=e.length-2,r=3;return"whitespace"===e[r][1].type&&(r+=2),i-2>r&&"whitespace"===e[i][1].type&&(i-=2),"atxHeadingSequence"===e[i][1].type&&(r===i-1||i-4>r&&"whitespace"===e[i-2][1].type)&&(i-=r+1===i?2:4),i>r&&(n={type:"atxHeadingText",start:e[r][1].start,end:e[i][1].end},s={type:"chunkText",start:e[r][1].start,end:e[i][1].end,contentType:"text"},Si(e,r,i-r+1,[["enter",n,t],["enter",s,t],["exit",s,t],["exit",n,t]])),e},tokenize:function(e,t,n){let s=0;return function(t){return e.enter("atxHeading"),function(t){return e.enter("atxHeadingSequence"),i(t)}(t)};function i(t){return 35===t&&s++<6?(e.consume(t),i):null===t||Oi(t)?(e.exit("atxHeadingSequence"),r(t)):n(t)}function r(n){return 35===n?(e.enter("atxHeadingSequence"),o(n)):null===n||qi(n)?(e.exit("atxHeading"),t(n)):$i(n)?Hi(e,r,"whitespace")(n):(e.enter("atxHeadingText"),a(n))}function o(t){return 35===t?(e.consume(t),o):(e.exit("atxHeadingSequence"),r(t))}function a(t){return null===t||35===t||Oi(t)?(e.exit("atxHeadingText"),r(t)):(e.consume(t),a)}}},wr=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Sr=["pre","script","style","textarea"],kr={concrete:!0,name:"htmlFlow",resolveTo:function(e){let t=e.length;for(;t--&&("enter"!==e[t][0]||"htmlFlow"!==e[t][1].type););return t>1&&"linePrefix"===e[t-2][1].type&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e},tokenize:function(e,t,n){const s=this;let i,r,o,a,c;return function(t){return function(t){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(t),l}(t)};function l(a){return 33===a?(e.consume(a),d):47===a?(e.consume(a),r=!0,p):63===a?(e.consume(a),i=3,s.interrupt?t:D):Ti(a)?(e.consume(a),o=String.fromCharCode(a),m):n(a)}function d(r){return 45===r?(e.consume(r),i=2,u):91===r?(e.consume(r),i=5,a=0,h):Ti(r)?(e.consume(r),i=4,s.interrupt?t:D):n(r)}function u(i){return 45===i?(e.consume(i),s.interrupt?t:D):n(i)}function h(i){return i==="CDATA[".charCodeAt(a++)?(e.consume(i),6===a?s.interrupt?t:j:h):n(i)}function p(t){return Ti(t)?(e.consume(t),o=String.fromCharCode(t),m):n(t)}function m(a){if(null===a||47===a||62===a||Oi(a)){const c=47===a,l=o.toLowerCase();return c||r||!Sr.includes(l)?wr.includes(o.toLowerCase())?(i=6,c?(e.consume(a),f):s.interrupt?t(a):j(a)):(i=7,s.interrupt&&!s.parser.lazy[s.now().line]?n(a):r?g(a):y(a)):(i=1,s.interrupt?t(a):j(a))}return 45===a||Ai(a)?(e.consume(a),o+=String.fromCharCode(a),m):n(a)}function f(i){return 62===i?(e.consume(i),s.interrupt?t:j):n(i)}function g(t){return $i(t)?(e.consume(t),g):I(t)}function y(t){return 47===t?(e.consume(t),I):58===t||95===t||Ti(t)?(e.consume(t),v):$i(t)?(e.consume(t),y):I(t)}function v(t){return 45===t||46===t||58===t||95===t||Ai(t)?(e.consume(t),v):b(t)}function b(t){return 61===t?(e.consume(t),x):$i(t)?(e.consume(t),b):y(t)}function x(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),c=t,w):$i(t)?(e.consume(t),x):S(t)}function w(t){return t===c?(e.consume(t),c=null,k):null===t||qi(t)?n(t):(e.consume(t),w)}function S(t){return null===t||34===t||39===t||47===t||60===t||61===t||62===t||96===t||Oi(t)?b(t):(e.consume(t),S)}function k(e){return 47===e||62===e||$i(e)?y(e):n(e)}function I(t){return 62===t?(e.consume(t),C):n(t)}function C(t){return null===t||qi(t)?j(t):$i(t)?(e.consume(t),C):n(t)}function j(t){return 45===t&&2===i?(e.consume(t),T):60===t&&1===i?(e.consume(t),A):62===t&&4===i?(e.consume(t),F):63===t&&3===i?(e.consume(t),D):93===t&&5===i?(e.consume(t),P):!qi(t)||6!==i&&7!==i?null===t||qi(t)?(e.exit("htmlFlowData"),R(t)):(e.consume(t),j):(e.exit("htmlFlowData"),e.check(Ir,L,R)(t))}function R(t){return e.check(Cr,M,L)(t)}function M(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),E}function E(t){return null===t||qi(t)?R(t):(e.enter("htmlFlowData"),j(t))}function T(t){return 45===t?(e.consume(t),D):j(t)}function A(t){return 47===t?(e.consume(t),o="",N):j(t)}function N(t){if(62===t){const n=o.toLowerCase();return Sr.includes(n)?(e.consume(t),F):j(t)}return Ti(t)&&o.length<8?(e.consume(t),o+=String.fromCharCode(t),N):j(t)}function P(t){return 93===t?(e.consume(t),D):j(t)}function D(t){return 62===t?(e.consume(t),F):45===t&&2===i?(e.consume(t),D):j(t)}function F(t){return null===t||qi(t)?(e.exit("htmlFlowData"),L(t)):(e.consume(t),F)}function L(n){return e.exit("htmlFlow"),t(n)}}},Ir={partial:!0,tokenize:function(e,t,n){return function(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(Yi,t,n)}}},Cr={partial:!0,tokenize:function(e,t,n){const s=this;return function(t){return qi(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),i):n(t)};function i(e){return s.parser.lazy[s.now().line]?n(e):t(e)}}},jr={name:"htmlText",tokenize:function(e,t,n){const s=this;let i,r,o;return function(t){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(t),a};function a(t){return 33===t?(e.consume(t),c):47===t?(e.consume(t),x):63===t?(e.consume(t),v):Ti(t)?(e.consume(t),k):n(t)}function c(t){return 45===t?(e.consume(t),l):91===t?(e.consume(t),r=0,p):Ti(t)?(e.consume(t),y):n(t)}function l(t){return 45===t?(e.consume(t),h):n(t)}function d(t){return null===t?n(t):45===t?(e.consume(t),u):qi(t)?(o=d,N(t)):(e.consume(t),d)}function u(t){return 45===t?(e.consume(t),h):d(t)}function h(e){return 62===e?A(e):45===e?u(e):d(e)}function p(t){return t==="CDATA[".charCodeAt(r++)?(e.consume(t),6===r?m:p):n(t)}function m(t){return null===t?n(t):93===t?(e.consume(t),f):qi(t)?(o=m,N(t)):(e.consume(t),m)}function f(t){return 93===t?(e.consume(t),g):m(t)}function g(t){return 62===t?A(t):93===t?(e.consume(t),g):m(t)}function y(t){return null===t||62===t?A(t):qi(t)?(o=y,N(t)):(e.consume(t),y)}function v(t){return null===t?n(t):63===t?(e.consume(t),b):qi(t)?(o=v,N(t)):(e.consume(t),v)}function b(e){return 62===e?A(e):v(e)}function x(t){return Ti(t)?(e.consume(t),w):n(t)}function w(t){return 45===t||Ai(t)?(e.consume(t),w):S(t)}function S(t){return qi(t)?(o=S,N(t)):$i(t)?(e.consume(t),S):A(t)}function k(t){return 45===t||Ai(t)?(e.consume(t),k):47===t||62===t||Oi(t)?I(t):n(t)}function I(t){return 47===t?(e.consume(t),A):58===t||95===t||Ti(t)?(e.consume(t),C):qi(t)?(o=I,N(t)):$i(t)?(e.consume(t),I):A(t)}function C(t){return 45===t||46===t||58===t||95===t||Ai(t)?(e.consume(t),C):j(t)}function j(t){return 61===t?(e.consume(t),R):qi(t)?(o=j,N(t)):$i(t)?(e.consume(t),j):I(t)}function R(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),i=t,M):qi(t)?(o=R,N(t)):$i(t)?(e.consume(t),R):(e.consume(t),E)}function M(t){return t===i?(e.consume(t),i=void 0,T):null===t?n(t):qi(t)?(o=M,N(t)):(e.consume(t),M)}function E(t){return null===t||34===t||39===t||60===t||61===t||96===t?n(t):47===t||62===t||Oi(t)?I(t):(e.consume(t),E)}function T(e){return 47===e||62===e||Oi(e)?I(e):n(e)}function A(s){return 62===s?(e.consume(s),e.exit("htmlTextData"),e.exit("htmlText"),t):n(s)}function N(t){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),P}function P(t){return $i(t)?Hi(e,D,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):D(t)}function D(t){return e.enter("htmlTextData"),o(t)}}},Rr={name:"labelEnd",resolveAll:function(e){let t=-1;const n=[];for(;++t<e.length;){const s=e[t][1];if(n.push(e[t]),"labelImage"===s.type||"labelLink"===s.type||"labelEnd"===s.type){const e="labelImage"===s.type?4:2;s.type="data",t+=e}}return e.length!==n.length&&Si(e,0,e.length,n),e},resolveTo:function(e,t){let n,s,i,r,o=e.length,a=0;for(;o--;)if(n=e[o][1],s){if("link"===n.type||"labelLink"===n.type&&n._inactive)break;"enter"===e[o][0]&&"labelLink"===n.type&&(n._inactive=!0)}else if(i){if("enter"===e[o][0]&&("labelImage"===n.type||"labelLink"===n.type)&&!n._balanced&&(s=o,"labelLink"!==n.type)){a=2;break}}else"labelEnd"===n.type&&(i=o);const c={type:"labelLink"===e[s][1].type?"link":"image",start:{...e[s][1].start},end:{...e[e.length-1][1].end}},l={type:"label",start:{...e[s][1].start},end:{...e[i][1].end}},d={type:"labelText",start:{...e[s+a+2][1].end},end:{...e[i-2][1].start}};return r=[["enter",c,t],["enter",l,t]],r=ki(r,e.slice(s+1,s+a+3)),r=ki(r,[["enter",d,t]]),r=ki(r,Vi(t.parser.constructs.insideSpan.null,e.slice(s+a+4,i-3),t)),r=ki(r,[["exit",d,t],e[i-2],e[i-1],["exit",l,t]]),r=ki(r,e.slice(i+1)),r=ki(r,[["exit",c,t]]),Si(e,s,e.length,r),e},tokenize:function(e,t,n){const s=this;let i,r,o=s.events.length;for(;o--;)if(("labelImage"===s.events[o][1].type||"labelLink"===s.events[o][1].type)&&!s.events[o][1]._balanced){i=s.events[o][1];break}return function(t){return i?i._inactive?d(t):(r=s.parser.defined.includes(Ei(s.sliceSerialize({start:i.end,end:s.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelEnd"),a):n(t)};function a(t){return 40===t?e.attempt(Mr,l,r?l:d)(t):91===t?e.attempt(Er,l,r?c:d)(t):r?l(t):d(t)}function c(t){return e.attempt(Tr,l,d)(t)}function l(e){return t(e)}function d(e){return i._balanced=!0,n(e)}}},Mr={tokenize:function(e,t,n){return function(t){return e.enter("resource"),e.enter("resourceMarker"),e.consume(t),e.exit("resourceMarker"),s};function s(t){return Oi(t)?gr(e,i)(t):i(t)}function i(t){return 41===t?l(t):pr(e,r,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(t)}function r(t){return Oi(t)?gr(e,a)(t):l(t)}function o(e){return n(e)}function a(t){return 34===t||39===t||40===t?fr(e,c,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(t):l(t)}function c(t){return Oi(t)?gr(e,l)(t):l(t)}function l(s){return 41===s?(e.enter("resourceMarker"),e.consume(s),e.exit("resourceMarker"),e.exit("resource"),t):n(s)}}},Er={tokenize:function(e,t,n){const s=this;return function(t){return mr.call(s,e,i,r,"reference","referenceMarker","referenceString")(t)};function i(e){return s.parser.defined.includes(Ei(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(e):n(e)}function r(e){return n(e)}}},Tr={tokenize:function(e,t,n){return function(t){return e.enter("reference"),e.enter("referenceMarker"),e.consume(t),e.exit("referenceMarker"),s};function s(s){return 93===s?(e.enter("referenceMarker"),e.consume(s),e.exit("referenceMarker"),e.exit("reference"),t):n(s)}}},Ar={name:"labelStartImage",resolveAll:Rr.resolveAll,tokenize:function(e,t,n){const s=this;return function(t){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(t),e.exit("labelImageMarker"),i};function i(t){return 91===t?(e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelImage"),r):n(t)}function r(e){return 94===e&&"_hiddenFootnoteSupport"in s.parser.constructs?n(e):t(e)}}},Nr={name:"labelStartLink",resolveAll:Rr.resolveAll,tokenize:function(e,t,n){const s=this;return function(t){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelLink"),i};function i(e){return 94===e&&"_hiddenFootnoteSupport"in s.parser.constructs?n(e):t(e)}}},Pr={name:"lineEnding",tokenize:function(e,t){return function(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),Hi(e,t,"linePrefix")}}},Dr={name:"thematicBreak",tokenize:function(e,t,n){let s,i=0;return function(t){return e.enter("thematicBreak"),function(e){return s=e,r(e)}(t)};function r(r){return r===s?(e.enter("thematicBreakSequence"),o(r)):i>=3&&(null===r||qi(r))?(e.exit("thematicBreak"),t(r)):n(r)}function o(t){return t===s?(e.consume(t),i++,o):(e.exit("thematicBreakSequence"),$i(t)?Hi(e,r,"whitespace")(t):r(t))}}},Fr={continuation:{tokenize:function(e,t,n){const s=this;return s.containerState._closeFlow=void 0,e.check(Yi,function(n){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,Hi(e,t,"listItemIndent",s.containerState.size+1)(n)},function(n){return s.containerState.furtherBlankLines||!$i(n)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,i(n)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(qr,t,i)(n))});function i(i){return s.containerState._closeFlow=!0,s.interrupt=void 0,Hi(e,e.attempt(Fr,t,n),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(i)}}},exit:function(e){e.exit(this.containerState.type)},name:"list",tokenize:function(e,t,n){const s=this,i=s.events[s.events.length-1];let r=i&&"linePrefix"===i[1].type?i[2].sliceSerialize(i[1],!0).length:0,o=0;return function(t){const i=s.containerState.type||(42===t||43===t||45===t?"listUnordered":"listOrdered");if("listUnordered"===i?!s.containerState.marker||t===s.containerState.marker:Di(t)){if(s.containerState.type||(s.containerState.type=i,e.enter(i,{_container:!0})),"listUnordered"===i)return e.enter("listItemPrefix"),42===t||45===t?e.check(Dr,n,c)(t):c(t);if(!s.interrupt||49===t)return e.enter("listItemPrefix"),e.enter("listItemValue"),a(t)}return n(t)};function a(t){return Di(t)&&++o<10?(e.consume(t),a):(!s.interrupt||o<2)&&(s.containerState.marker?t===s.containerState.marker:41===t||46===t)?(e.exit("listItemValue"),c(t)):n(t)}function c(t){return e.enter("listItemMarker"),e.consume(t),e.exit("listItemMarker"),s.containerState.marker=s.containerState.marker||t,e.check(Yi,s.interrupt?n:l,e.attempt(Lr,u,d))}function l(e){return s.containerState.initialBlankLine=!0,r++,u(e)}function d(t){return $i(t)?(e.enter("listItemPrefixWhitespace"),e.consume(t),e.exit("listItemPrefixWhitespace"),u):n(t)}function u(n){return s.containerState.size=r+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(n)}}},Lr={partial:!0,tokenize:function(e,t,n){const s=this;return Hi(e,function(e){const i=s.events[s.events.length-1];return!$i(e)&&i&&"listItemPrefixWhitespace"===i[1].type?t(e):n(e)},"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5)}},qr={partial:!0,tokenize:function(e,t,n){const s=this;return Hi(e,function(e){const i=s.events[s.events.length-1];return i&&"listItemIndent"===i[1].type&&i[2].sliceSerialize(i[1],!0).length===s.containerState.size?t(e):n(e)},"listItemIndent",s.containerState.size+1)}},Or={name:"setextUnderline",resolveTo:function(e,t){let n,s,i,r=e.length;for(;r--;)if("enter"===e[r][0]){if("content"===e[r][1].type){n=r;break}"paragraph"===e[r][1].type&&(s=r)}else"content"===e[r][1].type&&e.splice(r,1),i||"definition"!==e[r][1].type||(i=r);const o={type:"setextHeading",start:{...e[n][1].start},end:{...e[e.length-1][1].end}};return e[s][1].type="setextHeadingText",i?(e.splice(s,0,["enter",o,t]),e.splice(i+1,0,["exit",e[n][1],t]),e[n][1].end={...e[i][1].end}):e[n][1]=o,e.push(["exit",o,t]),e},tokenize:function(e,t,n){const s=this;let i;return function(t){let o,a=s.events.length;for(;a--;)if("lineEnding"!==s.events[a][1].type&&"linePrefix"!==s.events[a][1].type&&"content"!==s.events[a][1].type){o="paragraph"===s.events[a][1].type;break}return s.parser.lazy[s.now().line]||!s.interrupt&&!o?n(t):(e.enter("setextHeadingLine"),i=t,function(t){return e.enter("setextHeadingLineSequence"),r(t)}(t))};function r(t){return t===i?(e.consume(t),r):(e.exit("setextHeadingLineSequence"),$i(t)?Hi(e,o,"lineSuffix")(t):o(t))}function o(s){return null===s||qi(s)?(e.exit("setextHeadingLine"),t(s)):n(s)}}},$r={tokenize:function(e){const t=this,n=e.attempt(Yi,function(s){if(null!==s)return e.enter("lineEndingBlank"),e.consume(s),e.exit("lineEndingBlank"),t.currentConstruct=void 0,n;e.consume(s)},e.attempt(this.parser.constructs.flowInitial,s,Hi(e,e.attempt(this.parser.constructs.flow,s,e.attempt(ur,s)),"linePrefix")));return n;function s(s){if(null!==s)return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),t.currentConstruct=void 0,n;e.consume(s)}}},zr={resolveAll:Wr()},_r=Hr("string"),Br=Hr("text");function Hr(e){return{resolveAll:Wr("text"===e?Kr:void 0),tokenize:function(t){const n=this,s=this.parser.constructs[e],i=t.attempt(s,r,o);return r;function r(e){return c(e)?i(e):o(e)}function o(e){if(null!==e)return t.enter("data"),t.consume(e),a;t.consume(e)}function a(e){return c(e)?(t.exit("data"),i(e)):(t.consume(e),a)}function c(e){if(null===e)return!0;const t=s[e];let i=-1;if(t)for(;++i<t.length;){const e=t[i];if(!e.previous||e.previous.call(n,n.previous))return!0}return!1}}}}function Wr(e){return function(t,n){let s,i=-1;for(;++i<=t.length;)void 0===s?t[i]&&"data"===t[i][1].type&&(s=i,i++):t[i]&&"data"===t[i][1].type||(i!==s+2&&(t[s][1].end=t[i-1][1].end,t.splice(s+2,i-s-2),i=s+2),s=void 0);return e?e(t,n):t}}function Kr(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||"lineEnding"===e[n][1].type)&&"data"===e[n-1][1].type){const s=e[n-1][1],i=t.sliceStream(s);let r,o=i.length,a=-1,c=0;for(;o--;){const e=i[o];if("string"==typeof e){for(a=e.length;32===e.charCodeAt(a-1);)c++,a--;if(a)break;a=-1}else if(-2===e)r=!0,c++;else if(-1!==e){o++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(c=0),c){const i={type:n===e.length||r||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?a:s.start._bufferIndex+a,_index:s.start._index+o,line:s.end.line,column:s.end.column-c,offset:s.end.offset-c},end:{...s.end}};s.end={...i.start},s.start.offset===s.end.offset?Object.assign(s,i):(e.splice(n,0,["enter",i,t],["exit",i,t]),n+=2)}n++}return e}const Qr={42:Fr,43:Fr,45:Fr,48:Fr,49:Fr,50:Fr,51:Fr,52:Fr,53:Fr,54:Fr,55:Fr,56:Fr,57:Fr,62:Xi},Ur={91:yr},Vr={[-2]:ir,[-1]:ir,32:ir},Gr={35:xr,42:Dr,45:[Or,Dr],60:kr,61:Or,95:Dr,96:sr,126:sr},Jr={38:tr,92:er},Zr={[-5]:Pr,[-4]:Pr,[-3]:Pr,33:Ar,38:tr,42:Gi,60:[Zi,jr],91:Nr,92:[br,er],93:Rr,95:Gi,96:or},Yr={null:[Gi,zr]},Xr=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:Ur,disable:{null:[]},document:Qr,flow:Gr,flowInitial:Vr,insideSpan:Yr,string:Jr,text:Zr},Symbol.toStringTag,{value:"Module"})),eo=/[\0\t\n\r]/g,to=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function no(e){return e.replace(to,so)}function so(e,t,n){if(t)return t;if(35===n.charCodeAt(0)){const e=n.charCodeAt(1),t=120===e||88===e;return Mi(n.slice(t?2:1),t?16:10)}return wi(n)||e}function io(e){return e&&"object"==typeof e?"position"in e||"type"in e?oo(e.position):"start"in e||"end"in e?oo(e):"line"in e||"column"in e?ro(e):"":""}function ro(e){return ao(e&&e.line)+":"+ao(e&&e.column)}function oo(e){return ro(e&&e.start)+"-"+ro(e&&e.end)}function ao(e){return e&&"number"==typeof e?e:1}const co={}.hasOwnProperty;function lo(e,t,n){return t&&"object"==typeof t&&(n=t,t=void 0),function(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(v),autolinkProtocol:d,autolinkEmail:d,atxHeading:i(f),blockQuote:i(function(){return{type:"blockquote",children:[]}}),characterEscape:d,characterReference:d,codeFenced:i(m),codeFencedFenceInfo:r,codeFencedFenceMeta:r,codeIndented:i(m,r),codeText:i(function(){return{type:"inlineCode",value:""}},r),codeTextData:d,data:d,codeFlowValue:d,definition:i(function(){return{type:"definition",identifier:"",label:null,title:null,url:""}}),definitionDestinationString:r,definitionLabelString:r,definitionTitleString:r,emphasis:i(function(){return{type:"emphasis",children:[]}}),hardBreakEscape:i(g),hardBreakTrailing:i(g),htmlFlow:i(y,r),htmlFlowData:d,htmlText:i(y,r),htmlTextData:d,image:i(function(){return{type:"image",title:null,url:"",alt:null}}),label:r,link:i(v),listItem:i(function(e){return{type:"listItem",spread:e._spread,checked:null,children:[]}}),listItemValue:function(e){this.data.expectingFirstListItemValue&&(this.stack[this.stack.length-2].start=Number.parseInt(this.sliceSerialize(e),10),this.data.expectingFirstListItemValue=void 0)},listOrdered:i(b,function(){this.data.expectingFirstListItemValue=!0}),listUnordered:i(b),paragraph:i(function(){return{type:"paragraph",children:[]}}),reference:function(){this.data.referenceType="collapsed"},referenceString:r,resourceDestinationString:r,resourceTitleString:r,setextHeading:i(f),strong:i(function(){return{type:"strong",children:[]}}),thematicBreak:i(function(){return{type:"thematicBreak"}})},exit:{atxHeading:a(),atxHeadingSequence:function(e){const t=this.stack[this.stack.length-1];if(!t.depth){const n=this.sliceSerialize(e).length;t.depth=n}},autolink:a(),autolinkEmail:function(e){u.call(this,e),this.stack[this.stack.length-1].url="mailto:"+this.sliceSerialize(e)},autolinkProtocol:function(e){u.call(this,e),this.stack[this.stack.length-1].url=this.sliceSerialize(e)},blockQuote:a(),characterEscapeValue:u,characterReferenceMarkerHexadecimal:p,characterReferenceMarkerNumeric:p,characterReferenceValue:function(e){const t=this.sliceSerialize(e),n=this.data.characterReferenceType;let s;n?(s=Mi(t,"characterReferenceMarkerNumeric"===n?10:16),this.data.characterReferenceType=void 0):s=wi(t),this.stack[this.stack.length-1].value+=s},characterReference:function(e){this.stack.pop().position.end=uo(e.end)},codeFenced:a(function(){const e=this.resume();this.stack[this.stack.length-1].value=e.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}),codeFencedFence:function(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)},codeFencedFenceInfo:function(){const e=this.resume();this.stack[this.stack.length-1].lang=e},codeFencedFenceMeta:function(){const e=this.resume();this.stack[this.stack.length-1].meta=e},codeFlowValue:u,codeIndented:a(function(){const e=this.resume();this.stack[this.stack.length-1].value=e.replace(/(\r?\n|\r)$/g,"")}),codeText:a(function(){const e=this.resume();this.stack[this.stack.length-1].value=e}),codeTextData:u,data:u,definition:a(),definitionDestinationString:function(){const e=this.resume();this.stack[this.stack.length-1].url=e},definitionLabelString:function(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=Ei(this.sliceSerialize(e)).toLowerCase()},definitionTitleString:function(){const e=this.resume();this.stack[this.stack.length-1].title=e},emphasis:a(),hardBreakEscape:a(h),hardBreakTrailing:a(h),htmlFlow:a(function(){const e=this.resume();this.stack[this.stack.length-1].value=e}),htmlFlowData:u,htmlText:a(function(){const e=this.resume();this.stack[this.stack.length-1].value=e}),htmlTextData:u,image:a(function(){const e=this.stack[this.stack.length-1];if(this.data.inReference){const t=this.data.referenceType||"shortcut";e.type+="Reference",e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;this.data.referenceType=void 0}),label:function(){const e=this.stack[this.stack.length-1],t=this.resume(),n=this.stack[this.stack.length-1];if(this.data.inReference=!0,"link"===n.type){const t=e.children;n.children=t}else n.alt=t},labelText:function(e){const t=this.sliceSerialize(e),n=this.stack[this.stack.length-2];n.label=no(t),n.identifier=Ei(t).toLowerCase()},lineEnding:function(e){const n=this.stack[this.stack.length-1];if(this.data.atHardBreak)return n.children[n.children.length-1].position.end=uo(e.end),void(this.data.atHardBreak=void 0);!this.data.setextHeadingSlurpLineEnding&&t.canContainEols.includes(n.type)&&(d.call(this,e),u.call(this,e))},link:a(function(){const e=this.stack[this.stack.length-1];if(this.data.inReference){const t=this.data.referenceType||"shortcut";e.type+="Reference",e.referenceType=t,delete e.url,delete e.title}else delete e.identifier,delete e.label;this.data.referenceType=void 0}),listItem:a(),listOrdered:a(),listUnordered:a(),paragraph:a(),referenceString:function(e){const t=this.resume(),n=this.stack[this.stack.length-1];n.label=t,n.identifier=Ei(this.sliceSerialize(e)).toLowerCase(),this.data.referenceType="full"},resourceDestinationString:function(){const e=this.resume();this.stack[this.stack.length-1].url=e},resourceTitleString:function(){const e=this.resume();this.stack[this.stack.length-1].title=e},resource:function(){this.data.inReference=void 0},setextHeading:a(function(){this.data.setextHeadingSlurpLineEnding=void 0}),setextHeadingLineSequence:function(e){this.stack[this.stack.length-1].depth=61===this.sliceSerialize(e).codePointAt(0)?1:2},setextHeadingText:function(){this.data.setextHeadingSlurpLineEnding=!0},strong:a(),thematicBreak:a()}};ho(t,(e||{}).mdastExtensions||[]);const n={};return function(e){let i={type:"root",children:[]};const a={stack:[i],tokenStack:[],config:t,enter:o,exit:c,buffer:r,resume:l,data:n},d=[];let u=-1;for(;++u<e.length;)"listOrdered"!==e[u][1].type&&"listUnordered"!==e[u][1].type||("enter"===e[u][0]?d.push(u):u=s(e,d.pop(),u));for(u=-1;++u<e.length;){const n=t[e[u][0]];co.call(n,e[u][1].type)&&n[e[u][1].type].call(Object.assign({sliceSerialize:e[u][2].sliceSerialize},a),e[u][1])}if(a.tokenStack.length>0){const e=a.tokenStack[a.tokenStack.length-1];(e[1]||mo).call(a,void 0,e[0])}for(i.position={start:uo(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:uo(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},u=-1;++u<t.transforms.length;)i=t.transforms[u](i)||i;return i};function s(e,t,n){let s,i,r,o,a=t-1,c=-1,l=!1;for(;++a<=n;){const t=e[a];switch(t[1].type){case"listUnordered":case"listOrdered":case"blockQuote":"enter"===t[0]?c++:c--,o=void 0;break;case"lineEndingBlank":"enter"===t[0]&&(!s||o||c||r||(r=a),o=void 0);break;case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:o=void 0}if(!c&&"enter"===t[0]&&"listItemPrefix"===t[1].type||-1===c&&"exit"===t[0]&&("listUnordered"===t[1].type||"listOrdered"===t[1].type)){if(s){let o=a;for(i=void 0;o--;){const t=e[o];if("lineEnding"===t[1].type||"lineEndingBlank"===t[1].type){if("exit"===t[0])continue;i&&(e[i][1].type="lineEndingBlank",l=!0),t[1].type="lineEnding",i=o}else if("linePrefix"!==t[1].type&&"blockQuotePrefix"!==t[1].type&&"blockQuotePrefixWhitespace"!==t[1].type&&"blockQuoteMarker"!==t[1].type&&"listItemIndent"!==t[1].type)break}r&&(!i||r<i)&&(s._spread=!0),s.end=Object.assign({},i?e[i][1].start:t[1].end),e.splice(i||a,0,["exit",s,t[2]]),a++,n++}if("listItemPrefix"===t[1].type){const i={type:"listItem",_spread:!1,start:Object.assign({},t[1].start),end:void 0};s=i,e.splice(a,0,["enter",i,t[2]]),a++,n++,r=void 0,o=!0}}}return e[t][1]._spread=l,n}function i(e,t){return function(n){o.call(this,e(n),n),t&&t.call(this,n)}}function r(){this.stack.push({type:"fragment",children:[]})}function o(e,t,n){this.stack[this.stack.length-1].children.push(e),this.stack.push(e),this.tokenStack.push([t,n||void 0]),e.position={start:uo(t.start),end:void 0}}function a(e){return function(t){e&&e.call(this,t),c.call(this,t)}}function c(e,t){const n=this.stack.pop(),s=this.tokenStack.pop();if(!s)throw new Error("Cannot close `"+e.type+"` ("+io({start:e.start,end:e.end})+"): it’s not open");s[0].type!==e.type&&(t?t.call(this,e,s[0]):(s[1]||mo).call(this,e,s[0])),n.position.end=uo(e.end)}function l(){return yi(this.stack.pop())}function d(e){const t=this.stack[this.stack.length-1].children;let n=t[t.length-1];n&&"text"===n.type||(n={type:"text",value:""},n.position={start:uo(e.start),end:void 0},t.push(n)),this.stack.push(n)}function u(e){const t=this.stack.pop();t.value+=this.sliceSerialize(e),t.position.end=uo(e.end)}function h(){this.data.atHardBreak=!0}function p(e){this.data.characterReferenceType=e.type}function m(){return{type:"code",lang:null,meta:null,value:""}}function f(){return{type:"heading",depth:0,children:[]}}function g(){return{type:"break"}}function y(){return{type:"html",value:""}}function v(){return{type:"link",title:null,url:"",children:[]}}function b(e){return{type:"list",ordered:"listOrdered"===e.type,start:null,spread:e._spread,children:[]}}}(n)(function(e){for(;!lr(e););return e}(function(e){const t={constructs:Ci([Xr,...(e||{}).extensions||[]]),content:n(Wi),defined:[],document:n(Ki),flow:n($r),lazy:{},string:n(_r),text:n(Br)};return t;function n(e){return function(n){return function(e,t,n){let s={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const i={},r=[];let o=[],a=[];const c={attempt:f(function(e,t){g(e,t.from)}),check:f(m),consume:function(e){qi(e)?(s.line++,s.column=1,s.offset+=-3===e?2:1,y()):-1!==e&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===o[s._index].length&&(s._bufferIndex=-1,s._index++)),l.previous=e},enter:function(e,t){const n=t||{};return n.type=e,n.start=h(),l.events.push(["enter",n,l]),a.push(n),n},exit:function(e){const t=a.pop();return t.end=h(),l.events.push(["exit",t,l]),t},interrupt:f(m,{interrupt:!0})},l={code:null,containerState:{},defineSkip:function(e){i[e.line]=e.column,y()},events:[],now:h,parser:e,previous:null,sliceSerialize:function(e,t){return function(e,t){let n=-1;const s=[];let i;for(;++n<e.length;){const r=e[n];let o;if("string"==typeof r)o=r;else switch(r){case-5:o="\r";break;case-4:o="\n";break;case-3:o="\r\n";break;case-2:o=t?" ":"\t";break;case-1:if(!t&&i)continue;o=" ";break;default:o=String.fromCharCode(r)}i=-2===r,s.push(o)}return s.join("")}(u(e),t)},sliceStream:u,write:function(e){return o=ki(o,e),function(){let e;for(;s._index<o.length;){const t=o[s._index];if("string"==typeof t)for(e=s._index,s._bufferIndex<0&&(s._bufferIndex=0);s._index===e&&s._bufferIndex<t.length;)p(t.charCodeAt(s._bufferIndex));else p(t)}}(),null!==o[o.length-1]?[]:(g(t,0),l.events=Vi(r,l.events,l),l.events)}};let d=t.tokenize.call(l,c);return t.resolveAll&&r.push(t),l;function u(e){return function(e,t){const n=t.start._index,s=t.start._bufferIndex,i=t.end._index,r=t.end._bufferIndex;let o;if(n===i)o=[e[n].slice(s,r)];else{if(o=e.slice(n,i),s>-1){const e=o[0];"string"==typeof e?o[0]=e.slice(s):o.shift()}r>0&&o.push(e[i].slice(0,r))}return o}(o,e)}function h(){const{_bufferIndex:e,_index:t,line:n,column:i,offset:r}=s;return{_bufferIndex:e,_index:t,line:n,column:i,offset:r}}function p(e){d=d(e)}function m(e,t){t.restore()}function f(e,t){return function(n,i,r){let o,d,u,p;return Array.isArray(n)?m(n):"tokenize"in n?m([n]):function(e){return function(t){const n=null!==t&&e[t],s=null!==t&&e.null;return m([...Array.isArray(n)?n:n?[n]:[],...Array.isArray(s)?s:s?[s]:[]])(t)}}(n);function m(e){return o=e,d=0,0===e.length?r:f(e[d])}function f(e){return function(n){return p=function(){const e=h(),t=l.previous,n=l.currentConstruct,i=l.events.length,r=Array.from(a);return{from:i,restore:function(){s=e,l.previous=t,l.currentConstruct=n,l.events.length=i,a=r,y()}}}(),u=e,e.partial||(l.currentConstruct=e),e.name&&l.parser.constructs.disable.null.includes(e.name)?v():e.tokenize.call(t?Object.assign(Object.create(l),t):l,c,g,v)(n)}}function g(t){return e(u,p),i}function v(e){return p.restore(),++d<o.length?f(o[d]):r}}}function g(e,t){e.resolveAll&&!r.includes(e)&&r.push(e),e.resolve&&Si(l.events,t,l.events.length-t,e.resolve(l.events.slice(t),l)),e.resolveTo&&(l.events=e.resolveTo(l.events,l))}function y(){s.line in i&&s.column<2&&(s.column=i[s.line],s.offset+=i[s.line]-1)}}(t,e,n)}}}(n).document().write(function(){let e,t=1,n="",s=!0;return function(i,r,o){const a=[];let c,l,d,u,h;for(i=n+("string"==typeof i?i.toString():new TextDecoder(r||void 0).decode(i)),d=0,n="",s&&(65279===i.charCodeAt(0)&&d++,s=void 0);d<i.length;){if(eo.lastIndex=d,c=eo.exec(i),u=c&&void 0!==c.index?c.index:i.length,h=i.charCodeAt(u),!c){n=i.slice(d);break}if(10===h&&d===u&&e)a.push(-3),e=void 0;else switch(e&&(a.push(-5),e=void 0),d<u&&(a.push(i.slice(d,u)),t+=u-d),h){case 0:a.push(65533),t++;break;case 9:for(l=4*Math.ceil(t/4),a.push(-2);t++<l;)a.push(-1);break;case 10:a.push(-4),t=1;break;default:e=!0,t=1}d=u+1}return o&&(e&&a.push(-5),n&&a.push(n),a.push(null)),a}}()(e,t,!0))))}function uo(e){return{line:e.line,column:e.column,offset:e.offset}}function ho(e,t){let n=-1;for(;++n<t.length;){const s=t[n];Array.isArray(s)?ho(e,s):po(e,s)}}function po(e,t){let n;for(n in t)if(co.call(t,n))switch(n){case"canContainEols":{const s=t[n];s&&e[n].push(...s);break}case"transforms":{const s=t[n];s&&e[n].push(...s);break}case"enter":case"exit":{const s=t[n];s&&Object.assign(e[n],s);break}}}function mo(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+io({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+io({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+io({start:t.start,end:t.end})+") is still open")}const fo=new WeakMap;function go(e){const t=e=>{if("image"===e.type||"html"===e.type)return"";if("string"==typeof e.value)return e.value;const n=["root","list","listItem","blockquote"].includes(e.type)?"\n":"";return(e.children??[]).map(e=>t(e)).join(n)};return t(lo(e))}function yo(e,t){const n=t.trim().toLowerCase();return n?e.flatMap((e,t)=>{if(Us(e))return[];let s=fo.get(e);s?.content!==e.content&&(s={content:e.content,text:go(e.content).toLowerCase()},fo.set(e,s));const i=s.text,r=[];for(let o=i.indexOf(n);o>=0;o=i.indexOf(n,o+n.length))r.push({index:t,message:e,occurrence:r.length});return r}):[]}function vo(e,t){const n=t.trim().toLowerCase();if(!n)return[];const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),i=[];let r="";for(;s.nextNode();){const e=s.currentNode;e.parentElement?.closest('button, [hidden], [aria-hidden="true"]')||(i.push({node:e,start:r.length,end:r.length+e.length}),r+=e.data)}const o=[],a=r.toLowerCase();for(let c=a.indexOf(n);c>=0;c=a.indexOf(n,c+n.length)){const e=c+n.length,t=i.find(e=>e.end>c),s=i.find(t=>t.end>=e);if(!t||!s)continue;const r=document.createRange();r.setStart(t.node,c-t.start),r.setEnd(s.node,e-s.start),o.push(r)}return o}const bo=160;function xo(e){return Math.max(0,e-bo)}const wo=()=>null,So=()=>()=>{};function ko({activeSession:e,activeUsage:t,messages:n,renameTitle:s,busy:i,t:a,onBrowseFiles:c,onClose:l,onExport:u,onJumpToMessage:h,onRename:p,onRenameTitleChange:m,onToggleArchived:y,onTogglePinned:v,onViewChanges:b}){const[x,w]=o.useState(""),{copyText:S,feedback:k}=As(a.commandCopied,a.copyResumeFailed),I=o.useRef(null),C=f(l,I),j=o.useMemo(()=>_t(e),[e]),R=o.useMemo(()=>{const e=x.trim().toLowerCase();return e?n.map((e,t)=>({message:e,index:t})).filter(({message:t})=>("user"===t.role||"assistant"===t.role)&&t.content.toLowerCase().includes(e)).slice(0,20):[]},[n,x]);return r.jsxs("div",{"aria-labelledby":"session-detail-title","aria-modal":"true",className:"session-detail-drawer",ref:C,role:"dialog",tabIndex:-1,children:[r.jsx("div",{className:"drawer-backdrop",onClick:l,"aria-hidden":"true"}),r.jsxs("aside",{className:"session-detail-panel",children:[r.jsxs("header",{className:"drawer-header",children:[r.jsxs("div",{children:[r.jsx("span",{className:"eyebrow",children:e.agent}),r.jsx("strong",{id:"session-detail-title",title:d(e),children:r.jsx(hi,{title:d(e),draft:s,label:a.rename,disabled:i,onDraftChange:m,onCommit:p},e.sessionId)})]}),r.jsx("button",{"aria-label":a.closeSessionDetails,title:a.closeSessionDetails,className:"icon-button",onClick:l,ref:I,type:"button",children:r.jsx(He,{"aria-hidden":"true"})})]}),r.jsxs("div",{className:"detail-info-grid",children:[r.jsxs("div",{children:[r.jsx(te,{"aria-hidden":"true"}),r.jsx("span",{children:a.workingDirectory}),r.jsx("strong",{title:e.cwd,children:e.cwd})]}),r.jsxs("div",{children:[r.jsx(ge,{"aria-hidden":"true"}),r.jsx("span",{children:a.messages}),r.jsx("strong",{children:n.filter(e=>"user"===e.role||"assistant"===e.role).length})]}),r.jsxs("div",{children:[r.jsx(ce,{"aria-hidden":"true"}),r.jsx("span",{children:a.session}),r.jsx("strong",{title:e.sessionId,children:e.sessionId})]}),r.jsxs("div",{children:[r.jsx($e,{"aria-hidden":"true"}),r.jsx("span",{children:a.runtime}),r.jsx("strong",{children:a.runtimeState(e.runtime.state)})]})]}),e.branch||e.diffStat?r.jsxs("button",{className:"detail-command-card detail-changes-card",type:"button",onClick:b,children:[r.jsx(re,{"aria-hidden":"true"}),r.jsx("span",{className:"detail-change-label",children:e.branch??a.changes}),r.jsx("span",{className:"detail-change-stats",role:"group","aria-label":a.changes,children:e.diffStat?r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"diff-add",children:["+",e.diffStat.additions]}),r.jsxs("span",{className:"diff-del",children:["-",e.diffStat.deletions]})]}):null})]}):null,r.jsxs("label",{className:"detail-search",children:[r.jsx(Ee,{"aria-hidden":"true"}),r.jsx("input",{value:x,onChange:e=>w(e.target.value),placeholder:a.searchMessages}),x.trim()?r.jsx("small",{children:a.searchResultCount(R.length)}):null]}),x.trim()&&R.length?r.jsx("div",{className:"detail-search-results",children:R.map(({message:e,index:t})=>r.jsxs("button",{type:"button",onClick:()=>{h(t,x),l()},children:[r.jsx("span",{children:on(e,a)}),r.jsx("strong",{children:e.content})]},`${e.historyKey??e.timestamp??t}:${t}`))}):null,x.trim()?null:r.jsxs(r.Fragment,{children:[r.jsxs("button",{className:"detail-command-card",type:"button",onClick:c,children:[r.jsx(te,{"aria-hidden":"true"}),r.jsx("span",{children:a.browseFiles})]}),j&&r.jsxs("button",{className:"detail-command-card",type:"button",onClick:()=>{S(j)},children:[r.jsx(W,{"aria-hidden":"true"}),r.jsx("span",{title:j,children:j})]}),r.jsx(Ns,{feedback:k}),r.jsxs("div",{className:"detail-action-grid",children:[r.jsxs("button",{className:"icon-text-button",disabled:i,type:"button",onClick:v,children:[r.jsx(ke,{"aria-hidden":"true"}),e.pinned?a.unpin:a.pin]}),r.jsxs("button",{className:"icon-text-button",disabled:i,type:"button",onClick:y,children:[r.jsx(P,{"aria-hidden":"true"}),e.archived?a.unarchive:a.archive]}),r.jsxs("button",{className:"icon-text-button",type:"button",onClick:u,children:[r.jsx(g,{"aria-hidden":"true"}),a.exportSession]})]}),t?r.jsxs("p",{className:"detail-usage",children:[a.usage,": ",t.limits?.fiveHour?.usedPercent??"-","% 5h ·"," ",t.limits?.weekly?.usedPercent??"-","% weekly"]}):null,r.jsxs("p",{className:"detail-usage",children:[a.created," ",rn(e.createdAt,Date.now(),a)]})]})]})]})}function Io({client:e,activeSession:t,activeSessionId:n,activeModelOptions:s,activeQueue:i,queueControls:a,activeUsage:c,agent:l,approvalMode:d,attachments:u,busy:h,cwd:p,draft:m,effort:f,errorText:g,failedSend:y,onDismissFailedSend:v,fastMode:b,historyLoading:x,hasOlderHistory:w,olderHistoryLoading:S,onLoadOlderHistory:k,messages:I,messagesSessionId:C,model:j,phase:R,quickReplies:M,onQuickRepliesChange:E,quickRepliesOpen:T,onQuickRepliesOpenChange:A,onSendQuickReply:N,renameTitle:P,respondingSessionIds:D,sendShortcut:F,skills:L,uploadBusy:q,detailsOpen:O,t:$,onApprovalModeChange:z,onBrowseFiles:_,onCancelQueuedTurn:B,onClearInterrupt:H,onDraftChange:W,onDetailsOpenChange:K,onEffortChange:Q,onExportActiveSession:U,onRewindMessage:V,onFastModeChange:G,onRetryFailedSend:J,onModelChange:Z,onOpenRemoteFile:Y,onInterrupt:X,onRetry:ee,onDismissError:te,onRefreshSkills:ne,onRenameSession:se,onRenameTitleChange:ie,onRemoveAttachment:re,onSubmit:oe,onToggleArchived:ae,onTogglePinned:ce,onUploadFiles:le,onViewChanges:de}){const ue=lt(e,l,p,n,j,s,$),he=function(e,t,n,s){const i=o.useSyncExternalStore(e.submission?.subscribe??So,e.submission?.getSnapshot??wo,wo),r=o.useRef(new Set),a=async e=>{if(!r.current.has(s)){r.current.add(s);try{await e()}finally{r.current.delete(s)}}};return{sending:!!i?.some(e=>e.sessionId===s),submit:t=>{if(t?.preventDefault(),n)return a(()=>e())},retry:()=>a(t)}}(oe,J,"connected"===R&&!h&&!!m.trim(),n),pe=o.useRef({onRewindMessage:V,onOpenRemoteFile:Y,onDismissFailedSend:v,retry:he.retry});o.useLayoutEffect(()=>{pe.current={onRewindMessage:V,onOpenRemoteFile:Y,onDismissFailedSend:v,retry:he.retry}});const[me,fe]=o.useState(null),[ge,ye]=o.useState(null),[ve,be]=o.useState(!1),xe=function(e,t,n){let s;for(let o=t.length-1;o>=0;o--)if("assistant"===t[o].role&&"info"!==t[o].type){s=t[o];break}const i=s?`${s.historyKey??s.timestamp}:${s.content.length}`:"",r=o.useRef({sessionId:e,revision:i}),[a,c]=o.useState(!1);return o.useEffect(()=>{r.current.sessionId===e&&n?i&&i!==r.current.revision&&c(!0):c(!1),r.current={sessionId:e,revision:i}},[e,i,n]),n&&r.current.sessionId===e&&a}(n,C===n?I:[],ve),we=o.useRef(null),Se=o.useRef([]),ke=o.useRef(null),Ie=o.useRef(null),Ce=o.useRef(!1),je=o.useRef(!1),Re=o.useRef(!0),Me=o.useRef(0),Ee=o.useRef(0),Te=o.useMemo(()=>function(e){const t=[];for(let n=0;n<e.length;n+=1){const s=e[n];if(!Us(s)){t.push({type:"message",index:n,message:s});continue}const i=[];let r=n;for(;r<e.length&&Us(e[r]);)i.push({index:r,message:e[r]}),r+=1;t.push({type:"toolGroup",entries:i,id:`tool-group:${i.map(({index:e,message:t})=>Gs(t,e)).join("|")}`}),n=r-1}return t}(I),[I]),Ae=Boolean(n&&D.has(n)),Ne=Ae&&C===n&&!x,De=Ne&&"assistant"===I.at(-1)?.role&&"info"!==I.at(-1)?.type?I.length-1:-1,[Fe,Le]=o.useState(!1),{ensureMessageVisible:qe,hiddenItemCount:Oe,hiddenLaterItemCount:$e,revealAll:ze,revealEarlier:_e,revealLatest:Be,revealStart:He,visibleItems:We}=function(e,t,n=!1){const s=t.length,[i,r]=o.useState(()=>({sessionId:e,start:xo(s),total:s})),a=i.sessionId!==e?xo(s):n?0:-1===i.start?-1:s>i.total&&i.start+bo>=i.total?xo(s):Math.min(i.start,xo(s));o.useLayoutEffect(()=>{i.sessionId===e&&i.start===a&&i.total===s||r({sessionId:e,start:a,total:s})},[e,a,i,s]);const c=o.useCallback(()=>{r(t=>({sessionId:e,start:Math.max(0,(t.sessionId===e?t.start:xo(s))-120),total:s}))},[e,s]),l=o.useCallback(n=>{const i=t.findIndex(e=>function(e,t){return"message"===e.type?e.index===t:e.entries.some(e=>e.index===t)}(e,n));if(-1===a||i<0||i>=a&&i<a+bo)return!1;const o=Math.min(xo(s),Math.max(0,i-40));return r({sessionId:e,start:o,total:s}),!0},[t,e,a,s]),d=o.useCallback(()=>{r({sessionId:e,start:xo(s),total:s})},[e,s]),u=o.useCallback(()=>{r({sessionId:e,start:0,total:s})},[e,s]),h=Math.max(0,a),p=-1===a?s:Math.min(s,a+bo);return{ensureMessageVisible:l,hiddenItemCount:h,hiddenLaterItemCount:Math.max(0,s-p),revealEarlier:c,revealLatest:d,revealStart:u,revealAll:()=>r({sessionId:e,start:-1,total:s}),visibleItems:o.useMemo(()=>t.slice(h,p),[t,h,p])}}(n,Te,Fe),Ke=o.useRef(!1),Qe=o.useRef(null),Ue=o.useMemo(()=>Boolean(y&&We.some(e=>"message"===e.type&&e.message.historyKey===y.historyKey)),[y,We]),Ve=o.useRef(null),{copyText:Ge,feedback:Je}=As($.messageCopied,$.copyFailed),Ze=function(e,t,n,s){const[i,r]=o.useState(""),[a,c]=o.useState(0),l=o.useMemo(()=>yo(e,i),[e,i]),d=l.length?a%l.length:0,u=l[d],h=o.useRef(s);return h.current=s,o.useEffect(()=>{r(""),c(0)},[t]),o.useEffect(()=>{u&&h.current(u.index)},[i,d,u?.index]),o.useEffect(()=>{const e=n.current;if(!i.trim()||!e||"undefined"==typeof CSS||!CSS.highlights||"undefined"==typeof Highlight)return;let t=0,s=!1;const r=()=>{const t=[],n=[];for(const s of e.querySelectorAll(".message-frame[data-message-index]")){const e=s.querySelector(".message-markdown, .message-markdown-source, .message > pre");if(!e)continue;const r=vo(e,i);t.push(...r),Number(s.getAttribute("data-message-index"))===u?.index&&r[u.occurrence]&&n.push(r[u.occurrence])}if(CSS.highlights.set("conversation-matches",new Highlight(...t)),CSS.highlights.set("conversation-current",new Highlight(...n)),n[0]&&!s){s=!0;const t=n[0].getBoundingClientRect(),i=e.getBoundingClientRect();(t.top<i.top||t.bottom>i.bottom)&&(e.scrollTop+=t.top-i.top-i.height/2)}},o=()=>{cancelAnimationFrame(t),t=requestAnimationFrame(()=>{t=requestAnimationFrame(r)})},a=new MutationObserver(o);return a.observe(e,{childList:!0,characterData:!0,subtree:!0}),o(),()=>{a.disconnect(),cancelAnimationFrame(t),CSS.highlights.delete("conversation-matches"),CSS.highlights.delete("conversation-current")}},[i,d,u?.index,u?.occurrence,n]),{query:i,matchCount:l.length,activeMatchIndex:l.length?d+1:0,activeMessageIndex:u?.index,onChange:e=>{r(e),c(0)},onJump:(t,n)=>{r(n),c(Math.max(0,yo(e,n).findIndex(e=>e.index===t)))},onNext:()=>c(e=>l.length?(e+1)%l.length:0),onPrevious:()=>c(e=>l.length?(e+l.length-1)%l.length:0)}}(I,n,we,e=>((e,t="smooth")=>{Re.current=!1,Me.current=0;const n=qe(e),s=()=>Se.current[e]?.scrollIntoView({behavior:t,block:"center"});n?requestAnimationFrame(()=>requestAnimationFrame(s)):s()})(e,"instant")),Ye=o.useCallback(()=>{const e=we.current;e&&(Re.current=!0,Me.current=0,e.scrollTop=e.scrollHeight,be(!1))},[]),Xe=o.useCallback(e=>{Re.current=!0,Me.current=0,je.current=!0,Ce.current=!1,Ve.current=null;const t=we.current,n=t?t.scrollHeight-t.scrollTop-t.clientHeight:0,s=e??(0===$e&&t&&n<=t.clientHeight?"smooth":"auto"),i=()=>{const e=we.current;e&&je.current&&(e.scrollTo({top:e.scrollHeight,behavior:s}),be(!1),requestAnimationFrame(()=>{je.current=!1}))};$e>0?(Be(),requestAnimationFrame(()=>requestAnimationFrame(i))):i()},[$e,Be]),et=()=>{const e=we.current;e&&(Ve.current=function(e,t){const n=e.querySelector(".message-frame"),s=t[0];return{element:n,message:"message"===s?.type?s.message:s?.entries[0]?.message,top:n?n.getBoundingClientRect().top-e.getBoundingClientRect().top:e.scrollTop,height:e.scrollHeight}}(e,We))},tt=async()=>{if(!n||!w||!k||x||S||Qe.current)return;const e=n;Qe.current=e,Ke.current=!0,Re.current=!1,Ce.current=!0,et(),Le(!0);try{await k()}finally{Qe.current===e&&(Qe.current=null,Le(!1))}},nt=()=>{const e=we.current;if(!e)return;Me.current>0&&e.scrollTop<160&&C===n&&!Ce.current&&!je.current&&(Oe>0?(Ce.current=!0,et(),_e()):tt());const t=e.scrollTop>Ee.current;Ee.current=e.scrollTop;const s=e.scrollHeight-e.scrollTop-e.clientHeight;Me.current>0&&!je.current&&!Ce.current&&(Re.current=t&&s<=2&&0===$e),be(s>180||$e>0)};o.useLayoutEffect(()=>{$e>0&&be(!0)},[$e]);const st=function(e,t,n,s,i,r,o,a=0){const c=()=>{const o=t.current||s.current;n.current=null,s.current=!1,t.current=!1,i.current=performance.now();const a=e.current;r.current=a?.scrollTop??0,o&&a?.scrollTo({top:a.scrollTop,behavior:"auto"})};return{toStart:()=>{const c=e.current;c&&(n.current=null,s.current=!1,t.current=!1,i.current=performance.now(),r.current=0,c.scrollTo({top:c.scrollTop,behavior:"auto"}),a>0&&o?.(),requestAnimationFrame(()=>requestAnimationFrame(()=>e.current?.scrollTo({top:0,behavior:a>0?"auto":"smooth"}))))},onWheel:t=>{if(!t.deltaY)return;const n=e.current;(t.deltaY<0||n&&n.scrollHeight-n.scrollTop-n.clientHeight>2)&&c()},onPointerDown:e=>{const t=e.currentTarget.getBoundingClientRect();(1===e.button||e.clientX>=t.right-16)&&c()},onTouchStart:c,onKeyDown:e=>{e.target instanceof Element&&e.target.closest('input,textarea,[contenteditable="true"]')||["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(e.key)&&c()}}}(we,Re,Ie,je,Me,Ee,He,Oe),it=function(e){const t=e.at(-1);return t?`${e.length}:${t.historyKey??""}:${t.timestamp??""}:${t.content.length}`:"0"}(I);o.useLayoutEffect(()=>{ke.current!==n&&(Ve.current=null,Ce.current=!1,Ke.current=!1,Qe.current=null,Le(!1));const e=Ve.current,t=we.current;if(e&&t){if(Fe)return;return Oe>0&&Ke.current?void He():(function(e,t,n,s){const i=t.message,r=i?n.findIndex(e=>e===i||(i.historyKey?e.historyKey===i.historyKey:e.role===i.role&&e.timestamp===i.timestamp&&e.content===i.content)):-1,o=r>=0?s[r]:t.element;e.scrollTop+=o?.isConnected?o.getBoundingClientRect().top-e.getBoundingClientRect().top-t.top:e.scrollHeight-t.height}(t,e,I,Se.current),Ve.current=null,Ce.current=!1,void(Ke.current=!1))}if(ke.current!==n&&(ke.current=n,Ie.current=n,fe(null),ye(null)),!we.current)return;const s=C===n;if(null!==n&&Ie.current===n&&s&&(!x||I.length>0)){Ye();let e=0,t=-1,s=0;const i=performance.now(),r=()=>{if(Ie.current!==n)return;Ye();const o=we.current?.scrollHeight??0;s=o===t?s+1:0,t=o;const a=performance.now()-i>=1400;!x&&s>=4||!x&&a?Ie.current=null:a||(e=requestAnimationFrame(r))};return e=requestAnimationFrame(r),be(!1),()=>cancelAnimationFrame(e)}Re.current&&0===$e&&Ye()},[n,Oe,$e,x,it,Fe,He,I.length,C,R,Ne,Ye]),o.useLayoutEffect(()=>{const e=we.current;if(!e)return;const t=new ResizeObserver(()=>{Re.current&&0===$e&&Ye()});t.observe(e);for(const n of e.children)t.observe(n);return()=>t.disconnect()},[n,it,Oe,$e,Ne,Ye]);const rt=Ze.activeMessageIndex;return function(e,t,n){const s=o.useRef(n);s.current=n;const i=o.useRef(!1),[r,a]=o.useState(0);o.useLayoutEffect(()=>{i.current=!1;const t=t=>{"focusin"===t.type&&t.target instanceof Element&&t.target.contains(e.current)||(i.current=t.target instanceof Element&&Boolean(e.current?.contains(t.target))&&!t.target.closest("input,textarea,select")&&!t.target.isContentEditable)},n=[["pointerdown",t],["focusin",t],["keydown",e=>{i.current&&!e.isComposing&&(!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey||"a"!==e.key.toLowerCase()||(e.preventDefault(),s.current(),a(e=>e+1)))}]];return n.forEach(([e,t])=>document.addEventListener(e,t,!0)),()=>n.forEach(([e,t])=>document.removeEventListener(e,t,!0))},[e,t]),o.useLayoutEffect(()=>{if(!i.current)return;const t=e.current?.querySelectorAll(".message-frame"),n=t?.[t.length-1];n&&window.getSelection()?.setBaseAndExtent(t[0],0,n,n.childNodes.length)},[r,e,t])}(we,n,()=>{et(),ze()}),r.jsxs("section",{className:"chat-pane","aria-label":$.chat,children:[r.jsx(fi,{activeSession:t,agent:l,cwd:p,t:$,onOpenDetails:()=>t&&K(!0),onScrollToStart:st.toStart,renameTitle:P,busy:h,onRename:se,onRenameTitleChange:ie,onViewChanges:de,search:Ze}),r.jsxs("div",{className:"message-scroll","data-session-id":C===n?n??void 0:void 0,"aria-busy":x,"data-history-loading":x?"true":"false","data-rendered-items":We.length,"data-hidden-items":Oe,"data-hidden-later-items":$e,"data-total-messages":I.length,ref:we,onScroll:nt,...st,onWheel:e=>{st.onWheel(e),e.deltaY<0&&nt()},children:[x&&0===I.length?r.jsx(Ds,{label:$.loadingHistory}):null,x||0!==I.length||Ne?null:r.jsxs("div",{className:"empty-state compact",children:[r.jsx(Pe,{"aria-hidden":"true"}),r.jsx("h2",{children:t?$.noVisibleMessages:$.startDaemonSession}),r.jsx("p",{children:$.emptyChatHint})]}),w&&0===Oe?r.jsx("div",{className:"conversation-window-gate",children:r.jsx("button",{type:"button",disabled:S,onClick:()=>{tt()},children:S?$.loadingHistory:$.loadEarlierMessages})}):null,Oe>0?r.jsx("div",{className:"conversation-window-gate",children:r.jsx("button",{type:"button",onClick:()=>{Ce.current=!0,et(),_e()},children:$.showEarlierMessages(Oe)})}):null,r.jsx(di,{items:We,activeQueue:C===n?i:void 0,actions:pe,messageRefs:Se,activeMatchedMessageIndex:rt,baseCwd:t?.cwd,canRewind:!h&&!Ae,hiddenLaterItemCount:$e,replyingMessageIndex:De,openSourceKey:me,openToolKey:ge,setOpenSourceKey:fe,setOpenToolKey:ye,copyText:Ge,failedSend:y,t:$}),Ne&&0===$e&&De<0?r.jsx("div",{className:"message-frame assistant","data-replying-placeholder":"true",children:r.jsx("div",{className:"message assistant replying-placeholder",children:r.jsx(ri,{label:$.replyingMessage})})}):null,$e>0?r.jsx("div",{className:"conversation-window-gate",children:r.jsx("button",{type:"button",onClick:()=>Xe("auto"),children:$.showLatestMessages($e)})}):null,r.jsx("div",{"aria-hidden":"true",className:"message-latest-anchor"})]}),ve?r.jsx(Ls,{label:xe?$.interactionNewReply:$.interactionLatest,onClick:()=>Xe()}):null,r.jsx(Ns,{feedback:Je}),r.jsx(Es,{terminals:t?.runtime.backgroundTerminals,t:$},`terminals:${n}`),r.jsx(ui,{activeSession:t,busy:h,errorText:g,failedSend:y,failedSendVisibleInConversation:Ue,onClearInterrupt:H,onDismissError:te,onDismissFailedSend:v,onRetry:ee,onRetryFailedSend:()=>{he.retry()},t:$}),r.jsx(Ms,{activeModelOptions:ue,activeQueue:i,queueControls:{...a,onAction:(e,t)=>(Xe("auto"),a.onAction(e,t))},agent:l,approvalMode:d,attachments:u,busy:h,sending:he.sending,responding:Ae,onStop:X,draft:m,effort:f,fastMode:b,model:j,phase:R,quickReplies:M,onQuickRepliesChange:E,quickRepliesOpen:T,onQuickRepliesOpenChange:A,onSendQuickReply:N,sendShortcut:F,skills:L,uploadBusy:q,onApprovalModeChange:z,onCancelQueuedTurn:B,onDraftChange:W,onEffortChange:Q,onFastModeChange:G,onModelChange:Z,onRemoveAttachment:re,onOpenRemoteFile:Y,onRefreshSkills:ne,onSubmit:e=>(Xe("auto"),he.submit(e)),onUploadFiles:le,t:$},n),O&&t?r.jsx(ko,{activeSession:t,activeUsage:c,busy:h,messages:I,renameTitle:P,t:$,onBrowseFiles:()=>{K(!1),_()},onClose:()=>K(!1),onExport:U,onJumpToMessage:(e,t)=>{Ze.onJump(e,t)},onRename:se,onRenameTitleChange:ie,onToggleArchived:ae,onTogglePinned:ce,onViewChanges:()=>{K(!1),de(t.sessionId)}}):null]})}const Co=["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"],jo=["authorization","proxy-authorization"],Ro=["cookie","set-cookie"],Mo=[...jo,...Ro],Eo=(e,t)=>t.length-e.length,To=[...Co].sort(Eo).join("|"),Ao=Co.filter(e=>!Mo.includes(e)).sort(Eo).join("|"),No=[...jo].sort(Eo).join("|"),Po=[...Ro].sort(Eo).join("|"),Do=new RegExp(`(?:${To}|credential|private[-_ ]?key|session[-_ ]?id|e-?mail|phone|mobile|address)`,"i"),Fo=new RegExp(`(["']?(?:${No})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|(?:Basic|Bearer)\\s+[^\\s,;}]+|AWS4-HMAC-SHA256[^\\r\\n]*(?=\\r?$)|[^\\s,;}]+)`,"gim"),Lo=new RegExp(`(["']?(?:${Po})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\r\\n]+)`,"gi"),qo=new RegExp(`(["']?(?:${Ao})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\s,;}&]+)`,"gi"),Oo=new RegExp(`([?&](?:${To})=)[^&\\s]+`,"gi");function $o(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]")}(function(e,t="[REDACTED]"){const n=(e,n,s)=>{const i='"'===s[0]||"'"===s[0]?s[0]:"";if(!i)return`${n}${t}`;const r=s.slice(1,-1).trim(),o=/^(Basic|Bearer)\b/i.exec(r)?.[1];return`${n}${i}${o?`${o} `:""}${t}${i}`};return e.replace(/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gi,t).replace(Fo,n).replace(Lo,n).replace(qo,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(Oo,`$1${t}`)}(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 zo(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 _o(e,t={}){const n=new AbortController,s=Number.isFinite(t.timeoutMs)&&(t.timeoutMs??0)>0?t.timeoutMs:15e3;let i;try{const r=(t.transport??zo)({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)=>{i=setTimeout(()=>{n.abort(),t(new Error("Feedback request timed out"))},s)}),a=await Promise.race([r,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{i&&clearTimeout(i)}}const Bo=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 Ho(e){const t={contextSchemaVersion:1};if(e)for(const[n,s]of Object.entries(e))Bo.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),i=Math.max(0,t.maxDepth??8),r=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=$o(e).slice(0,Math.min(o,a.remaining));return a.remaining-=t.length,t}if(t>=i)return"[MAX_DEPTH]";if("object"!=typeof e)return $o(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,i]of Object.entries(e).slice(0,r)){if(a.remaining<=0)break;const e=$o(s).slice(0,Math.min(120,a.remaining));a.remaining-=e.length,n[e]=Do.test(s)?"[REDACTED]":l(i,t+1)}return n};return l(e,0)}(t)}const Wo={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"},Ko={title:"意见反馈",subtitle:"报告问题,或告诉我们希望改进的地方。",bug:"问题",feature:"建议",description:"详细说明",descriptionPlaceholder:"发生了什么,或者你希望我们怎样改进?",email:"邮箱(选填)",emailPlaceholder:"便于我们回复你",includeDiagnostics:"附带经过隐私处理的诊断信息",privacyNotice:"仅在需要时附带诊断信息;发送前会移除已识别的凭据、个人标识和本地路径。",submit:"发送反馈",sending:"正在发送…",success:"感谢反馈,已经发送成功。",error:"发送失败,请稍后重试。",close:"关闭"},Qo={title:"意見回饋",subtitle:"回報問題,或告訴我們希望改善的地方。",bug:"問題",feature:"建議",description:"詳細說明",descriptionPlaceholder:"發生了什麼,或你希望我們如何改善?",email:"電子郵件(選填)",emailPlaceholder:"方便我們回覆你",includeDiagnostics:"附上經過隱私處理的診斷資訊",privacyNotice:"僅在需要時附上診斷資訊;傳送前會移除已識別的憑證、個人識別資訊和本機路徑。",submit:"傳送回饋",sending:"正在傳送…",success:"感謝回饋,已成功傳送。",error:"傳送失敗,請稍後再試。",close:"關閉"};function Uo(e){const t=e?.trim().toLowerCase().replace(/_/g,"-")??"";return/^zh(?:-(?:tw|hk|mo|hant))(?:-|$)/u.test(t)?Qo:t.startsWith("zh")?Ko:Wo}const Vo=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function Go(e){if(!e?.length)return;if(e.length>4)throw new Error("Feedback supports at most 4 images");const t=e.map(e=>{if(!Vo.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:$o(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 Jo({language:e,entry:t="web-settings"}){const i=s(e),a=o.useMemo(()=>Uo(i),[i]),[c,l]=o.useState("bug"),[d,u]=o.useState(""),[h,p]=o.useState(""),[m,f]=o.useState("idle");return r.jsxs("section",{className:"control-section compact-section",children:[r.jsx("h2",{children:a.title}),r.jsx("p",{className:"empty-copy",children:a.subtitle}),r.jsxs("div",{className:"feedback-type-grid",children:[r.jsx("button",{className:"bug"===c?"primary-button":"",type:"button","aria-pressed":"bug"===c,onClick:()=>l("bug"),children:a.bug}),r.jsx("button",{className:"feature"===c?"primary-button":"",type:"button","aria-pressed":"feature"===c,onClick:()=>l("feature"),children:a.feature})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:a.description}),r.jsx("textarea",{rows:5,maxLength:8e3,value:d,placeholder:a.descriptionPlaceholder,onChange:e=>u(e.target.value)})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:a.email}),r.jsx("input",{type:"email",maxLength:320,value:h,placeholder:a.emailPlaceholder,onChange:e=>p(e.target.value)})]}),r.jsx("button",{className:"primary-button",type:"button",disabled:!d.trim()||"sending"===m,onClick:()=>{(async()=>{if(d.trim()&&"sending"!==m){f("sending");try{await _o(function(e){const t=function(e){return $o(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=$o(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:Ho(e.metadata),images:Go(e.images)}}({product:"vibelet",source:"desktop"===n().kind?"desktop":"web",type:c,description:d,email:h,appVersion:n().appVersion||"web",locale:i,platform:navigator.platform||"web",metadata:{app:"desktop"===n().kind?"vibelet-desktop":"vibelet-web",entry:t,screen:"connection-guide"===t?"connection-guide":"settings/language",module:"feedback",action:"manual-submit",userAgent:navigator.userAgent}})),u(""),f("success")}catch{f("error")}}})()},children:"sending"===m?a.sending:a.submit}),"success"===m?r.jsx("p",{className:"empty-copy success-copy",children:a.success}):null,"error"===m?r.jsx("p",{className:"empty-copy error-copy",children:a.error}):null]})}const Zo={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 Yo(){const e=Zo[s(i().language)],[t,n]=o.useState(""),[a,c]=o.useState("");return r.jsxs("form",{className:"web-pairing-form",onSubmit:n=>{n.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,i=s.searchParams.get("data");return i&&!s.hash&&"vibelet:"===s.protocol&&"pair"===s.hostname&&(s.hash=new URLSearchParams({pair:i}).toString(),s.searchParams.delete("data")),s}(e.trim()),n=os(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}(t)),n=e.origin===window.location.origin&&e.pathname===window.location.pathname&&e.search===window.location.search;window.location.assign(e.href),n&&window.location.reload()}catch(s){c(s instanceof Error&&"expired"===s.message?e.expired:e.invalid)}},children:[r.jsx("label",{htmlFor:"web-pairing-link",children:e.label}),r.jsx("p",{children:e.hint}),r.jsx("input",{id:"web-pairing-link",value:t,onChange:e=>{n(e.target.value),c("")},autoComplete:"off",spellCheck:!1,required:!0}),r.jsx("button",{className:"primary-button",type:"submit",children:e.connect}),a&&r.jsx("p",{role:"alert",className:"connection-guide-error",children:a})]})}const Xo="vibelet --access=quick";function ea({errorText:e,t}){const[n,s]=o.useState("idle"),[a,c]=o.useState(!1),l=i().language,d=Uo(l);return r.jsx("main",{className:"connection-guide",id:"vibelet-main-content",tabIndex:-1,children:r.jsxs("section",{className:"connection-guide-content","aria-labelledby":"connection-guide-title",children:[r.jsx("span",{className:"connection-guide-mark","aria-hidden":"true",children:r.jsx(Le,{})}),r.jsx("span",{className:"connection-guide-eyebrow",children:"Vibelet"}),r.jsx("h1",{id:"connection-guide-title",children:t.openDaemonWebLink}),r.jsx("p",{children:t.openDaemonWebLinkHint}),r.jsx(Yo,{}),r.jsxs("div",{className:"connection-command",children:[r.jsx("code",{children:Xo}),r.jsxs("button",{className:"primary-button",onClick:()=>{(async()=>{try{await Ts(Xo),s("success")}catch{s("error")}window.setTimeout(()=>s("idle"),1800)})()},type:"button",children:["success"===n?r.jsx($,{"aria-hidden":"true"}):r.jsx(U,{"aria-hidden":"true"}),r.jsx("span",{children:"success"===n?t.commandCopied:"error"===n?t.copyFailed:t.copyStartCommand})]})]}),r.jsx("p",{className:"connection-guide-footnote",children:t.connectionGuideFootnote}),e?r.jsx("p",{className:"connection-guide-error",children:e}):null,r.jsxs("button",{className:"connection-feedback-toggle",type:"button","aria-expanded":a,onClick:()=>c(e=>!e),children:[r.jsx(ge,{"aria-hidden":"true"}),d.title]}),a?r.jsx("div",{className:"connection-feedback-panel",children:r.jsx(Jo,{language:l,entry:"connection-guide"})}):null]})})}const ta=o.lazy(()=>m(()=>import("./ImageViewer-BGZDYUl-.js"),__vite__mapDeps([8,1,2,9,10])));function na(){const[e,t]=o.useState(null);return o.useEffect(()=>{const e=e=>t(e.detail);return window.addEventListener(Tn,e),()=>window.removeEventListener(Tn,e)},[]),e?r.jsx(o.Suspense,{fallback:null,children:r.jsx(ta,{request:e,onClose:()=>t(null)},e.images[e.index].src)}):null}function sa(e,t){const n=o.useRef(new Map);n.current.has(e)||n.current.set(e,"function"==typeof t?t():t);const[s,i]=o.useState(()=>new Map);return[s.has(e)?s.get(e):n.current.get(e),o.useCallback(t=>{i(s=>{const i=s.has(e)?s.get(e):n.current.get(e),r="function"==typeof t?t(i):t;return Object.is(i,r)?s:new Map(s).set(e,r)})},[e])]}function ia(e,t){return JSON.stringify([e??null,t??null])}function ra(e,t){try{const[n,s]=JSON.parse(e),[i,r]=JSON.parse(t);return n===i&&null===s&&"string"==typeof r}catch{return!1}}const oa=o.createContext(null);function aa({children:e,scopeKey:t}){const n=function(e="default"){const t=o.useRef(null),n=o.useRef(null),s=o.useRef({browser:0,terminal:0}),[i,r]=o.useState(0),[a,c]=o.useState([]),l=a.filter(t=>(t.scopeKey??"default")===e),[d,u]=sa(`${i}:${e}`,null),[h,p]=sa(`${i}:${e}`,()=>({})),[m,f]=o.useState({}),g=o.useCallback((t,n,i,r,o,a)=>{const l=crypto.randomUUID(),d="diff"===t?"center":"right",h=n;return"diff"!==t&&(n=`${n} ${++s.current[t]}`),c(s=>[...s,{id:l,kind:t,title:n,defaultTitle:h,cwd:i,session:r,scope:o,path:a,location:d,scopeKey:e}]),"center"===d?u(l):p(e=>({...e,[t]:l})),l},[e,u,p]),y=o.useRef(new Set),v=o.useCallback((n,s)=>{const i=l.filter(e=>"browser"===e.kind&&"right"===e.location&&!e.url&&!e.currentUrl&&!y.current.has(e.id)),r=i.find(e=>e.id===h.browser)??i[0],o=r?.id??crypto.randomUUID();r&&y.current.add(o),c(t=>r?t.map(e=>e.id===o?{...e,title:s,url:n,emptyPlaceholder:!1}:e):[...t,{id:o,kind:"browser",location:"right",title:s,defaultTitle:s,url:n,scopeKey:e}]),p(e=>({...e,browser:o})),t.current?.("browser",!0)},[l,h.browser,e,p]),b=o.useCallback((e,t)=>{c(n=>n.map(n=>n.id===e&&n.currentUrl!==t?{...n,currentUrl:t,emptyPlaceholder:!t&&n.emptyPlaceholder}:n))},[]),x=o.useCallback((e,n)=>{const s=l.find(t=>t.id===e);s&&(c(t=>t.map(t=>t.id===e?{...t,location:n}:t)),"center"===n?(u(e),p(t=>({...t,[s.kind]:l.find(t=>t.id!==e&&t.kind===s.kind&&"right"===t.location)?.id}))):(p(t=>({...t,[s.kind]:e})),t.current?.(s.kind),d===e&&u(null)))},[l,d,u,p]),w=o.useCallback(t=>{y.current.delete(t);const s=l.find(e=>e.id===t);if(!s)return;const i=l.find(e=>e.id!==t&&e.kind===s.kind&&e.location===s.location),r=i||"diff"===s.kind||"right"!==s.location&&l.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};c(e=>[...e.filter(e=>e.id!==t),...r?[r]:[]]),i||"right"!==s.location||"diff"===s.kind||n.current?.(s.kind),d===t&&u(null),(r||h[s.kind]===t)&&p(e=>({...e,[s.kind]:r?.id??i?.id}))},[l,d,h,e,u,p]),S=o.useCallback(e=>{c(t=>t.map(t=>t.id===e&&t.emptyPlaceholder?{...t,emptyPlaceholder:!1}:t))},[]),k=o.useCallback((e,t)=>c(n=>n.map(n=>n.id===e&&n.title!==t?{...n,title:t}:n)),[]),I=o.useCallback((e,t)=>f(n=>{if(n[e]===t||!n[e]&&!t)return n;const s={...n};return t?s[e]=t:delete s[e],s}),[]),C=o.useCallback(()=>{y.current.clear(),c([]),u(null),p({}),r(e=>e+1)},[u,p]);return o.useMemo(()=>({scopeKey:e,allItems:a,openRight:t,closeRight:n,openBrowser:v,updateBrowserUrl:b,activate:S,epoch:i,items:l,center:d,right:h,hosts:m,add:g,move:x,close:w,rename:k,register:I,reset:C,setCenter:u,setRight:p}),[e,a,v,b,S,i,l,d,h,m,g,x,w,k,I,C])}(t);return r.jsx(oa.Provider,{value:n,children:e})}function ca(){const e=o.useContext(oa);if(!e)throw new Error("Dock workspace provider missing");return e}function la(){return o.useContext(oa)}const da="application/x-vibelet-workspace-tab",ua=o.createContext(null),ha={browser:ae,terminal:Le,diff:re};function pa(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 ma({location:e,kind:t,t:n,cwd:s}){const i=ca(),c=pa(n),l=o.useRef(null),d=o.useRef(null),u=i.items.filter(n=>n.location===e&&(!t||n.kind===t)),h=function(e,t,n,s=""){const i=o.useContext(ua),r=i?.element;t=t&&i?.kind===n;const[a,c]=o.useState(!1);return o.useLayoutEffect(()=>{const n=e.current,s=r?.querySelector(".control-tabs");if(!(t&&r&&n&&s))return;const i=()=>{const t=(e.current??n).cloneNode(!0);t.setAttribute("aria-hidden","true"),t.inert=!0,Object.assign(t.style,{position:"fixed",visibility:"hidden",width:"max-content",maxWidth:"none",left:"-10000px",font:getComputedStyle(n).font}),document.body.append(t);const i=t.getBoundingClientRect().width;t.remove();const o=r.clientWidth-s.getBoundingClientRect().width-8;c(e=>i>0?i<=o:e)},o=new ResizeObserver(i);return o.observe(r),o.observe(s),i(),()=>o.disconnect()},[t,r,e,s]),t&&a?r:null}(d,"right"===e&&u.length>1,t,u.map(e=>`${e.id}:${e.title}`).join("|"));if(o.useEffect(()=>{"right"===e&&t&&!i.items.some(e=>e.kind===t)&&i.add(t,n["browser"===t?"browser":"terminal"],s)},[e,t,i.epoch,i.scopeKey]),o.useEffect(()=>{if("right"!==e||!l.current)return;const t=l.current.querySelector('.dock-tab[data-active="true"]');t&&(l.current.scrollLeft=Math.max(0,t.offsetLeft-l.current.offsetLeft))},[e,t,i.right,u.map(e=>e.title).join("|")]),"right"===e&&t&&1===u.length)return null;const p=r.jsxs("div",{className:"dock-tabs",ref:d,role:"right"===e?"tablist":"group","aria-label":t?n["browser"===t?"browser":"terminal"]:void 0,children:["right"===e&&t&&i.right[t]&&r.jsx("button",{type:"button",className:"dock-move dock-move-first","aria-label":c.center,title:c.center,onClick:()=>i.move(i.right[t],"center"),children:r.jsx(F,{})}),r.jsx("div",{className:"dock-tab-items",ref:l,children:u.map(t=>{const s="center"===e?i.center===t.id:i.right[t.kind]===t.id,o=ha[t.kind];return r.jsxs("div",{className:"document-tab dock-tab","data-active":s,"data-dock-id":t.id,draggable:!0,onDragStart:e=>{e.dataTransfer.setData(da,t.id),e.dataTransfer.effectAllowed="move"},children:[r.jsxs("button",{type:"button",role:"tab","aria-selected":s,title:t.title,onClick:()=>"center"===e?i.setCenter(t.id):i.setRight(e=>({...e,[t.kind]:t.id})),children:[r.jsx(o,{}),r.jsx("span",{children:t.title})]}),s&&"center"===e&&r.jsx("button",{type:"button",className:"dock-move","aria-label":c.right,title:c.right,onClick:()=>i.move(t.id,"right"),children:r.jsx(L,{})}),r.jsx("button",{type:"button",className:"document-tab-close","aria-label":`${n.close} ${t.title}`,title:n.close,onClick:()=>i.close(t.id),children:r.jsx(He,{})})]},t.id)})}),"right"===e&&t&&r.jsx("button",{type:"button",className:"dock-new","aria-label":c.create,title:nt(c.create,"newTab"),onClick:()=>i.add(t,n["browser"===t?"browser":"terminal"],s),children:r.jsx(Ce,{})})]});return h?a.createPortal(p,h):p}function fa({item:e,t}){const n=ca(),s=pa(t);return r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button","aria-label":s.center,title:s.center,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(da,e.id),t.dataTransfer.effectAllowed="move"},onClick:()=>n.move(e.id,"center"),children:r.jsx(F,{})}),r.jsx("button",{type:"button","aria-label":s.create,title:nt(s.create,"newTab"),onClick:()=>n.add(e.kind,t["browser"===e.kind?"browser":"terminal"],e.cwd),children:r.jsx(Ce,{})})]})}function ga({location:e,kind:t}){const n=ca(),s="center"===e?"center":`right-${t}`,i=o.useCallback(e=>n.register(s,e),[n.register,s]);return r.jsx("div",{ref:i,className:"dock-slot","data-dock-location":e,"data-dock-kind":t})}function ya(e,t){const n=la();return n?{onDragOver:e=>{e.dataTransfer.types.includes(da)&&(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 i=s.dataTransfer.getData(da),r=n.items.find(e=>e.id===i);r&&(s.preventDefault(),s.stopPropagation(),document.body.classList.remove("dock-dragging"),n.move(i,e),t?.(r.kind))}}:{}}const va=o.lazy(()=>m(()=>import("./BrowserControlPanel-hHGqu9rG.js"),__vite__mapDeps([11,1,2,9]))),ba=o.lazy(()=>m(()=>import("./TerminalControlPanel-D78_YtrT.js"),__vite__mapDeps([12,1,2]))),xa=o.lazy(()=>m(()=>Promise.resolve().then(()=>Aa),void 0).then(e=>({default:e.DiffDrawer})));function wa({item:e,...t}){const n=ca(),s=ya(e.location),[i]=o.useState(()=>document.createElement("div")),c="right"===e.location,l=c&&1===n.items.filter(t=>"right"===t.location&&t.kind===e.kind).length,d=l?r.jsx(fa,{item:e,t:t.t}):void 0,u=(e.scopeKey??"default")===n.scopeKey&&(c?"diff"===e.kind?n.right.diff===e.id:t.rightVisible&&t.controlTab===e.kind&&n.right[e.kind]===e.id:n.center===e.id),h=n.hosts[c?`right-${e.kind}`:"center"]??n.hosts.parking,p=n.hosts.parking;o.useLayoutEffect(()=>{p&&i.parentElement!==p&&p.appendChild(i)},[i,p]),o.useLayoutEffect(()=>{i.className="dock-surface",i.dataset.dockId=e.id,i.dataset.location=e.location,i.dataset.kind=e.kind,i.hidden=!u;const t=c&&"diff"===e.kind,n=()=>{const e=h?.getBoundingClientRect();Object.assign(i.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 h&&s.observe(h),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)}},[i,h,u,e.id,e.location,e.kind,c]),o.useLayoutEffect(()=>()=>i.remove(),[i]);const m=o.useCallback(t=>n.updateBrowserUrl(e.id,t),[n.updateBrowserUrl,e.id]);return a.createPortal(r.jsx("div",{className:"dock-surface-content",...s,children:r.jsx(o.Suspense,{fallback:r.jsx("p",{className:"control-panel-loading",children:t.t.loading}),children:"browser"===e.kind?r.jsx(va,{initialUrl:e.url,visible:u,onUrlChange:m,t:t.t,dockActions:d,onClose:l?()=>n.close(e.id):void 0,onTitleChange:t=>n.rename(e.id,t)}):"terminal"===e.kind?r.jsx(ba,{client:t.client,cwd:e.cwd??"",deviceName:t.deviceName,visible:u,autoOpen:!1!==e.autoOpenTerminal,onOpen:()=>n.activate(e.id),onCloseTab:()=>n.close(e.id),t:t.t,dockActions:d}):e.session&&t.client?r.jsx(xa,{client:t.client,sessionId:e.session.sessionId,cwd:e.session.cwd,sessionTitle:e.title,t:t.t,onClose:()=>n.close(e.id),onDock:()=>n.move(e.id,c?"center":"right"),dockLabel:pa(t.t).center,presentation:c?"drawer":"workspace",initialScope:e.scope,initialPath:e.path}):null})}),i)}function Sa(e){const t=ca();t.openRight.current=(t,n)=>{"browser"===t&&n&&e.onOpenBrowserLink?.(),"browser"!==t&&"terminal"!==t||e.onOpenRight?.(t)},t.closeRight.current=t=>{e.controlTab===t&&e.onCloseRight?.()},o.useEffect(()=>n().subscribeCommand?.(n=>{if(!n.startsWith("open-link:"))return;const s=n.slice(10);/^https?:\/\//i.test(s)&&t.openBrowser(s,e.t.browser)}),[t.openBrowser,e.t.browser]);const s=o.useCallback(e=>t.register("parking",e),[t.register]);return o.useEffect(()=>{t.reset()},[e.daemonId]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"dock-parking",ref:s}),r.jsx("div",{className:"dock-overlay-slot",children:r.jsx(ga,{location:"right",kind:"diff"})}),t.allItems.map(t=>r.jsx(wa,{item:t,...e},t.id))]})}function ka({patch:e,truncated:t,truncatedLabel:n,loadingLabel:s}){const i=o.useMemo(()=>function(e){let t=0,n=0;return e.split("\n").map(e=>{const s=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(e);return s?(t=Number(s[1]),n=Number(s[2]),{text:e,kind:"hunk",oldLine:"",newLine:"",sign:""}):e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("---")||e.startsWith("+++")||!t&&!n?{text:e,kind:"header",oldLine:"",newLine:"",sign:""}:e.startsWith("+")?{text:e.slice(1),kind:"add",oldLine:"",newLine:String(n++),sign:"+"}:e.startsWith("-")?{text:e.slice(1),kind:"del",oldLine:String(t++),newLine:"",sign:"−"}:e.startsWith(" ")?{text:e.slice(1),kind:"ctx",oldLine:String(t++),newLine:String(n++),sign:""}:{text:e,kind:"header",oldLine:"",newLine:"",sign:""}})}(e),[e]),[a,c]=o.useState(400),l=o.useRef(null);return o.useEffect(()=>{c(400)},[e]),o.useEffect(()=>{const e=l.current;if(!e)return;const t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&c(e=>e+400)},{root:e.closest(".diff-patch"),rootMargin:"200px"});return t.observe(e),()=>t.disconnect()},[a,i.length]),r.jsxs("div",{className:"diff-patch-view",children:[i.slice(0,a).map((e,t)=>r.jsxs("div",{className:`diff-line ${e.kind}`,children:[r.jsx("span",{className:"diff-line-number","aria-hidden":"true",children:e.oldLine}),r.jsx("span",{className:"diff-line-number","aria-hidden":"true",children:e.newLine}),r.jsx("span",{className:"diff-line-sign","aria-hidden":"true",children:e.sign}),r.jsx("span",{className:"diff-line-text",children:e.text||" "})]},t)),a<i.length&&r.jsx("div",{ref:l,className:"diff-more",role:"status",children:s}),t&&r.jsx("p",{className:"diff-empty",children:n})]})}const Ia=new WeakMap;function Ca(e,t,n){let s=Ia.get(e);s||Ia.set(e,s=new Map);const i=JSON.stringify([t.sessionId,t.cwd,n]);let r=s.get(i);return r||(s.size>=12&&s.delete(s.keys().next().value),s.set(i,r={updated:0,patches:new Map})),r}function ja(e,t,n){return Ca(e,t,n)}function Ra(e,t,n){const s=Ca(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 Ma(e,t,n,s){const i=Ca(e,t,n),r=i.patches.get(s);if(r?.pending)return r.pending;if(r?.data&&Date.now()-i.updated<5e3)return Promise.resolve(r.data);i.patches.size>=12&&i.patches.delete(i.patches.keys().next().value);const o={};return i.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}const Ea={loading:!1,files:null,error:null};function Ta({client:e,sessionId:t,cwd:n,sessionTitle:s,t:i,onClose:a,onDock:c,dockLabel:l,presentation:d="drawer",initialScope:u="unstaged",initialPath:h}){const p=o.useId(),m=o.useRef(null),[g,y]=o.useState(!1),v=o.useRef(void 0),b=o.useCallback(()=>{void 0===v.current&&("workspace"===d||window.matchMedia("(prefers-reduced-motion: reduce)").matches?a():(y(!0),v.current=window.setTimeout(a,180)))},[a,d]);o.useEffect(()=>()=>window.clearTimeout(v.current),[]);const x=f(b,m,"drawer"===d),w=ja(e,{sessionId:t,cwd:n},u),[S,k]=o.useState(u),[I,C]=o.useState({unstaged:Ea,staged:Ea,[u]:{...Ea,files:w.data?.files??null}}),[j,R]=o.useState(h??w.data?.files[0]?.path??null),[M,E]=o.useState(w.patches.get(h??w.data?.files[0]?.path??"")?.data??null),[T,A]=o.useState(!1),[N,P]=o.useState(null),D=function(e){const t=o.useRef(void 0);return o.useEffect(()=>()=>t.current?.(),[]),{"data-dock-draggable":!!e,onPointerDown:n=>{if(!e||0!==n.button||n.target.closest("button"))return;t.current?.();const s=n.currentTarget,i=n.clientX,r=n.clientY,o=document.querySelector(".workspace-documents");if(!o)return;let a=!1;const c=(e,t)=>{const n=o.getBoundingClientRect();return e>=n.left&&e<=n.right&&t>=n.top&&t<=n.bottom},l=e=>{Math.hypot(e.clientX-i,e.clientY-r)<6&&!a||(a=!0,document.body.classList.add("dock-dragging"),o.classList.toggle("dock-drop-target",c(e.clientX,e.clientY)))},d=()=>{document.body.classList.remove("dock-dragging"),o.classList.remove("dock-drop-target"),window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",d),s.hasPointerCapture(n.pointerId)&&s.releasePointerCapture(n.pointerId),t.current=void 0},u=t=>{const n=a&&c(t.clientX,t.clientY);d(),n&&e()};t.current=d,s.setPointerCapture(n.pointerId),window.addEventListener("pointermove",l),window.addEventListener("pointerup",u),window.addEventListener("pointercancel",d),n.preventDefault()}}}("drawer"===d&&c?()=>c({scope:S,path:j}):void 0),L=I[S],q=o.useCallback(async s=>{C(e=>({...e,[s]:{loading:!0,files:e[s].files,error:null}}));try{const i=await Ra(e,{sessionId:t,cwd:n},s);C(e=>({...e,[s]:{loading:!1,files:i.files,error:null}}))}catch(i){C(e=>({...e,[s]:{loading:!1,files:null,error:i instanceof Error?i.message:String(i)}}))}},[e,t,n]);o.useEffect(()=>{q(S)},[S,q]),o.useEffect(()=>{const e=L.files;e&&(e.length?R(t=>e.some(e=>e.path===t)?t:e[0].path):R(null))},[L.files]),o.useEffect(()=>{if(!j)return E(null),void P(null);let s=!1;const i=ja(e,{sessionId:t,cwd:n},S).patches.get(j)?.data;return E(e=>i??(e?.path===j?e:null)),A(!i&&M?.path!==j),P(null),Ma(e,{sessionId:t,cwd:n},S,j).then(e=>{s||(E(e),A(!1))}).catch(e=>{s||(P(e instanceof Error?e.message:String(e)),A(!1))}),()=>{s=!0}},[e,t,n,S,j,L.files]);const O=o.useMemo(()=>{const e=e=>e?e.reduce((e,t)=>({adds:e.adds+t.additions,dels:e.dels+t.deletions,count:e.count+1}),{adds:0,dels:0,count:0}):{adds:0,dels:0,count:0};return{unstaged:e(I.unstaged.files),staged:e(I.staged.files)}},[I]);return r.jsxs("div",{"aria-labelledby":p,"aria-modal":"drawer"===d||void 0,className:`diff-drawer ${"workspace"===d?"diff-workspace":""} ${g?"closing":""}`,ref:x,role:"drawer"===d?"dialog":"region",tabIndex:-1,children:["drawer"===d&&r.jsx("div",{className:"diff-drawer-backdrop",onClick:b,"aria-hidden":"true"}),r.jsxs("div",{className:"diff-drawer-panel",children:[r.jsxs("header",{className:"diff-drawer-header",...D,children:[c&&"drawer"===d&&r.jsx("button",{type:"button",className:"icon-button","aria-label":l,title:l,onClick:()=>c({scope:S,path:j}),children:r.jsx(F,{})}),r.jsxs("div",{children:[r.jsx("strong",{id:p,children:i.changes}),r.jsx("span",{children:s})]}),r.jsx("button",{"aria-label":i.closeChanges,className:"icon-button",onClick:b,ref:m,type:"button",title:i.closeChanges,children:r.jsx(He,{"aria-hidden":"true"})})]}),r.jsx("div",{className:"diff-tabs",role:"tablist",children:["unstaged","staged"].map(e=>{const t=O[e],n=S===e;return r.jsxs("button",{type:"button",role:"tab","aria-selected":n,className:"diff-tab "+(n?"active":""),onClick:()=>{e!==S&&(R(null),E(null),P(null),k(e))},children:[r.jsx("span",{className:"diff-tab-label",children:"unstaged"===e?i.workingChanges:i.stagedChanges}),t.count>0?r.jsxs("span",{className:"diff-tab-meta",children:[r.jsxs("span",{className:"diff-add",children:["+",t.adds]}),r.jsxs("span",{className:"diff-del",children:["-",t.dels]})]}):null]},e)})}),r.jsxs("div",{className:"diff-body",children:[r.jsxs("aside",{className:"diff-files","aria-label":i.changedFiles,children:[L.loading&&!L.files?r.jsx("p",{className:"diff-empty",children:i.loading}):null,L.error?r.jsx("p",{className:"diff-empty diff-error",children:L.error}):null,L.files&&0===L.files.length?r.jsx("p",{className:"diff-empty",children:i.noChanges}):null,L.files?.map(e=>r.jsxs("button",{type:"button",className:`diff-file diff-file-${e.status} ${j===e.path?"active":""}`,onClick:()=>R(e.path),children:[r.jsx("span",{className:`diff-status diff-status-${e.status}`,children:e.status}),r.jsx("span",{className:"diff-file-path",title:e.path,children:e.path}),r.jsxs("span",{className:"diff-file-stats",children:[e.binary?r.jsx("span",{className:"diff-binary",children:"bin"}):null,!e.binary&&e.additions>0?r.jsxs("span",{className:"diff-add",children:["+",e.additions]}):null,!e.binary&&e.deletions>0?r.jsxs("span",{className:"diff-del",children:["-",e.deletions]}):null]})]},e.path))]}),r.jsx("section",{className:"diff-patch","aria-label":i.fileDiff,children:j?T?r.jsx("p",{className:"diff-empty",children:i.loadingPatch}):N?r.jsx("p",{className:"diff-empty diff-error",children:N}):M?.binary?r.jsx("p",{className:"diff-empty",children:i.binaryDiffUnavailable}):M?r.jsx(ka,{patch:M.patch,truncated:M.truncated,truncatedLabel:i.patchTruncated,loadingLabel:i.loadingPatch},`${S}:${j}`):null:r.jsxs("div",{className:"diff-empty",children:[r.jsx(ee,{"aria-hidden":"true"}),r.jsx("p",{children:i.selectFileForDiff})]})})]})]})]})}const Aa=Object.freeze(Object.defineProperty({__proto__:null,DiffDrawer:Ta},Symbol.toStringTag,{value:"Module"})),Na=o.lazy(async()=>m(()=>import("./FilesControlPanel-D9CJg2LW.js"),__vite__mapDeps([13,1,2,14,15])).then(e=>({default:e.FilesControlPanel}))),Pa=o.lazy(async()=>m(()=>import("./LanguageSettingsPanel-BLfFkm8K.js"),__vite__mapDeps([16,1,2,17])).then(e=>({default:e.LanguageSettingsPanel}))),Da=o.lazy(async()=>m(()=>import("./ThemeSettingsPanel-C2uyAU3b.js"),__vite__mapDeps([18,1,2,17])).then(e=>({default:e.ThemeSettingsPanel}))),Fa=o.lazy(async()=>m(()=>import("./NotificationSettingsPanel-GendGci0.js"),__vite__mapDeps([19,1,2])).then(e=>({default:e.NotificationSettingsPanel})));function La({t:e}){return r.jsxs("div",{className:"control-panel-loading","aria-live":"polite","aria-busy":"true",children:[r.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),r.jsx("span",{children:e.loadingControls})]})}function qa({client:e,id:t,activeSession:n,sessions:s,t:i,close:a}){const c=la(),l=n?.sessionId,u=n?.cwd,h=n?.runtime.isResponding;o.useEffect(()=>{if(!e||!l)return;const t=window.setTimeout(()=>{"hidden"!==document.visibilityState&&async function(e,t){const n=await Ra(e,t,"unstaged");n.files[0]&&await Ma(e,t,"unstaged",n.files[0].path)}(e,{sessionId:l,cwd:u}).catch(()=>{})},350);return()=>window.clearTimeout(t)},[e,l,u,h]);const p=s.find(e=>e.sessionId===t);return p&&e?r.jsx(Ta,{client:e,sessionId:p.sessionId,cwd:p.cwd,sessionTitle:d(p),t:i,onClose:a,dockLabel:pa(i).center,onDock:c?({scope:e,path:t})=>{c.add("diff",d(p),p.cwd,p,e,t),a()}:void 0},p.sessionId):null}function Oa(e,t,n){return e.replace(/tailcat/gi,t).replace(/(?:https?:\/\/|wss?:\/\/)?\b127\.0\.0\.1\b(?::\d+)?/gi,n)}const $a="vibelet.web.hideDeviceAddresses";function za({activeDaemonId:e,busy:s,fallbackName:i,phase:a,statusText:c,t:l,targets:d,onConnect:u,onRename:h,onEditConnection:p}){const{hidden:m,toggle:f}=function(){const[e,n]=o.useState(()=>{try{return"true"===t().getItem($a)}catch{return!1}});return{hidden:e,toggle:()=>{const s=!e;n(s);try{t().setItem($a,String(s))}catch{}}}}(),g=e=>m?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 i=Math.min(3,Math.floor((t.length-1)/2));return`${i>0?`${t.slice(0,i)}***${t.slice(-i)}`:"***"}:${n}`})}(e):e,y=m?l.showDeviceAddresses:l.hideDeviceAddresses,[v,b]=o.useState(!1),[x,w]=o.useState(null),[S,k]=o.useState(""),I=o.useRef(null),C=o.useRef(null),j=n().isLocalDaemon??(()=>!1),R=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,j),M=d.find(t=>t.daemonId===e),E=g(M?.label||i||e?.slice(0,10)||"Vibelet");return o.useEffect(()=>{v||w(null),x&&C.current?.select()},[v,x]),o.useEffect(()=>{if(!v)return;const e=e=>{e.target instanceof Node&&!I.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)}},[v]),r.jsxs("div",{className:"device-switcher",ref:I,children:[r.jsxs("button",{"aria-expanded":v,"aria-haspopup":"menu",className:"device-switcher-trigger",onClick:()=>b(e=>!e),title:E,type:"button",children:[r.jsx("strong",{children:E}),r.jsx(z,{"aria-hidden":"true"})]}),r.jsxs("span",{className:`brand-connection ${a}`,children:[r.jsx("i",{"aria-hidden":"true"}),"connected"===a?l.connected:c]}),v?r.jsxs("div",{"aria-label":l.savedDevices,className:"device-switcher-menu",role:"menu",children:[r.jsxs("div",{className:"device-switcher-menu-header",children:[r.jsx("span",{children:l.savedDevices}),r.jsx("button",{type:"button",className:"device-rename-button","aria-label":y,title:y,onClick:f,children:m?r.jsx(Z,{"aria-hidden":"true"}):r.jsx(Y,{"aria-hidden":"true"})})]}),R.map(t=>{const i=t.daemonId===e,o=(e=>{const t=n();if(!j(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 r.jsx("div",{className:"device-switcher-row"+(i?" is-active":""),children:x===t.daemonId?r.jsxs("form",{className:"device-rename-form",onSubmit:e=>{e.preventDefault(),x&&S.trim()&&(h(x,S),w(null))},children:[r.jsx("input",{ref:C,"aria-label":l.rename,autoFocus:!0,onChange:e=>k(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),w(null))},value:S}),r.jsx("button",{"aria-label":l.rename,title:l.rename,disabled:!S.trim(),type:"submit",children:r.jsx($,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":l.cancel,title:l.cancel,type:"button",onClick:()=>w(null),children:r.jsx(He,{"aria-hidden":"true"})})]}):r.jsxs(r.Fragment,{children:[r.jsxs("button",{className:"device-connect-button",disabled:s||i,onClick:()=>{u(t),b(!1)},role:"menuitem","aria-current":i?"true":void 0,type:"button",children:[i?r.jsx($,{"aria-hidden":"true"}):r.jsx(Ie,{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsxs("strong",{className:"device-target-heading",children:[r.jsx("span",{children:a}),i?r.jsx("em",{className:"device-active-label",children:l.active}):null]}),t.displayName&&t.displayName!==t.label?r.jsx("small",{children:g(t.displayName)}):null,j(t.daemonId)||!t.displayName?r.jsx("small",{children:j(t.daemonId)?l.currentDevice:g(t.daemonId)}):null,o?r.jsx("small",{className:"device-connection-endpoint",children:g(o)}):null]})]}),r.jsx("button",{"aria-label":`${l.rename} ${a}`,title:`${l.rename} ${a}`,className:"device-rename-button",onClick:()=>(e=>{w(e.daemonId),k(e.label)})(t),type:"button",children:r.jsx(Se,{"aria-hidden":"true"})}),p&&n().canEditConnection?.(t.daemonId)&&r.jsx("button",{"aria-label":`${l.editConnection} ${a}`,title:`${l.editConnection} ${a}`,className:"device-rename-button",onClick:()=>{p(t),b(!1)},type:"button",children:r.jsx(Ae,{"aria-hidden":"true"})})]})},t.daemonId)}),0===d.length?r.jsx("p",{className:"empty-copy",children:l.noSavedDevices}):null]}):null]})}function _a({label:e,value:t,options:n,onChange:s}){const i=o.useId();return r.jsxs("div",{className:"filter-section",children:[r.jsx("span",{className:"filter-section-label",id:i,children:e}),r.jsx("div",{className:"filter-choice-list",role:"radiogroup","aria-labelledby":i,children:n.map(e=>r.jsxs("label",{className:"filter-menu-row",children:[r.jsx("input",{type:"radio",name:i,value:e.value,checked:t===e.value,onChange:()=>s(e.value)}),r.jsx("span",{children:e.label}),r.jsx($,{className:"filter-menu-check","aria-hidden":"true","data-checked":t===e.value})]},e.value))})]})}function Ba({folder:e,initialValue:t,t:n,onClose:s,onSave:i}){const[c,l]=o.useState(t),d=o.useRef(null),u=f(s,d);return a.createPortal(r.jsxs("div",{"aria-labelledby":"folder-tag-dialog-title","aria-modal":"true",className:"folder-tag-dialog-layer",ref:u,role:"dialog",tabIndex:-1,children:[r.jsx("div",{"aria-hidden":"true",className:"folder-tag-dialog-backdrop",onClick:s}),r.jsxs("form",{className:"folder-tag-dialog",onSubmit:e=>{e.preventDefault(),i(c)},children:[r.jsxs("header",{children:[r.jsx("span",{className:"folder-tag-dialog-icon","aria-hidden":"true",children:r.jsx(Oe,{})}),r.jsxs("div",{children:[r.jsx("strong",{id:"folder-tag-dialog-title",children:n.editDirectoryTags}),r.jsx("span",{title:e,children:e})]}),r.jsx("button",{"aria-label":n.cancel,title:n.cancel,className:"mini-button",onClick:s,type:"button",children:r.jsx(He,{"aria-hidden":"true"})})]}),r.jsxs("label",{className:"folder-tag-dialog-field",children:[r.jsx("span",{children:n.directoryTags}),r.jsx("textarea",{"aria-describedby":"folder-tag-dialog-help",placeholder:n.directoryTagsPlaceholder,ref:d,rows:3,value:c,onChange:e=>l(e.target.value)})]}),r.jsx("p",{id:"folder-tag-dialog-help",children:n.directoryTagsDescription}),r.jsxs("footer",{children:[r.jsx("button",{className:"icon-text-button",onClick:s,type:"button",children:n.cancel}),r.jsx("button",{className:"primary-button",type:"submit",children:n.saveDirectoryTags})]})]})]}),document.body)}function Ha({folderToggle:e,search:t,connected:n,filtersOpen:s,filtersActive:i,t:a,onSearchChange:c,onSearchCommit:l,onToggleFilters:d,onCreate:u}){const[h,p]=o.useState(Boolean(t)),m=o.useRef(null),f=o.useRef(null),g=o.useRef(!1),y=()=>{g.current=!0,l(),c(""),p(!1),f.current?.focus(),g.current=!1};return o.useEffect(()=>{const e=()=>{p(!0),requestAnimationFrame(()=>m.current?.focus())};return window.addEventListener("vibelet.session-search",e),()=>window.removeEventListener("vibelet.session-search",e)},[]),r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"rail-list-heading",children:[r.jsx("div",{className:"rail-heading-folders",children:e}),r.jsxs("div",{className:"rail-heading-actions",children:[r.jsx("button",{ref:f,"aria-label":a.searchSessions,"aria-expanded":h,className:"rail-create-button",title:nt(a.searchSessions,"searchSessions"),type:"button",onClick:()=>{p(!0),requestAnimationFrame(()=>m.current?.focus())},children:r.jsx(Ee,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":a.newSession,className:"rail-create-button",disabled:!n,onClick:u,title:a.newSession,type:"button",children:r.jsx(Ce,{"aria-hidden":"true"})}),r.jsx("button",{"aria-expanded":s,"aria-label":a.sessionFilters,className:"filter-toggle "+(s||i?"selected":""),onClick:d,title:a.sessionFilters,type:"button",children:r.jsx(se,{"aria-hidden":"true"})})]})]}),h&&r.jsxs("div",{className:"search-box",onBlur:e=>{g.current||e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||(l(),p(!1))},children:[r.jsx(Ee,{"aria-hidden":"true"}),r.jsx("input",{ref:m,"aria-label":a.searchSessions,value:t,onChange:e=>c(e.target.value),placeholder:a.searchSessions,onKeyDown:e=>{"Enter"===e.key&&l(),"Escape"===e.key&&y()}}),r.jsx("button",{className:"search-close","aria-label":a.cancel,title:a.cancel,type:"button",onClick:y,children:r.jsx(He,{"aria-hidden":"true"})})]})]})}function Wa({menu:e,pending:t,t:n,onOpen:s,onDetails:i,onRename:o,onCopyResumeCommand:a,onResumeInTerminal:c,terminalBusy:l,onTogglePinned:d,onToggleArchived:u,onDelete:h}){return r.jsxs("div",{className:"session-context-menu",role:"menu",style:{left:e.x,top:e.y},onPointerDown:e=>e.stopPropagation(),children:[r.jsxs("button",{type:"button",role:"menuitem",onClick:s,children:[r.jsx(y,{"aria-hidden":"true"}),n.open]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:o,children:[r.jsx(Se,{"aria-hidden":"true"}),n.rename]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:i,children:[r.jsx(de,{"aria-hidden":"true"}),n.details]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:a,children:[r.jsx(U,{"aria-hidden":"true"}),n.copyResumeCommand]}),c&&r.jsxs("button",{type:"button",role:"menuitem",disabled:t||l,title:l?n.resumeTerminalBusy:n.resumeInTerminal,onClick:c,children:[r.jsx($e,{"aria-hidden":"true"}),n.resumeInTerminal]}),r.jsx("span",{className:"context-menu-separator"}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:d,children:[r.jsx(ke,{"aria-hidden":"true"}),e.session.pinned?n.unpin:n.pin]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:u,children:[r.jsx(P,{"aria-hidden":"true"}),e.session.archived?n.unarchive:n.archive]}),r.jsxs("button",{className:"danger",type:"button",role:"menuitem",onClick:h,children:[r.jsx(ze,{"aria-hidden":"true"}),n.delete]})]})}function Ka({title:e,t,onClose:n,onSave:s}){const[i,a]=o.useState(e),[c,l]=o.useState(!1),[d,u]=o.useState(!1),h=o.useRef(null),p=o.useRef(!1),m=o.useRef(!1),f=()=>{const e=h.current?.closest(".session-item")?.querySelector(".session-row");n(),m.current&&window.requestAnimationFrame(()=>e?.isConnected&&e.focus())};o.useLayoutEffect(()=>{h.current?.focus(),h.current?.select()},[]);const g=async()=>{if(p.current)return;const t=i.trim();if(t&&t!==e){p.current=!0,u(!0),l(!1);try{if(await s(t))return void f()}catch{}p.current=!1,u(!1),l(!0),h.current?.focus()}else f()};return r.jsxs("form",{className:"session-rename-inline",onSubmit:e=>{e.preventDefault(),g()},children:[r.jsx("input",{ref:h,"aria-label":t.rename,value:i,readOnly:d,onChange:e=>a(e.target.value),onBlur:()=>{g()},onKeyDown:e=>{e.stopPropagation(),e.nativeEvent.isComposing||229===e.keyCode||("Enter"===e.key&&(m.current=!0),"Escape"!==e.key||d||(e.preventDefault(),p.current=!0,m.current=!0,f()))}}),c&&r.jsx("small",{role:"alert",children:t.renameFailed})]})}function Qa({session:e,renamingRowId:t,onRename:n,onCloseRename:s,active:i,selected:c=!1,responding:l,pending:u=!1,attentionReason:h,tagLabels:p,showFolder:m=!0,t:f,onSelect:g,onContextMenu:y,onToggleArchived:v,onTogglePinned:b}){const x=o.useId(),w=t===x,S=d(e),k=rn(e.lastActivityAt,Date.now(),f),I=e.cwd?.split(/[\\/]/).filter(Boolean).at(-1)||e.cwd||".",C=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),[j,R]=o.useState(!1),M=o.useRef(null),E=o.useRef(null),T=o.useRef({x:0,y:0}),A=o.useRef(null),N=()=>{const e=E.current;if(!e)return;const{x:t,y:n}=T.current,s=e.getBoundingClientRect(),i=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(i,window.innerHeight-s.height-8))}px`,e.style.visibility="visible"};o.useLayoutEffect(()=>{j&&N()},[j,S]);const D=()=>{null!==M.current&&window.clearTimeout(M.current),M.current=null,null!==A.current&&window.cancelAnimationFrame(A.current),A.current=null,R(!1)};return o.useEffect(()=>()=>{null!==M.current&&window.clearTimeout(M.current),null!==A.current&&window.cancelAnimationFrame(A.current)},[e.sessionId]),o.useEffect(()=>{if(!j)return;const e=()=>R(!1);return document.addEventListener("scroll",e,!0),()=>document.removeEventListener("scroll",e,!0)},[j]),r.jsxs("div",{className:"session-item","data-renaming":w||void 0,"data-active":i||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},w||(e=>{null!==M.current&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{M.current=null,e.isConnected&&e.matches(":hover")&&R(!0)},2e3)})(e.currentTarget)},onMouseMove:e=>{T.current={x:e.clientX,y:e.clientY},j&&null===A.current&&(A.current=window.requestAnimationFrame(()=>{A.current=null,N()}))},onMouseLeave:D,onFocusCapture:e=>{if(!w&&e.target instanceof HTMLElement&&e.target.matches(":focus-visible")){null!==M.current&&window.clearTimeout(M.current),M.current=null;const t=e.currentTarget.getBoundingClientRect();T.current={x:t.left+t.width/2,y:t.bottom},R(!0)}},onBlurCapture:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||D()},children:[r.jsxs("button",{className:`session-row ${i?"active":""} ${e.archived?"archived":""} ${l?"responding":""}`,"data-session-id":e.sessionId,"data-row-id":x,disabled:w,"aria-current":i?"true":void 0,"aria-pressed":c,onContextMenu:y,onClick:g,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},type:"button",children:[r.jsxs("span",{className:"session-row-head",children:[r.jsx("strong",{children:S}),r.jsx("span",{className:"session-row-metadata",children:r.jsx("span",{className:"session-row-time",title:k,children:k})}),l?r.jsx("span",{className:"session-running-indicator",role:"img","aria-label":f.agentResponding,title:f.agentResponding}):r.jsx("span",{className:"session-running-placeholder","aria-hidden":"true"})]}),h&&r.jsx("span",{className:"session-attention-reason",children:h}),e.runtime.backgroundTerminals?.length?r.jsx("span",{className:"session-terminal-count",children:f.backgroundTerminalsRunning(e.runtime.backgroundTerminals.length)}):null,p?.length?r.jsx("span",{className:"directory-tag-row",title:f.directoryTags,children:p.map(e=>r.jsx("em",{children:e},e))}):null,r.jsx("span",{className:"session-row-footer","aria-hidden":"true"})]}),w&&n&&s&&r.jsx(Ka,{title:S,t:f,onClose:s,onSave:t=>n(e,t)}),r.jsxs("div",{className:"session-quick-actions",children:[r.jsx("button",{"aria-label":e.pinned?f.unpin:f.pin,className:e.pinned?"is-pinned":void 0,disabled:u,onClick:b,title:e.pinned?f.unpin:f.pin,type:"button",children:r.jsx(ke,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":e.archived?f.unarchive:f.archive,className:e.archived?"is-archived":void 0,disabled:u,onClick:v,title:e.archived?f.unarchive:f.archive,type:"button",children:r.jsx(P,{"aria-hidden":"true"})})]}),r.jsxs("div",{className:"session-git-links",children:[m&&r.jsx("span",{className:"session-git-folder",title:e.cwd,children:I}),e.branch&&(C&&i?r.jsx("a",{className:"session-branch-link",href:C,target:"_blank",rel:"noopener noreferrer",title:e.branch,children:e.branch}):r.jsx("span",{className:"session-branch-link",title:e.branch,children:e.branch})),e.pullRequest&&(i?r.jsxs("a",{className:"session-pr-link",href:e.pullRequest.url,target:"_blank",rel:"noopener noreferrer",title:e.pullRequest.title,children:["PR #",e.pullRequest.number]}):r.jsxs("span",{className:"session-pr-link",title:e.pullRequest.title,children:["PR #",e.pullRequest.number]})),e.pinned?r.jsx("span",{className:"session-row-status",children:f.pinned}):null,e.archived?r.jsx("span",{className:"session-row-status",children:f.archived}):null,r.jsx("span",{className:"session-row-agent",children:"codex"===e.agent?"Codex":"Claude"})]}),j&&a.createPortal(r.jsx("div",{"aria-hidden":"true",className:"session-title-tooltip",ref:E,style:{left:0,top:0,visibility:"hidden"},children:S}),document.body)]})}function Ua(e){const t=o.useRef(e);o.useLayoutEffect(()=>{t.current=e});const n=o.useMemo(()=>({onRenameSession:(e,n)=>t.current.onRenameSession?.(e,n)??Promise.resolve(!1),onCloseRename:()=>t.current.onCloseRename?.(),onEditFolderTags:e=>t.current.onEditFolderTags(e),onOpenCreateMenu:(e,n)=>t.current.onOpenCreateMenu(e,n),onOpenSessionMenu:(e,n)=>t.current.onOpenSessionMenu(e,n),onSelectSession:e=>t.current.onSelectSession(e),onToggleSessionArchived:e=>t.current.onToggleSessionArchived(e),onToggleSessionPinned:e=>t.current.onToggleSessionPinned(e),onToggleFolder:e=>t.current.onToggleFolder(e)}),[]);return r.jsx(Va,{...e,...n})}const Va=o.memo(function({activeSessionId:e,renamingRowId:t,onRenameSession:n,onCloseRename:s,collapsedFolders:i,folderCounts:a,getFolderTags:c,groupFolders:l,groupedSessions:d,phase:u,attentionReasons:h,pendingSessionIds:p,respondingSessionIds:m,t:f,visibleSessions:g,onEditFolderTags:y,onOpenCreateMenu:v,onOpenSessionMenu:b,onSelectSession:x,onToggleSessionArchived:w,onToggleSessionPinned:S,onToggleFolder:k}){const I=o.useId(),[C,j]=o.useState(()=>new Set),R=o.useRef(null),M=o.useMemo(()=>{const e=l?d.flatMap(e=>i[e.folder]?[]:e.sessions):g;return[...new Set(e.map(e=>e.sessionId))]},[i,l,d,g]);o.useEffect(()=>{const e=new Set(M);j(t=>[...t].every(t=>e.has(t))?t:new Set([...t].filter(t=>e.has(t)))),R.current&&!e.has(R.current)&&(R.current=null)},[M]),o.useEffect(()=>{0===C.size&&(R.current=e)},[e,C]);const E=(t,n)=>{if(n.shiftKey){const s=R.current??e??t,i=M.indexOf(s),r=M.indexOf(t),o=M.slice(Math.min(i<0?r:i,r),Math.max(i,r)+1);return j(e=>{const t=n.metaKey||n.ctrlKey?new Set(e):new Set;for(const n of o)t.add(n);return t}),void(R.current=s)}R.current=t,n.metaKey||n.ctrlKey?j(n=>{const s=n.size?new Set(n):new Set(e?[e]:[]);return s.has(t)?s.delete(t):s.add(t),s}):(j(new Set),x(t))};return l?r.jsxs(r.Fragment,{children:[d.map(o=>{const l=!!i[o.folder],d=`${I}-${encodeURIComponent(o.folder)}`,g="folder"===o.kind?a[o.folder]??o.sessions.length:o.sessions.length,x="attention"===o.kind?f.needsAttentionSessionsGroup:"running"===o.kind?f.runningSessionsGroup:"pinned"===o.kind?f.pinnedSessionsGroup:o.folder;return r.jsxs("div",{className:"folder-group "+("folder"!==o.kind?"virtual-session-group":""),"data-group-kind":o.kind,children:[r.jsxs("div",{className:"folder-heading",children:[r.jsxs("div",{className:"folder-header",children:[r.jsxs("button",{"aria-expanded":!l,"aria-controls":d,title:x,onClick:()=>k(o.folder),type:"button",children:[r.jsx(_,{className:"folder-disclosure","aria-hidden":"true"}),"attention"===o.kind?r.jsx(de,{"aria-hidden":"true"}):"running"===o.kind?r.jsx(A,{"aria-hidden":"true"}):"pinned"===o.kind?r.jsx(ke,{"aria-hidden":"true"}):l?r.jsx(ne,{"aria-hidden":"true"}):r.jsx(te,{"aria-hidden":"true"}),r.jsx("span",{children:"folder"===o.kind?o.folder.split(/[\\/]/).filter(Boolean).at(-1)||o.folder:x})]}),"folder"===o.kind?r.jsxs(r.Fragment,{children:[r.jsx("button",{"aria-label":c(o.folder).length?f.editDirectoryTags:f.addDirectoryTags,className:"mini-button folder-hover-action",onClick:()=>y(o.folder),title:c(o.folder).length?f.editDirectoryTags:f.addDirectoryTags,type:"button",children:r.jsx(Oe,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":f.newSession,className:"mini-button folder-hover-action",disabled:"connected"!==u,onClick:e=>v(e,o.folder),title:f.newSession,type:"button",children:r.jsx(Ce,{"aria-hidden":"true"})})]}):null,r.jsx("small",{className:"folder-session-count",title:`${g} ${f.sessions}`,children:g})]}),"folder"===o.kind&&c(o.folder).length?r.jsx("div",{className:"folder-tag-row",children:c(o.folder).map(e=>r.jsx("span",{children:e},e))}):null]}),r.jsx("div",{className:"folder-session-list",id:d,hidden:l,children:l?null:o.sessions.map(i=>r.jsx(Qa,{renamingRowId:t,onRename:n,onCloseRename:s,active:i.sessionId===e,selected:C.has(i.sessionId),responding:m.has(i.sessionId),attentionReason:h?.[i.sessionId],pending:p?.has(i.sessionId),session:i,showFolder:"folder"!==o.kind,tagLabels:c(i.cwd),t:f,onContextMenu:e=>b(e,i),onSelect:e=>E(i.sessionId,e),onToggleArchived:()=>w(i),onTogglePinned:()=>S(i)},i.sessionId))})]},o.folder)}),0===g.length?r.jsx("div",{className:"session-empty-state",children:r.jsx("p",{children:f.noSessionsMatch})}):null]}):r.jsxs(r.Fragment,{children:[g.map(i=>r.jsx(Qa,{renamingRowId:t,onRename:n,onCloseRename:s,active:i.sessionId===e,selected:C.has(i.sessionId),responding:m.has(i.sessionId),attentionReason:h?.[i.sessionId],pending:p?.has(i.sessionId),session:i,tagLabels:c(i.cwd),t:f,onContextMenu:e=>b(e,i),onSelect:e=>E(i.sessionId,e),onToggleArchived:()=>w(i),onTogglePinned:()=>S(i)},i.sessionId)),0===g.length?r.jsx("div",{className:"session-empty-state",children:r.jsx("p",{children:f.noSessionsMatch})}):null]})});function Ga({agentFilter:e,t,onAgentFilterChange:n}){return r.jsx(_a,{label:t.agentFilterLabel,value:e,options:[{value:"all",label:t.agentFilterAll},{value:"claude",label:t.agentFilterClaude},{value:"codex",label:t.agentFilterCodex}],onChange:n})}function Ja({groupFolders:e,hideArchived:t,separatePinnedGroup:n,showNeedsAttentionGroup:s,showRunningGroup:i,t:o,onToggleGroupFolders:a,onToggleHideArchived:c,onToggleNeedsAttentionGroup:l,onToggleRunningGroup:d,onToggleSeparatePinnedGroup:u}){const h=[[o.showNeedsAttentionGroup,s,l],[o.showRunningGroup,i,d],[o.separatePinnedGroup,n,u]];return r.jsxs("div",{className:"filter-section",children:[r.jsx("span",{className:"filter-section-label",children:o.filterViewOptions}),r.jsxs("div",{className:"filter-view-list",children:[r.jsxs("button",{"aria-pressed":e,className:"filter-menu-row",onClick:a,type:"button",children:[r.jsx("span",{children:o.groupByFolder}),r.jsx($,{className:"filter-menu-check","aria-hidden":"true","data-checked":e})]}),h.map(([t,n,s])=>r.jsxs("button",{"aria-pressed":e&&n,className:"filter-menu-row nested-filter-option",disabled:!e,onClick:s,type:"button",children:[r.jsx("span",{children:t}),r.jsx($,{className:"filter-menu-check","aria-hidden":"true","data-checked":e&&n})]},t)),r.jsxs("button",{"aria-pressed":t,className:"filter-menu-row",onClick:c,type:"button",children:[r.jsx("span",{children:o.hideArchived}),r.jsx($,{className:"filter-menu-check","aria-hidden":"true","data-checked":t})]})]})]})}function Za({connectionIndicators:e,activeSessionId:t,busy:s,collapsedFolders:i,allFoldersCollapsed:c,currentCwd:l,activeDaemonId:d,displayName:u,savedTargets:h,directoryTags:p,folderCounts:m,groupFolders:f,sessionSort:g,onSessionSortChange:y,groupedSessions:v,hideArchived:b,separatePinnedGroup:x,showNeedsAttentionGroup:w,showRunningGroup:S,inventoryVersion:k,nextCursor:I,phase:C,attentionReasons:j,pendingSessionIds:R,respondingSessionIds:M,search:E,sessionAgentFilter:T,sessionsCount:A,sinceFilter:N,statusText:P,t:D,visibleSessions:F,onLoadMore:L,onCopyResumeCommand:q,onResumeInTerminal:O,onConnectTarget:$,onRequestNewSession:z,onDeleteSession:_,onRenameSession:B,onEditFolderTags:H,onOpenSessionDetails:W,onResetFilters:K,onRenameTarget:Q,onEditConnection:U,onSearchChange:V,onSearchCommit:G,onSelectSession:J,onToggleSessionArchived:Z,onToggleSessionPinned:Y,onSessionAgentFilterChange:X,onSinceFilterChange:ee,onToggleFolder:te,onToggleAllFolders:ne,onToggleGroupFolders:se,onToggleHideArchived:ie,onToggleNeedsAttentionGroup:re,onToggleRunningGroup:oe,onToggleSeparatePinnedGroup:ae}){const[ce,le]=o.useState(null),[de,ue]=o.useState(!1),[he,pe]=o.useState(null);o.useEffect(()=>{if(!he)return;const e=window.setTimeout(()=>pe(null),2400);return()=>window.clearTimeout(e)},[he]);const[ge,ye]=o.useState(null),[be,xe]=o.useState(null),we=o.useRef(null),Se=o.useRef(null),[ke,Ie]=o.useState(null),Ce="updated"!==g||"all"!==T||"30d"!==N||!f||f&&(w||S||x)||b,je=function(e,t,n=!1){const s=o.useMemo(()=>e,[e?.lastActivityAt,e?.sessionId]),i=o.useRef(null),r=o.useRef(null),a=o.useRef(t),[c,l]=o.useState(null),d=Boolean(e?.lastActivityAt&&e.sessionId),u=d?`${e?.lastActivityAt}:${e?.sessionId}`:null;return o.useEffect(()=>{a.current=t},[t]),o.useEffect(()=>{const e=i.current;if(!e||!s||!u)return r.current=null,void l(null);const t=e.closest(".session-list");if(!(t instanceof HTMLElement))return;let o,c=!0;l(null);const d=()=>{r.current!==u&&(r.current=u,l(u),a.current(s).catch(()=>{c&&(o=window.setTimeout(()=>{c&&(r.current=null,n?d():(h?.unobserve(e),h?.observe(e)))},1500))}).finally(()=>{c&&l(e=>e===u?null:e)}))},h=n?null:new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&d()},{root:t,rootMargin:"0px 0px 240px 0px",threshold:.01});return n?d():h?.observe(e),()=>{c=!1,r.current=null,void 0!==o&&window.clearTimeout(o),h?.disconnect()}},[u,s,n]),{canLoadMore:d,loading:d&&c===u,sentinelRef:i}}(I,L,"updated"!==g||!b),Re=!!be&&Boolean(R?.has(be.session.sessionId)),Me=o.useCallback(e=>p[function(e){return"string"==typeof e&&e.trim().length>0?e:void 0}(e)??"/"]??[],[p]),Ee=`${P} · ${"connected"===C?`${F.length}/${A} sessions · v${k??"-"}`:D.sameOriginAccess}`,Te=n().toolbarTarget?.("left");o.useLayoutEffect(()=>{if(!de)return;const e=()=>{const e=we.current?.getBoundingClientRect();if(!e)return;const t=Math.min(820,window.innerWidth-24);Ie({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)},[de]),o.useEffect(()=>{if(!de&&!be)return;const e=e=>{const t=e.target;t instanceof Node&&(we.current?.contains(t)||Se.current?.contains(t))||(ue(!1),xe(null))},t=e=>{"Escape"===e.key&&(ue(!1),xe(null))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[be,de]);const Ae=(e,t)=>{xe(null),ue(!1),z(t)},Pe=()=>xe(null),De=e=>{if(!be)return;const{session:t}=be;Pe(),e(t)},Fe=r.jsxs("div",{className:"brand-block",title:Ee,children:[r.jsx("div",{className:"brand-mark","aria-hidden":"true",children:r.jsx("img",{alt:"",className:"brand-logo",height:"40",src:"/web/assets/logo-SQcOtj-8.png",width:"40"})}),r.jsx(za,{activeDaemonId:d,busy:s,fallbackName:u,phase:C,statusText:P,t:D,targets:h,onConnect:$,onRename:Q,onEditConnection:U})]});return r.jsxs("aside",{className:"session-rail","aria-label":D.sessions,children:[Te?a.createPortal(Fe,Te):Fe,r.jsxs("div",{className:"search-filter-wrap",ref:we,children:[r.jsx(Ha,{folderToggle:f&&v.length>0&&r.jsx("button",{"aria-label":c?D.expandAllSessions:D.collapseAllSessions,"aria-pressed":c,className:"session-folders-toggle",onClick:ne,title:c?D.expandAllSessions:D.collapseAllSessions,type:"button",children:c?r.jsx(fe,{"aria-hidden":"true"}):r.jsx(ve,{"aria-hidden":"true"})}),search:E,connected:"connected"===C,filtersOpen:de,filtersActive:Ce,t:D,onSearchChange:V,onSearchCommit:G,onToggleFilters:()=>ue(e=>!e),onCreate:Ae}),de&&ke?a.createPortal(r.jsxs("div",{className:"filter-popover session-filter-popover",role:"dialog","aria-label":D.sessionFilters,ref:Se,style:{top:ke.top,left:ke.left},children:[r.jsx(_a,{label:D.sessionSortLabel,value:g,options:[{value:"updated",label:D.sessionSortUpdated},{value:"created",label:D.sessionSortCreated},{value:"title",label:D.sessionSortTitle},{value:"folder",label:D.sessionSortFolder}],onChange:y}),r.jsx(Ga,{agentFilter:T,t:D,onAgentFilterChange:X}),r.jsx(_a,{label:D.searchTimeRangeLabel,value:N,options:[{value:"all",label:D.searchTimeRangeAllTime},{value:"7d",label:D.searchTimeRangeLast7Days},{value:"30d",label:D.searchTimeRangeLast30Days},{value:"90d",label:D.searchTimeRangeLast90Days}],onChange:ee}),r.jsx(Ja,{groupFolders:f,hideArchived:b,separatePinnedGroup:x,showNeedsAttentionGroup:w,showRunningGroup:S,t:D,onToggleGroupFolders:se,onToggleHideArchived:ie,onToggleNeedsAttentionGroup:re,onToggleRunningGroup:oe,onToggleSeparatePinnedGroup:ae}),Ce?r.jsx("button",{className:"filter-reset-button",onClick:K,type:"button",children:D.resetFilters}):null]}),document.body):null]}),r.jsxs("div",{className:"session-list",children:[r.jsx(Ua,{activeSessionId:t,renamingRowId:ce,onRenameSession:B,onCloseRename:()=>le(null),collapsedFolders:i,folderCounts:m,getFolderTags:Me,groupFolders:f,groupedSessions:v,phase:C,attentionReasons:j,pendingSessionIds:R,respondingSessionIds:M,t:D,visibleSessions:F,onEditFolderTags:e=>{ue(!1),xe(null),ye({folder:e,value:Me(e).join(", ")})},onOpenCreateMenu:Ae,onOpenSessionMenu:(e,t)=>{e.preventDefault(),xe({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:J,onToggleSessionArchived:Z,onToggleSessionPinned:Y,onToggleFolder:te},d??"unconnected"),je.canLoadMore?r.jsx("div",{"aria-live":"polite",className:"session-load-sentinel "+(je.loading?"loading":""),ref:je.sentinelRef,role:"status",children:je.loading?r.jsxs(r.Fragment,{children:[r.jsx(me,{className:"spin","aria-hidden":"true"}),r.jsx("span",{children:D.loadingMore})]}):null}):null]}),r.jsxs("div",{className:"session-rail-footer",children:[r.jsx("div",{className:"rail-footer-indicators",children:e}),n().openSettings&&r.jsxs("button",{"aria-label":D.settings,className:"icon-button rail-settings-button",onClick:()=>n().openSettings?.(),title:D.settings,type:"button",children:[r.jsx(Ne,{"aria-hidden":"true"}),n().settingsBadge]})]}),ge?r.jsx(Ba,{folder:ge.folder,initialValue:ge.value,t:D,onClose:()=>ye(null),onSave:e=>{ge&&(H(ge.folder,e),ye(null))}}):null,be?r.jsx(Wa,{menu:be,pending:Re,t:D,onOpen:()=>De(e=>J(e.sessionId)),onRename:()=>{le(be.rowId),Pe()},onDetails:()=>De(W),onCopyResumeCommand:()=>De(e=>{Promise.resolve(q(e)).then(()=>pe({message:D.commandCopied,tone:"success"})).catch(()=>pe({message:D.copyResumeFailed,tone:"error"}))}),onResumeInTerminal:O&&d&&n().resumeInTerminal&&n().isLocalDaemon?.(d)?()=>De(O):void 0,terminalBusy:M.has(be.session.sessionId),onTogglePinned:()=>De(Y),onToggleArchived:()=>De(Z),onDelete:()=>De(_)}):null,r.jsx(Ns,{feedback:he})]})}function Ya({collapsed:e,children:t,onExpand:s,onResize:i,t:o}){const c=n().toolbarTarget?.("left"),l=r.jsx("button",{"aria-label":e?o.expandSessionSidebar:o.collapseSessionSidebar,className:"sidebar-titlebar-toggle",onClick:s,title:nt(e?o.expandSessionSidebar:o.collapseSessionSidebar,"leftSidebar"),type:"button",children:r.jsx(be,{"aria-hidden":"true"})});return r.jsxs(r.Fragment,{children:[c?a.createPortal(l,c):l,r.jsx("div",{className:"session-sidebar-motion",inert:e,"aria-hidden":e,children:t}),r.jsx("button",{"aria-label":o.resizeSessionSidebar,"aria-hidden":e,className:"resize-handle",disabled:e,onPointerDown:i,title:o.resizeSessionSidebar,type:"button",children:r.jsx("span",{})})]})}const Xa={version:"",latestVersion:"",loading:!1,error:null};function ec(e){const t=e.match(/^\d+/);return t?Number(t[0]):0}function tc(e,t){return function(e,t){const n=e.split(/[+-]/,1)[0].split(".").map(ec),s=t.split(/[+-]/,1)[0].split(".").map(ec),i=Math.max(n.length,s.length);for(let r=0;r<i;r+=1){const e=n[r]??0,t=s[r]??0;if(e<t)return-1;if(e>t)return 1}return 0}(e,t)<0}function nc({busy:e,connected:t,dismissed:n,feedback:s,synced:i,t:o,onPull:a,onPushMerge:c,onPushReplace:l,onSkip:d}){const u=!t||null!==e;return r.jsxs("section",{className:"control-section compact-section archive-sync-panel",children:[r.jsx("h2",{children:o.archiveSyncTitle}),r.jsx("p",{className:"empty-copy",children:i?o.archiveSyncSynced:n?o.archiveSyncSkippedState:o.archiveSyncBody}),r.jsxs("div",{className:"action-grid archive-sync-actions",children:[r.jsxs("button",{className:"icon-text-button",disabled:u,onClick:c,type:"button",children:[r.jsx(oe,{"aria-hidden":"true"}),"pushMerge"===e?o.archiveSyncSyncing:o.archiveSyncPushMerge]}),r.jsxs("button",{className:"icon-text-button",disabled:u,onClick:a,type:"button",children:[r.jsx(g,{"aria-hidden":"true"}),"pull"===e?o.archiveSyncSyncing:o.archiveSyncPull]}),r.jsxs("button",{className:"icon-text-button",disabled:u,onClick:l,type:"button",children:[r.jsx(_e,{"aria-hidden":"true"}),"pushReplace"===e?o.archiveSyncSyncing:o.archiveSyncPushReplace]}),r.jsxs("button",{className:"icon-text-button",disabled:u,onClick:d,type:"button",children:[r.jsx(N,{"aria-hidden":"true"}),o.archiveSyncSkip]})]}),s?r.jsx("p",{className:"empty-copy "+("error"===s.tone?"error-copy":"success-copy"),children:s.message}):null]})}function sc({pairing:e,label:t,phase:n,t:s,onForgetPairing:i}){const o="connected"===n?"connected":e?n:s.notPaired;return r.jsxs("section",{className:"control-section compact-section",children:[r.jsx("h2",{children:s.currentDevice}),r.jsxs("dl",{children:[r.jsxs("div",{children:[r.jsx("dt",{children:s.daemon}),r.jsxs("dd",{className:"connection-device-name",children:[r.jsx("strong",{children:t||e?.displayName||e?.daemonId||s.notPaired}),t&&e?.displayName&&t!==e.displayName?r.jsx("small",{children:e.displayName}):null]})]}),r.jsxs("div",{children:[r.jsx("dt",{children:s.status}),r.jsx("dd",{children:o})]})]}),r.jsx("div",{className:"action-grid",children:r.jsxs("button",{className:"danger-button",disabled:!e,onClick:i,type:"button",children:[r.jsx(ue,{"aria-hidden":"true"}),s.forget]})})]})}function ic({connected:e,metadata:t,showUpdate:n,updateBusy:s,restartBusy:i,t:o,updateStatus:a,onUpdate:c,onRestart:l}){const d=t.version&&t.latestVersion&&n?`${t.version} -> ${t.latestVersion}`:t.version||o.unknown;return r.jsxs("section",{className:"control-section compact-section",children:[r.jsx("h2",{children:o.desktopConnector}),r.jsx("dl",{children:r.jsxs("div",{children:[r.jsx("dt",{children:o.version}),r.jsx("dd",{children:t.loading?o.checking:d})]})}),r.jsxs("div",{className:"action-grid",children:[n?r.jsxs("button",{className:"primary-button",disabled:!e||s||i,onClick:c,type:"button",children:[r.jsx(g,{"aria-hidden":"true"}),s?o.updating:o.update]}):null,r.jsxs("button",{className:"danger-button",disabled:!e||i,onClick:l,type:"button",children:[r.jsx(je,{"aria-hidden":"true"}),i?o.restarting:o.restart]})]}),t.error?r.jsx("p",{className:"empty-copy",children:t.error}):null,a?r.jsx("p",{className:"empty-copy",children:a}):null]})}function rc({activeDaemonId:e,busy:t,t:n,targets:s,onConnect:i,onForget:o}){return r.jsxs("section",{className:"control-section compact-section",children:[r.jsx("h2",{children:n.savedDevices}),r.jsxs("div",{className:"stack-list",children:[s.map(s=>r.jsxs("div",{className:"data-row target-row",children:[r.jsxs("div",{children:[r.jsxs("strong",{children:[s.label,s.daemonId===e?` · ${n.active}`:""]}),r.jsxs("span",{children:[s.displayName??s.daemonId," ·"," ",s.lastConnectedAt?rn(s.lastConnectedAt,Date.now(),n):n.notConnectedRecently]})]}),r.jsxs("div",{className:"row-actions",children:[r.jsx("button",{"aria-label":`Connect to ${s.label}`,title:`Connect to ${s.label}`,className:"icon-button",disabled:t,onClick:()=>i(s),type:"button",children:r.jsx(Ie,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":`Forget ${s.label}`,title:`Forget ${s.label}`,className:"icon-button danger-icon",disabled:t,onClick:()=>o(s.daemonId),type:"button",children:r.jsx(ze,{"aria-hidden":"true"})})]})]},s.daemonId)),0===s.length?r.jsx("p",{className:"empty-copy",children:n.noSavedDevices}):null]})]})}function oc({workspace:e,portalOnly:t=!1}){const[s,i]=o.useState(()=>n().settingsTarget?.()??null);o.useEffect(()=>{const e=()=>i(n().settingsTarget?.()??null);return window.addEventListener("vibelet.settings.target.changed",e),e(),()=>window.removeEventListener("vibelet.settings.target.changed",e)},[]);const c=e,l=r.jsxs(r.Fragment,{children:[!t&&r.jsxs(r.Fragment,{children:[r.jsx(sc,{pairing:c.pairing,label:c.savedTargets.find(e=>e.daemonId===c.pairing?.daemonId)?.label,phase:c.phase,t:c.t,onForgetPairing:c.clearPairing}),r.jsx(rc,{activeDaemonId:c.pairing?.daemonId,busy:c.busy,t:c.t,targets:c.savedTargets,onConnect:c.connectSavedTarget,onForget:c.forgetSavedTarget})]}),r.jsx(nc,{busy:c.archiveSyncBusy,connected:"connected"===c.phase,dismissed:c.archiveSyncDismissed,feedback:c.archiveSyncStatus,synced:c.archiveSynced,t:c.t,onPull:()=>{c.runArchiveSync("pull")},onPushMerge:()=>{c.runArchiveSync("pushMerge")},onPushReplace:()=>{c.runArchiveSync("pushReplace")},onSkip:c.skipArchiveSync}),r.jsx(ic,{connected:"connected"===c.phase,metadata:c.daemonMetadata,restartBusy:c.admin.loading&&"restart"===c.admin.action,showUpdate:Boolean(c.daemonMetadata.version&&c.daemonMetadata.latestVersion&&tc(c.daemonMetadata.version,c.daemonMetadata.latestVersion)),t:c.t,updateBusy:c.admin.loading&&"update"===c.admin.action,updateStatus:c.admin.statusText,onRestart:()=>{c.runAdminAction("restart")},onUpdate:()=>{c.runAdminAction("update")}})]}),d=r.jsx("div",{className:"remote-workspace-settings",children:l});return t?s?a.createPortal(d,s):null:d}function ac(){const e=n().polishSettings,t="en"!==s(i().language),[a,c]=o.useState(),[l,d]=o.useState({...v}),[u,h]=o.useState(""),[p,m]=o.useState(!1),[f,g]=o.useState(""),[y,b]=o.useState(!1);if(o.useEffect(()=>{let n=!0;return e?.status().then(e=>{n&&(c(e),d(e.settings))}).catch(()=>{n&&(b(!0),g(t?"无法读取润色设置。":"Could not load polishing settings."))}),()=>{n=!1}},[e]),!e)return null;const x=async n=>{m(!0),g(""),b(!1);try{const s=await e.save(l,n);c(s),d(s.settings),h(""),g(t?"已保存":"Saved"),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch{b(!0),g(t?"保存失败,请检查 HTTPS API 地址、模型和提示词。":"Save failed. Check the HTTPS API URL, model and prompts.")}finally{m(!1)}};return r.jsxs("section",{className:"control-section compact-section speech-polish-settings",children:[r.jsx("h2",{children:t?"语音润色":"Voice polishing"}),r.jsxs("label",{className:"speech-enabled",children:[r.jsx("input",{type:"checkbox",role:"switch","aria-checked":l.enabled,className:"settings-switch",checked:l.enabled,disabled:!a||p,onChange:async n=>{const s={...l,enabled:n.target.checked};d(s),m(!0),g(""),b(!1);try{const t=await e.save({...a.settings,enabled:s.enabled});c(t),d(s),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch{d(l),b(!0),g(t?"无法保存开关设置":"Could not save setting")}finally{m(!1)}}}),t?"启用语音润色":"Enable voice polishing"]}),l.enabled&&r.jsxs("fieldset",{disabled:!a||p,className:"speech-polish-fields",children:[r.jsx("p",{className:"empty-copy",children:t?"识别后轻度整理口误、重复和标点,保留原意。转写文字会发送到你配置的模型;失败时保留原始文字,仅填入草稿。":"Lightly correct slips, repetition and punctuation while preserving meaning. Transcripts are sent to your configured model. Failures keep the original text; nothing is sent from your draft."}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"API 地址":"API URL"}),r.jsx("input",{type:"url",value:l.baseUrl,onChange:e=>d({...l,baseUrl:e.target.value}),autoComplete:"off"})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"模型":"Model"}),r.jsx("input",{value:l.model,onChange:e=>d({...l,model:e.target.value}),autoComplete:"off"})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"润色 API Key":"Polishing API Key"}),r.jsx("input",{type:"password",autoComplete:"off",value:u,onChange:e=>h(e.target.value),placeholder:a?.configured?t?"已保存 · 留空保留":"Saved · leave blank to keep":"API Key"})]}),r.jsx("p",{className:"empty-copy",children:"encrypted"===a?.persistence?t?"密钥加密保存在这台 Mac。支持 OpenAI 兼容接口。":"Key encrypted on this Mac. Supports OpenAI-compatible APIs.":t?"密钥仅保留在当前页面,刷新后需重新填写。Web API 需允许跨域访问。":"Key kept only in this page; enter it again after reload. The API must allow cross-origin requests."}),l.enabled&&!a?.configured&&!u.trim()&&r.jsx("p",{className:"empty-copy",children:t?"请填写 API Key 并保存,润色才能生效。":"Enter and save an API key to use polishing."}),r.jsxs("details",{className:"speech-polish-advanced",children:[r.jsx("summary",{children:t?"自定义提示词":"Custom prompts"}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"中文提示词":"Chinese prompt"}),r.jsx("textarea",{rows:5,value:l.promptZh,onChange:e=>d({...l,promptZh:e.target.value})})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"英文提示词":"English prompt"}),r.jsx("textarea",{rows:5,value:l.promptEn,onChange:e=>d({...l,promptEn:e.target.value})})]}),r.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>d({...l,promptZh:v.promptZh,promptEn:v.promptEn}),children:t?"恢复默认提示词":"Reset prompts"})]}),r.jsxs("div",{className:"attention-actions",children:[r.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{x(u.trim()||void 0)},children:t?"保存润色设置":"Save polishing settings"}),a?.configured&&r.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{x("")},children:t?"移除润色密钥":"Remove polishing key"})]})]}),f&&r.jsx("p",{role:y?"alert":"status",className:y?"error-copy":"empty-copy",children:f})]})}const cc={en:{title:"Voice input",disclosure:"Recording adds text to your draft without sending it. Audio is uploaded to Deepgram Nova-3 and billed to your Deepgram account.",saved:"Saved; your key is never displayed",session:"The key is kept only in this page’s memory. Enter it again after reloading or closing the page.",secure:"The key is encrypted on this Mac.",save:"Save API key",remove:"Remove API key",enabled:"Enable voice input",unsupported:"Recording requires a secure connection and a browser that supports WebM audio recording."},zh:{title:"语音输入",disclosure:"录音后将文字填入草稿,不会自动发送。音频会上传到 Deepgram Nova-3,并按你的 Deepgram 账户计费。",saved:"已保存,密钥不会回显",session:"密钥只保留在当前页面内存中,刷新或关闭页面后需要重新填写。",secure:"密钥会在此 Mac 上加密保存。",save:"保存密钥",remove:"移除密钥",enabled:"启用语音输入",unsupported:"录音需要安全连接,以及支持 WebM 音频录制的浏览器。"},"zh-TW":{title:"語音輸入",disclosure:"錄音後將文字填入草稿,不會自動傳送。音訊會上傳到 Deepgram Nova-3,並按你的 Deepgram 帳戶計費。",saved:"已儲存,金鑰不會回顯",session:"金鑰只保留在目前頁面記憶體中,重新整理或關閉頁面後需要重新填寫。",secure:"金鑰會在此 Mac 上加密儲存。",save:"儲存金鑰",remove:"移除金鑰",enabled:"啟用語音輸入",unsupported:"錄音需要安全連線,以及支援 WebM 音訊錄製的瀏覽器。"}};function lc(){const e=n().speechSettings,a=cc[s(i().language)],[c,l]=o.useState(),[d,u]=o.useState(""),[h,p]=o.useState(!1),[m,f]=o.useState(""),[g,y]=o.useState("true"===t().getItem("vibelet.web.voice.enabled")),v=Boolean(globalThis.isSecureContext&&"function"==typeof globalThis.navigator?.mediaDevices?.getUserMedia&&globalThis.MediaRecorder?.isTypeSupported("audio/webm"));o.useEffect(()=>{let t=!0;return e?.status().then(e=>{t&&l(e)}).catch(()=>{t&&f("Unable to load speech settings.")}),()=>{t=!1}},[e]);const b=e=>{y(e),t().setItem("vibelet.web.voice.enabled",String(e)),window.dispatchEvent(new Event("vibelet.speech.changed"))},x=async t=>{if(e&&!h){p(!0),f("");try{l(await e.saveKey(t)),u(""),t||b(!1),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch(n){f(n instanceof Error?n.message:String(n))}finally{p(!1)}}};if(!e)return null;const w="volcengine"===c?.engine,S=[...c?.systemAvailable?[{value:"system",label:"macOS · Apple"}]:[],{value:"deepgram",label:"Deepgram · Nova-3"},{value:"volcengine",label:"en"===s(i().language)?"Volcengine · ASR Flash":"火山引擎 · 录音识别"}];return r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:"control-section compact-section speech-input-settings",children:[r.jsx("h2",{children:a.title}),r.jsxs("label",{className:"speech-enabled",children:[r.jsx("input",{type:"checkbox",role:"switch","aria-checked":g,className:"settings-switch",checked:g,disabled:!v,onChange:e=>b(e.target.checked)}),a.enabled]}),g&&r.jsxs(r.Fragment,{children:[e.setEngine&&r.jsxs("div",{className:"field speech-engine-field",children:[r.jsx("span",{children:"en"===s(i().language)?"Recognition engine":"识别引擎"}),r.jsx(vs,{icon:ye,menuLabel:"Speech engine",label:S.find(e=>e.value===c?.engine)?.label??"Deepgram · Nova-3",options:S,value:c?.engine??"deepgram",disabled:h,onSelect:async t=>{p(!0),f(""),u("");try{l(await e.setEngine(t)),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch(n){f(n instanceof Error?n.message:String(n))}finally{p(!1)}}})]}),r.jsx("p",{className:"empty-copy",children:"system"===c?.engine?"en"===s(i().language)?"No API key needed. macOS 26+ uses on-device recognition and may download a language model on first use. Earlier versions may send audio to Apple. Text is added to your draft without sending.":"无需 API Key。macOS 26 及以上在本机识别,首次可能下载语言模型;较旧系统可能将音频发送给 Apple。文字只填入草稿,不会自动发送。":w?"en"===s(i().language)?"Audio is sent to Volcengine ASR Flash (volc.bigasr.auc_turbo), billed to your account. Enable this voice resource and use its API Key. Text only enters your draft.":"音频会上传至火山引擎录音识别极速版(volc.bigasr.auc_turbo),按你的账户计费。请开通此语音资源并填写语音 API Key,文字只追加到草稿。":a.disclosure}),"system"!==c?.engine&&r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"empty-copy",children:"encrypted"===c?.persistence?a.secure:a.session}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:w?"火山引擎 API Key":"Deepgram API Key"}),r.jsx("input",{type:"password",autoComplete:"off",value:d,onChange:e=>u(e.target.value),placeholder:c?.configured?a.saved:"API Key"})]}),r.jsxs("div",{className:"attention-actions",children:[r.jsx("button",{type:"button",className:"icon-text-button",disabled:h||!d.trim(),onClick:()=>{x(d)},children:a.save}),c?.configured&&r.jsx("button",{type:"button",className:"icon-text-button",disabled:h,onClick:()=>{x("")},children:a.remove})]})]})]}),!v&&r.jsx("p",{className:"empty-copy",children:a.unsupported}),m&&r.jsx("p",{role:"alert",className:"error-copy",children:m})]}),g&&r.jsx(ac,{})]})}async function dc(e,t,n){for(let i=0;i<2&&n();i++)try{return await e.request(t(),{timeoutMs:135e3})}catch(s){if(!(s instanceof Error&&/timeout|timed out/i.test(s.message)))return}}function uc(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 hc(e){return e?"success":"warning"}function pc(e,t){return e&&null!==t?t<150?"success":t<500?"warning":"danger":"warning"}function mc({connected:e,latencyMs:t,limits:n,t:s}){const i=function(e){const t=[],n=uc(e.codex),s=uc(e.claude);return null!==n&&t.push({agent:"codex",label:"Codex",...n}),null!==s&&t.push({agent:"claude",label:"Claude",...s}),t}({codex:n.codex?.limits,claude:n.claude?.limits}),[a,c]=o.useState(0);o.useEffect(()=>{if(c(0),i.length<2)return;const e=setInterval(()=>c(e=>(e+1)%i.length),4e3);return()=>clearInterval(e)},[i.length]);const l=i[a%i.length],d=l?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())}`}(l.resetsAt):null,u=l?`${l.label} ${l.availablePercent}%`:"",h=e?null===t?s.latencyMeasuring:`${t} ms`:s.latencyDisconnected;return r.jsxs("div",{className:"connection-indicators",children:[l&&r.jsxs("span",{role:"img",className:"connection-quota",title:`${s.remainingQuota}: ${u} · ${d?s.quotaResetsAt.replace("{time}",d):s.quotaResetUnavailable}${e?"":` · ${s.latencyDisconnected}`}`,"aria-label":`${s.remainingQuota}: ${u}${e?"":` · ${s.latencyDisconnected}`}`,children:[r.jsx("span",{className:"connection-quota-dot",style:{background:`var(--${hc(e)})`}}),r.jsx("span",{className:"connection-quota-text",children:u})]}),r.jsxs("span",{role:"img",className:"connection-latency",style:{color:`var(--${pc(e,t)})`},"aria-label":`${s.connectionLatency}: ${h}`,children:[r.jsx(A,{size:11,"aria-hidden":"true"}),r.jsx("span",{className:"connection-latency-text",children:h})]})]})}function fc({workspace:e}){const{phase:t,clientRef:n,pairing:s,t:i}=e,[a,c]=o.useState(null),[l,d]=o.useState({});return o.useEffect(()=>{d({})},[s?.daemonId]),o.useEffect(()=>{const e=n.current;if(c(null),"connected"!==t||!e)return;let s=!0;const i=e.onLatency(c),r=new Set,o=()=>{for(const t of["codex","claude"])r.has(t)||(r.add(t),dc(e,()=>({action:"usage.limits.fetch",id:e.makeId("header-usage"),agent:t}),()=>s&&n.current===e&&e.isConnected).then(i=>{i&&s&&n.current===e&&d(e=>({...e,[t]:i}))}).finally(()=>r.delete(t)))};o();const a=setInterval(o,6e4);return()=>{s=!1,i(),clearInterval(a)}},[t,n,s?.daemonId]),r.jsx(mc,{connected:"connected"===t,latencyMs:a,limits:l,t:i})}function gc({value:e,t,showSession:n=!0,onChange:s}){const i=[...n?[{tab:"session",label:t.session,Icon:De}]:[],{tab:"files",label:t.files,Icon:te},{tab:"terminal",label:t.terminal,Icon:Le},{tab:"browser",label:t.browser,Icon:ae}];return r.jsx("div",{className:"control-tabs",children:i.map(({tab:t,label:n,Icon:i})=>r.jsxs("button",{"aria-label":n,"aria-pressed":e===t,className:e===t?"selected":"",onClick:()=>s(t),title:n,type:"button",children:[r.jsx(i,{"aria-hidden":"true"}),r.jsx("span",{children:n})]},t))})}function yc(){const[e,t]=o.useState(null);return o.useEffect(()=>{let e=null,n=null;const s=()=>{e&&null!==n&&e.setAttribute("title",n),e=null,n=null,t(null)},i=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},r=i=>{if(i===e)return;if(s(),!i)return;const r=i.getAttribute("title")||i.getAttribute("aria-label");if(!r)return;e=i,n=i.getAttribute("title"),null!==n&&i.removeAttribute("title");const o=i.getBoundingClientRect(),a=o.bottom+42>window.innerHeight,c=o.right>window.innerWidth-140?"end":o.left<140?"start":"center";t({label:r,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=>r(i(e.target)),a=t=>{e&&t.relatedTarget instanceof Node&&e.contains(t.relatedTarget)||i(t.target)===e&&s()},c=e=>r(i(e.target)),l=t=>{i(t.target)===e&&s()};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),s()}},[]),e?a.createPortal(r.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 vc({chinese:e}){const[s,i]=o.useState(et),[a,c]=o.useState(null),[l,d]=o.useState(""),u=e=>{!function(e){t().setItem(Xe,JSON.stringify(e)),window.dispatchEvent(new Event(Ke))}(e),i(e),d("")};return r.jsxs("section",{className:"control-section compact-section workspace-shortcut-settings",children:[r.jsx("h2",{children:e?"应用内快捷键":"In-app shortcuts"}),r.jsx("p",{className:"empty-copy",children:e?"点击组合键后直接按键录制。Esc 取消,退格键清除。新建标签会沿用当前终端或浏览器;其他页面默认新建浏览器标签。":"Click a shortcut to record it. Escape cancels; Backspace clears. New tab follows the current terminal or browser; elsewhere it opens a browser tab."}),Ue.map(t=>r.jsxs("div",{className:"workspace-shortcut-row",children:[r.jsx("span",{children:e?t.zh:t.en}),r.jsx("button",{type:"button","data-shortcut-recording":a===t.id?"true":void 0,"aria-label":`${e?"设置快捷键:":"Set shortcut: "}${e?t.zh:t.en}`,onClick:()=>{c(t.id),d("")},onBlur:()=>c(null),onKeyDown:i=>{if(a!==t.id)return;if(i.preventDefault(),i.stopPropagation(),"Escape"===i.key)return c(null),void d("");if("Backspace"===i.key||"Delete"===i.key)return u({...s,[t.id]:""}),void c(null);const r=Je(i.nativeEvent);if(!r)return;const o=function(e,t,s){return"browser"===n().kind?"mod+w"===t?"reserved":Ye(e,t,{closeTab:"mod+alt+w",...s}):Ye(e,t,s)}(t.id,r,s);if(o){const t=Ue.find(e=>e.id===o);return void d("reserved"===o?e?"此组合键用于系统菜单或编辑操作,请换一个组合。":"Reserved for a system menu or editing action. Choose another combination.":`${e?"已用于:":"Already assigned to: "}${e?t?.zh:t?.en}`)}u({...s,[t.id]:r}),c(null)},children:a===t.id?e?"按下快捷键…":"Press shortcut…":Ze(tt(t.id,s))||(e?"未设置":"Not set")})]},t.id)),l&&r.jsx("p",{role:"alert",children:l}),r.jsx("div",{className:"attention-actions",children:r.jsx("button",{type:"button",onClick:()=>{u({}),c(null)},children:e?"恢复默认快捷键":"Restore defaults"})}),r.jsx("p",{className:"empty-copy",children:e?"⌘N 新建会话,⌘, 打开设置;⌘W 保留为关闭窗口。关闭标签默认使用 ⌘⌥W。":"⌘N creates a session; ⌘, opens settings; ⌘W closes the window. Close tab defaults to ⌘⌥W."})]})}function bc({children:e,t,onClose:n}){const s=o.useRef(null);return o.useEffect(()=>{const e=document.getElementById("vibelet-workspace");return e&&(e.inert=!0),s.current?.focus(),()=>{e&&(e.inert=!1)}},[]),a.createPortal(r.jsxs("section",{className:"browser-settings-page","aria-label":t.settings,onKeyDown:e=>{if("Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),n()),"Tab"!==e.key)return;const t=[...e.currentTarget.querySelectorAll("button:not(:disabled),input:not(:disabled),a[href]")].filter(e=>e.getBoundingClientRect().width>0),s=t[0],i=t.at(-1);e.shiftKey&&document.activeElement===s&&(e.preventDefault(),i?.focus()),e.shiftKey||document.activeElement!==i||(e.preventDefault(),s?.focus())},children:[r.jsxs("button",{ref:s,type:"button",className:"icon-text-button",onClick:n,children:["← ",t.chat]}),r.jsx("h1",{children:t.settings}),r.jsxs("div",{className:"browser-settings-body",children:[r.jsx(ot,{}),e,r.jsx(vc,{chinese:"Browser"!==t.browser})]})]}),document.body)}function xc({children:e,collapsed:t,t:s,value:i,showSession:c,onChange:l,onResize:d}){const u=ya("right",e=>{"terminal"!==e&&"browser"!==e||l(e)}),h=n().toolbarTarget?.("controls"),[p,m]=o.useState(null),f=r.jsx("div",{className:"right-dock-toolbar",ref:m,children:r.jsx(gc,{value:i,t:s,showSession:c,onChange:l})});return"admin"===i&&"browser"===n().kind?r.jsx(bc,{t:s,onClose:()=>l("files"),children:e}):r.jsxs(ua.Provider,{value:{element:p,kind:i},children:[r.jsx(yc,{}),h&&!t?a.createPortal(f,h):null,r.jsx("button",{"aria-label":s.resizeControlsSidebar,"aria-hidden":t,className:"resize-handle right-resize-handle",disabled:t,onPointerDown:d,title:s.resizeControlsSidebar,type:"button",children:r.jsx("span",{})}),r.jsx("div",{className:"workspace-control-sidebar-motion",inert:t,"aria-hidden":t,children:r.jsxs("aside",{tabIndex:-1,"aria-label":s.controls,className:"control-pane",...u,children:[!h&&r.jsx("div",{className:"control-pane-toolbar",children:f}),e]})})]})}function wc({path:e,label:t,zh:n}){const{copyText:s,feedback:i}=As(n?"已复制路径":"Path copied",n?"复制失败,请重试":"Copy failed. Please try again."),o=i?.message??t;return r.jsx("button",{type:"button",title:o,"aria-label":o,onClick:()=>{s(e)},children:i?"success"===i.tone?r.jsx($,{}):r.jsx(He,{}):r.jsx(U,{})})}function Sc(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 kc(e){return`<!doctype html><meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data: blob: https:; media-src data: blob:; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'none'; base-uri 'none'; form-action 'none'">${e}`}function Ic(){const e=s(i().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 Cc({file:e}){const[t,c]=o.useState(!1),l=f(()=>c(!1),void 0,t),d=Ys(),u=s(i().language),h="en"===u?"Close":"zh-TW"===u?"關閉":"关闭",p=n().pdfPreviewUrl?.(e.path,e.cwd)??e.objectUrl;return r.jsxs(r.Fragment,{children:[r.jsxs("button",{className:"icon-text-button",type:"button",onClick:()=>c(!0),children:[r.jsx(ee,{"aria-hidden":"true"}),d.pdfPreview]}),t&&a.createPortal(r.jsx("div",{className:"remote-document-layer",onPointerDown:e=>{e.target===e.currentTarget&&c(!1)},children:r.jsxs("div",{ref:l,className:"remote-document-dialog","aria-label":d.pdfPreview,role:"dialog","aria-modal":"true",tabIndex:-1,children:[r.jsxs("header",{children:[r.jsx("span",{children:e.path.split("/").pop()}),r.jsx("button",{className:"icon-button",type:"button","aria-label":h,title:h,onClick:()=>c(!1),children:r.jsx(He,{"aria-hidden":"true"})})]}),r.jsx("iframe",{title:d.pdfPreview,src:`${p}#toolbar=1&navpanes=0&view=Fit`})]})}),document.body)]})}function jc({file:e}){const[t,s]=o.useState(),i=e.objectUrl??e.path,a=()=>s(i),c=Ys(),l=Sc(e.path,e.contentType,"text"===e.kind);if(t===i)return r.jsx("p",{className:"empty-copy",role:"status",children:c.mediaError});if("html"===l){const t=e.dirty?void 0:n().htmlPreviewUrl?.(e.path,e.cwd);return r.jsx("iframe",{className:"remote-document-preview",sandbox:"allow-scripts",title:c.htmlPreview,src:t,srcDoc:t?void 0:kc(e.text)})}return e.objectUrl?"image"===l?r.jsx("div",{className:"remote-media-viewer remote-image-viewer",children:r.jsx("img",{className:"remote-image",src:e.objectUrl,alt:e.path,onError:a})}):"audio"===l?r.jsx("audio",{"aria-label":c.audioPreview,controls:!0,preload:"metadata",src:e.objectUrl,onError:a}):"video"===l?r.jsx("div",{className:"remote-media-viewer remote-video-viewer",children:r.jsx("video",{"aria-label":c.videoPreview,controls:!0,playsInline:!0,preload:"metadata",src:e.objectUrl,onError:a},e.objectUrl)}):"pdf"===l?r.jsx(Cc,{file:e}):r.jsx("p",{className:"empty-copy",children:c.mediaError}):null}const Rc="vibelet:file-operation-before",Mc="vibelet:file-operation-done";function Ec(e,t=""){const n=e.replace(/\\/g,"/"),s=/^(\/|[a-z]:\/|~)/i.test(n)?n:`${t.replace(/\\/g,"/")}/${n}`,i=[];for(const r of s.split("/"))r&&"."!==r&&(".."===r?i.pop():i.push(r));return`${s.startsWith("/")?"/":""}${i.join("/")}`}function Tc(e,t,n){const s=Ec(e,n),i=Ec(t,n);return s===i||s.startsWith(`${i}/`)}async function Ac(e,t){const n=new CustomEvent(Rc,{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)}),i=await s.text();let r;try{r=JSON.parse(i)}catch{throw new Error(404===s.status||/^Vibelet Daemon v/.test(i)?"daemon_update_required":"operation_failed")}if(404===s.status&&"ENOENT"!==r.error)throw new Error("daemon_update_required");if(!s.ok)throw new Error(r.error??"operation_failed");return ls()?.daemonId===t.daemonId&&window.dispatchEvent(new CustomEvent(Mc,{detail:{...r,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd,source:e.path}})),r}function Nc(e){const t=e.split("#")[0];return/\.[^/\\.]+$/.test(t)?t:`${t}.md`}function Pc(e,t){return Cn(Ec(e,t))??t??"."}function Dc(e,t,n){if(!e)return{path:Ec(t,n),cwd:n??Pc(t,n)};const s=e.includes("/")&&!/^\.\.?\//.test(e)?n??Pc(t,n):Pc(t,n);return{path:Nc(e||t),cwd:s}}function Fc(e,t){if(!t)return;let n=t.replace(/^#/,"");try{n=decodeURIComponent(n)}catch{}const s=e.querySelectorAll(n.startsWith("^")?"p,li":"h1,h2,h3,h4,h5,h6"),i=Array.from(s).find(e=>n.startsWith("^")?e.textContent?.trim().endsWith(n):e.textContent?.trim()===n||e.id===n);i?.scrollIntoView({block:"start"})}const Lc=new Map;function qc(e,t,n){for(const[s,i]of Lc)Date.now()-i.time>1e4&&Lc.delete(s);n&&Lc.set(Ec(e,t),{hash:n,time:Date.now()})}function Oc(e,t){const n=Ec(e,t),s=Lc.get(n);return Lc.delete(n),s&&Date.now()-s.time<1e4?s.hash:""}const $c=o.lazy(()=>m(()=>import("./MarkdownModePanel-vIEhq98H.js"),__vite__mapDeps([20,1,2,21])).then(e=>({default:e.MarkdownModePanel}))),zc=o.lazy(()=>m(()=>import("./file-editor-FileCodeEditor-C4drlwzi.js"),__vite__mapDeps([22,1,2,23,24])).then(e=>({default:e.FileCodeEditor}))),_c=o.lazy(()=>m(()=>import("./file-editor-ObsidianCodeEditor-BWzRCMya.js"),__vite__mapDeps([25,1,2,22,23,24,26,27,28,29,30,31,32,3,33,6,34,35,36])).then(e=>({default:e.ObsidianCodeEditor}))),Bc=o.lazy(()=>m(()=>import("./file-editor-ObsidianFileEditor-Bo11_LxW.js"),__vite__mapDeps([37,1,2,32,3,23,33,38,27,5,39,40,41,42])).then(e=>({default:e.ObsidianFileEditor})));function Hc({file:e,client:t,onOpenRemoteFile:n,onTextChange:a}){const c=function(e,t){return o.useMemo(()=>{let n;return async(s,i)=>{const r=Dc(s,i,t),o={path:Ec(r.path,r.cwd),cwd:t??r.cwd};if(!e?.isConnected||!t||!s||/^([/.]|[a-z]:)/i.test(s))return o;n??=e.request({action:"vault.listMarkdown",id:`editor-vault-${crypto.randomUUID()}`,cwd:t});try{const{entries:e}=await n,i=s.replace(/\.(?:md|markdown)$/i,"").toLowerCase(),a=e.filter(e=>e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase()===i||e.basename.toLowerCase()===i||e.aliases?.includes(i)),c=Ec(Nc(s),r.cwd),l=a.find(e=>Ec(e.relPath,t)===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:Ec(l.relPath,t),cwd:t}:o}catch{return n=void 0,o}}},[e,t])}(t,e.cwd),l=function(e){return/\.(md|mdx|markdown|mdown)$/i.test(e)}(e.path),[d,u]=o.useState("preview"),h="html"===Sc(e.path,e.contentType,!0),p="en"!==s(i().language);return r.jsxs(r.Fragment,{children:[h&&r.jsxs("div",{className:"segmented editor-mode-tabs",children:[r.jsx("button",{type:"button",className:"edit"===d?"selected":"",onClick:()=>u("edit"),children:p?"编辑":"Edit"}),r.jsx("button",{type:"button",className:"preview"===d?"selected":"",onClick:()=>u("preview"),children:p?"预览":"Preview"})]}),l?r.jsx(o.Suspense,{fallback:r.jsx("pre",{className:"remote-editor",children:e.text}),children:r.jsx($c,{text:e.text,modes:["edit","source"],initialMode:"edit",labels:Ic(),renderVisual:s=>r.jsx(Bc,{client:t,resolveFile:c,path:e.path,cwd:e.cwd,text:e.text,readOnly:s,onChange:a,onOpenFile:n}),renderCode:s=>r.jsx(_c,{client:t,cwd:e.cwd,path:e.path,resolveFile:c,onOpenFile:n,text:e.text,onChange:a,preview:s})})}):h&&"preview"===d?r.jsx(jc,{file:e}):r.jsx(o.Suspense,{fallback:r.jsx("pre",{className:"remote-editor",children:e.text}),children:r.jsx(zc,{path:e.path,text:e.text,onChange:a})})]})}function Wc({workspace:e,children:t}){const a=ca(),c=ia(e.pairing?.daemonId,e.activeSessionId),l=ya("center"),[d,u]=sa(c,()=>({})),[h,p]=sa(c,null),[m,f]=o.useState(null),y=o.useRef({files:d,remoteFile:e.remoteFile,daemonId:e.pairing?.daemonId});y.current={files:d,remoteFile:e.remoteFile,daemonId:e.pairing?.daemonId};const v=o.useRef(new Map),w="en"!==s(i().language);o.useEffect(()=>{y.current.files={},u({}),p(null),v.current.set(c,null)},[e.pairing?.daemonId]),o.useEffect(()=>{if(!e.remoteFile)return void v.current.set(c,null);const t=e.remoteFile,n=y.current.files[t.path];if(n?.dirty&&!t.dirty&&n.cwd===t.cwd&&n.text!==t.text)return e.setRemoteFile(n),p(n.path),void a.setCenter(null);u(e=>({...e,[t.path]:t})),v.current.get(c)!==t.path&&(p(t.path),a.setCenter(null)),v.current.set(c,t.path)},[e.remoteFile,c]);const S=t=>{a.setCenter(null),e.setRemoteFile(d[t]),p(t)},k=async t=>{const n=d[t],s=e.pairing?.daemonId;if(!n)return;const i=b();n.dirty&&!(await x({title:i.discard,message:t,confirmLabel:i.discardAction,danger:!0}))||y.current.daemonId===s&&y.current.files[t]?.text===n.text&&(u(e=>{const n={...e};return delete n[t],n}),t===h&&(p(null),v.current.set(c,null),e.setRemoteFile(null)))};!function(e){const t=o.useRef(e);t.current=e,o.useEffect(()=>{const e=e=>{const{detail:n}=e,s=t.current;s.daemonId===n.daemonId&&"copy"!==n.action&&"restore"!==n.action&&[...Object.values(s.files),s.remoteFile].filter(Boolean).some(e=>e.dirty&&Tc(e.path,n.path,n.cwd))&&e.preventDefault()},n=e=>{const{detail:n}=e,s=t.current;if(s.daemonId!==n.daemonId||"copy"===n.action||"restore"===n.action)return;const i=n.source??n.path,r=e=>{if(!Tc(e.path,i,n.cwd))return e;if("delete"===n.action)return null;const t=`${n.target}${Ec(e.path,n.cwd).slice(Ec(i,n.cwd).length)}`;return{...e,path:t}};s.setFiles(e=>Object.fromEntries(Object.values(e).flatMap(e=>{const t=r(e);return t?[[t.path,t]]:[]}))),s.active&&s.files[s.active]&&s.setActive(r(s.files[s.active])?.path??null),s.setRemoteFile(e=>e?r(e):e);const o=new URL(window.location.href),a=o.searchParams.get("file");a&&Tc(a,i,n.cwd)&&("delete"===n.action?o.searchParams.delete("file"):o.searchParams.set("file",`${n.target}${Ec(a,n.cwd).slice(Ec(i,n.cwd).length)}`),window.history.replaceState(null,"",o.href))};return window.addEventListener(Rc,e),window.addEventListener(Mc,n),()=>{window.removeEventListener(Rc,e),window.removeEventListener(Mc,n)}},[])}({daemonId:e.pairing?.daemonId,files:d,active:h,remoteFile:e.remoteFile,setFiles:u,setActive:p,setRemoteFile:e.setRemoteFile}),o.useEffect(()=>{const e=e=>{const t=e.detail;if("closeTab"===t)return void(a.center?a.close(a.center):h&&k(h));const n=[null,...Object.keys(d),...a.items.filter(e=>"center"===e.location).map(e=>e.id)],s=n.indexOf(a.center||h),i=n[(Math.max(s,0)+("nextTab"===t?1:n.length-1))%n.length];i?d[i]?S(i):a.setCenter(i):(p(null),a.setCenter(null))};return window.addEventListener(Qe,e),()=>window.removeEventListener(Qe,e)},[d,h,a]);const I=h?d[h]:null,C=n().toolbarTarget?.("conversation"),j=I&&!a.center&&r.jsxs("header",{className:"document-file-header",role:"toolbar","aria-label":w?"文件操作":"File actions",children:[r.jsx("button",{type:"button",title:e.t.download,"aria-label":e.t.download,onClick:()=>{e.downloadRemoteFile()},children:r.jsx(g,{})}),r.jsx(wc,{path:I.path,label:e.t.copyPath,zh:w},I.path),"text"===I.kind&&r.jsx("button",{type:"button",title:e.t.saveFile,"aria-label":e.t.saveFile,disabled:!I.dirty||e.busy,onClick:()=>{e.saveRemoteFile()},children:r.jsx(Me,{})})]});return r.jsx(pi.Provider,{value:m,children:r.jsxs("div",{className:"workspace-documents",...l,children:[!C&&r.jsx("div",{className:"chat-header document-conversation-header",ref:f}),(Object.keys(d).length>0||a.items.some(e=>"center"===e.location))&&r.jsxs("div",{className:"document-tabs",children:[r.jsxs("div",{className:"document-tab-items",role:"tablist","aria-label":w?"工作区标签页":"Workspace tabs",children:[r.jsx("button",{role:"tab","aria-selected":!h&&!a.center,onClick:()=>{p(null),a.setCenter(null),v.current.set(c,null)},type:"button",children:e.t.chat}),Object.values(d).map(t=>r.jsxs("div",{className:"document-tab","data-active":!a.center&&h===t.path,children:[r.jsxs("button",{type:"button",role:"tab","aria-selected":!a.center&&h===t.path,title:t.path,onClick:()=>S(t.path),children:[r.jsx(ee,{}),r.jsxs("span",{className:"document-tab-label",children:[mn(t.path),t.dirty?" ·":""]})]}),r.jsx("button",{type:"button",className:"document-tab-close",title:e.t.close,"aria-label":`${e.t.close} ${mn(t.path)}`,onClick:()=>k(t.path),children:r.jsx(He,{})})]},t.path)),r.jsx(ma,{location:"center",t:e.t})]}),j]}),r.jsx("div",{hidden:!!h||!!a.center,className:"document-chat",children:t}),r.jsx("div",{hidden:!a.center,className:"dock-center-content",children:r.jsx(ga,{location:"center"})}),I&&!a.center&&r.jsxs("section",{className:"document-file",role:"tabpanel","aria-label":mn(I.path),children:["text"===I.kind?r.jsx(Hc,{client:e.clientRef?.current,file:I,onOpenRemoteFile:(t,n)=>{e.openRemoteFile(t,n,{updateRoute:!0})},onTextChange:t=>e.setRemoteFile(e=>e?{...e,text:t,dirty:!0}:e)},I.path):r.jsx(jc,{file:I},I.path),e.remoteFileConflict&&r.jsxs("div",{role:"alert",className:"inline-notice warning",children:[r.jsx("span",{children:e.t.remoteFileConflict(I.path)}),r.jsx("button",{type:"button",onClick:()=>{(async()=>{const t=e.remoteFile;t&&await x({message:e.t.confirmOverwrite(mn(t.path)),danger:!0})&&y.current.remoteFile===t&&await e.saveRemoteFile({force:!0})})()},children:e.t.forceSave})]})]})]})})}const Kc="vibelet.web.savedTargets";function Qc(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 Uc(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const s of e){const e=Qc(s);if(e&&!t.has(e.daemonId)&&(t.add(e.daemonId),n.push(e),n.length>=12))break}return n}function Vc(e=t()){const n=e.getItem(Kc);if(!n)return[];try{return Uc(JSON.parse(n))}catch{return[]}}function Gc(e,n=t()){n.setItem(Kc,JSON.stringify(Uc(e)))}class Jc{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 Zc extends Error{name="VibeletRequestRejectedError"}function Yc(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}class Xc{heartbeat=new Jc;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&&ts(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 i=await this.requestOnSocket({action:"auth.hello",id:Yc("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=i.capabilities??{},this.heartbeat.start(()=>t.send(JSON.stringify({action:"ping"})),()=>t.close()),i}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 i={action:e.action,resolve:n,reject:s};t.timeoutMs&&t.timeoutMs>0&&(i.timeoutId=setTimeout(()=>{this.pending.delete(e.id),s(new Error(t.timeoutMessage||`Request timed out (${e.action}).`))},t.timeoutMs)),this.pending.set(e.id,i),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}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 Yc(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,i]of this.pending)i.action===e&&(this.pending.delete(s),i.timeoutId&&clearTimeout(i.timeoutId),i.reject(new Zc(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 Zc(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()}}const el="vibelet.web.sessionListCache";function tl(e){return e instanceof Error&&"auth_failed"===e.message}const nl="vibelet.web.composerDrafts",sl={draftsBySessionId:{},newSessionDraft:""};function il(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function rl(e){return il(e)?{draftsBySessionId:il(e.draftsBySessionId)?Object.fromEntries(Object.entries(e.draftsBySessionId).filter(e=>"string"==typeof e[1])):{},newSessionDraft:"string"==typeof e.newSessionDraft?e.newSessionDraft:""}:sl}function ol(e=t()){const n=e.getItem(nl);if(!n)return sl;try{return rl(JSON.parse(n))}catch{return sl}}function al(e,n=t()){n.setItem(nl,JSON.stringify(rl(e)))}function cl(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 ll(e,t){return t?e.draftsBySessionId[t]??"":e.newSessionDraft}function dl(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}}function ul(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":/timeout|timed out/u.test(t)?"timeout":/failed to reconnect|process exited|reconnected concurrently/u.test(t)?"reconnect":/websocket|network|disconnect|connection|offline|closed/u.test(t)?"network":"unknown"}const hl=13e4;function pl(e,t){return Boolean(t)&&Object.hasOwn(e,t)}function ml(e,t,n){return t&&0!==n.length?{...e,[t]:Zt(e[t]??[],n)}:e}function fl(e,t){const n=new Map,s=Zt(e,t,(e,t)=>{t.localClientMessageId&&n.set(e,t)}),i=t.map(e=>{const t=n.get(e);return t?{...e,localClientMessageId:t.localClientMessageId,localDelivery:t.localDelivery}:{...e}}),r=new Set(i.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 i of t){const e=Date.parse(i.timestamp??""),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 r=n.findIndex(e=>t.historyKey&&e.historyKey===t.historyKey||t.liveReply&&e.liveReply&&e.timestamp===t.timestamp);return r<0||n.indexOf(i)<r}):-1;s.splice(t<0?s.length:t,0,i)}return s}(i,s.filter(e=>e.localClientMessageId&&e.historyKey?.startsWith("client:")&&!r.has(e.localClientMessageId)),e)}function gl(e,t,n){const s=new Set(e);return n?s.add(t):s.delete(t),s}async function yl(e){return{[e]:"desktop-free"}}function vl(){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()}}}}}function bl(e,t,n){const s=ll(e.composerDraftsRef.current,e.activeSessionId),i=s===t?s:[s,t].filter(Boolean).join("\n\n"),r=cl(e.composerDraftsRef.current,e.activeSessionId,i);e.composerDraftsRef.current=r,e.setComposerDrafts(r),e.activeSessionIdRef.current===e.activeSessionId&&e.setDraft(i);try{al(r)}catch{}e.setAttachments(e=>[...e,...n.filter(t=>!e.some(e=>e.path===t.path))])}const xl="Session send timed out.";function wl(e){return"string"==typeof e&&e.trim().length>0?e:void 0}const Sl="vibelet.web.sessionSettings";function kl(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function Il(e=window.location.search){const t=new URLSearchParams(e),n=kl(t.get("folder")),s=kl(t.get("file")),i=kl(t.get("cwd"));return{...n?{folder:n}:{},...s?{file:s}:{},...i?{cwd:i}:{}}}function Cl(e,t={}){const n=t.history??window.history,s=t.location??window.location,i=[];e.folder&&i.push("file","cwd"),e.file&&i.push("folder");const r=function(e,t,n=[]){const s=new URLSearchParams(e);for(const r of n)s.delete(r);for(const[r,o]of Object.entries(t))o?s.set(r,o):s.delete(r);const i=s.toString();return i?`?${i}`:""}(s.search,e,i),o=`${s.pathname}${r}${s.hash}`;t.replace?n.replaceState(null,"",o):n.pushState(null,"",o)}function jl(e,t){o.useEffect(()=>{e.current=t},[e,t])}class Rl{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)=>{"failed"===n?this.failed.set(t,e):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))};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 Ml(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)}async function El(e,t,n,s){const i=await fetch(`/upload?name=${encodeURIComponent(e.name)}`,{method:"POST",signal:n,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 r=function(e){const t=e;return"string"==typeof t.path?t.path:null}(await i.json());if(!r)throw new Error(s.uploadPathMissing);return{path:r,name:e.name,type:e.type||"application/octet-stream",size:e.size}}function Tl(e){return e.historyKey?`key:${e.historyKey}`:e.timestamp?JSON.stringify([e.timestamp,e.role,e.type,e.content,e.images,e.toolName,e.toolInput]):void 0}const Al="vibelet.web.historyDiskCache.v1";function Nl(){try{const e=JSON.parse(t().getItem(Al)||"[]");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 Pl(e,n){try{const s=Nl().filter(t=>t.daemonId!==e||!Object.hasOwn(n,t.sessionId));for(const[t,r]of Object.entries(n)){if(!r)continue;const n={daemonId:e,sessionId:t,messages:r.slice(-1e3)};for(;n.messages.length&&(new TextEncoder).encode(JSON.stringify(n)).length>524288;)n.messages.shift();(n.messages.length||0===r.length)&&s.unshift(n)}const i=s.slice(0,40);for(;i.length&&(new TextEncoder).encode(JSON.stringify(i)).length>2097152;)i.pop();t().setItem(Al,JSON.stringify(i))}catch{}}const Dl=new Set(["attachmentCount","domNodes","durationMs","errorKind","failureKind","longTaskCount","maxLongTaskMs","online","phase","visibilityState"]);function Fl(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 Ll(e,t){return t.has(e.sessionId)||!0===e.runtime?.isResponding||"daemonActive"===e.runtime?.state||"externalRunning"===e.runtime?.state}class ql{cleared=new Map;live(e,t,n){const s=new Set(n.map(e=>e.clientMessageId)),i=this.cleared.get(t)??new Set;for(const r of e[t]??[])r.clientMessageId&&!s.has(r.clientMessageId)&&i.add(r.clientMessageId);for(const r of s)r&&i.delete(r);return this.cleared.set(t,i),{...e,[t]: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 Ol=o.lazy(()=>m(()=>import("./NewSessionDialog-BMPED8-_.js"),__vite__mapDeps([43,1,2,14,44]))),$l=o.lazy(()=>m(()=>import("./GlobalPendingDialog-brYHIW1O.js"),__vite__mapDeps([45,1,2])));function zl({workspace:e}){const t=function(e){const[t,n]=o.useState(0),[s,i]=o.useState(0);return o.useLayoutEffect(()=>{if(!s)return;const e=requestAnimationFrame(()=>{document.querySelector('[role="dialog"]')||document.querySelector(".document-chat:not([hidden]) .composer textarea")?.focus({preventScroll:!0})});return()=>cancelAnimationFrame(e)},[s]),{selectSession:t=>{i(e=>e+1),e.activeSessionIdRef.current=t,e.setActiveSessionId(t);const s=e.displaySessions.find(e=>e.sessionId===t);if(!e.pendingApprovals[t]&&!e.pendingQuestions[t]&&!s?.runtime.needsAttention)return;n(e=>e+1);const r=e.clientRef.current;e.requestReconnectSnapshot().catch(n=>{e.clientRef.current===r&&e.activeSessionIdRef.current===t&&e.setErrorText(n instanceof Error?n.message:String(n))})},revealKey:t}}(e),[s,i]=o.useState(!0),[a,c]=o.useState(!1),[l,d]=o.useState(!1);!function(e){const t=ca(),[s,i]=o.useState(et),r=o.useRef({workspace:e,dock:t,shortcuts:s});r.current={workspace:e,dock:t,shortcuts:s},o.useEffect(()=>{const e=()=>i(et()),t=e=>e instanceof Element&&!!e.closest('.workspace-control-sidebar-motion, .dock-surface[data-location="right"], #desktop-toolbar-controls');let s=!1;const o=e=>{s=t(e.target)},a=(e,n,i=e.target)=>{if(e.defaultPrevented||e.isComposing||e.repeat||document.querySelector('[data-shortcut-recording="true"], [role="dialog"], .desktop-workspace-container[hidden], .browser-settings-page'))return;const o=Je(e);if(!o&&!n)return;const{workspace:a,dock:c,shortcuts:l}=r.current,d=n??Ue.find(e=>tt(e.id,l)===o)?.id;if(!d)return;if("searchMessages"===d&&(t(i)||!document.querySelector(".document-chat:not([hidden]) .chat-pane")))return;e.preventDefault(),e.stopPropagation();const u="terminal"===a.controlTab?"terminal":"browser",h=c.items.find(e=>e.id===c.center),p=!a.rightSidebarCollapsed&&(t(i)||i===document.body&&s),m=!p&&h?h:c.items.find(e=>e.id===c.right[u]);switch(d){case"searchMessages":window.dispatchEvent(new Event("vibelet.message-search"));break;case"leftSidebar":a.setLeftSidebarCollapsed(e=>!e);break;case"rightSidebar":a.setRightSidebarCollapsed(e=>!e);break;case"files":case"terminal":case"browser":a.setControlTabAndOpen(d);break;case"searchSessions":a.setLeftSidebarCollapsed(!1),window.dispatchEvent(new Event("vibelet.session-search"));break;case"newTab":{const e="terminal"===m?.kind||"browser"===m?.kind?m.kind:u;c.add(e,a.t[e],a.cwd),a.setControlTabAndOpen(e);break}case"moveTab":m&&c.move(m.id,"center"===m.location?"right":"center");break;case"diff":a.activeSession&&a.setDiffSessionId(a.activeSession.sessionId);break;case"closeTab":case"nextTab":case"previousTab":if(p)if("closeTab"===d)!m||m.emptyPlaceholder?a.setRightSidebarCollapsed(!0):(document.querySelector(".control-pane")?.focus(),c.close(m.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===m?.id))+("nextTab"===d?1:e.length-1))%e.length].id}))}else window.dispatchEvent(new CustomEvent(Qe,{detail:d}))}},c=e=>a(e),l=n().subscribeCommand?.(e=>{"close-tab"===e&&a(new KeyboardEvent("keydown"),"closeTab",document.activeElement)});return window.addEventListener(Ke,e),window.addEventListener("focusin",o,!0),window.addEventListener("pointerdown",o,!0),window.addEventListener("keydown",c,!0),()=>{l?.(),window.removeEventListener(Ke,e),window.removeEventListener("focusin",o,!0),window.removeEventListener("pointerdown",o,!0),window.removeEventListener("keydown",c,!0)}},[])}(e);const[u,h]=function(e){const[t,s]=o.useState(null);return o.useEffect(()=>{const t=()=>s(t=>t??{cwd:e}),i=n().subscribeCommand?.(e=>{"new-session"===e&&t()}),r=e=>{"browser"!==n().kind||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey||"n"!==e.key.toLowerCase()||(e.preventDefault(),t())};return window.addEventListener("keydown",r),()=>{i?.(),window.removeEventListener("keydown",r)}},[e]),[t,s]}(e.cwd);o.useEffect(()=>{"browser"===e.controlTab&&i(!0)},[e.controlTab]),o.useEffect(()=>{"terminal"===e.controlTab&&c(!0)},[e.controlTab]),o.useEffect(()=>{("session"===e.controlTab||"desktop"===n().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]),o.useEffect(()=>{e.activeQuestion&&e.setQuestionAnswers(gn(e.activeQuestion))},[e.activeQuestion,e.setQuestionAnswers]);const{clientRef:p,phase:m,statusText:f,errorText:g,pairing:y,sessions:v,nextCursor:b,folderCounts:x,inventoryVersion:w,activeSessionId:S,diffSessionId:k,setDiffSessionId:I,respondingSessions:C,questionAnswers:j,agent:R,cwd:M,approvalMode:E,model:T,setModel:A,effort:N,setEffort:P,fastMode:D,setFastMode:F,renameTitle:L,setRenameTitle:q,draft:O,webPreferences:$,sessionSort:z,setSessionSort:_,search:B,setSearch:H,sinceFilter:W,setSinceFilter:K,hideArchived:Q,setHideArchived:U,groupFolders:V,setGroupFolders:G,showNeedsAttentionGroup:J,setShowNeedsAttentionGroup:Z,showRunningGroup:Y,setShowRunningGroup:X,separatePinnedGroup:ee,setSeparatePinnedGroup:te,collapsedFolders:ne,setCollapsedFolders:se,sessionAgentFilter:ie,setSessionAgentFilter:re,directoryTags:oe,composerPreferences:ae,savedTargets:ce,leftSidebarCollapsed:le,setLeftSidebarCollapsed:de,rightSidebarCollapsed:ue,setRightSidebarCollapsed:he,workspaceClassName:pe,wideMainClassName:me,workspaceStyle:fe,beginPaneResize:ge,commitSearch:ye,saveTargets:ve,setLanguagePreference:be,setThemePreference:xe,updateComposerPreferences:we,t:Se,busy:ke,rewindMessage:Ie,controlTab:Ce,setControlTab:je,detailsOpen:Re,setDetailsOpen:Me,setControlTabAndOpen:Ee,skills:Te,admin:Ae,daemonMetadata:Ne,notificationSettings:Pe,notificationPermission:De,archiveSyncBusy:Fe,archiveSyncStatus:Le,attachments:qe,setAttachments:Oe,uploadBusy:$e,directory:ze,newDirName:_e,setNewDirName:Be,remoteFile:He,uploadFiles:We,openRemoteFile:Ve,listDirectory:Ge,listSessionDirectories:Ze,listFileTreeDirectory:Ye,createDirectory:Xe,createSessionDirectory:nt,pendingActionsCount:st,activeQueue:it,activeModelOptions:rt,activeUsage:ot,activeApproval:at,activeQuestion:lt,activeSession:dt,displaySessions:ut,groupedSessions:ht,pendingSessionIds:pt,visibleSessions:mt,historyLoading:ft,hasOlderHistory:gt,olderHistoryLoading:yt,requestHistory:vt,messages:bt,messagesSessionIdRef:xt,updateDraft:wt,requestReconnectSnapshot:St,requestSessions:kt,fetchAgentResources:It,failedSend:Ct,dismissFailedSend:jt,retryFailedSend:Rt,stagePendingSession:Mt,listSessionModels:Et,loadDirectoryGitMetadata:Tt,sendDraft:At,sendQuickReply:Nt,respondApproval:Pt,respondQuestion:Dt,cancelQuestion:Ft,setQuestionChoice:Lt,requestActiveAction:qt,interruptActiveSession:Ot,retrySessions:$t,updateApprovalMode:zt,cancelQueuedTurn:_t,setSessionPinned:Bt,setSessionArchived:Ht,deleteSession:Wt,updatePinned:Kt,updateArchived:Qt,renameSession:Ut,runArchiveSync:Vt,skipArchiveSync:Gt,runAdminAction:Jt,exportActiveSession:Zt,clearPairing:Yt,setNotificationsEnabled:Xt,connectSavedTarget:en,forgetSavedTarget:tn,openSessionDetails:nn,editFolderTags:sn,copyResumeCommand:rn,resumeInTerminal:on,notificationsBlocked:an,hasDaemonUpdate:ln,archiveSynced:dn,archiveSyncDismissed:un}=e,hn=o.useMemo(()=>function(e,t,n){const s={};for(const i of Object.values(e))s[i.sessionId]=`${n.interactionWaitingApproval} · ${i.description||i.toolName}`;for(const i of Object.values(t))s[i.sessionId]=`${n.interactionWaitingAnswer} · ${i.questions[0]?.question??""}`;return s}(e.pendingApprovals,e.pendingQuestions,Se),[e.pendingApprovals,e.pendingQuestions,Se]),pn=o.useMemo(()=>l?Object.fromEntries(ht.map(e=>[e.folder,!1!==ne[e.folder]])):ne,[l,ne,ht]),mn=ht.length>0&&ht.every(e=>pn[e.folder]);return"missing-pair"===m?r.jsxs(r.Fragment,{children:[r.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:Se.skipToConversation}),r.jsx(ea,{errorText:g,t:Se})]}):r.jsxs("main",{className:pe,id:"vibelet-workspace",style:fe,children:[u&&r.jsx(o.Suspense,{fallback:null,children:r.jsx(Ol,{client:"connected"===m?p.current:null,onOpenRemoteFile:Ve,pairing:y,onLoadGitMetadata:Tt,cwd:u.cwd,agent:R,device:y?.daemonId??"disconnected",connected:"connected"===m,approvalMode:E,model:T,t:Se,onClose:()=>h(null),onCreate:Mt,onListModels:Et,onListDirectories:Ze,onCreateDirectory:nt},y?.daemonId??"disconnected")}),r.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:Se.skipToConversation}),r.jsx(Ya,{collapsed:le,onExpand:()=>de(e=>!e),onResize:ge("left"),t:Se,children:r.jsx(Za,{connectionIndicators:r.jsx(fc,{workspace:e}),activeDaemonId:y?.daemonId,activeSessionId:S,busy:ke,collapsedFolders:pn,allFoldersCollapsed:mn,currentCwd:M,directoryTags:oe,displayName:y?.displayName,savedTargets:ce,folderCounts:x,groupFolders:V,sessionSort:z,onSessionSortChange:_,groupedSessions:ht,hideArchived:Q,separatePinnedGroup:ee,showNeedsAttentionGroup:J,showRunningGroup:Y,inventoryVersion:w,nextCursor:b,phase:m,respondingSessionIds:C,search:B,sessionAgentFilter:ie,sessionsCount:ut.length,sinceFilter:W,statusText:f,t:Se,visibleSessions:mt,onLoadMore:e=>kt({append:!0,cursor:e}),onCopyResumeCommand:rn,onResumeInTerminal:on,onConnectTarget:en,attentionReasons:hn,pendingSessionIds:pt,onRequestNewSession:e=>h({cwd:e??M}),onRenameSession:Ut,onDeleteSession:e=>{Wt(e)},onEditFolderTags:sn,onOpenSessionDetails:nn,onResetFilters:()=>{_("updated"),re("all"),K("30d"),U(!1),G(!0),Z(!1),X(!1),te(!1)},onRenameTarget:(e,t)=>ve(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:n().settingsTarget?e=>window.dispatchEvent(new CustomEvent("vibelet.desktop.edit-connection",{detail:e.pairToken})):void 0,onSearchChange:H,onSearchCommit:ye,onSelectSession:t.selectSession,onToggleSessionArchived:e=>{Ht(e,!e.archived)},onToggleSessionPinned:e=>{Bt(e,!e.pinned)},onSessionAgentFilterChange:re,onSinceFilterChange:K,onToggleFolder:e=>se(t=>({...t,[e]:l?!1===t[e]:!t[e]})),onToggleAllFolders:()=>{d(!mn),se({})},onToggleGroupFolders:()=>G(e=>!e),onToggleHideArchived:()=>U(e=>!e),onToggleNeedsAttentionGroup:()=>{e.toggleSessionViewGroup("needsAttention")},onToggleRunningGroup:()=>{e.toggleSessionViewGroup("running")},onToggleSeparatePinnedGroup:()=>{e.toggleSessionViewGroup("pinned")},onToggleCollapse:()=>de(!0)})}),r.jsxs("section",{className:me,"aria-label":Se.vibeletWorkspace,id:"vibelet-main-content",tabIndex:-1,children:[r.jsx(Wc,{workspace:e,children:r.jsx(Io,{client:"connected"===m?p.current:null,activeSession:dt,activeSessionId:S,activeModelOptions:rt,activeQueue:it,activeUsage:ot,agent:R,approvalMode:E,attachments:qe,busy:ke,cwd:M,draft:O,effort:N,errorText:g,failedSend:Ct,onDismissFailedSend:jt,fastMode:D,historyLoading:ft,hasOlderHistory:gt,olderHistoryLoading:yt,onLoadOlderHistory:()=>dt?vt(dt,{older:!0}):Promise.resolve(),messages:bt,messagesSessionId:xt.current,model:T,phase:m,quickReplies:ae.quickReplies,onQuickRepliesChange:e=>we(t=>({...t,quickReplies:e})),quickRepliesOpen:ae.quickRepliesOpen,onQuickRepliesOpenChange:e=>we(t=>({...t,quickRepliesOpen:e})),renameTitle:L,respondingSessionIds:C,sendShortcut:ae.sendShortcut,skills:Te,uploadBusy:$e,detailsOpen:Re,t:Se,onApprovalModeChange:e=>{zt(e)},onBrowseFiles:()=>{const e=dt?.cwd||M||cn;Ee("files"),Ge(e,{updateRoute:!0})},queueControls:e.queueControls,onCancelQueuedTurn:e=>{_t(e)},onClearInterrupt:()=>{qt("session.clearInterrupt")},onDraftChange:wt,onDetailsOpenChange:Me,onEffortChange:P,onExportActiveSession:()=>{Zt()},onRewindMessage:e=>{Ie(e)},onFastModeChange:F,onRetryFailedSend:Rt,onModelChange:A,onOpenRemoteFile:(e,t)=>{Ve(e,t,{updateRoute:!0})},onInterrupt:Ot,onDismissError:()=>e.setErrorText(null),onRetry:()=>{$t(),It(dt?.agent??R,M)},onRenameSession:e=>{Ut(void 0,e)},onRenameTitleChange:q,onRemoveAttachment:e=>Oe(t=>t.filter(t=>t.path!==e)),onRefreshSkills:()=>{It(dt?.agent??R,M)},onSubmit:At,onSendQuickReply:Nt,onToggleArchived:()=>{Qt()},onTogglePinned:()=>{Kt()},onUploadFiles:We,onViewChanges:I})}),r.jsxs(xc,{collapsed:ue,t:Se,value:Ce,showSession:!1,onChange:je,onResize:ge("right"),children:[r.jsx("div",{hidden:"files"!==Ce,style:{display:"files"===Ce?"contents":"none"},children:r.jsx(o.Suspense,{fallback:r.jsx(La,{t:Se}),children:r.jsx(Na,{busy:ke,cwd:M,directory:ze,onLoadChildren:Ye,newDirName:_e,remoteFile:He,t:Se,onCreateDirectory:()=>{Xe()},onListDirectory:e=>{Ge(e,{updateRoute:!0})},onNewDirNameChange:Be,onOpenRemoteFile:(e,t)=>{Ve(e,t,{updateRoute:!0})}},y?.daemonId)})}),a?r.jsxs("div",{hidden:"terminal"!==Ce,className:"terminal-tab-content",children:[r.jsx(ma,{location:"right",kind:"terminal",t:Se,cwd:M===cn?ze.path:M}),r.jsx(ga,{location:"right",kind:"terminal"})]}):null,s?r.jsxs("div",{hidden:"browser"!==Ce,className:"browser-tab-content",children:[r.jsx(ma,{location:"right",kind:"browser",t:Se}),r.jsx(ga,{location:"right",kind:"browser"})]}):null,"admin"===Ce?r.jsxs(o.Suspense,{fallback:r.jsx(La,{t:Se}),children:[r.jsx(Pa,{language:$.language,t:Se,onLanguageChange:be}),!n().settingsTarget&&r.jsx(lc,{}),r.jsx(Da,{t:Se,theme:$.theme,onThemeChange:xe}),r.jsx(Fa,{notificationsBlocked:an,permission:De,settings:Pe,t:Se,onToggleEnabled:Xt}),!n().settingsTarget&&r.jsx(oc,{workspace:e})]}):null]})]}),n().settingsTarget&&r.jsx(oc,{workspace:e,portalOnly:!0}),r.jsx("div",{className:"workspace-header-actions",children:r.jsx(ct,{activeSession:dt,busy:ke,controlsOpen:!ue,pendingCount:st,t:Se,onOpenControls:()=>{ue&&0===st&&"session"===Ce&&je("files"),he(e=>!e)},onRefreshSessions:()=>{kt({force:!0})},onRestoreSnapshot:()=>{St()},onToggleArchived:()=>{Qt()},onTogglePinned:()=>{Kt()},onViewChanges:I})}),r.jsx(o.Suspense,{fallback:null,children:r.jsx($l,{activeApproval:at,activeQuestion:lt,pendingCount:st,requestKey:ai(e.pendingApprovals,e.pendingQuestions),sessions:v,busy:ke,errorText:g,questionAnswers:j,t:Se,onCancelQuestion:()=>{Ft()},onQuestionChoice:Lt,onRespondApproval:e=>{Pt(e)},onRespondQuestion:()=>{Dt()},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({})}},t.revealKey)}),r.jsx(na,{}),r.jsx(Sa,{onOpenBrowserLink:e.applyBrowserDefaultWidth,onOpenRight:Ee,onCloseRight:()=>he(!0),client:"connected"===m?p.current:null,daemonId:y?.daemonId,deviceName:y?.displayName??"",controlTab:Ce,rightVisible:!ue,t:Se}),r.jsx(qa,{activeSession:dt,client:p.current,close:()=>I(null),id:k,sessions:v,t:Se})]})}const _l=Object.freeze(Object.defineProperty({__proto__:null,App:function(){const e=function(){const e=function(){const e=function(){const e=o.useRef(null),t=o.useRef(async()=>{}),n=o.useRef(null),[r]=o.useState(()=>({permission:Kt(),notifications:Wt(),preferences:i(),drafts:ol(),targets:Vc()})),a=o.useRef(r.permission),c=o.useRef(r.notifications),l=o.useRef(r.preferences),d=o.useRef(r.drafts),h=o.useRef(r.targets),m=o.useRef(a.current),f=o.useRef(c.current),g=o.useRef(d.current),y=o.useRef(null),v=o.useRef(null),b=o.useRef(new Set),x=o.useRef(null),w=o.useRef(new Set),S=o.useRef(null),k=o.useRef(0),I=o.useRef(new Set),C=o.useRef({}),M=o.useRef(!1),[E,T]=o.useState("connecting"),[A,N]=o.useState(()=>u[s(l.current.language)].preparingVibeletWeb),[P,D]=o.useState(null),[F,L]=o.useState(null),[q,O]=o.useState([]),[$,z]=o.useState({}),[_,B]=o.useState({}),[H,W]=o.useState(),[K,Q]=o.useState({}),[U,V]=o.useState(),[G,J]=o.useState(null),Z=ia(F?.daemonId,G),[Y,X]=o.useState(null),[ee,te]=o.useState(()=>new Set),[ne,se]=o.useState({}),[ie,re]=o.useState({}),[oe,ae]=o.useState({}),{pendingQueues:ce,setPendingQueues:le,setLivePendingQueue:de,remapPendingQueue:ue}=function(){const e=o.useRef(new ql),[t,n]=o.useState({});return{pendingQueues:t,setPendingQueues:o.useCallback(t=>{n(n=>e.current.snapshot("function"==typeof t?t(n):t))},[]),setLivePendingQueue:o.useCallback((t,s)=>{n(n=>e.current.live(n,t,s))},[]),remapPendingQueue:o.useCallback((t,n)=>{e.current.remap(t,n)},[])}}(),[he,pe]=o.useState("claude"),[me,fe]=o.useState(cn),[ge,ye]=o.useState(ln),[ve]=o.useState(!1),[be,xe]=o.useState(""),[we,Se]=o.useState(""),[ke,Ie]=o.useState(!1),[Ce,je]=o.useState(""),[Re,Me]=o.useState(d.current),[Ee,Te]=o.useState(()=>ll(d.current,null)),{webPreferences:Ae,sessionSort:Ne,setSessionSort:Pe,setRightSidebarCollapsed:De,search:Fe,setSearch:Le,sinceFilter:qe,setSinceFilter:Oe,hideArchived:$e,setHideArchived:ze,groupFolders:_e,setGroupFolders:Be,showNeedsAttentionGroup:He,setShowNeedsAttentionGroup:We,showRunningGroup:Ke,setShowRunningGroup:Qe,separatePinnedGroup:Ue,setSeparatePinnedGroup:Ve,collapsedFolders:Ge,setCollapsedFolders:Je,sessionAgentFilter:Ze,setSessionAgentFilter:Ye,directoryTags:Xe,archiveSyncedDaemonIds:et,archiveSyncCardDismissedDaemonIds:tt,composerPreferences:nt,savedTargets:st,setSavedTargets:it,leftSidebarCollapsed:rt,setLeftSidebarCollapsed:ot,rightSidebarCollapsed:at,workspaceClassName:ct,wideMainClassName:lt,workspaceStyle:dt,beginPaneResize:ut,applyBrowserDefaultWidth:ht,commitSearch:pt,saveTargets:mt,setLanguagePreference:ft,setThemePreference:gt,updateSessionListPreferences:yt,updateComposerPreferences:vt}=function(e,t,n="default"){const[s,r]=o.useState(e);o.useEffect(()=>{const e=()=>{const e=i();r(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[a,c]=o.useState(e.sessionList.sortOrder),[l,d]=o.useState(""),[u,h]=o.useState(e.sessionList.searchHistory),[m,f]=o.useState(e.sessionList.sinceFilter),[g,y]=o.useState(e.sessionList.hideArchived),[v,b]=o.useState(e.sessionList.groupFolders),[x,w]=o.useState(e.sessionList.showNeedsAttentionGroup),[S,k]=o.useState(e.sessionList.showRunningGroup),[I,C]=o.useState(e.sessionList.separatePinnedGroup),[R,M]=o.useState(e.sessionList.collapsedFolders),[E,T]=o.useState(e.sessionList.agentFilter),[A,N]=o.useState(t),[P,D]=o.useState(e.layout.leftSidebarCollapsed),[F,L]=o.useState(e.layout.rightSidebarCollapsed),{leftPaneWidth:q,rightPaneWidth:O,beginPaneResize:$,applyBrowserDefaultWidth:z}=function(e,t,n="default"){const[s,i]=o.useState(288),[r,a]=sa(n,"third"),[c,l]=o.useState(()=>window.innerWidth),[d,u]=o.useState(null);o.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()},[n]);const h=d??c-(e?0:s+10),p="number"==typeof r?r:Math.round(h/("half"===r?2:3)),m=o.useCallback(()=>{a(e=>"number"==typeof e?e:"half")},[a]),f=o.useRef(null);o.useEffect(()=>()=>f.current?.(),[e,t,n]),o.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,i=n+s,r=i>t?Math.max(0,t)/i:1;return{leftPaneWidth:e.leftCollapsed?e.leftPaneWidth:Math.floor(n*r),rightPaneWidth:e.rightCollapsed?e.rightPaneWidth:Math.floor(s*r)}}({leftCollapsed:e,rightCollapsed:t,leftPaneWidth:s,rightPaneWidth:p},c-96-64),y=o.useCallback(e=>t=>{if(0!==t.button||!1===t.isPrimary)return;t.preventDefault(),f.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 p();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)},p=()=>{if(r){r=!1,o.remove(),document.body.classList.remove("pane-resizing"),window.removeEventListener("pointermove",h,!0),window.removeEventListener("pointerup",m,!0),window.removeEventListener("pointercancel",m,!0),window.removeEventListener("blur",p),window.removeEventListener("keydown",y,!0),document.removeEventListener("visibilitychange",v),n.removeEventListener("lostpointercapture",m);try{n.hasPointerCapture?.(s)&&n.releasePointerCapture(s)}catch{}f.current===p&&(f.current=null)}},m=e=>{e.pointerId===s&&p()},y=e=>{"Escape"===e.key&&(e.preventDefault(),p())},v=()=>{"hidden"===document.visibilityState&&p()};f.current=p,document.body.classList.add("pane-resizing"),window.addEventListener("pointermove",h,!0),window.addEventListener("pointerup",m,!0),window.addEventListener("pointercancel",m,!0),window.addEventListener("blur",p),window.addEventListener("keydown",y,!0),document.addEventListener("visibilitychange",v),n.addEventListener("lostpointercapture",m);try{n.setPointerCapture?.(s)}catch{}},[g.leftPaneWidth,g.rightPaneWidth,a]);return{...g,beginPaneResize:y,applyBrowserDefaultWidth:m}}(P,F,n),_=s.sessionList.directoryTags,B=s.sessionList.archiveSyncedDaemonIds,H=s.sessionList.archiveSyncCardDismissedDaemonIds,W=s.composer,K=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:F,leftPaneWidth:q,rightPaneWidth:O});o.useEffect(()=>{r(e=>{const t={...e,sessionList:{...e.sessionList,searchHistory:u,sortOrder:a,sinceFilter:m,hideArchived:g,groupFolders:v,showNeedsAttentionGroup:x,showRunningGroup:S,separatePinnedGroup:I,collapsedFolders:R,agentFilter:E},layout:{...e.layout,leftSidebarCollapsed:P,rightSidebarCollapsed:F}};return p(t),t})},[R,v,g,P,F,u,I,E,x,S,m,a]);const Q=o.useCallback(()=>{h(e=>j(e,l))},[l]),U=o.useCallback(e=>{N(e),Gc(e)},[]),V=o.useCallback(e=>{r(t=>{const n={...t,language:e};return p(n),n})},[]),G=o.useCallback(e=>{r(t=>{const n={...t,theme:e};return p(n),n})},[]),J=o.useCallback(e=>{r(t=>{const n={...t,sessionList:e(t.sessionList)};return p(n),n})},[]),Z=o.useCallback(e=>{r(t=>{const n={...t,composer:e(t.composer)};return p(n),n})},[]);return{webPreferences:s,sessionSort:a,setSessionSort:c,search:l,setSearch:d,sinceFilter:m,setSinceFilter:f,hideArchived:g,setHideArchived:y,groupFolders:v,setGroupFolders:b,showNeedsAttentionGroup:x,setShowNeedsAttentionGroup:w,showRunningGroup:S,setShowRunningGroup:k,separatePinnedGroup:I,setSeparatePinnedGroup:C,collapsedFolders:R,setCollapsedFolders:M,sessionAgentFilter:E,setSessionAgentFilter:T,directoryTags:_,archiveSyncedDaemonIds:B,archiveSyncCardDismissedDaemonIds:H,composerPreferences:W,savedTargets:A,setSavedTargets:N,leftSidebarCollapsed:P,setLeftSidebarCollapsed:D,rightSidebarCollapsed:F,setRightSidebarCollapsed:L,workspaceClassName:K.workspaceClassName,wideMainClassName:K.wideMainClassName,workspaceStyle:K.style,beginPaneResize:$,applyBrowserDefaultWidth:z,commitSearch:Q,saveTargets:U,setLanguagePreference:V,setThemePreference:G,updateSessionListPreferences:J,updateComposerPreferences:Z}}(l.current,h.current,Z),bt=s(Ae.language),xt=u[bt],[wt,St]=sa(Z,!1),[kt,It]=sa(Z,"files"),[Ct,jt]=o.useState(!1);!function(e){o.useEffect(()=>{const t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>R(e,document.documentElement,t.matches);if(n(),"system"===e)return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[e])}(Ae.theme);const Rt=o.useCallback(e=>{It(e),De(!1)},[It,De]),[Mt,Et]=o.useState({}),[Tt,At]=o.useState({}),[Nt,Pt]=o.useState([]),[Dt,Ft]=o.useState({statusText:"",loading:!1,action:null}),[Lt,qt]=o.useState(Xa),[Ot,$t]=o.useState(c.current),[zt,_t]=o.useState(a.current),[Bt,Ht]=o.useState(null),[Qt,Ut]=o.useState(null);return{clientRef:e,connectWithPairingRef:t,activeSessionIdRef:n,initialNotificationPermissionRef:a,initialNotificationSettingsRef:c,initialPreferencesRef:l,initialComposerDraftsRef:d,initialSavedTargetsRef:h,notificationPermissionRef:m,notificationSettingsRef:f,composerDraftsRef:g,lastHistorySessionIdRef:y,historyCacheDaemonIdRef:v,historyPrefetchingSessionIdsRef:b,pairingRef:x,notifiedEventsRef:w,reconnectTimerRef:S,connectionAttemptIdRef:k,respondingSessionsRef:I,turnNotificationCountsRef:C,intentionalDisconnectRef:M,phase:E,setPhase:T,statusText:A,setStatusText:N,errorText:P?Oa(P,xt.remoteDirectConnection,xt.localConnection):null,setErrorText:D,pairing:F,setPairing:L,sessions:q,setSessions:O,pendingSessions:$,setPendingSessions:z,optimisticSessions:_,setOptimisticSessions:B,nextCursor:H,setNextCursor:W,folderCounts:K,setFolderCounts:Q,inventoryVersion:U,setInventoryVersion:V,activeSessionId:G,setActiveSessionId:J,diffSessionId:Y,setDiffSessionId:X,respondingSessions:ee,setRespondingSessions:te,pendingApprovals:ne,setPendingApprovals:se,pendingQuestions:ie,setPendingQuestions:re,questionAnswers:oe,setQuestionAnswers:ae,pendingQueues:ce,setPendingQueues:le,setLivePendingQueue:de,remapPendingQueue:ue,agent:he,setAgent:pe,cwd:me,setCwd:fe,approvalMode:ge,setApprovalMode:ye,continueSession:ve,model:be,setModel:xe,effort:we,setEffort:Se,fastMode:ke,setFastMode:Ie,renameTitle:Ce,setRenameTitle:je,composerDrafts:Re,setComposerDrafts:Me,draft:Ee,setDraft:Te,webPreferences:Ae,sessionSort:Ne,setSessionSort:Pe,search:Fe,setSearch:Le,sinceFilter:qe,setSinceFilter:Oe,hideArchived:$e,setHideArchived:ze,groupFolders:_e,setGroupFolders:Be,showNeedsAttentionGroup:He,setShowNeedsAttentionGroup:We,showRunningGroup:Ke,setShowRunningGroup:Qe,separatePinnedGroup:Ue,setSeparatePinnedGroup:Ve,collapsedFolders:Ge,setCollapsedFolders:Je,sessionAgentFilter:Ze,setSessionAgentFilter:Ye,directoryTags:Xe,archiveSyncedDaemonIds:et,archiveSyncCardDismissedDaemonIds:tt,composerPreferences:nt,savedTargets:st,setSavedTargets:it,leftSidebarCollapsed:rt,setLeftSidebarCollapsed:ot,rightSidebarCollapsed:at,setRightSidebarCollapsed:De,workspaceClassName:ct,wideMainClassName:lt,workspaceStyle:dt,beginPaneResize:ut,applyBrowserDefaultWidth:ht,commitSearch:pt,saveTargets:mt,setLanguagePreference:ft,setThemePreference:gt,updateSessionListPreferences:yt,updateComposerPreferences:vt,language:bt,t:xt,busy:wt,setBusy:St,controlTab:kt,setControlTab:It,detailsOpen:Ct,setDetailsOpen:jt,setControlTabAndOpen:Rt,modelOptions:Mt,setModelOptions:Et,usageLimits:Tt,setUsageLimits:At,skills:Nt,setSkills:Pt,admin:Dt,setAdmin:Ft,daemonMetadata:Lt,setDaemonMetadata:qt,notificationSettings:Ot,setNotificationSettings:$t,notificationPermission:zt,setNotificationPermission:_t,archiveSyncBusy:Bt,setArchiveSyncBusy:Ht,archiveSyncStatus:Qt,setArchiveSyncStatus:Ut}}(),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:r,activeSessionIdRef:a,notificationPermissionRef:c,notificationSettingsRef:l,composerDraftsRef:h,lastHistorySessionIdRef:m,historyPrefetchingSessionIdsRef:f,pairingRef:g,reconnectTimerRef:y,respondingSessionsRef:v,phase:b,setStatusText:x,setErrorText:S,pairing:k,setSessions:I,setOptimisticSessions:A,setNextCursor:N,setFolderCounts:P,setInventoryVersion:D,activeSessionId:F,setActiveSessionId:L,respondingSessions:q,setRespondingSessions:O,pendingApprovals:$,setPendingApprovals:z,pendingQuestions:_,setPendingQuestions:B,setQuestionAnswers:H,pendingQueues:W,setPendingQueues:K,agent:Q,setAgent:U,cwd:V,setCwd:G,setApprovalMode:J,composerDrafts:Z,setComposerDrafts:Y,search:X,sinceFilter:ee,hideArchived:te,sessionAgentFilter:ne,setRightSidebarCollapsed:se,t:ie,controlTab:re,setControlTab:oe,setControlTabAndOpen:ae,modelOptions:ce,setModelOptions:le,usageLimits:de,setUsageLimits:ue,setSkills:he,setDaemonMetadata:pe,notificationSettings:me,setNotificationSettings:fe,notificationPermission:ge,setNotificationPermission:ye,sessions:ve,pendingSessions:be,optimisticSessions:xe,setDraft:we,setBusy:Se}=e,{remoteFile:ke,attachments:Ie,setAttachments:Ce,uploadBusy:je,directory:Re,setDirectory:Me,newDirName:Ee,setNewDirName:Te,setRemoteFile:Ae,remoteFileConflict:Ne,uploadFiles:Pe,openRemoteFile:De,saveRemoteFile:Fe,downloadRemoteFile:Le,listDirectory:qe,listSessionDirectories:Oe,listFileTreeDirectory:$e,createDirectory:ze,createSessionDirectory:_e}=function(e){const{clientRef:t,pairing:n,cwd:s,phase:i,controlTab:r,setControlTab:a,setBusy:c,setErrorText:l,t:d,scopeKey:u="default"}=e,h=o.useRef(!1),p=o.useRef(null),m=p.current&&ra(p.current.key,u)?p.current:null,[f,g]=sa(u,()=>[]),[y,v]=o.useState(!1),b=o.useRef(new Set),[x,w]=sa(u,()=>({path:m?.directory.path||!h.current&&(Il().folder||Il().cwd)||s||cn,entries:[],loading:!1,loaded:!1})),[S,k]=sa(u,""),[I,C]=sa(u,()=>m?.file??null),[j,R]=sa(u,()=>new Set);p.current={key:u,file:I,directory:x};const M=e=>JSON.stringify([e.cwd,e.path,e.etag]),E=!!I&&j.has(M(I)),T=o.useRef(null),A=o.useRef(null),N=o.useRef(0),P=o.useRef(x.path);o.useEffect(()=>()=>{p.current&&ra(u,p.current.key)&&!p.current.file&&Il().file&&(h.current=!1),N.current++,w(e=>e.loading?{...e,loading:!1}:e),A.current?.abort(),T.current&&c(!1),T.current?.abort(),T.current=null;for(const e of b.current)e.abort();b.current.clear(),v(!1)},[u]),o.useEffect(()=>{P.current!==x.path&&(N.current++,P.current=x.path)},[x.path]),o.useEffect(()=>(N.current++,w({path:!h.current&&(Il().folder||Il().cwd)||s||cn,entries:[],loading:!1,loaded:!1}),g([]),v(!1),C(null),R(new Set),()=>{N.current++;for(const e of b.current)e.abort();b.current.clear(),A.current?.abort(),T.current&&(T.current.abort(),T.current=null,c(!1))}),[n?.pairToken]),o.useEffect(()=>{x.path!==cn||Il().folder||(N.current++,w(e=>({...e,entries:[],loaded:!1,loading:!1})))},[s]);const D=o.useRef(new Set);o.useEffect(()=>{I?.objectUrl&&D.current.add(I.objectUrl)},[I?.objectUrl]),o.useEffect(()=>()=>{for(const e of D.current)URL.revokeObjectURL(e);D.current.clear()},[n?.pairToken]);const F=o.useCallback(async e=>{if(!e?.length||!n)return;const t=new AbortController;b.current.add(t),v(!0),l(null);const s=Array.from(e).map(e=>({file:e,path:URL.createObjectURL(e)}));g(e=>[...e,...s.map(({file:e,path:t})=>({path:t,name:e.name,type:e.type,size:e.size,uploading:!0}))]);try{for(const{file:e,path:i}of s){const s=await El(e,n.pairToken,t.signal,d);if(t.signal.aborted)return;g(e=>e.map(e=>e.path===i?s:e))}}catch(i){t.signal.aborted||l(i instanceof Error?i.message:String(i))}finally{const e=new Set(s.map(e=>e.path));g(t=>t.filter(t=>!e.has(t.path)));for(const t of e)URL.revokeObjectURL(t);b.current.delete(t)&&v(b.current.size>0)}},[n,l,d.uploadFailed,d.uploadPathMissing,u]),L=o.useCallback(async(e,t,s)=>{if(!n)return;A.current?.abort();const i=new AbortController;A.current=i,l(null);try{const r=/^(?:https?:\/\/|data:image\/|blob:)/i.test(e),o=await fetch(r?e:Rn(e,t),{headers:r?{}:{authorization:`Bearer ${n.pairToken}`},signal:i.signal});if(!o.ok)throw new Error(await o.text().catch(()=>d.fileOpenFailed)||d.fileOpenFailed);const a=o.headers.get("content-type")??"application/octet-stream";if(r&&!a.startsWith("image/"))throw new Error(d.fileOpenFailed);const c=Sc(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)C({path:e,cwd:t,kind:"text",contentType:a,text:u,etag:Mn(o.headers,"etag"),lastModified:Mn(o.headers,"last-modified"),size:Number(o.headers.get("content-length"))||void 0,dirty:!1});else{const n="pdf"===Sc(e,a,!1)?new Blob([l],{type:"application/pdf"}):l;C({path:e,cwd:t,kind:jn(e,a)?"image":"binary",contentType:a,text:"",objectUrl:URL.createObjectURL(n),etag:Mn(o.headers,"etag"),lastModified:Mn(o.headers,"last-modified"),size:l.size,dirty:!1})}s?.updateRoute&&Cl({file:e,...t?{cwd:t}:{}},{replace:s.replaceRoute})}catch(r){if(i.signal.aborted)return;l(r instanceof Error?r.message:String(r))}},[n,l,u]),q=o.useCallback(async e=>{if(!n||!I||"text"!==I.kind||T.current)return;const t=new AbortController;T.current=t,c(!0),l(null);try{const s=await fetch(Rn(I.path,I.cwd),{method:"PUT",signal:t.signal,headers:{authorization:`Bearer ${n.pairToken}`,"content-type":"text/markdown; charset=utf-8",...I.etag&&!e?.force?{"if-match":I.etag}:{}},body:I.text});if(t.signal.aborted)return;if(!s.ok){if(409===s.status)throw R(e=>new Set(e).add(M(I))),new Error(d.remoteFileConflict(I.path));throw new Error(await s.text().catch(()=>d.fileSaveFailed)||d.fileSaveFailed)}const i=await s.json().catch(()=>({}));if(t.signal.aborted)return;R(e=>{const t=new Set(e);return t.delete(M(I)),t}),C(e=>function(e,t,n){return e&&e.path===t.path&&e.cwd===t.cwd?{...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}(e,I,i))}catch(s){t.signal.aborted||l(s instanceof Error?s.message:String(s))}finally{T.current===t&&(T.current=null,c(!1))}},[n,I,c,l,u]),O=o.useCallback(async()=>{if(n&&I)try{const e=/^(?:https?:\/\/|data:image\/|blob:)/i.test(I.path),t=await fetch(e?I.path:Rn(I.path,I.cwd),{headers:e?{}:{authorization:`Bearer ${n.pairToken}`}});if(!t.ok)throw new Error(d.downloadFailed);const s=URL.createObjectURL(await t.blob()),i=document.createElement("a");i.href=s,i.download=mn(I.path),i.click(),URL.revokeObjectURL(s)}catch(e){l(e instanceof Error?e.message:String(e))}},[n,I,l,u]),$=o.useCallback(async(e=x.path,n)=>{const i=t.current;if(!i?.isConnected)return;P.current=e;const r=++N.current;w(t=>({...t,path:e,entries:e===t.path?t.entries:[],loading:!0,loaded:!1,error:void 0}));try{const t=await i.request({action:"dirs.list",id:i.makeId("dirs"),path:e,cwd:s||void 0});if(r!==N.current)return;w({path:e,entries:t.entries??[],loading:!1,loaded:!0}),n?.updateRoute&&Cl({folder:e},{replace:n.replaceRoute})}catch(o){if(r!==N.current)return;w(e=>({...e,loading:!1,loaded:!0,error:o instanceof Error?o.message:String(o)}))}},[t,s,x.path,u]),z=o.useCallback(async e=>{const n=t.current;if(!n?.isConnected)throw new Error(d.webSocketNotConnected);return(await n.request({action:"dirs.list",id:n.makeId("dirs"),path:e,cwd:s||void 0},{timeoutMs:1e4,timeoutMessage:d.directoryListTimedOut})).entries??[]},[t,s,u]),_=o.useCallback(async e=>(await z(e)).filter(e=>e.isDirectory),[z]);o.useEffect(()=>{!h.current||"files"!==r||"connected"!==i||x.loading||x.loaded||$(x.path||s||cn)},[r,s,x.loaded,x.loading,x.path,$,i]),o.useEffect(()=>{if("connected"!==i||h.current)return;const e=Il();if(e.folder||e.file){if(h.current=!0,e.folder)return a("files"),void $(e.folder,{updateRoute:!1});e.file&&(e.cwd&&w(t=>({...t,path:e.cwd,loaded:!1})),L(e.file,e.cwd,{updateRoute:!1}))}else h.current=!0},[$,L,i,a]);const B=o.useCallback(async()=>{const e=t.current;if(e?.isConnected&&0!==S.trim().length){c(!0),l(null);try{await e.request({action:"dirs.create",id:e.makeId("mkdir"),path:In(x.path,S),cwd:s||void 0}),k(""),await $(x.path)}catch(n){l(n instanceof Error?n.message:String(n))}finally{c(!1)}}},[t,s,x.path,$,S,c,l,u]),H=o.useCallback(async e=>{const n=t.current;if(!n?.isConnected)throw new Error(d.webSocketNotConnected);await n.request({action:"dirs.create",id:n.makeId("mkdir"),path:e,cwd:s||void 0},{timeoutMs:1e4,timeoutMessage:d.directoryCreationTimedOut})},[t,s,u]);return{attachments:f,setAttachments:g,uploadBusy:y,directory:x,setDirectory:w,newDirName:S,setNewDirName:k,remoteFile:I,setRemoteFile:C,remoteFileConflict:E,uploadFiles:F,openRemoteFile:L,saveRemoteFile:q,downloadRemoteFile:O,listDirectory:$,listSessionDirectories:_,listFileTreeDirectory:z,createDirectory:B,createSessionDirectory:H}}({scopeKey:ia(k?.daemonId,F),clientRef:r,pairing:k,cwd:V,phase:b,controlTab:re,setControlTab:ae,setBusy:Se,setErrorText:S,t:ie}),Be=Object.keys($).length+Object.keys(_).length,He=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}(F?W[F]??[]:[],F,Q),We=ce[Q]??[],Ke=de[Q],{completionAttention:Qe,reviewSessionIds:Ue}=function(e,t,n){const s=o.useMemo(()=>{let t;try{t=window.localStorage}catch{}return new Rl(t,`vibelet:completion-attention:${e??"disconnected"}`,Ml)},[e]),i=o.useSyncExternalStore(s.subscribe,s.getSnapshot),r=o.useRef(new Set);return o.useEffect(()=>{r.current=new Set},[s]),o.useEffect(()=>{for(const e of t)s.reconcile(e.sessionId,Boolean(e.runtime.isResponding))},[s,t]),o.useEffect(()=>{for(const e of n)r.current.has(e)||s.observe(e);r.current=n},[s,n]),o.useEffect(()=>{if(!i.size)return;const e=window.setInterval(s.acknowledgeVisible,250);return window.addEventListener("focus",s.acknowledgeVisible),document.addEventListener("visibilitychange",s.acknowledgeVisible),()=>{window.clearInterval(e),window.removeEventListener("focus",s.acknowledgeVisible),document.removeEventListener("visibilitychange",s.acknowledgeVisible)}},[s,i]),{completionAttention:s,reviewSessionIds:i}}(k?.daemonId,ve,q),{historyCacheRef:Ve,historyPageStartRef:Ge,hydrateVisibleHistory:Je,messagesSessionIdRef:Ze,remapCachedHistory:Ye,appendCachedDelta:Xe,appendCachedHistory:et,appendInfoMessage:tt,clearHistoryLoading:nt,ensureCachedHistoryEntry:st,setCachedMessageDelivery:it,resolveCachedMessageSession:rt,historyLoading:ot,hasOlderHistory:at,olderHistoryLoading:ct,messages:lt,mergeCachedHistoryPage:dt,removeCachedHistory:ut,renderCachedHistory:ht,replaceCachedHistory:pt,requestHistory:mt,setMessages:ft}=function(e){const t=o.useRef({}),n=function(e,t){const n=o.useRef(new Map),s=o.useRef(new Set),i=o.useRef(null),r=e=>JSON.stringify([t?.current,e]),a=o.useCallback(()=>{i.current&&clearTimeout(i.current),i.current=null;for(const[e,t]of n.current)Pl(e,t);n.current.clear()},[]);return o.useEffect(()=>(window.addEventListener("pagehide",a),window.addEventListener("beforeunload",a),()=>{a(),window.removeEventListener("pagehide",a),window.removeEventListener("beforeunload",a)}),[a]),{changed:s=>{const r=t?.current;r&&(n.current.set(r,{...n.current.get(r),[s]:e.current[s]}),i.current||(i.current=setTimeout(a,500)))},fresh:e=>s.current.delete(r(e)),isStale:e=>s.current.has(r(e)),restore:n=>{if(!t?.current||Object.hasOwn(e.current,n))return;const i=function(e,t){return Nl().find(n=>n.daemonId===e&&n.sessionId===t)?.messages}(t.current,n);return i?(e.current={...e.current,[n]:i},s.current.add(r(n)),!0):void 0}}}(t,e.historyCacheDaemonIdRef),s=o.useRef(n);s.current=n;const i=o.useRef(null),r=o.useRef({}),a=o.useRef({}),c=o.useRef(new Map),[l,d]=o.useState(null),u=o.useRef(null),[h,p]=o.useState(!1),[m,f]=o.useState([]),g=o.useCallback(e=>!(e&&i.current&&i.current!==e||(i.current=null,p(!1),0)),[]),y=o.useCallback(e=>(s.current.restore(e)&&(delete r.current[e],delete a.current[e]),!!pl(t.current,e)&&(u.current=e,f(t.current[e]??[]),!0)),[]),v=o.useCallback((n,i,r)=>{t.current=function(e,t,n){return t?{...e,[t]:fl(e[t]??[],n)}:e}(t.current,n,i),s.current.changed(n),s.current.fresh(n);const o=t.current[n]??[];return!1!==r?.renderActive&&n===e.activeSessionIdRef.current&&(u.current=n,f(o)),o},[e.activeSessionIdRef]),b=o.useCallback((e,n,s)=>{const i=pl(t.current,e)?a.current[e]:void 0;if(a.current[e]=s,"byte"===s?.cursorMode){const o=function(e,t,n,s){if(!n||"byte"!==n.cursorMode)return[...t];if(s.start<n.start){const n=new Set(t.map(Tl).filter(Boolean));return[...t,...e.filter(e=>{const t=Tl(e);return!t||!n.has(t)})]}const i=t[0],r=i?e.findIndex(e=>i.historyKey&&e.historyKey?i.historyKey===e.historyKey:Boolean(i.timestamp)&&i.timestamp===e.timestamp&&i.role===e.role&&i.type===e.type&&i.content===e.content&&JSON.stringify(i.images)===JSON.stringify(e.images)&&i.toolName===e.toolName&&JSON.stringify(i.toolInput)===JSON.stringify(e.toolInput)):-1;return r>=0?[...e.slice(0,r),...t]:[...t]}(t.current[e]??[],n,i,s);return"byte"===i?.cursorMode&&o.length>n.length&&s.start>=i.start&&(a.current[e]={...s,start:i.start,hasMore:i.hasMore}),r.current[e]=a.current[e]?.start,v(e,o)}if(!s)return r.current[e]=void 0,v(e,n);const o=r.current[e],c=t.current[e]??[],l=s.start+n.length;if(void 0===o||l<o||s.start>o+c.length)return r.current[e]=s.start,v(e,n);r.current[e]=Math.min(o,s.start),a.current[e]={...s,start:Math.min(o,s.start),hasMore:Math.min(o,s.start)>0};const d=c.slice(0,Math.max(0,s.start-o)),u=c.slice(Math.max(0,l-o),Math.max(0,s.total-o));return v(e,[...d,...n,...u])},[v]),x=o.useCallback((e,t)=>{delete a.current[e],r.current[e]=0;const n=v(e,t,{renderActive:!1});u.current=e,f(n)},[v]),w=o.useCallback((n,i)=>{t.current=ml(t.current,n,i),s.current.changed(n),n===e.activeSessionIdRef.current&&(u.current=n,f(t.current[n]??[]))},[e.activeSessionIdRef]),S=o.useCallback((n,i)=>{t.current=function(e,t,n){return n.historyKey&&e[t]?.some(e=>e.historyKey===n.historyKey)?e:ml(e,t,[n])}(t.current,n,i),s.current.changed(n),n===e.activeSessionIdRef.current&&(u.current=n,f(t.current[n]??[]))},[e.activeSessionIdRef]),k=o.useCallback((e,n)=>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}(t.current,e,n),[]),I=o.useCallback((n,i,r,o)=>{if(n=k(n,i),!o&&!t.current[n]?.some(e=>e.localClientMessageId===i||e.historyKey===`client:${i}`))return;const a=function(e,t,n,s){const i=e.findIndex(e=>e.localClientMessageId===t||e.historyKey===`client:${t}`),r=e.slice();if(i<0)s&&r.push({role:"user",...s,timestamp:(new Date).toISOString(),historyKey:`client:${t}`,localClientMessageId:t,localDelivery:n});else{const s=e[i],o="delivered"===s.localDelivery||"accepted"===s.delivery||s.historyKey&&!s.historyKey.startsWith("client:");r[i]={...s,localClientMessageId:t,localDelivery:o&&"failed"===n?"delivered":n}}return r}(t.current[n]??[],i,r,o);t.current={...t.current,[n]:a},s.current.changed(n),n!==e.activeSessionIdRef.current&&n!==u.current||(u.current=n,f(t.current[n]??[]));const c=a.find(e=>e.localClientMessageId===i)?.localDelivery;return c&&e.onDeliveryChanged?.(n,i,c),c},[e.activeSessionIdRef,e.onDeliveryChanged]),C=o.useCallback((n,i)=>{t.current=function(e,t,n){return t&&n?{...e,[t]:Yt(hn(e[t]??[],n))}:e}(t.current,n,i),s.current.changed(n),n===e.activeSessionIdRef.current&&(u.current=n,f(t.current[n]??[]))},[e.activeSessionIdRef]),j=o.useCallback((e,t)=>{w(e,[{role:"assistant",type:"info",content:t,timestamp:(new Date).toISOString()}])},[w]),R=o.useCallback(e=>{t.current=function(e,t){if(!pl(e,t))return e;const n={...e};return delete n[t],n}(t.current,e),s.current.changed(e),delete r.current[e],delete a.current[e]},[]),M=o.useCallback((e,n)=>{t.current=function(e,t,n){if(!t||!n||t===n||!pl(e,t))return e;const s={...e};return s[n]=e[t],delete s[t],s}(t.current,e,n),s.current.changed(e),s.current.changed(n),r.current[n]=r.current[e],delete r.current[e],a.current[n]=a.current[e],delete a.current[e]},[]),E=o.useCallback(async(t,{older:n=!1,refresh:o=!1}={})=>{const l=e.clientRef.current;if(!l?.isConnected)return;for(;c.current.get(t.sessionId)?.client===l;){if(!o)return;if(await c.current.get(t.sessionId).settled,e.clientRef.current!==l||!l.isConnected||e.activeSessionIdRef.current!==t.sessionId)return}const u=a.current[t.sessionId];if(n&&(!u?.hasMore||u.start<=0))return;let h;const m={client:l,settled:new Promise(e=>{h=e})};c.current.set(t.sessionId,m),n&&d(t.sessionId);const f=()=>e.clientRef.current===l,v=y(t.sessionId);v?g(t.sessionId):(i.current=t.sessionId,delete r.current[t.sessionId],p(!0),e.setErrorText(null));try{if(!n&&!o&&v&&!s.current.isStale(t.sessionId)){const n=await l.request({action:"reconnect.snapshot",id:l.makeId("snapshot"),activeSessionId:t.sessionId,activeAgent:t.agent,skipActiveSessionHistory:!0,skipGitMetadata:!0});if(!f())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??[])I(t.sessionId,e,"delivered")}return}if(await l.request({action:"session.history",id:l.makeId("history"),sessionId:t.sessionId,agent:t.agent,limit:n?100:20,...n&&"byte"!==u?.cursorMode?{before:u?.start}:{pageMode:"cursor",...n?{beforeCursor:u?.start}:{}}},{timeoutMessage:e.historyTimeoutMessage,timeoutMs:15e3}),!f())return}catch(b){f()&&e.activeSessionIdRef.current===t.sessionId&&e.setErrorText(b instanceof Error?b.message:String(b))}finally{c.current.get(t.sessionId)===m&&c.current.delete(t.sessionId),h(),f()&&(n&&d(e=>e===t.sessionId?null:e),g(t.sessionId))}},[g,e.activeSessionIdRef,e.clientRef,e.historyTimeoutMessage,e.setErrorText,e.setPendingQueues,y,I]);return{hasOlderHistory:Boolean(a.current[e.activeSessionIdRef.current??""]?.hasMore),olderHistoryLoading:l===e.activeSessionIdRef.current&&null!==l,resolveCachedMessageSession:k,setCachedMessageDelivery:I,appendCachedDelta:C,appendCachedHistory:w,appendInfoMessage:j,clearHistoryLoading:g,ensureCachedHistoryEntry:S,historyCacheRef:t,historyLoading:h,historyPageStartRef:r,hydrateVisibleHistory:x,messages:m,messagesSessionIdRef:u,mergeCachedHistoryPage:b,remapCachedHistory:M,removeCachedHistory:R,renderCachedHistory:y,replaceCachedHistory:v,requestHistory:E,setMessages:f}}({onDeliveryChanged:Qe.deliveryChanged,historyCacheDaemonIdRef:e.historyCacheDaemonIdRef,activeSessionIdRef:a,clientRef:r,historyTimeoutMessage:ie.historyRequestTimedOut,setPendingQueues:K,setErrorText:S}),gt=o.useMemo(()=>new Set(Object.entries(Ve.current).filter(([,e])=>e?.some(e=>"failed"===e.localDelivery)).map(([e])=>e)),[Ve.current]),{activeSession:yt,activeApproval:vt,activeQuestion:bt,displaySessions:xt,groupedSessions:wt,pendingSessionIds:St,visibleSessions:kt}=function(e){const t=o.useRef({protectedSessionIds:[]}),n=o.useMemo(()=>bn(bn(e.sessions,Object.values(e.optimisticSessions)),Object.values(e.pendingSessions)),[e.optimisticSessions,e.pendingSessions,e.sessions]),s=o.useMemo(()=>new Set(Object.keys(e.pendingSessions)),[e.pendingSessions]),i=o.useMemo(()=>n.find(t=>t.sessionId===e.activeSessionId)??null,[e.activeSessionId,n]),r=(e.activeSessionId?e.pendingApprovals[e.activeSessionId]:null)??Object.values(e.pendingApprovals)[0]??null,a=(e.activeSessionId?e.pendingQuestions[e.activeSessionId]:null)??Object.values(e.pendingQuestions)[0]??null,c=o.useMemo(()=>w(function(e,t){return e.filter(e=>(!t.hideArchived||!e.archived)&&("all"===t.agentFilter||e.agent===t.agentFilter)&&function(e,t){const n=t.trim().toLowerCase();return!n||[d(e),e.cwd,e.agent,e.branch??"",...e.titleAliases??[]].some(e=>e.toLowerCase().includes(n))}(e,t.search))}(n,{search:e.search,hideArchived:e.hideArchived,agentFilter:e.sessionAgentFilter}),e.sessionSort??"updated",!1),[n,e.hideArchived,e.search,e.sessionAgentFilter,e.sessionSort]),l=o.useMemo(()=>new Set([...Object.keys(e.pendingApprovals),...Object.keys(e.pendingQuestions),...e.reviewSessionIds??[],...e.failedSessionIds??[]]),[e.pendingApprovals,e.pendingQuestions,e.reviewSessionIds,e.failedSessionIds]),u=o.useMemo(()=>{if(e.search.trim()||"updated"!==(e.sessionSort??"updated"))return c;const n=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,i=[];for(const l of e)s.set(l.sessionId,l),(t[l.sessionId]||l.runtime.isResponding)&&i.push(l.sessionId);if(0===i.length)return 0===n.protectedSessionIds.length?{sessions:e,state:n}:{sessions:e,state:{protectedSessionIds:[]}};const r=new Set(i),o=n.protectedSessionIds.filter(e=>s.has(e)&&r.has(e)),a=new Set(o);let c=o.length!==n.protectedSessionIds.length;for(const l of i)a.has(l)||(a.add(l),o.push(l),c=!0);return{sessions:sn(e,o,s),state:c?{protectedSessionIds:o}:n}}(c,Object.fromEntries([...e.respondingSessionIds].map(e=>[e,!0])),t.current);return t.current=n.state,n.sessions},[c,e.respondingSessionIds,e.search,e.sessionSort]),h=o.useMemo(()=>Object.fromEntries(u.map((e,t)=>[e.sessionId,t])),[u]),p=o.useMemo(()=>[...w(u.filter(e=>e.pinned&&!e.archived),"updated"),...u.filter(e=>!e.pinned||e.archived)],[u]),m=o.useMemo(()=>C(function(e,t={}){const n=e=>Object.fromEntries(Array.from(e??[],e=>[e,!0])),s=function(e,t,n,s={}){const i=new Map,r=[],o=[],a=[];for(const l of e){const e=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&&en(l,s.pinnedSessionIds,s.pendingPinnedSessionIds)&&n){r.push(l);continue}const c=i.get(e);c?c.push(l):i.set(e,[l])}const c=[];o.length&&c.push({folder:"@vibelet/needs-attention",kind:"attention",sessions:tn(o,s.regularSessionOrderById)}),a.length&&c.push({folder:"@vibelet/running",kind:"running",sessions:tn(a,s.regularSessionOrderById)}),r.length&&c.push({folder:"@vibelet/pinned",kind:"pinned",sessions:s.orderPinnedByLastActivity?nn(r):tn(r,s.regularSessionOrderById)});for(const[l,d]of i)c.push({folder:l,kind:"folder",sessions:d});return c}(e,n(t.respondingSessionIds),0,{...t,needsAttentionSessionIds:n(t.needsAttentionSessionIds),orderPinnedByLastActivity:!0}),i=new Map(t.runningSessionOrder?.map((e,t)=>[e,t]));if(i.size){const e=s.find(e=>"running"===e.kind);e?.sessions.sort((e,t)=>(i.get(e.sessionId)??1/0)-(i.get(t.sessionId)??1/0))}return s}(p,{needsAttentionSessionIds:l,regularSessionOrderById:h,respondingSessionIds:e.respondingSessionIds,separatePinnedGroup:e.separatePinnedGroup,showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup}),e.sessionSort??"updated"),[l,h,e.respondingSessionIds,e.separatePinnedGroup,e.showNeedsAttentionGroup,e.showRunningGroup,e.sessionSort,p]);return{activeApproval:r,activeQuestion:a,activeSession:i,displaySessions:n,groupedSessions:m,pendingSessionIds:s,visibleSessions:p}}({activeSessionId:F,reviewSessionIds:Ue,failedSessionIds:gt,hideArchived:te,optimisticSessions:xe,pendingApprovals:$,pendingQuestions:_,pendingSessions:be,respondingSessionIds:q,search:X,separatePinnedGroup:n.separatePinnedGroup,sessionAgentFilter:ne,sessionSort:e.sessionSort,sessions:ve,showNeedsAttentionGroup:n.showNeedsAttentionGroup,showRunningGroup:n.showRunningGroup});jl(a,F),jl(g,k),jl(v,q),jl(l,me),jl(c,ge),jl(h,Z);const{updateNewSessionDraft:It,updateDraft:Ct}=function({activeSessionIdRef:e,composerDraftsRef:t,setComposerDrafts:n,setDraft:s}){const i=o.useRef(null),r=o.useRef(null),a=o.useRef(!1),c=o.useCallback(()=>{if(i.current&&clearTimeout(i.current),r.current&&clearTimeout(r.current),i.current=r.current=null,a.current){a.current=!1;try{al(t.current)}catch{}}},[t]),l=o.useCallback(()=>{a.current=!0,i.current&&clearTimeout(i.current),i.current=setTimeout(c,300),r.current||(r.current=setTimeout(c,2e3))},[c]);return o.useEffect(()=>{const e=()=>{"hidden"===document.visibilityState&&c()};return window.addEventListener("pagehide",c),window.addEventListener("beforeunload",c),document.addEventListener("visibilitychange",e),()=>{c(),window.removeEventListener("pagehide",c),window.removeEventListener("beforeunload",c),document.removeEventListener("visibilitychange",e)}},[c]),{updateDraft:o.useCallback(i=>{const r=cl(t.current,e.current,i);t.current=r,n(r),s(i),l()},[e,t,n,s,l]),updateNewSessionDraft:o.useCallback(i=>{const r=cl(t.current,null,i);t.current=r,n(r),e.current||s(i),l()},[e,t,n,s,l])}}({activeSessionIdRef:a,composerDraftsRef:h,setComposerDrafts:Y,setDraft:we});o.useEffect(()=>{M();const e=E();e&&(It(e),oe("session"),T())},[It]),o.useEffect(()=>{const e=()=>{fe(Wt()),ye(Kt())};return window.addEventListener("vibelet.notifications.changed",e),()=>window.removeEventListener("vibelet.notifications.changed",e)},[]),o.useEffect(()=>{"admin"===re&&ye(Kt())},[re]),o.useEffect(()=>()=>{y.current&&window.clearTimeout(y.current)},[]);const jt=o.useCallback((e,n=!1)=>{I(t=>function(e,t,n=!1){const s=new Set(t.map(e=>e.sessionId));return bn(n?e:e.filter(e=>s.has(e.sessionId)),t)}(t,e.sessions,n)),A(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),n||function(e,n,s=t(),i=(new Date).toISOString()){if(!e)return;const r={daemonId:e,page:{...n,sessions:n.sessions.slice(0,120)},cachedAt:i};s.setItem(el,JSON.stringify(r))}(g.current?.daemonId,e),x(e.inventoryBackfillInFlight?ie.connectedIndexing:ie.connected)},[ie.connected,ie.connectedIndexing]),Rt=function({clientRef:e,sessions:t,setSessions:n,activeSessionIdRef:s}){const i=o.useRef(new Map),r=o.useRef(t);r.current=t,o.useEffect(()=>()=>i.current.clear(),[]);const a=o.useCallback(async t=>{const r=e.current;if(!r?.isConnected)return;const o=t.find(e=>e.sessionId===s?.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 r.request({action:"sessions.gitMetadata",id:r.makeId("git"),cwds:c});if(e.current!==r||!r.isConnected)return;n(n=>n.map(n=>{if(e.current!==r||!r.isConnected||i.current.get(n.cwd)!==l)return n;const s=Object.hasOwn(t.branches,n.cwd),o=s?t.branches[n.cwd]??void 0:n.branch,a=s&&o!==n.branch,c=t.gitLinksCwds?.includes(n.cwd)??s;return{...n,pullRequest:c?t.pullRequests?.[n.cwd]:a?void 0:n.pullRequest,branchUrl:t.branchUrls?.[n.cwd]??(c||a?void 0:n.branchUrl),branch:o,diffStat:Object.hasOwn(t.diffStats,n.cwd)?t.diffStats[n.cwd]??void 0:n.diffStat}}))}catch{}},[e,n,s]);return o.useEffect(()=>{let e=!1;const t=()=>{"hidden"===document.visibilityState||e||(e=!0,a(r.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:r,sessions:ve,setSessions:I,activeSessionIdRef:a}),Mt=o.useCallback((e,t=v.current)=>{const n=r.current;if(!n?.isConnected||0===e.length)return;const s=function(e,t,n,s,i=6){if(i<=0)return[];const r=[];for(const o of e){if(r.length>=i)break;o.sessionId&&Ll(o,n)&&(pl(t,o.sessionId)||s.has(o.sessionId)||r.push(o))}return r}(e,Ve.current,t,f.current);for(const i of s)f.current.add(i.sessionId),n.request({action:"session.history",id:n.makeId("history_prefetch"),pageMode:"cursor",limit:20,sessionId:i.sessionId,agent:i.agent},{timeoutMessage:ie.historyPrefetchTimedOut,timeoutMs:15e3}).catch(()=>{}).finally(()=>{f.current.delete(i.sessionId)})},[ie.historyPrefetchTimedOut]),Et=o.useCallback(e=>{const t=function(e,t={}){const n=new Set,s={},i={},r={};for(const p of e.sessions)p.runtime.isResponding&&n.add(p.sessionId);for(const p of e.pendingApprovals??[])s[p.sessionId]={type:"approval.request",...p};for(const p of e.pendingQuestions??[])i[p.sessionId]={type:"question.request",...p};let o,a,c,l,d,u,h=null;if(e.activeSession){const p=e.activeSession,m=e.sessions.find(e=>e.sessionId===p.sessionId);if(h=p.sessionId,o=p.agent,a=m?.cwd||t.currentCwd||cn,c=p.approvalMode??m?.approvalMode??ln,l=p.approvalMode??null,d=Xt(p.messages??[],p.partialReplyText),(p.isResponding||p.externallyResponding)&&n.add(p.sessionId),p.pendingApproval&&(s[p.sessionId]={type:"approval.request",sessionId:p.sessionId,...p.pendingApproval}),p.pendingQuestion){const e={type:"question.request",sessionId:p.sessionId,...p.pendingQuestion};i[p.sessionId]=e,u=gn(e)}p.pendingQueue?.length&&(r[p.sessionId]=p.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||cn,c=s.approvalMode??ln)}return{page:{sessions:e.sessions,nextCursor:an(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:i,pendingQueues:r,questionAnswers:u}}(e,{currentActiveSessionId:a.current,currentCwd:V});jt(t.page,!1),N(t.page.nextCursor),D(t.page.inventoryVersion),void 0!==e.activeSession?.messages&&t.messages&&t.activeSessionId&&Je(t.activeSessionId,t.messages);for(const n of e.activeSession?.acceptedClientMessageIds??[])it(e.activeSession.sessionId,n,"delivered");e.activeSession&&void 0===e.activeSession.messages&&mt(e.activeSession,{refresh:!0}),L(t.activeSessionId),t.activeAgent&&U(t.activeAgent),t.activeCwd&&G(t.activeCwd),t.activeApprovalMode&&J(t.activeApprovalMode),t.questionAnswers&&H(t.questionAnswers),v.current=new Set(t.respondingSessionIds),O(v.current),z(t.pendingApprovals),B(t.pendingQuestions),K(t.pendingQueues),Rt(e.sessions),Mt(e.sessions,new Set(t.respondingSessionIds))},[V,Rt,Je,Mt,mt,jt,it]),Tt=function(e){const{clientRef:t,activeSessionIdRef:n,search:s,sinceFilter:i,hideArchived:r,sessionAgentFilter:a}=e,c=o.useMemo(()=>({}),[s,i,r,a,n.current]),l=o.useRef({scope:c,options:e,request:0});return l.current.scope=c,l.current.options=e,o.useEffect(()=>()=>{l.current.request++},[]),o.useCallback(async()=>{const e=t.current;if(!e?.isConnected)return;const s=++l.current.request,i=()=>t.current===e&&e.isConnected&&l.current.request===s;for(;i();){const t=l.current,s=t.scope,o=t.options,a=n.current,c=()=>l.current.scope===s&&n.current===a;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:vn(o.sinceFilter),hideArchived:o.hideArchived,skipGitMetadata:!0,skipActiveSessionHistory:!0});if(!i())return;if(!c())continue;return void l.current.options.apply(t.snapshot)}catch(r){if(!i())return;if(c())throw r}}},[t,n])}({clientRef:r,activeSessionIdRef:a,activeAgent:yt?.agent??Q,sessionAgentFilter:ne,search:X,sinceFilter:ee,hideArchived:te,apply:Et}),At=function(e){const{clientRef:t,search:n,sinceFilter:s,hideArchived:i,sessionAgentFilter:r,viewKey:a}=e,c=o.useMemo(()=>({refresh:0}),[n,s,i,r,a]),l=o.useRef({options:e,scope:c});l.current={options:e,scope:c};const d=o.useRef(c);o.useLayoutEffect(()=>{d.current!==c&&(d.current=c,e.setNextCursor(void 0))},[e.setNextCursor,c]);const u=o.useRef(!0);return o.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]),o.useCallback(async e=>{const o=t.current;if(!u.current||!o?.isConnected||l.current.scope!==c)return;const a=e?.append?c.refresh:++c.refresh,d=()=>u.current&&t.current===o&&o.isConnected&&l.current.scope===c&&(e?.append||a===c.refresh);try{const t=await o.request({action:"sessions.list",id:o.makeId(e?.append?"sessions_more":"sessions"),limit:e?.preserveLoaded?Math.max(80,l.current.options.loadedCount):80,cursor:e?.cursor,agent:"all"===r?void 0:r,search:n.trim()||void 0,sinceMs:vn(s),hideArchived:i,skipGitMetadata:!0,force:e?.force});if(!d())return;const a=pn(t),c=l.current.options;c.setSessionsFromPage(a,e?.append),c.setActiveSessionId(e=>e??a.sessions[0]?.sessionId??null),c.hydrateGitMetadata(a.sessions),c.prefetchActiveHistories(a.sessions)}catch(h){if(d())throw h}},[t,c,n,s,i,r])}({clientRef:r,search:X,sinceFilter:ee,hideArchived:te,sessionAgentFilter:ne,viewKey:[e.sessionSort,e.groupFolders,n.showNeedsAttentionGroup,n.showRunningGroup,n.separatePinnedGroup].join(":"),loadedCount:ve.length,setNextCursor:N,setSessionsFromPage:jt,setActiveSessionId:L,hydrateGitMetadata:Rt,prefetchActiveHistories:Mt}),Nt=function({clientRef:e,setModelOptions:t,setUsageLimits:n,setSkills:s,setErrorText:i,t:r}){const a=o.useRef(0),c=o.useRef(null);return o.useEffect(()=>()=>{a.current++},[]),o.useCallback((o,l)=>{const d=e.current;if(!d?.isConnected)return Promise.resolve();if(c.current?.client===d&&c.current.agent===o&&c.current.cwd===l)return c.current.promise;const u=++a.current,h=()=>a.current===u&&e.current===d&&d.isConnected,p="codex"===o?"Codex":"Claude",m=[],f=Promise.allSettled([d.request({action:"models.list",id:d.makeId("models"),agent:o},{timeoutMs:hl}).then(e=>{h()&&t(t=>({...t,[o]:e.options??[]}))}).catch((e=>t=>{if(!h())return;const n=t instanceof Error?t.message:String(t);m.push(/timeout|timed out/i.test(n)?r.resourceLoadTimedOut(e):r.resourceLoadFailed(e,n)),i(m.join("\n"))})(`${p} · ${r.model}`)),dc(d,()=>({action:"usage.limits.fetch",id:d.makeId("usage"),agent:o}),h).then(e=>{e&&h()&&n(t=>({...t,[o]:e}))}),dc(d,()=>({action:"skills.list",id:d.makeId("skills"),cwd:l||void 0}),h).then(e=>{e&&h()&&s(Array.isArray(e.skills)?e.skills:[])})]).then(()=>{a.current===u&&(c.current=null)});return c.current={client:d,agent:o,cwd:l,promise:f},f},[e,t,n,s,i,r])}({t:ie,clientRef:r,setModelOptions:le,setUsageLimits:ue,setSkills:he,setErrorText:S}),Pt=o.useCallback((e,t,n="info")=>{const s=r.current;s?.isConnected&&s.request({action:"log.report",id:s.makeId("log"),entries:[{level:n,event:e,data:t,ts:(new Date).toISOString()}]}).catch(()=>{})},[]);!function(e){o.useEffect(()=>{const t=performance.now(),n=(t,n,s="info")=>e(t,function(e){const t={};for(const[n,s]of Object.entries(e))Dl.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:Fl(e.error)},"error")},i=e=>{n("web.telemetry.unhandled_rejection",{errorKind:Fl(e.reason)},"error")},r=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",i),()=>{window.clearTimeout(r),window.removeEventListener("error",s),window.removeEventListener("unhandledrejection",i),c?.disconnect(),o>0&&n("web.telemetry.long_tasks",{longTaskCount:o,maxLongTaskMs:a},"warn")}},[e])}(Pt);const Dt=o.useCallback(async(e=g.current)=>{if(e){pe(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"});if(!t.ok)throw new Error(`HTTP ${t.status}`);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));pe({...n,loading:!1,error:null})}catch{pe(e=>({...e,loading:!1,error:ie.connectorVersionFailed}))}}else pe(Xa)},[ie.connectorVersionFailed]);o.useEffect(()=>{const e=()=>{fe(Wt()),ye(Kt())};return window.addEventListener("vibelet.notifications.changed",e),()=>window.removeEventListener("vibelet.notifications.changed",e)},[]),o.useEffect(()=>{"admin"===re&&"connected"===b&&Dt()},[re,b,Dt]);const Ft=o.useCallback(e=>{fe(n=>{const s={...n,...e};return l.current=s,function(e,n=t()){n.setItem(Bt,JSON.stringify(e))}(s),s})},[]),Lt=o.useCallback((t,n)=>{t&&n&&t!==n&&(L(e=>e===t?n:e),m.current===t&&(m.current=n),Ze.current===t&&(Ze.current=n),Qe.remap(t,n),Ye(t,n),v.current=kn(v.current,t,n),O(e=>kn(e,t,n)),z(e=>Sn(e,t,n)),B(e=>Sn(e,t,n)),e.remapPendingQueue(t,n),K(e=>Sn(e,t,n)),A(e=>{const s=e[t];if(!s)return e;const i={...e};return delete i[t],i[n]={...s,sessionId:n},i}),Y(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 i={...e.draftsBySessionId};return delete i[t],s.trim()&&(i[n]=s),{...e,draftsBySessionId:i}}(e,t,n);return s!==e&&(h.current=s,al(s)),s}))},[Qe]);return{completionAttention:Qe,...e,...n,attachments:Ie,setAttachments:Ce,uploadBusy:je,directory:Re,setDirectory:Me,newDirName:Ee,setNewDirName:Te,remoteFile:ke,setRemoteFile:Ae,remoteFileConflict:Ne,uploadFiles:Pe,openRemoteFile:De,saveRemoteFile:Fe,downloadRemoteFile:Le,listDirectory:qe,listSessionDirectories:Oe,listFileTreeDirectory:$e,createDirectory:ze,createSessionDirectory:_e,pendingActionsCount:Be,activeQueue:He,activeModelOptions:We,activeUsage:Ke,activeApproval:vt,activeQuestion:bt,activeSession:yt,displaySessions:xt,groupedSessions:wt,pendingSessionIds:St,visibleSessions:kt,appendCachedDelta:Xe,appendCachedHistory:et,appendInfoMessage:tt,clearHistoryLoading:nt,ensureCachedHistoryEntry:st,setCachedMessageDelivery:it,resolveCachedMessageSession:rt,historyCacheRef:Ve,historyLoading:ot,hasOlderHistory:at,olderHistoryLoading:ct,historyPageStartRef:Ge,hydrateVisibleHistory:Je,messages:lt,messagesSessionIdRef:Ze,mergeCachedHistoryPage:dt,remapCachedHistory:Ye,removeCachedHistory:ut,renderCachedHistory:ht,replaceCachedHistory:pt,requestHistory:mt,setMessages:ft,updateDraft:Ct,updateNewSessionDraft:It,setSessionsFromPage:jt,hydrateGitMetadata:Rt,prefetchActiveHistories:Mt,applyReconnectSnapshot:Et,requestReconnectSnapshot:Tt,requestSessions:At,fetchAgentResources:Nt,reportLog:Pt,refreshDaemonMetadata:Dt,updateNotificationSettings:Ft,remapLocalSessionState:Lt}}();!function(e){const t=o.useRef({daemonId:"",pending:!0,initial:!0});o.useLayoutEffect(()=>{const s=e.pairing?.daemonId;if("desktop"!==n().kind||"connected"!==e.phase||!s)return;if(t.current.daemonId!==s&&(t.current={daemonId:s,pending:!0,initial:!t.current.daemonId}),!t.current.pending)return;const i=w(e.visibleSessions,"updated",!1)[0];i&&(t.current.initial&&e.activeSessionId||e.setActiveSessionId(i.sessionId),t.current.pending=!1)},[e.pairing?.daemonId,e.phase,e.activeSessionId,e.visibleSessions])}(e);const r=o.useRef(void 0),a=o.useRef(new Set),c=function(e){const t=o.useRef(!1);return async n=>{const s=e.activeSession,i=e.clientRef.current;if(!s||!i?.isConnected||t.current||e.busy)return;const r=Ys(),o=e.historyCacheRef.current[s.sessionId]??[],a=function(e,t){const n=e.indexOf(t);if(n>=0)return n;const s=t.historyKey;if(s)return e.findIndex(e=>e.historyKey===s);const i=t.rewindPoint;if(i)return e.findIndex(e=>JSON.stringify(e.rewindPoint)===JSON.stringify(i));const r=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===r.length?r[0]:-1}(o,n);if(a<0||"user"!==n.role||"info"===n.type)return void e.setErrorText(r.unavailable);if((e.historyPageStartRef.current[s.sessionId]??0)>0)return void e.setErrorText(r.incompleteHistory);t.current=!0;let c=!1;try{c=await x({message:r.confirmRewind})}finally{t.current=!1}if(c&&e.clientRef.current===i&&i.isConnected&&e.activeSessionIdRef.current===s.sessionId){t.current=!0,e.setBusy(!0),e.setErrorText(null);try{const t=await i.request({action:"session.rewind",id:i.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:await yl("sessionRewind")},{timeoutMs:15e4,timeoutMessage:r.rewindFailed});if(!t||"string"!=typeof t.sessionId||!t.sessionId||t.sessionId===s.sessionId||t.sourceSessionId!==s.sessionId||!0!==t.archivedSource||!Array.isArray(t.messages)||t.messages.some(e=>!e||"string"!=typeof e.content||!["user","assistant","tool"].includes(e.role)))throw new Error(r.invalidResponse);const c={...s,sessionId:t.sessionId,archived:!1};e.setOptimisticSessions(e=>{const n={...e};return delete n[s.sessionId],n[t.sessionId]=c,n}),e.setSessions(e=>[...e.filter(e=>e.sessionId!==t.sessionId).map(e=>e.sessionId===s.sessionId?{...e,archived:!0,pinned:!1}:e),c]),e.replaceCachedHistory(t.sessionId,t.messages),e.lastHistorySessionIdRef.current=t.sessionId,e.activeSessionIdRef.current=t.sessionId,e.setActiveSessionId(t.sessionId),e.renderCachedHistory(t.sessionId),e.updateDraft(n.content),e.setAttachments((n.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.setErrorText(l instanceof Error?l.message:r.rewindFailed)}finally{t.current=!1,e.setBusy(!1)}}}}(e),{initialSavedTargetsRef:l,composerDraftsRef:h,lastHistorySessionIdRef:m,respondingSessionsRef:f,phase:g,setErrorText:y,pairing:v,setSessions:A,pendingSessions:N,activeSessionId:P,setActiveSessionId:D,setRespondingSessions:F,setPendingApprovals:L,setPendingQuestions:q,setPendingQueues:O,setLivePendingQueue:$,agent:z,setAgent:_,cwd:B,setCwd:H,setApprovalMode:W,setModel:K,setEffort:Q,setFastMode:U,setRenameTitle:V,setDraft:G,archiveSyncedDaemonIds:J,archiveSyncCardDismissedDaemonIds:Z,setControlTabAndOpen:Y,daemonMetadata:X,notificationPermission:ee,setDirectory:te,displaySessions:ne,appendInfoMessage:se,clearHistoryLoading:ie,messagesSessionIdRef:re,renderCachedHistory:oe,replaceCachedHistory:ae,requestHistory:ce,setMessages:le,requestSessions:de,remapLocalSessionState:ue,attachments:he,setAttachments:pe,listDirectory:me,activeApproval:fe,activeQuestion:ge,activeSession:ye,appendCachedDelta:ve,appendCachedHistory:be,ensureCachedHistoryEntry:xe,setCachedMessageDelivery:we,resolveCachedMessageSession:Se,historyCacheRef:ke,messages:Ie,mergeCachedHistoryPage:Ce,removeCachedHistory:je,updateDraft:Re,setSessionsFromPage:Me,requestReconnectSnapshot:Ee,fetchAgentResources:Te,reportLog:Ae,refreshDaemonMetadata:Ne,updateNotificationSettings:Pe,clientRef:De,connectWithPairingRef:Fe,activeSessionIdRef:Le,notificationPermissionRef:qe,notificationSettingsRef:Oe,historyCacheDaemonIdRef:$e,pairingRef:ze,notifiedEventsRef:_e,reconnectTimerRef:Be,connectionAttemptIdRef:He,turnNotificationCountsRef:We,intentionalDisconnectRef:Ke,setPhase:Qe,setStatusText:Ue,setPairing:Ve,setPendingSessions:Ge,setOptimisticSessions:Je,questionAnswers:Ze,setQuestionAnswers:Ye,approvalMode:Xe,continueSession:et,model:tt,effort:nt,fastMode:st,renameTitle:it,setComposerDrafts:rt,draft:ot,search:at,sinceFilter:ct,savedTargets:lt,setSavedTargets:dt,saveTargets:ut,updateSessionListPreferences:ht,t:pt,busy:mt,setBusy:ft,setDetailsOpen:gt,setAdmin:yt,setDaemonMetadata:xt,setNotificationPermission:wt,archiveSyncBusy:St,setArchiveSyncBusy:It,setArchiveSyncStatus:Ct}=e,jt=o.useCallback(async(e,t,n)=>{const s="string"==typeof n.sessionId?n.sessionId:e,i="string"==typeof n.oldSessionId?n.oldSessionId:e;i&&s&&i!==s&&ue(i,s),"clear"===t.name?(ae(s,[]),O(e=>{const t={...e};return delete t[s],delete t[i],t}),L(e=>{const t={...e};return delete t[s],delete t[i],t}),q(e=>{const t={...e};return delete t[s],delete t[i],t}),D(s)):"new"===t.name?(D(s),re.current=s,oe(s)):"exit"===t.name?(A(e=>e.map(e=>e.sessionId===s?{...e,archived:!0}:e)),D(null),re.current=null,m.current=null,le([])):"goal"===t.name&&"goal"in n&&se(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&&(f.current=new Set(f.current).add(s),F(e=>new Set(e).add(s))),await de({force:!0})},[se,ue,oe,ae,de]),Rt=function(e){const t=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})},s=o.useCallback((t,s,i,r,o)=>{const a=e.notificationSettingsRef.current;a[r]&&!e.notifiedEventsRef.current.has(t)&&function(e,t,s={}){const i=s.notificationFactory??("undefined"==typeof Notification?void 0:Notification);if(!i&&!n().notifications)return!1;if(!function(e,t,n=("undefined"==typeof document?"visible":document.visibilityState)){return!(!e.enabled||"granted"!==t||e.hiddenOnly&&"visible"===n)}(s.settings??{enabled:!0,hiddenOnly:!1},s.permission??Kt(),s.visibilityState??("undefined"==typeof document?"visible":document.visibilityState)))return!1;if(n().notifications)return n().notifications.show(e,t,s.onClick),!0;const r=new i(e,{body:t,tag:s.tag});return s.onClick&&(r.onclick=s.onClick),!0}(s,i,{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 o.useCallback(n=>{switch(n.type){case"response":dn(n.data)&&"string"==typeof n.data.oldSessionId&&"string"==typeof n.data.sessionId&&e.remapLocalSessionState(n.data.oldSessionId,n.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":n.isResponding||n.externallyResponding?e.completionAttention?.observe(n.sessionId):e.completionAttention?.complete(n.sessionId),e.setSessions(e=>{const t=e.findIndex(e=>e.sessionId===n.sessionId&&e.stallWarning!==n.stallWarning);if(t<0)return e;const s=[...e];return s[t]={...e[t],stallWarning:n.stallWarning},s}),e.setPendingQueues(e=>({...e,[n.sessionId]:n.pendingQueue??[]})),e.clearHistoryLoading(n.sessionId),e.mergeCachedHistoryPage(n.sessionId,function(e,t){return Xt(e.map(e=>({...e})),t)}(n.messages,n.partialReplyText),n.historyPage);for(const t of n.acceptedClientMessageIds??[])e.setCachedMessageDelivery(n.sessionId,t,"delivered");n.sessionId===e.activeSessionIdRef.current&&(e.setPendingApprovals(e=>{const t={...e};return n.pendingApproval?t[n.sessionId]={type:"approval.request",sessionId:n.sessionId,...n.pendingApproval}:delete t[n.sessionId],t}),e.setPendingQuestions(t=>{const s={...t};if(n.pendingQuestion){const t={type:"question.request",sessionId:n.sessionId,...n.pendingQuestion};s[n.sessionId]=t,e.setQuestionAnswers(gn(t))}else delete s[n.sessionId];return s})),e.setRespondingSessions(t=>{const s=gl(t,n.sessionId,Boolean(n.isResponding||n.externallyResponding));return e.respondingSessionsRef.current=s,s});break;case"session.history.append":e.appendCachedHistory(n.sessionId,n.messages);break;case"text.delta":e.completionAttention?.observe(n.sessionId),t(n.sessionId),e.appendCachedDelta(n.sessionId,n.content),e.respondingSessionsRef.current=gl(e.respondingSessionsRef.current,n.sessionId,!0),e.setRespondingSessions(e=>gl(e,n.sessionId,!0));break;case"session.background_terminals":e.setSessions(e=>e.map(e=>e.sessionId===n.sessionId?{...e,runtime:{...e.runtime,backgroundTerminals:n.terminals}}:e));break;case"tool.call":t(n.sessionId),e.appendCachedHistory(n.sessionId,[{role:"tool",type:"info",toolName:n.toolName,toolInput:n.input,content:`${e.t.toolCallLabel}: ${n.toolName}\n\n${fn(n.input)}`,timestamp:(new Date).toISOString()}]);break;case"tool.result":t(n.sessionId),e.appendCachedHistory(n.sessionId,[{role:"tool",type:"info",content:n.output,timestamp:(new Date).toISOString()}]);break;case"approval.request":e.setPendingApprovals(e=>({...e,[n.sessionId]:n})),s(`approval:${n.sessionId}:${n.requestId}`,e.t.notificationApprovalTitle,n.description||n.toolName,"approvals",n.sessionId);break;case"question.request":e.setPendingQuestions(e=>({...e,[n.sessionId]:n})),s(`question:${n.sessionId}:${n.requestId}`,e.t.notificationQuestionTitle,e.t.notificationQuestionCount(n.questions.length),"questions",n.sessionId);break;case"question.cleared":e.setPendingQuestions(e=>{const t={...e};return t[n.sessionId]?.requestId===n.requestId&&delete t[n.sessionId],t});break;case"session.queue":e.setLivePendingQueue(n.sessionId,n.pending);break;case"session.stall_warning":e.setSessions(e=>e.map(e=>e.sessionId===n.sessionId?{...e,stallWarning:n.warning}:e));break;case"session.interrupted_notice":e.setSessions(e=>e.map(e=>e.sessionId===n.sessionId?{...e,interruptReason:n.reason,stallWarning:void 0}:e));break;case"session.done":if(e.respondingSessionsRef.current.has(n.sessionId)&&e.completionAttention?.observe(n.sessionId),e.completionAttention?.complete(n.sessionId),t(n.sessionId),e.respondingSessionsRef.current.has(n.sessionId)){const t=(e.turnNotificationCountsRef.current[n.sessionId]??0)+1;e.turnNotificationCountsRef.current[n.sessionId]=t,s(`done:${n.sessionId}:${t}`,e.t.notificationReplyTitle,e.t.notificationReplyBody,"replies",n.sessionId)}e.respondingSessionsRef.current=gl(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(e=>gl(e,n.sessionId,!1)),e.setPendingApprovals(e=>{const t={...e};return delete t[n.sessionId],t}),e.setPendingQuestions(e=>{const t={...e};return delete t[n.sessionId],t}),n.usage&&e.setSessions(e=>e.map(e=>e.sessionId===n.sessionId?{...e,lastUsage:n.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?.(n.sessionId),e.respondingSessionsRef.current=gl(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(e=>gl(e,n.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===n.sessionId?{...e,customTitle:n.title}:e));break;case"error":e.respondingSessionsRef.current=gl(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(e=>gl(e,n.sessionId,!1)),t(n.sessionId),e.setPendingApprovals(e=>{const t={...e};return delete t[n.sessionId],t}),e.setPendingQuestions(e=>{const t={...e};return delete t[n.sessionId],t}),e.setSessions(e=>e.map(e=>e.sessionId===n.sessionId?{...e,runtime:{...e.runtime,isResponding:!1},interruptReason:n.reason??{kind:"driver_error",at:(new Date).toISOString(),humanText:n.message}}:e)),n.sessionId||e.setErrorText(n.message)}},[e,s])}({refreshInterruptedHistory:e=>{if(e!==Le.current)return;const t=ne.find(t=>t.sessionId===e);t&&ce(t,{refresh:!0})},completionAttention:e.completionAttention,notificationSettingsRef:Oe,notifiedEventsRef:_e,notificationPermissionRef:qe,activeSessionIdRef:Le,respondingSessionsRef:f,turnNotificationCountsRef:We,t:pt,setActiveSessionId:D,setErrorText:y,setPendingQueues:O,setLivePendingQueue:$,setPendingApprovals:L,setPendingQuestions:q,setQuestionAnswers:Ye,setRespondingSessions:F,setSessions:A,remapLocalSessionState:ue,requestSessions:de,clearHistoryLoading:ie,replaceCachedHistory:ae,setCachedMessageDelivery:we,mergeCachedHistoryPage:Ce,appendCachedHistory:be,appendCachedDelta:ve});(function(e){const s=o.useRef(null),i=()=>{null!==s.current&&window.clearTimeout(s.current),s.current=null},r=o.useRef(null),a=o.useRef(e);a.current=e;const c=o.useCallback(e=>{const t=a.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))},[]),l=o.useCallback(async(e,r=!1)=>{const o=a.current;i(),o.reconnectTimerRef.current&&(window.clearTimeout(o.reconnectTimerRef.current),o.reconnectTimerRef.current=null),o.intentionalDisconnectRef.current=!1,o.setPhase("connecting"),o.setStatusText(r?o.t.reconnectingToDaemon:o.t.connectingToDaemon),o.setErrorText(null);const l=new Xc,d=o.connectionAttemptIdRef.current+1;o.connectionAttemptIdRef.current=d;const u=o.clientRef.current;o.clientRef.current=l,u?.disconnect();const h=()=>o.connectionAttemptIdRef.current===d&&o.clientRef.current===l;l.onMessage(e=>{h()&&a.current.handleServerMessage(e)});let p=!1;l.onClose(()=>{h()&&p&&(o.clientRef.current=null,i(),o.intentionalDisconnectRef.current||(o.setPhase("connecting"),o.setStatusText(o.t.reconnectingToDaemon),o.setErrorText(o.t.webSocketClosedRetrying),c(e)))});try{const i=await(n().prepareConnection?.(e))??e;if(!h())return;let c,d=i;try{c=await l.connect(i)}catch(m){if(!h()||!i.webSocketUrl||tl(m))throw m;d={...i,webSocketUrl:void 0},o.setStatusText(o.t.reconnectingToDaemon),c=await l.connect(d)}if(!h())return;p=!0;const u={...d,displayName:c.displayName??d.displayName},f=!!o.pairingRef.current&&o.pairingRef.current.daemonId!==u.daemonId;f&&o.resetDeviceWorkspace(),o.historyCacheDaemonIdRef.current&&o.historyCacheDaemonIdRef.current!==u.daemonId&&(o.historyCacheRef.current={},o.messagesSessionIdRef.current=null,o.lastHistorySessionIdRef.current=null,o.setMessages([])),o.historyCacheDaemonIdRef.current=u.daemonId,o.setPairing(u),o.pairingRef.current=u,ds(u);const g=function(e,n=t()){if(!e)return null;try{const t=n.getItem(el);if(!t)return null;const s=function(e){if(!function(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}(e)||"string"!=typeof e.daemonId||!e.daemonId)return null;const t=pn(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()}}(JSON.parse(t));return s?.daemonId===e?s.page:null}catch{return null}}(u.daemonId);g&&o.setSessionsFromPage(g,!1),o.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,u);return Gc(t),t}),o.setPhase("connected"),o.setStatusText(o.t.connectedTo(c.displayName??e.displayName??"Vibelet Daemon")),o.refreshDaemonMetadata(u);let y=null;const v=async()=>{if(h())try{if(await a.current.requestReconnectSnapshot(),h()&&y){const e=y;o.setErrorText(t=>t===e?null:t)}}catch(m){if(!h())return;y=m instanceof Error?m.message:String(m),o.setErrorText(y),s.current=window.setTimeout(()=>{s.current=null,v()},1600)}};v();const b=a.current;b.fetchAgentResources(b.agent,f?cn:b.cwd).catch(e=>{h()&&o.setErrorText(e instanceof Error?e.message:String(e))}),o.reportLog("web.connected",{reconnecting:r})}catch(m){if(!h())return;o.clientRef.current=null,l.disconnect(),tl(m)&&ls()?.pairToken===e.pairToken&&us(),o.setPhase("error"),o.setStatusText(o.t.connectionFailed),o.setErrorText(tl(m)?o.t.pairingAuthFailed:m instanceof Error?m.message:String(m)),tl(m)||c(e)}},[c]);o.useEffect(()=>{a.current.connectWithPairingRef.current=l},[l]),o.useEffect(()=>{const e=a.current;let t=!1;return async function(){const n=os(),s=ls()??e.rememberedTarget;if(!n&&!s)return e.setPhase("missing-pair"),void e.setStatusText(e.t.missingPair);try{e.setPhase("pairing"),n&&r.current?.pairNonce!==n.pairNonce&&(r.current={pairNonce:n.pairNonce,promise:hs(n,s)});const i=n?await(r.current?.promise):s;if(!i||t)return;n&&(ds(i),r.current=null,function(){if(!window.location.hash.includes(`${Vn}=`))return;const e=`${window.location.pathname}${window.location.search}`;window.history.replaceState(null,"",e)}()),await e.connectWithPairingRef.current(i)}catch(i){if(t)return;n&&(r.current=null),e.setPhase("error"),e.setStatusText(e.t.pairingFailed),e.setErrorText(function(e,t){return e instanceof Zn&&"pair_window_expired"===e.code?t.pairingLinkExpired:e instanceof Error?e.message:String(e)}(i,e.t))}}(),()=>{t=!0,i(),e.intentionalDisconnectRef.current=!0,e.connectionAttemptIdRef.current+=1,e.reconnectTimerRef.current&&window.clearTimeout(e.reconnectTimerRef.current),e.clientRef.current?.disconnect()}},[e.t]),o.useEffect(()=>{const e=a.current;if("connected"!==e.phase)return;const t=window.setTimeout(()=>{e.requestSessions({force:!0}).catch(t=>e.setErrorText(t instanceof Error?t.message:String(t)))},260);return()=>window.clearTimeout(t)},[e.phase,e.requestSessions,e.search,e.sinceFilter]),o.useEffect(()=>{const e=a.current;"connected"===e.phase&&e.fetchAgentResources(e.agent,e.cwd)},[e.agent,e.cwd,e.fetchAgentResources,e.phase])})({clientRef:De,connectWithPairingRef:Fe,pairingRef:ze,reconnectTimerRef:Be,connectionAttemptIdRef:He,intentionalDisconnectRef:Ke,historyCacheRef:ke,historyCacheDaemonIdRef:$e,messagesSessionIdRef:re,lastHistorySessionIdRef:m,rememberedTarget:l.current[0]??null,agent:z,cwd:B,phase:g,search:at,sinceFilter:ct,t:pt,handleServerMessage:Rt,setPhase:Qe,setStatusText:Ue,setErrorText:y,setMessages:le,setPairing:Ve,setSavedTargets:dt,setSessionsFromPage:Me,resetDeviceWorkspace:()=>{Le.current=null,D(null),H(cn),A([]),Ge({}),Je({}),e.setDiffSessionId(null),L({}),q({}),O({}),f.current=new Set,F(new Set),r.current=void 0,a.current.clear(),Cl({folder:void 0,file:void 0,cwd:void 0},{replace:!0})},refreshDaemonMetadata:Ne,requestReconnectSnapshot:Ee,fetchAgentResources:Te,reportLog:Ae,requestSessions:de}),o.useLayoutEffect(()=>{G(ll(h.current,P))},[P,v?.daemonId]),o.useEffect(()=>{const e=ne.find(e=>e.sessionId===P);if(!e)return m.current=null,re.current=null,ie(),void le([]);_(e.agent),H(e.cwd||cn),V(e.customTitle??e.title??"");const t=r.current,n=`${v?.daemonId}:${e.sessionId}`;r.current=n;const s=Il(),i=!a.current.has(n);if(a.current.add(n),i&&te(i=>function(e,t,n,s,i){if(t===n)return e;const r=!t&&i?i:s||cn;return r===e.path?e:{path:r,entries:[],loading:!1,loaded:!1}}(i,t,n,e.cwd||cn,s.folder||s.cwd)),N[e.sessionId])return m.current=e.sessionId,ie(),void(re.current!==e.sessionId&&(re.current=e.sessionId,le([])));if(oe(e.sessionId)){const t=m.current!==e.sessionId;return m.current=e.sessionId,ie(e.sessionId),void(t&&ce(e,{refresh:!0}))}m.current!==e.sessionId&&(m.current=e.sessionId,re.current!==e.sessionId&&(re.current=e.sessionId,le([])),ce(e,{refresh:!0}))},[P,ie,ne,N,oe,ce]);const Mt=function({daemonId:e,session:n,setModel:s,setEffort:i,setFastMode:r,setApprovalMode:a,setPendingSessions:c}){const l=o.useRef(null);l.current||(l.current=function(){try{const e=JSON.parse(t().getItem(Sl)||"{}");return e&&"object"==typeof e&&!Array.isArray(e)?e:{}}catch{return{}}}());const d=JSON.stringify([e??"",n?.sessionId??""]),u={model:n?.model??"",effort:n?.effort??"",fastMode:n?.fastMode??!1,approvalMode:n?.approvalMode??ln},h=()=>{try{t().setItem(Sl,JSON.stringify(l.current))}catch{}},p=e=>{const t=l.current[d]?.[e];return void 0===t?u[e]:(u[e]===t&&delete l.current[d][e],t)};o.useLayoutEffect(()=>{n&&(s(p("model")),i(p("effort")),r(p("fastMode")),a(p("approvalMode")),h())},[d,u.model,u.effort,u.fastMode,u.approvalMode]);const m=(e,t)=>{n&&(l.current[d]={...l.current[d],[e]:t},h(),c(s=>{const i=s[n.sessionId];if(!i)return s;const r="model"===e?yn(t):"effort"===e?t||void 0:t;return{...s,[n.sessionId]:{...i,[e]:r}}})),"model"===e&&s(t),"effort"===e&&i(t),"fastMode"===e&&r(t),"approvalMode"===e&&a(t)};return{setModel:e=>m("model",e),setEffort:e=>m("effort",e),setFastMode:e=>m("fastMode",e),setApprovalMode:e=>m("approvalMode",e)}}({daemonId:v?.daemonId,session:ye,setModel:K,setEffort:Q,setFastMode:U,setApprovalMode:W,setPendingSessions:Ge}),{stagePendingSession:Et,failedSend:Tt,dismissFailedSend:At,retryFailedSend:Nt,sendDraft:Pt,sendQuickReply:Dt}=function(e){const[t]=o.useState(vl),[n,s]=function(e,t){const[n,s]=o.useState({}),i=n=>t(n.sessionId,n.clientMessageId)===e,r=Object.values(n).find(i)??null;return[r,e=>{s(t=>{const n=r?t[r.clientMessageId]??null:Object.values(t).find(i)??null,s="function"==typeof e?e(n):e,o={...t};return n&&delete o[n.clientMessageId],s&&(o[s.clientMessageId]=s),o})}]}(e.activeSessionId,e.resolveCachedMessageSession),[i,r]=o.useState(null);o.useEffect(()=>{n&&e.messagesSessionIdRef.current===e.resolveCachedMessageSession(n.sessionId,n.clientMessageId)&&e.messages.some(e=>(e.localClientMessageId===n.clientMessageId||e.historyKey===n.historyKey)&&("accepted"===e.delivery||"delivered"===e.localDelivery||Boolean(e.historyKey&&!e.historyKey.startsWith("client:"))))&&s(null)},[n,e]);const a=o.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]),c=o.useCallback((t,n,s)=>{const i=wl(t)??wl(e.cwd)??cn,o=n??e.agent,a=function(e=Date.now()){return xn=(xn+1)%1e4,`pending_local_${e}_${xn}`}(),c=function(e){const t=e.now??(new Date).toISOString();return{sessionId:e.sessionId,agent:e.agent,cwd:e.cwd||cn,...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:o,cwd:i,approvalMode:s?.approvalMode??e.approvalMode,model:yn(s?.model??e.model),effort:e.effort||void 0,fastMode:e.fastMode,title:"codex"===o?e.t.newCodexSession:e.t.newClaudeSession}),l=s?.draft??(e.activeSessionIdRef.current?"":ll(e.composerDraftsRef.current,null));return e.setPendingSessions(e=>({...e,[a]:c})),e.setComposerDrafts(t=>{let n=cl(t,a,l);return e.activeSessionIdRef.current||(n=cl(n,null,"")),e.composerDraftsRef.current=n,al(n),n}),e.setCwd(i),e.setAgent(o),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)&&r({sessionId:a,attachments:s.attachments??[]}),e.setErrorText(null),e.reportLog("web.session.pending_create",{sessionId:a,agent:o,cwd:i}),a},[e]),l=o.useCallback(async(t,n,s)=>{const i=e.clientRef.current;if(!i?.isConnected)return e.setErrorText(e.t.webSocketNotConnected),null;const r=s?e.pendingSessions[s]:void 0,o=wl(t)??wl(r?.cwd)??wl(e.cwd)??cn,a=n??r?.agent??e.agent,c=r?.approvalMode??e.approvalMode,l=r?r.model:yn(e.model),d=r?.effort??(e.effort||void 0),u=r?.fastMode??e.fastMode;e.setErrorText(null);try{const t=await i.request({action:"session.create",id:i.makeId("create"),agent:a,cwd:o,approvalMode:c,continueSession:e.continueSession,model:l,effort:d,fastMode:u,...s?{clientSessionId:s}:{}}),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=dn(t)&&"string"==typeof t.oldSessionId?t.oldSessionId:s;return 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&&r?(e.setPendingSessions(e=>{const t={...e};return delete t[s],h&&h!==s&&delete t[h],t}),e.setOptimisticSessions(e=>({...e,[n]:wn(r,n)})),h&&h!==n&&e.remapLocalSessionState(h,n),s!==n&&e.remapLocalSessionState(s,n)):await e.requestSessions({force:!0}),e.reportLog("web.session.create",{sessionId:n,clientSessionId:s,agent:a,cwd:o}),n}catch(h){return e.setErrorText(h instanceof Error?h.message:String(h)),null}},[e]),d=o.useCallback(async t=>{if(!e.sessions.some(e=>e.sessionId===t&&e.archived))return;const n=e.clientRef.current;if(!n?.isConnected)throw new Error(e.t.webSocketNotConnected);await n.request({action:"session.setArchived",id:n.makeId("unarchive"),sessionId:t,archived:!1}),e.setSessions(e=>e.map(e=>e.sessionId===t?{...e,archived:!1}:e)),e.setOptimisticSessions(e=>e[t]?{...e,[t]:{...e[t],archived:!1}}:e),e.requestSessions({force:!0}).catch(()=>{})},[e]),u=o.useCallback(async(n,i,r)=>{n?.preventDefault();const o=(r??e.draft).trim(),c=i??e.attachments;if(c.some(e=>e.uploading))return;if(!o&&!c.length||e.busy||t.has(e.activeSessionId))return;const u=e.clientRef.current;if(!u?.isConnected)return void e.setErrorText(e.t.webSocketNotConnected);const h=t.start(e.activeSessionId);try{const t=kt(o)?"agentSkills":0===c.length&&vt(o,e.activeSession?.agent??e.agent)?"agentCommands":void 0;let n;if(t)try{n=await yl(t)}catch(p){return void e.setErrorText(p instanceof Error?p.message:String(p))}e.setErrorText(null),void 0===r&&e.updateDraft("");const i=c;void 0===r&&e.setAttachments([]);let m=e.activeSessionId,f=e.activeSession?.agent??e.agent;const g=m?e.pendingSessions[m]:void 0,y=g?g.model:yn(e.model);if(m&&e.pendingSessions[m]){const t=await l(e.pendingSessions[m].cwd,e.pendingSessions[m].agent,m);if(!t)return void(void 0===r&&bl(e,o,i));m=t,f=e.pendingSessions[e.activeSessionId??""]?.agent??f}else m||(m=await l());if(!m)return void(void 0===r&&bl(e,o,i));h.remap(m);const v=0===i.length?vt(o,f):null;if(v){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"}(v.command),s=t?u.makeId("cmd_msg"):void 0;t&&(e.activeSessionIdRef.current===m&&(e.messagesSessionIdRef.current=m),e.appendCachedHistory(m,[{role:"user",content:t,timestamp:(new Date).toISOString()}]),e.activeSessionIdRef.current===m&&e.renderCachedHistory(m));try{t&&await d(m);const i=await u.request({action:"session.command",id:u.makeId("command"),sessionId:m,agent:f,command:v.command,...s?{clientMessageId:s}:{},featureEntitlements:n});await e.handleSessionCommandResponse(m,v.command,i)}catch(p){const t=p instanceof Error?p.message:String(p);e.appendInfoMessage(m,bt(t)),e.activeSessionIdRef.current===m&&e.setErrorText(bt(t))}return}const b=function(e){return e.startsWith("//")?e.slice(1):e}(o),x=i.map(e=>e.path),w=u.makeId("msg"),S=`client:${w}`;e.activeSessionIdRef.current===m&&(e.messagesSessionIdRef.current=m),e.setCachedMessageDelivery(m,w,"sending",{content:b,...x.length?{images:x}:{}}),e.activeSessionIdRef.current===m&&e.renderCachedHistory(m),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(m),e.setRespondingSessions(e=>new Set(e).add(m));const k=kt(b)??void 0,I=k?n:void 0;try{await d(m);const t=await u.request({action:"session.send",id:u.makeId("send"),sessionId:m,agent:f,message:b,clientMessageId:w,images:x.length?x:void 0,model:y,effort:e.effort||void 0,fastMode:e.fastMode,skillInvocation:k,featureEntitlements:I},{timeoutMs:hl,timeoutMessage:xl});dn(t)&&"string"==typeof t.oldSessionId&&"string"==typeof t.sessionId&&(h.remap(t.sessionId),e.remapLocalSessionState(t.oldSessionId,t.sessionId)),e.setCachedMessageDelivery(dn(t)&&"string"==typeof t.sessionId?t.sessionId:m,w,"delivered"),e.reportLog("web.telemetry.send_accepted",{attachmentCount:x.length}),s(e=>e?.historyKey===S?null:e)}catch(p){m=e.resolveCachedMessageSession(m,w);const t=ul(En(p instanceof Error?p.message:String(p),Boolean(k)));if("delivered"===e.setCachedMessageDelivery(m,w,"failed"))return;e.activeSessionIdRef.current===m&&e.setErrorText(null),s({sessionId:m,agent:f,message:b,clientMessageId:w,historyKey:S,kind:t,retrying:!1,...x.length?{images:x}:{},model:y,effort:e.effort||void 0,fastMode:e.fastMode,skillInvocation:k,featureEntitlements:I}),e.reportLog("web.telemetry.send_failed",{attachmentCount:x.length,failureKind:t},"warn"),a(m)}}finally{h.finish()}},[a,l,e,t,d]),h=o.useCallback(async()=>{if(!n||n.retrying||e.busy||t.has(e.activeSessionId))return;const i=e.clientRef.current;if(!i?.isConnected)return void s(e=>e?{...e,kind:"network"}:null);let r=e.resolveCachedMessageSession(n.sessionId,n.clientMessageId);const o=t.start(r);s(e=>e?{...e,retrying:!0}:null),e.ensureCachedHistoryEntry(r,{role:"user",content:n.message,historyKey:n.historyKey,...n.images?.length?{images:n.images}:{}}),e.setCachedMessageDelivery(r,n.clientMessageId,"sending"),e.setErrorText(null),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(r),e.setRespondingSessions(e=>new Set(e).add(r));try{await d(r);const t=await i.request({action:"session.send",id:i.makeId("retry_send"),sessionId:r,agent:n.agent,message:n.message,clientMessageId:n.clientMessageId,images:n.images,model:n.model,effort:n.effort,fastMode:n.fastMode,skillInvocation:n.skillInvocation??void 0,featureEntitlements:n.skillInvocation?await yl("agentSkills"):void 0},{timeoutMs:hl,timeoutMessage:xl});dn(t)&&"string"==typeof t.oldSessionId&&"string"==typeof t.sessionId&&(o.remap(t.sessionId),e.remapLocalSessionState(t.oldSessionId,t.sessionId)),e.setCachedMessageDelivery(dn(t)&&"string"==typeof t.sessionId?t.sessionId:r,n.clientMessageId,"delivered"),e.reportLog("web.telemetry.retry_accepted",{attachmentCount:n.images?.length??0}),s(null)}catch(c){r=e.resolveCachedMessageSession(r,n.clientMessageId);const t=ul(En(c instanceof Error?c.message:String(c),Boolean(n.skillInvocation)));if("delivered"===e.setCachedMessageDelivery(r,n.clientMessageId,"failed"))return void s(null);s(e=>e?{...e,sessionId:r,kind:t,retrying:!1}:null),e.reportLog("web.telemetry.retry_failed",{attachmentCount:n.images?.length??0,failureKind:t},"warn"),a(r)}finally{o.finish()}},[a,n,e,t,d]);return o.useEffect(()=>{!i||e.busy||t.has(e.activeSessionId)||(e.activeSessionId===i.sessionId&&e.pendingSessions[i.sessionId]?(r(null),u(void 0,i.attachments)):r(null))},[i,e.activeSessionId,e.busy,e.pendingSessions,u]),{failedSend:n,dismissFailedSend:()=>s(null),retryFailedSend:h,stagePendingSession:c,sendDraft:Object.assign(u,{submission:t}),sendQuickReply:e=>u(void 0,[],e)}}({messages:Ie,sessions:ne,setSessions:A,clientRef:De,activeSessionIdRef:Le,composerDraftsRef:h,lastHistorySessionIdRef:m,messagesSessionIdRef:re,respondingSessionsRef:f,agent:z,cwd:B,approvalMode:Xe,continueSession:et,model:tt,effort:nt,fastMode:st,activeSessionId:P,activeSession:ye,pendingSessions:N,draft:ot,busy:mt,attachments:he,t:pt,setPendingSessions:Ge,setOptimisticSessions:Je,setComposerDrafts:rt,setCwd:H,setAgent:_,setActiveSessionId:D,setMessages:le,setDraft:G,setErrorText:y,setBusy:ft,setAttachments:pe,setRespondingSessions:F,clearHistoryLoading:ie,reportLog:Ae,remapLocalSessionState:ue,requestSessions:de,updateDraft:Re,appendCachedHistory:be,ensureCachedHistoryEntry:xe,setCachedMessageDelivery:we,resolveCachedMessageSession:Se,renderCachedHistory:oe,handleSessionCommandResponse:jt,appendInfoMessage:se}),{respondApproval:Ft,respondQuestion:Lt,cancelQuestion:qt,setQuestionChoice:Ot,requestActiveAction:$t,interruptActiveSession:zt,retrySessions:Ht,updateApprovalMode:Qt,cancelQueuedTurn:Ut,setSessionPinned:Vt,setSessionArchived:Gt,deleteSession:Jt,updatePinned:Zt,updateArchived:rn,renameSession:on}=function(e){const t=o.useCallback(async t=>{const n=e.clientRef.current,s=e.activeApproval;if(n?.isConnected&&s){e.setBusy(!0),e.setErrorText(null);try{await n.request({action:"session.approve",id:n.makeId("approve"),sessionId:s.sessionId,requestId:s.requestId,approved:t}),e.setPendingApprovals(e=>{const t={...e};return t[s.sessionId]?.requestId===s.requestId&&delete t[s.sessionId],t})}catch(i){const t=i instanceof Error?i.message:String(i);/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]),n=o.useCallback(async()=>{const t=e.clientRef.current;if(t?.isConnected&&e.activeQuestion){e.setBusy(!0),e.setErrorText(null);try{await t.request({action:"session.respondQuestion",id:t.makeId("question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId,answers:e.questionAnswers}),e.setPendingQuestions(t=>{const n={...t};return n[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete n[e.activeQuestion.sessionId],n})}catch(n){e.setErrorText(n instanceof Error?n.message:String(n))}finally{e.setBusy(!1)}}},[e]),s=o.useCallback(async()=>{const t=e.clientRef.current;if(t?.isConnected&&e.activeQuestion){e.setBusy(!0),e.setErrorText(null);try{await t.request({action:"session.cancelQuestion",id:t.makeId("cancel_question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId}),e.setPendingQuestions(t=>{const n={...t};return n[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete n[e.activeQuestion.sessionId],n})}catch(n){e.setErrorText(n instanceof Error?n.message:String(n))}finally{e.setBusy(!1)}}},[e]),i=o.useCallback((t,n,s)=>{e.setQuestionAnswers(e=>function(e,t,n,s=!1){if(!s)return{...e,[t]:[n]};const i=e[t]??[],r=i.includes(n)?i.filter(e=>e!==n):[...i,n];return{...e,[t]:r}}(e,t,n,Boolean(s)))},[e]),r=o.useCallback(async t=>{const n=e.clientRef.current,s=e.activeSession,i=s?.sessionId??("session.interrupt"===t?e.activeSessionIdRef.current:null);if(!n?.isConnected||!i)return!1;if("session.interrupt"!==t&&!s)return!1;if("session.delete"===t&&!(await S(b().deleteSession(d(s)))))return!1;if(e.clientRef.current!==n||!n.isConnected)return!1;e.setBusy(!0),e.setErrorText(null);try{return"session.resume"===t?await n.request({action:t,id:n.makeId("resume"),sessionId:i,agent:s.agent}):await n.request({action:t,id:n.makeId(t.split(".").at(-1)??"session"),sessionId:i}),"session.delete"===t&&(e.removeCachedHistory(s.sessionId),e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([])),"session.interrupt"!==t&&await e.requestSessions({force:!0,preserveLoaded:!0}),!0}catch(r){return e.setErrorText(r instanceof Error?r.message:String(r)),!1}finally{e.setBusy(!1)}},[e]),a=o.useCallback(async t=>{const n=e.clientRef.current;if(e.activeSession){if(n?.isConnected){e.setErrorText(null);try{await n.request({action:"session.setApprovalMode",id:n.makeId("approval_mode"),sessionId:e.activeSession.sessionId,approvalMode:t}),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){e.setErrorText(s instanceof Error?s.message:String(s))}}}else e.setApprovalMode(t)},[e]),c=function(e){return o.useCallback(async t=>{const n=e.clientRef.current;if(!n?.isConnected||!e.activeSessionId||!t.clientMessageId)return;const s=e.activeSessionId;let i=-1;e.setPendingQueues(e=>{const n=e[s]??[];return i=n.findIndex(e=>e.clientMessageId===t.clientMessageId),{...e,[s]:n.filter(e=>e.clientMessageId!==t.clientMessageId)}}),e.setBusy(!0),e.setErrorText(null);try{if(await n.request({action:"session.queue.cancel",id:n.makeId("queue_cancel"),sessionId:s,clientMessageId:t.clientMessageId},{timeoutMs:hl}),e.clientRef.current!==n)return}catch(o){if(e.clientRef.current!==n)return;return e.setPendingQueues(e=>{const n=e[s]??[];if(n.some(e=>e.clientMessageId===t.clientMessageId))return e;const r=Math.min(Math.max(i,0),n.length);return{...e,[s]:[...n.slice(0,r),t,...n.slice(r)]}}),void(e.activeSessionIdRef.current===s&&e.setErrorText(o instanceof Error?o.message:String(o)))}finally{e.setBusy(!1)}const r=e=>[e,t.content].filter(Boolean).join("\n\n");if(e.setComposerDrafts(t=>{const n=cl(t,s,r(ll(t,s)));return e.composerDraftsRef.current=n,al(n),n}),e.activeSessionIdRef.current===s&&e.setDraft(r),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:mn(e),type:"image/*",size:0}))]})}},[e])}(e),l=o.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 i=n?Date.now():void 0;await s.request({action:"session.setPinned",id:s.makeId("pin"),sessionId:t.sessionId,pinned:n,...i?{pinnedAt:i}:{}}),e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,pinned:n,pinnedAt:i}:e)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(i){e.setErrorText(i instanceof Error?i.message:String(i))}finally{e.setBusy(!1)}}},[e]),u=o.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{await s.request({action:"session.setArchived",id:s.makeId("archive"),sessionId:t.sessionId,archived:n}),e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,archived:n}:e)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(i){e.setErrorText(i instanceof Error?i.message:String(i))}finally{e.setBusy(!1)}}},[e]),h=o.useCallback(async t=>{if(e.pendingSessions[t.sessionId])return e.removeCachedHistory(t.sessionId),e.setPendingSessions(e=>{const n={...e};return delete n[t.sessionId],n}),e.setComposerDrafts(n=>{const s=cl(n,t.sessionId,"");return e.composerDraftsRef.current=s,al(s),s}),void(e.activeSessionIdRef.current===t.sessionId&&(e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([]),e.setDraft(ll(e.composerDraftsRef.current,null)),e.setDetailsOpen(!1)));const n=e.clientRef.current;if(n?.isConnected&&await S(b().deleteSession(d(t)))&&e.clientRef.current===n&&n.isConnected){e.setBusy(!0),e.setErrorText(null);try{await n.request({action:"session.delete",id:n.makeId("delete"),sessionId:t.sessionId}),e.removeCachedHistory(t.sessionId),e.setOptimisticSessions(e=>{if(!e[t.sessionId])return e;const n={...e};return delete n[t.sessionId],n}),e.activeSessionIdRef.current===t.sessionId&&(e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([]),e.setDetailsOpen(!1)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(s){e.setErrorText(s instanceof Error?s.message:String(s))}finally{e.setBusy(!1)}}},[e]),p=o.useCallback(async()=>{e.activeSession&&await l(e.activeSession,!e.activeSession.pinned)},[e.activeSession,l]),m=o.useCallback(async()=>{e.activeSession&&await u(e.activeSession,!e.activeSession.archived)},[e.activeSession,u]),f=o.useCallback(()=>{const t=e.activeSessionId;t&&r("session.interrupt").then(n=>{n&&(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,r]),g=o.useCallback(()=>{e.setErrorText(null),"connected"===e.phase?e.requestSessions({force:!0,preserveLoaded:!0}):window.location.reload()},[e]),y=o.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 i=e.clientRef.current;if(!i?.isConnected||!t)return!1;e.setBusy(!0),e.setErrorText(null);try{return await i.request({action:"session.rename",id:i.makeId("rename"),sessionId:t.sessionId,title:s||void 0}),e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,customTitle:s||void 0}:e)),!0}catch(r){return e.setErrorText(r instanceof Error?r.message:String(r)),!1}finally{e.setBusy(!1)}},[e]);return{respondApproval:t,respondQuestion:n,cancelQuestion:s,setQuestionChoice:i,requestActiveAction:r,interruptActiveSession:f,retrySessions:g,updateApprovalMode:a,cancelQueuedTurn:c,setSessionPinned:l,setSessionArchived:u,deleteSession:h,updatePinned:p,updateArchived:m,renameSession:y}}({clientRef:De,activeSessionIdRef:Le,composerDraftsRef:h,lastHistorySessionIdRef:m,messagesSessionIdRef:re,respondingSessionsRef:f,activeApproval:fe,activeQuestion:ge,activeSession:ye,activeSessionId:P,questionAnswers:Ze,pendingSessions:N,phase:g,renameTitle:it,setBusy:ft,setErrorText:y,setPendingApprovals:L,setPendingQuestions:q,setQuestionAnswers:Ye,setPendingQueues:O,setActiveSessionId:D,setMessages:le,setApprovalMode:W,setSessions:A,setPendingSessions:Ge,setComposerDrafts:rt,setDraft:G,setAttachments:pe,setDetailsOpen:gt,setRespondingSessions:F,setOptimisticSessions:Je,removeCachedHistory:je,requestSessions:de}),{runArchiveSync:un,skipArchiveSync:Cn,runAdminAction:Tn,exportActiveSession:An,clearPairing:Nn,setNotificationsEnabled:Pn,connectSavedTarget:Dn,forgetSavedTarget:Fn,openSessionDetails:Ln,editFolderTags:qn,browseFolder:On,copyResumeCommand:$n,resumeInTerminal:zn}=function(e){const t=o.useCallback((t,n)=>{e.updateSessionListPreferences(e=>({...e,archiveSyncedDaemonIds:"synced"===n?{...e.archiveSyncedDaemonIds,[t]:!0}:e.archiveSyncedDaemonIds,archiveSyncCardDismissedDaemonIds:{...e.archiveSyncCardDismissedDaemonIds,[t]:!0}}))},[e]),s=o.useCallback((n,s)=>{const i="pull"===n?e.t.archiveSyncSuccessPull:"pushMerge"===n?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,i,{timeout:e.t.archiveSyncFailedTimeout,disconnected:e.t.archiveSyncFailedDisconnected,generic:e.t.archiveSyncFailedGeneric})),!s.ok)return;const r=new Set(s.archivedSessionIds);e.setSessions(e=>e.map(e=>({...e,archived:r.has(e.sessionId)}))),e.pairingRef.current?.daemonId&&t(e.pairingRef.current.daemonId,"synced"),e.requestSessions({force:!0})},[t,e]),i=o.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));s(t,n),e.setArchiveSyncBusy(null)},[s,e]),r=o.useCallback(()=>{e.pairing?.daemonId&&(t(e.pairing.daemonId,"dismissed"),e.setArchiveSyncStatus({tone:"success",message:e.t.archiveSyncSkipped}))},[t,e]),a=o.useCallback(async t=>{const n=e.clientRef.current;if(n?.isConnected&&("update"!==t||await S(b().update))&&("restart"!==t||await S(b().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=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(e=>({...e,loading:!1,action:null,statusText:s.alreadyRunning?"Connector update already running":"Connector update started"}))}await n.request({action:"daemon.restart",id:n.makeId("daemon_restart")}),e.setAdmin(e=>({...e,loading:!1,action:null,statusText:"Connector restart requested"})),e.refreshDaemonMetadata()}catch(s){e.setAdmin(e=>({...e,loading:!1,action:null})),e.setErrorText(s instanceof Error?s.message:String(s))}}},[e]),c=o.useCallback(async()=>{if(!e.activeSession)return;const t=function(e,t){const n=[`# ${d(e)}`,"",`- Agent: ${e.agent}`,`- Session: \`${e.sessionId}\``,`- Working directory: \`${e.cwd}\``,`- Created: ${e.createdAt}`,`- Exported: ${(new Date).toISOString()}`,""];for(const s of t){if("user"!==s.role&&"assistant"!==s.role)continue;const e=s.content.trim(),t=(s.images??[]).map(e=>`- Attachment: \`${e}\``);(e||0!==t.length)&&(n.push("## "+("user"===s.role?"User":"Assistant"),""),e&&n.push(e,""),t.length&&n.push(...t,""))}return n.join("\n").trimEnd()}(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`}(d(e.activeSession),e.activeSession.sessionId),t),await(navigator.clipboard?.writeText(t).catch(()=>{}))},[e.activeSession,e.messages]),l=o.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]),u=o.useCallback(async()=>{const t=e.pairingRef.current;await S(b().forget)&&e.pairingRef.current===t&&(e.intentionalDisconnectRef.current=!0,e.connectionAttemptIdRef.current+=1,us(),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(Xa),e.setPhase("missing-pair"),e.setStatusText(e.t.missingPair))},[e]),h=o.useCallback(t=>{t&&"default"===e.notificationPermission?l():e.updateNotificationSettings({enabled:t})},[e,l]),p=o.useCallback(t=>{e.connectWithPairingRef.current(t,!0)},[e]),m=o.useCallback(t=>e.saveTargets(function(e,t){return e.filter(e=>e.daemonId!==t)}(e.savedTargets,t)),[e]),f=o.useCallback(t=>{e.setActiveSessionId(t.sessionId),e.setRenameTitle(t.customTitle??t.title??""),e.setDetailsOpen(!0)},[e]),g=o.useCallback((t,n)=>{const s=k(n);e.updateSessionListPreferences(e=>({...e,directoryTags:I(e.directoryTags,t,s)}))},[e]),y=o.useCallback(t=>{e.setControlTab("files"),e.listDirectory(t,{updateRoute:!0})},[e]),v=o.useCallback(async t=>{try{const n=_t(t);if(!n)return;await Ts(n),e.setStatusText(e.t.commandCopied)}catch{throw e.setErrorText(e.t.copyResumeFailed),new Error(e.t.copyResumeFailed)}},[e]),x=o.useRef(!1);return{runArchiveSync:i,skipArchiveSync:r,runAdminAction:a,exportActiveSession:c,clearPairing:u,setNotificationsEnabled:h,connectSavedTarget:p,forgetSavedTarget:m,openSessionDetails:f,editFolderTags:g,browseFolder:y,copyResumeCommand:v,resumeInTerminal:o.useCallback(async t=>{if(x.current)return;const s=n(),i=e.pairingRef.current?.daemonId;if(i&&s.resumeInTerminal&&s.isLocalDaemon?.(i)){x.current=!0;try{const n=e.clientRef.current;if(!n)throw new Error("Not connected");await n.request({action:"session.release",id:n.makeId("release"),sessionId:t.sessionId,agent:t.agent}),await s.resumeInTerminal({...t,daemonId:i,approvalMode:t.approvalMode??t.observedApprovalMode})}catch(r){e.setErrorText(String(r).includes("session_busy")?e.t.resumeTerminalBusy:e.t.resumeTerminalFailed)}finally{x.current=!1}}},[e])}}({clientRef:De,pairingRef:ze,connectWithPairingRef:Fe,notificationPermissionRef:qe,intentionalDisconnectRef:Ke,connectionAttemptIdRef:He,historyCacheRef:ke,historyCacheDaemonIdRef:$e,messagesSessionIdRef:re,lastHistorySessionIdRef:m,displaySessions:ne,pairing:v,t:pt,archiveSyncBusy:St,daemonMetadata:X,activeSession:ye,messages:Ie,notificationPermission:ee,savedTargets:lt,setArchiveSyncBusy:It,setArchiveSyncStatus:Ct,setSessions:A,setAdmin:yt,setErrorText:y,setNotificationPermission:wt,setStatusText:Ue,setMessages:le,setPairing:Ve,setDaemonMetadata:xt,setPhase:Qe,setActiveSessionId:D,setRenameTitle:V,setDetailsOpen:gt,setControlTab:Y,updateSessionListPreferences:ht,requestSessions:de,refreshDaemonMetadata:Ne,updateNotificationSettings:Pe,saveTargets:ut,listDirectory:me}),_n=o.useCallback(async e=>{const t=De.current;return t?.isConnected?(await t.request({action:"models.list",id:t.makeId("models"),agent:e})).options??[]:[]},[]),Bn=o.useCallback(async e=>{const t=De.current;if(!t?.isConnected)throw new Error(pt.webSocketNotConnected);return t.request({action:"sessions.gitMetadata",id:t.makeId("directoryGit"),cwds:[e]})},[De,pt.webSocketNotConnected]),Hn="denied"===ee||"unsupported"===ee,Wn=Boolean(X.version&&X.latestVersion&&tc(X.version,X.latestVersion)),Kn=v?.daemonId,Qn=Boolean(Kn&&J[Kn]),Un=Boolean(Kn&&Z[Kn]),Gn=function(e){const[t,n]=o.useState(null),s=e.clientRef.current,i=(t,n,s)=>{const i=n.map(t=>t.content||e.t.failedSendImages(t.images?.length??0)).join(" / ");return function(e,t,n,s){switch(dl(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 i=s instanceof Error?s.message:String(s);return s instanceof Zc?e.queueRequestRejected(t,n,i):e.queueRequestFailed(t,n,/timeout|timed out/i.test(i)?e.queueRequestTimeout:i)}(e.t,t,i,s)},r=e.activeSessionId,{busy:a,begin:c}=function(e,t){const n=o.useRef(new Set),[s,i]=o.useState([]),r=n=>n.client===e&&n.sessionId===t;return{busy:s.some(r),begin:()=>{if(!e||!t||[...n.current].some(r))return null;const s={client:e,sessionId:t};return n.current.add(s),i([...n.current]),()=>{n.current.delete(s),i([...n.current])}}}}(s,r),l=()=>e.clientRef.current===s,d=async()=>{l()&&await Promise.allSettled([e.requestSessions({force:!0,preserveLoaded:!0}),...e.activeSession?[e.requestHistory(e.activeSession,{refresh:!0})]:[]])},u=n=>t?.sessionId===r&&t.action===n&&t.runtime===e.activeSession?.runtime,h="daemonActive"===e.activeSession?.runtime.state&&!e.activeQueue.some(e=>e.waitingForStartup),p=!r||Boolean(e.pendingApprovals[r]||e.pendingQuestions[r]),m=!p&&!0===s?.supportsSessionSteer&&!!r&&e.respondingSessions.has(r)&&h&&!0===e.activeSession?.runtime.isResponding&&!u("guide"),f=!p&&h&&!u("sendNow")&&!0===s?.supportsQueueSendNow;return{busy:a,canGuide:m,canSendNow:f,onAction:async(t,o)=>{if(!r||!s?.isConnected||!("guide"===o?m:f))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 p=new Set;for(const n of u)e.setCachedMessageDelivery(r,n.clientMessageId,"sending",n);const g=t=>{p.add(t.clientMessageId),e.setCachedMessageDelivery(r,t.clientMessageId,"delivered")};try{if("sendNow"===o){if(await s.request({action:"session.queue.sendNow",id:s.makeId("queue_now"),sessionId:r,clientMessageIds:u.map(e=>e.clientMessageId)},{timeoutMs:hl}),!l())return;u.forEach(g)}else for(const t of u){if(!l())return;if(await s.request({action:"session.steer",id:s.makeId("queue_guide"),sessionId:r,clientMessageId:t.clientMessageId,message:t.content,images:t.images},{timeoutMs:hl}),!l())return;g(t),e.setPendingQueues(e=>({...e,[r]:(e[r]??[]).filter(e=>e.clientMessageId!==t.clientMessageId)}))}}catch(y){if(!l())return;const t=dl(y);let s=!1;for(const n of u)p.has(n.clientMessageId)||(s="delivered"!==e.setCachedMessageDelivery(r,n.clientMessageId,"failed")||s);t&&("no-active-turn"===t&&e.setRespondingSessions(e=>{const t=new Set(e);return t.delete(r),t}),e.activeSession&&n({sessionId:r,action:o,runtime:e.activeSession.runtime}),await d()),s&&l()&&e.activeSessionIdRef.current===r&&e.setErrorText(i("guide"===o?e.t.queueGuide:e.t.queueSendNow,u.filter(e=>!p.has(e.clientMessageId)),y))}finally{h()}},onCollect:async t=>{if(!r||!s?.isConnected)return;const n=new Set(t.map(e=>e.clientMessageId).filter(e=>!!e)),o=e.activeQueue.filter(e=>e.clientMessageId&&n.has(e.clientMessageId));if(o.length<2)return;const a=c();if(a){e.setErrorText(null);try{const t=await s.request({action:"session.queue.collect",id:s.makeId("queue_collect"),sessionId:r,clientMessageIds:o.map(e=>e.clientMessageId)},{timeoutMs:hl});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.setComposerDrafts(t=>{const n=cl(t,r,c(ll(t,r)));return e.composerDraftsRef.current=n,al(n),n}),e.activeSessionIdRef.current===r&&e.setDraft(c);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:mn(e),type:"image/*",size:0}))]}),e.setPendingQueues(e=>({...e,[r]:(e[r]??[]).filter(e=>!e.clientMessageId||!n.has(e.clientMessageId))}))}catch(u){if(!l())return;dl(u)&&await d(),l()&&e.activeSessionIdRef.current===r&&e.setErrorText(i(e.t.queueCollectAll,o,u))}finally{a()}}}}}(e);return{...e,setModel:Mt.setModel,setEffort:Mt.setEffort,setFastMode:Mt.setFastMode,queueControls:Gn,listSessionModels:_n,loadDirectoryGitMetadata:Bn,rewindMessage:c,handleSessionCommandResponse:jt,handleServerMessage:Rt,failedSend:Tt,dismissFailedSend:At,retryFailedSend:Nt,stagePendingSession:Et,sendDraft:Pt,sendQuickReply:Dt,respondApproval:Ft,respondQuestion:Lt,cancelQuestion:qt,setQuestionChoice:Ot,requestActiveAction:$t,interruptActiveSession:zt,retrySessions:Ht,updateApprovalMode:async e=>{Mt.setApprovalMode(e),ye&&!N[ye.sessionId]&&await Qt(e)},cancelQueuedTurn:Ut,setSessionPinned:Vt,setSessionArchived:Gt,deleteSession:Jt,updatePinned:Zt,updateArchived:rn,renameSession:on,runArchiveSync:un,skipArchiveSync:Cn,runAdminAction:Tn,exportActiveSession:An,clearPairing:Nn,setNotificationsEnabled:Pn,connectSavedTarget:Dn,forgetSavedTarget:Fn,openSessionDetails:Ln,editFolderTags:qn,browseFolder:On,copyResumeCommand:$n,resumeInTerminal:zn,notificationsBlocked:Hn,hasDaemonUpdate:Wn,activeDaemonId:Kn,archiveSynced:Qn,archiveSyncDismissed:Un}}();return r.jsx(aa,{scopeKey:ia(e.pairing?.daemonId,e.activeSessionId),children:r.jsx(zl,{workspace:e})},e.pairing?.daemonId??"unpaired")}},Symbol.toStringTag,{value:"Module"}));export{Si as $,q as A,O as B,$ as C,Ac as D,z as E,Jo as F,ae as G,_ as H,le as I,ne as J,ue as K,me as L,ee as M,_i as N,zi as O,Ce as P,Ei as Q,je as R,Pe as S,ze as T,Ai as U,Ti as V,Oi as W,He as X,Pi as Y,Yi as Z,Hi as _,Un as a,Vi as a0,Ui as a1,qi as a2,$i as a3,Ci as a4,Pc as a5,Ic as a6,gs as a7,Dc as a8,Rn as a9,Fc as aa,qc as ab,Oc as ac,yi as ad,io as ae,An as af,no as ag,Le as ah,ki as ai,_l as aj,Wn as b,mn as c,fn as d,U as e,lo as f,dt as g,js as h,ys as i,El as j,lt as k,In as l,te as m,vs as n,G as o,Is as p,Se as q,$n as r,nt as s,la as t,fs as u,sa as v,Ts as w,ls as x,Ec as y,Cn as z};
|