vibelet 1.2.235 → 1.2.237
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/vibelet.mjs +70 -38
- package/dist/web/assets/App-BY3qcVsa.css +1 -0
- package/dist/web/assets/App-CLTYkSvy.js +2 -0
- package/dist/web/assets/BrowserControlPanel-DJHj2vwI.js +1 -0
- package/dist/web/assets/{ChipGroup-BKnbqJkF.js → ChipGroup-DCvI-4nb.js} +1 -1
- package/dist/web/assets/FilesControlPanel-B-pqZWgH.js +1 -0
- package/dist/web/assets/{GlobalPendingDialog-D7F43nEr.js → GlobalPendingDialog-M2Dbntba.js} +1 -1
- package/dist/web/assets/{ImageViewer-YYuZb1G2.js → ImageViewer-ChfsVDQe.js} +1 -1
- package/dist/web/assets/{LanguageSettingsPanel-CG6ptWAj.js → LanguageSettingsPanel-P7H9JLtq.js} +1 -1
- package/dist/web/assets/{MarkdownModePanel-rXmtsjPb.js → MarkdownModePanel-B4zGnWRC.js} +1 -1
- package/dist/web/assets/NewSessionDialog-5JSvL7EJ.css +1 -0
- package/dist/web/assets/NewSessionDialog-Cw6WvtMR.js +1 -0
- package/dist/web/assets/{NotificationSettingsPanel-BW2YheO8.js → NotificationSettingsPanel-BAcpsROS.js} +1 -1
- package/dist/web/assets/ObsidianFileEditor-D2QjjPA3.css +1 -0
- package/dist/web/assets/RemoteLifeOSBlock-C46RjZWn.js +2 -0
- package/dist/web/assets/RemoteLifeOSBlock-DVhFsnY2.css +1 -0
- package/dist/web/assets/SessionTerminalPanel-pCQpIA-I.js +1 -0
- package/dist/web/assets/{ThemeSettingsPanel-CzNm33Ug.js → ThemeSettingsPanel-JUF7qFiS.js} +1 -1
- package/dist/web/assets/{abnfDiagram-VRR7QNED-DUxyOnUm.js → abnfDiagram-VRR7QNED-BUn7dXdz.js} +1 -1
- package/dist/web/assets/{arc-zRAAWsg9.js → arc-BW2CYTF6.js} +1 -1
- package/dist/web/assets/{architectureDiagram-ZJ3FMSHR-CANEZiNN.js → architectureDiagram-ZJ3FMSHR-QlFDuk3c.js} +1 -1
- package/dist/web/assets/{arrow-right-CF_MlpxP.js → arrow-right-BkDm1nz1.js} +1 -1
- package/dist/web/assets/{blockDiagram-677ZJIJ3-CQvH949j.js → blockDiagram-677ZJIJ3-Di1jkO8N.js} +1 -1
- package/dist/web/assets/{c4Diagram-LMCZKHZV-CO4XjrCG.js → c4Diagram-LMCZKHZV-BIE5S3xC.js} +1 -1
- package/dist/web/assets/channel-CgLW9Jd5.js +1 -0
- package/dist/web/assets/{chunk-2Q5K7J3B-DTXIfjoM.js → chunk-2Q5K7J3B-BZdVpYMm.js} +1 -1
- package/dist/web/assets/{chunk-32BRIVSS-BbmByeWb.js → chunk-32BRIVSS-DniTjuKD.js} +1 -1
- package/dist/web/assets/{chunk-5VM5RSS4-55dZW-IZ.js → chunk-5VM5RSS4-zU4WGQUt.js} +1 -1
- package/dist/web/assets/{chunk-EX3LRPZG-D-vCHfiB.js → chunk-EX3LRPZG-B_EGZWf3.js} +1 -1
- package/dist/web/assets/{chunk-JWPE2WC7-eBvTfuuu.js → chunk-JWPE2WC7-8R4xqfzd.js} +1 -1
- package/dist/web/assets/{chunk-MOJQB5TN-DYFPVu-x.js → chunk-MOJQB5TN-CmpQblce.js} +1 -1
- package/dist/web/assets/{chunk-RYQCIY6F-2xansKrF.js → chunk-RYQCIY6F-DrT9S-SZ.js} +1 -1
- package/dist/web/assets/{chunk-V7JOEXUC-TVnrO-Wr.js → chunk-V7JOEXUC-CEP012wY.js} +1 -1
- package/dist/web/assets/{chunk-VR4S4FIN-BVdWp9C5.js → chunk-VR4S4FIN-DcSau3fK.js} +1 -1
- package/dist/web/assets/{chunk-XXDRQBXY-CVwDg0PW.js → chunk-XXDRQBXY-BoXCe4yS.js} +1 -1
- package/dist/web/assets/classDiagram-OUVF2IWQ-BTbMtdvt.js +1 -0
- package/dist/web/assets/classDiagram-v2-EOCWNBFH-BTbMtdvt.js +1 -0
- package/dist/web/assets/clsx-DNJkZJoV.js +1 -0
- package/dist/web/assets/{collectMessageImages-Bd_KUcjR.js → collectMessageImages-CUMbRGiF.js} +1 -1
- package/dist/web/assets/{cose-bilkent-JH36ORCC-q0D5dKoq.js → cose-bilkent-JH36ORCC-DKrqebqO.js} +1 -1
- package/dist/web/assets/{cynefin-VYW2F7L2-C0iRs1H7.js → cynefin-VYW2F7L2-bQLn5vS2.js} +1 -1
- package/dist/web/assets/{cynefinDiagram-TSTJHNR4-BDoOhj6i.js → cynefinDiagram-TSTJHNR4-ezXQFC9o.js} +1 -1
- package/dist/web/assets/{dagre-VKFMJZFB-BhAVeafA.js → dagre-VKFMJZFB-CDV8r_Bq.js} +1 -1
- package/dist/web/assets/{diagram-FQU43EPY-19K6IibX.js → diagram-FQU43EPY-BICapB67.js} +1 -1
- package/dist/web/assets/{diagram-G47NLZAW-BKaIX5yb.js → diagram-G47NLZAW-TuVLjwN6.js} +1 -1
- package/dist/web/assets/{diagram-NH7WQ7WH-C0ly0NEX.js → diagram-NH7WQ7WH-B3dBWl3F.js} +1 -1
- package/dist/web/assets/{diagram-OA4YK3LP-CUkW2x74.js → diagram-OA4YK3LP-DeIQlN-6.js} +1 -1
- package/dist/web/assets/{diagram-WEI45ONY-DwdeWCAC.js → diagram-WEI45ONY-DZcwYcod.js} +1 -1
- package/dist/web/assets/{ebnfDiagram-CCIWWBDH-BsOwHiWw.js → ebnfDiagram-CCIWWBDH-4KcDP5Zj.js} +1 -1
- package/dist/web/assets/{erDiagram-Q63AITRT-qDA1uJgc.js → erDiagram-Q63AITRT-D4KIuggo.js} +1 -1
- package/dist/web/assets/{file-editor-FileCodeEditor-e_cHRyn4.js → file-editor-FileCodeEditor-Dn3f5PUl.js} +1 -1
- package/dist/web/assets/file-editor-ObsidianCodeEditor-BgXz3c5Z.js +48 -0
- package/dist/web/assets/{file-editor-ObsidianFileEditor-ByRz9GFK.js → file-editor-ObsidianFileEditor-CM9ucogo.js} +1 -1
- package/dist/web/assets/{flowDiagram-23GEKE2U-CWT82Psi.js → flowDiagram-23GEKE2U-BeHvede_.js} +1 -1
- package/dist/web/assets/{folder-plus-BuIbO5rO.js → folder-plus-BVS_Q2fe.js} +1 -1
- package/dist/web/assets/{ganttDiagram-NO4QXBWP-BwkNz011.js → ganttDiagram-NO4QXBWP-DrwEUqQX.js} +1 -1
- package/dist/web/assets/{gitGraphDiagram-IHSO6WYX-Dnd5wgTd.js → gitGraphDiagram-IHSO6WYX-Cm7T6TME.js} +1 -1
- package/dist/web/assets/{highlighted-body-TPN3WLV5-B-MOqwqs.js → highlighted-body-TPN3WLV5-DJAPujEc.js} +1 -1
- package/dist/web/assets/{index-BBUiU9K_.css → index-B3XA1dVd.css} +1 -1
- package/dist/web/assets/index-CX8KV6EH.js +2 -0
- package/dist/web/assets/{index-CMunTdjK.js → index-CapF4a8Y.js} +1 -1
- package/dist/web/assets/{infoDiagram-FWYZ7A6U-CsLiRudn.js → infoDiagram-FWYZ7A6U-CgeulgC-.js} +1 -1
- package/dist/web/assets/{ishikawaDiagram-FXEZZL3T-CQ2VItcU.js → ishikawaDiagram-FXEZZL3T-x4glLaWe.js} +1 -1
- package/dist/web/assets/{journeyDiagram-5HDEW3XC-20HUCiMA.js → journeyDiagram-5HDEW3XC-DHGcWBDR.js} +1 -1
- package/dist/web/assets/{kanban-definition-HUTT4EX6-BlFKyFGS.js → kanban-definition-HUTT4EX6-CqYivdRn.js} +1 -1
- package/dist/web/assets/{linear-DcEW9U4V.js → linear-BKnAjtJN.js} +1 -1
- package/dist/web/assets/mermaid-O7DHMXV3-B3e3pugB.js +2 -0
- package/dist/web/assets/{mermaid-O7DHMXV3-DQjp4PWc.css → mermaid-O7DHMXV3-CgN6EJ9a.css} +1 -1
- package/dist/web/assets/{mermaid.core-CKL91szq.js → mermaid.core-CTf8qcol.js} +2 -2
- package/dist/web/assets/{mindmap-definition-LN4V7U3C-D0VoTzwD.js → mindmap-definition-LN4V7U3C-NQnwG7IB.js} +1 -1
- package/dist/web/assets/{pegDiagram-2B236MQR-CefWKSzd.js → pegDiagram-2B236MQR-jfLjzzsG.js} +1 -1
- package/dist/web/assets/{pieDiagram-ENE6RG2P-DOqFxLRf.js → pieDiagram-ENE6RG2P-CgxRYPCf.js} +1 -1
- package/dist/web/assets/{quadrantDiagram-ABIIQ3AL-9deKwbNB.js → quadrantDiagram-ABIIQ3AL-0zHgV223.js} +1 -1
- package/dist/web/assets/{railroadDiagram-RFXS5EU6-DChzO2BS.js → railroadDiagram-RFXS5EU6-CQqf55Rk.js} +1 -1
- package/dist/web/assets/{requirementDiagram-TGXJPOKE-BxFcGapQ.js → requirementDiagram-TGXJPOKE-Dm9cKzLN.js} +1 -1
- package/dist/web/assets/{sankeyDiagram-HTMAVEWB-DbF_hrnW.js → sankeyDiagram-HTMAVEWB-BRBxR71X.js} +1 -1
- package/dist/web/assets/{sequenceDiagram-DBY2YBRQ-CnZJ1pvx.js → sequenceDiagram-DBY2YBRQ-DxVBmbfg.js} +1 -1
- package/dist/web/assets/{sizeCapture-X5ZJPWSS-eGmJC2ld.js → sizeCapture-X5ZJPWSS-DNNwG-Sh.js} +1 -1
- package/dist/web/assets/{stateDiagram-2N3HPSRC-C7xdkcAK.js → stateDiagram-2N3HPSRC-C8KGcqhJ.js} +1 -1
- package/dist/web/assets/stateDiagram-v2-6OUMAXLB-Bk6KXy8V.js +1 -0
- package/dist/web/assets/{swimlanes-5IMT3BWC-Bs93ZHOO.js → swimlanes-5IMT3BWC-CRe3WzWn.js} +2 -2
- package/dist/web/assets/swimlanesDiagram-G3AALYLV-DsL6VYKg.js +1 -0
- package/dist/web/assets/{timeline-definition-FHXFAJF6-BJoNIKQC.js → timeline-definition-FHXFAJF6-CQqiFe9j.js} +1 -1
- package/dist/web/assets/{vennDiagram-L72KCM5P-DKRz7LAp.js → vennDiagram-L72KCM5P-C_5c80TB.js} +1 -1
- package/dist/web/assets/{wardleyDiagram-EHGQE667-CzSi7t19.js → wardleyDiagram-EHGQE667-DJ2RRwLP.js} +1 -1
- package/dist/web/assets/{xychartDiagram-FW5EYKEG-CKOX-yaI.js → xychartDiagram-FW5EYKEG-MgVCQknE.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-CIWR_iGV.css +0 -1
- package/dist/web/assets/App-DenA3QIb.js +0 -2
- package/dist/web/assets/BrowserControlPanel-mCDy7Hcz.js +0 -1
- package/dist/web/assets/FilesControlPanel-BAguf3b6.js +0 -1
- package/dist/web/assets/NewSessionDialog-B_YNEU3D.css +0 -1
- package/dist/web/assets/NewSessionDialog-Pc6Vz8cD.js +0 -1
- package/dist/web/assets/ObsidianFileEditor-BM1om3jV.css +0 -1
- package/dist/web/assets/RemoteLifeOSBlock-BGPY9LfG.css +0 -1
- package/dist/web/assets/RemoteLifeOSBlock-I33jMQfs.js +0 -2
- package/dist/web/assets/TerminalControlPanel-CdYTgewy.js +0 -1
- package/dist/web/assets/channel-dQPqMnFx.js +0 -1
- package/dist/web/assets/classDiagram-OUVF2IWQ-BjI_mxx3.js +0 -1
- package/dist/web/assets/classDiagram-v2-EOCWNBFH-BjI_mxx3.js +0 -1
- package/dist/web/assets/clsx-DaxbA7nq.js +0 -1
- package/dist/web/assets/file-editor-ObsidianCodeEditor-DI7f8suj.js +0 -48
- package/dist/web/assets/index-CdwajBhR.js +0 -2
- package/dist/web/assets/mermaid-O7DHMXV3-CKUeIBKi.js +0 -2
- package/dist/web/assets/stateDiagram-v2-6OUMAXLB-Cyth9z2I.js +0 -1
- package/dist/web/assets/swimlanesDiagram-G3AALYLV-B5jki7rr.js +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid-O7DHMXV3-B3e3pugB.js","assets/index-CX8KV6EH.js","assets/index-B3XA1dVd.css","assets/index-CapF4a8Y.js","assets/collectMessageImages-CUMbRGiF.js","assets/clsx-DNJkZJoV.js","assets/index-1M7_HtDu.js","assets/mermaid-O7DHMXV3-CgN6EJ9a.css","assets/ImageViewer-ChfsVDQe.js","assets/arrow-right-BkDm1nz1.js","assets/ImageViewer-Fya-Uufq.css","assets/BrowserControlPanel-DJHj2vwI.js","assets/SessionTerminalPanel-pCQpIA-I.js","assets/FilesControlPanel-B-pqZWgH.js","assets/folder-plus-BVS_Q2fe.js","assets/FilesControlPanel-DQpsZVYc.css","assets/LanguageSettingsPanel-P7H9JLtq.js","assets/ChipGroup-DCvI-4nb.js","assets/ThemeSettingsPanel-JUF7qFiS.js","assets/NotificationSettingsPanel-BAcpsROS.js","assets/MarkdownModePanel-B4zGnWRC.js","assets/MarkdownModePanel-D73Xg4At.css","assets/file-editor-FileCodeEditor-Dn3f5PUl.js","assets/file-editor-index-C6CU7Fik.js","assets/FileCodeEditor-CW9KijoU.css","assets/file-editor-ObsidianCodeEditor-BgXz3c5Z.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-C46RjZWn.js","assets/RemoteLifeOSBlock-DVhFsnY2.css","assets/katex-uyR15voz.js","assets/marked.esm-BBjA1da9.js","assets/ObsidianCodeEditor-eECvmZRy.css","assets/file-editor-ObsidianFileEditor-CM9ucogo.js","assets/purify.es-BNLkGfTg.js","assets/isArrayLikeObject-C958pSF-.js","assets/_baseMerge-CwDZKfvJ.js","assets/_initCloneObject-C781OlVa.js","assets/ObsidianFileEditor-D2QjjPA3.css","assets/NewSessionDialog-Cw6WvtMR.js","assets/NewSessionDialog-5JSvL7EJ.css","assets/GlobalPendingDialog-M2Dbntba.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as e,i as t,h as n,b as s,d as r,j as i,r as o,f as a,S as c,m as l,t as d,n as u,o as h,p,u as f,_ as m,D as g,E as v,q as y,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 E,H as M,I as T}from"./index-CX8KV6EH.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"}]]),L=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"}]]),F=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"}]]),$=e("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),z=e("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),H=e("chevron-up",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]),B=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"}]]),U=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"}]]),W=e("clock-3",[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),K=e("cloud-check",[["path",{d:"m17 15-5.5 5.5L9 18",key:"15q87x"}],["path",{d:"M5 17.743A7 7 0 1 1 15.71 10h1.79a4.5 4.5 0 0 1 1.5 8.742",key:"9ho6ki"}]]),V=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"}]]),Q=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"}]]),G=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"}]]),J=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"}]]),Z=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"}]]),X=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"}]]),ee=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"}]]),te=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"}]]),ne=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"}]]),se=e("folder-search",[["path",{d:"M10.7 20H4a2 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.9H20a2 2 0 0 1 2 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]]),re=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"}]]),ie=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"}]]),oe=e("gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]),ae=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"}]]),ce=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"}]]),le=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"}]]),de=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"}]]),ue=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"}]]),he=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"}]]),pe=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"}]]),fe=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"}]]),me=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"}]]),ge=e("list-ordered",[["path",{d:"M11 5h10",key:"1cz7ny"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 19h10",key:"11t30w"}],["path",{d:"M4 4h1v5",key:"10yrso"}],["path",{d:"M4 9h2",key:"r1h2o0"}],["path",{d:"M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02",key:"xtkcd5"}]]),ve=e("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),ye=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"}]]),be=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"}]]),xe=e("message-square",[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]]),we=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"}]]),Se=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"}]]),ke=e("panel-left",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]),Ie=e("panel-right",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]),Ce=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"}]]),je=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"}]]),Re=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"}]]),Ee=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"}]]),Me=e("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),Te=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"}]]),Ae=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"}]]),Ne=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"}]]),Pe=e("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]),De=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"}]]),Le=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"}]]),Fe=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"}]]),qe=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"}]]),Oe=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"}]]),_e=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"}]]),$e=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"}]]),ze=e("square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]),He=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"}]]),Be=e("terminal",[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]]),Ue=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"}]]),We=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"}]]),Ke=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"}]]),Ve=e("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Qe=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"}]]),Ge="vibelet.shortcuts.changed",Je="vibelet.workspace.command",Ze=[{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:"browserAddress",zh:"聚焦浏览器地址栏",en:"Focus browser address",default:"mod+l"},{id:"browserCopyUrl",zh:"复制浏览器地址",en:"Copy browser address",default:"mod+shift+c"},{id:"newTab",zh:"新建终端 / 浏览器标签",en:"New terminal / browser tab",default:"mod+t"},{id:"previousTab",zh:"上一个标签",en:"Previous tab",default:"mod+shift+["},{id:"nextTab",zh:"下一个标签",en:"Next tab",default:"mod+shift+]"},{id:"closeTab",zh:"关闭当前标签",en:"Close current tab",default:"mod+w"},{id:"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 Xe(){return/Mac|iPhone|iPad/.test(navigator.platform)}const Ye={BracketLeft:"[",BracketRight:"]",Comma:",",Period:".",Slash:"/",Backslash:"\\",Minus:"-",Equal:"=",Space:"space"};function et(e,t=Xe()){const n=Ye[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 tt(e,t=Xe()){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 nt(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":Ze.find(s=>s.id!==e&&function(e,t={}){return t[e]??Ze.find(t=>t.id===e).default}(s.id,n)===t)?.id??null:null}const st="vibelet.web.shortcuts";function rt(){try{const e=JSON.parse(t().getItem(st)||"{}");return Object.fromEntries(Ze.filter(t=>"string"==typeof e?.[t.id]).map(t=>[t.id,e[t.id]]))}catch{return{}}}function it(e,t=rt()){return t[e]??("closeTab"===e&&"browser"===n().kind?"mod+alt+w":Ze.find(t=>t.id===e).default)}function ot(e,t){const n=it(t);return n?`${e} (${tt(n)})`:e}const at="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",ct="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 lt(){const e=s(r().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 dt(){const e=lt();return i.jsxs("section",{className:"mobile-companion-panel control-section",children:[i.jsx("p",{className:"mobile-companion-free",children:e.free}),i.jsx("h2",{children:e.title}),i.jsx("p",{children:e.description}),i.jsx("div",{className:"mobile-companion-downloads",children:[{label:e.ios,qr:ct,url:"https://apps.apple.com/app/id6761245790"},{label:e.android,qr:at,url:"https://www.feishu.cn/file/RUnbb7INMocEFjxj5AWcC7WEn6d"}].map(t=>i.jsxs("div",{children:[i.jsx("img",{src:t.qr,alt:`${t.label} · ${e.download}`,width:"140",height:"140"}),i.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",children:t.label})]},t.url))}),i.jsx("p",{children:e.pairing}),i.jsx("p",{className:"mobile-companion-hint",children:e.pro})]})}function ut({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=lt().title;return a.createPortal(i.jsx("div",{className:"mobile-companion-backdrop",onClick:t=>{t.target===t.currentTarget&&e()},children:i.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]")),r=s[0],i=s.at(-1);!n.shiftKey||document.activeElement!==r&&document.activeElement!==t.current?n.shiftKey||document.activeElement!==i||(n.preventDefault(),r?.focus()):(n.preventDefault(),i?.focus())},children:[i.jsx("button",{type:"button",className:"icon-button mobile-companion-close","aria-label":lt().close,title:lt().close,onClick:e,children:i.jsx(Ve,{"aria-hidden":"true"})}),i.jsx(dt,{})]})}),document.body)}function ht({activeSession:e,client:t,busy:s,controlsOpen:r,pendingCount:l=0,t:d,onOpenControls:u,onRefreshSessions:h,onRestoreSnapshot:p,onToggleArchived:f,onTogglePinned:m,onViewChanges:g}){const[v,y]=o.useState(!1),[b,x]=o.useState(!1),w=o.useRef(null);o.useEffect(()=>{if(!b)return;const e=e=>{e.target instanceof Node&&!w.current?.contains(e.target)&&x(!1)},t=e=>{"Escape"===e.key&&x(!1)};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[b]);const S=e=>{x(!1),e()},k=n(),I=i.jsxs("div",{className:"header-actions",children:[e&&k.renderSessionShare?.(e,t),("desktop"!==k.kind||l>0)&&i.jsxs("button",{type:"button",className:"icon-button header-pending-button","aria-label":d.pendingActionCount(l),title:d.pendingActionCount(l),onClick:()=>window.dispatchEvent(new Event("vibelet.pending.open")),children:[i.jsx(O,{"aria-hidden":"true"}),l>0&&i.jsx("span",{className:"header-pending-count","aria-hidden":"true",children:l})]}),v&&i.jsx(ut,{onClose:()=>y(!1)}),e?null:i.jsx("button",{"aria-label":d.refreshSessions,className:"icon-button",onClick:h,title:d.refreshSessions,type:"button",children:i.jsx(Te,{"aria-hidden":"true"})}),i.jsx("button",{"aria-expanded":r,"aria-label":r?d.collapseControlsSidebar:d.workspaceTools,title:ot(r?d.collapseControlsSidebar:d.workspaceTools,"rightSidebar"),className:"header-tool-button",onClick:u,type:"button",children:i.jsx(Ie,{"aria-hidden":"true"})}),e||k.openSettings?i.jsxs("div",{className:"header-more-wrap",ref:w,children:[i.jsx("button",{"aria-expanded":b,"aria-haspopup":"menu","aria-label":d.moreActions,className:"icon-button",onClick:()=>x(e=>!e),title:d.moreActions,type:"button",children:i.jsx(Z,{"aria-hidden":"true"})}),b?i.jsxs("div",{className:"header-action-menu",role:"menu",children:["desktop"===k.kind&&0===l&&i.jsxs("button",{role:"menuitem",type:"button",onClick:()=>S(()=>window.dispatchEvent(new Event("vibelet.pending.open"))),children:[i.jsx(O,{"aria-hidden":"true"}),i.jsx("span",{children:d.pendingActionCount(l)})]}),e&&i.jsxs(i.Fragment,{children:[i.jsxs("button",{onClick:()=>S(()=>g(e.sessionId)),role:"menuitem",type:"button",children:[i.jsx(ae,{"aria-hidden":"true"}),i.jsx("span",{children:d.viewChanges})]}),i.jsxs("button",{disabled:s,onClick:()=>S(m),role:"menuitem",type:"button",children:[i.jsx(Re,{"aria-hidden":"true"}),i.jsx("span",{children:e.pinned?d.unpin:d.pin})]}),i.jsxs("button",{disabled:s,onClick:()=>S(f),role:"menuitem",type:"button",children:[i.jsx(P,{"aria-hidden":"true"}),i.jsx("span",{children:e.archived?d.unarchive:d.archive})]}),i.jsxs("button",{onClick:()=>S(p),role:"menuitem",type:"button",children:[i.jsx(Ae,{"aria-hidden":"true"}),i.jsx("span",{children:d.restoreSnapshot})]})]}),i.jsxs("button",{role:"menuitem",type:"button",onClick:()=>S(()=>y(!0)),children:[i.jsx(c,{"aria-hidden":"true"}),i.jsx("span",{children:lt().title})]}),i.jsxs("button",{onClick:()=>S(h),role:"menuitem",type:"button",children:[i.jsx(Te,{"aria-hidden":"true"}),i.jsx("span",{children:d.refreshSessions})]})]}):null]}):null]}),C=k.toolbarTarget?.("right");return C?a.createPortal(I,C):I}function pt(e,t,n,s,r,i,a){const c=JSON.stringify([t,n,s,r]),[l,d]=o.useState(null);if(o.useEffect(()=>{if("codex"!==t||!e)return;let r,i=!1,o=0,a=0,l=!1,u=!1;const h=()=>{i||u||l||void 0!==r||a>=5||(r=setTimeout(g,1e3*2**Math.max(0,a-1)))},p=t=>{u=Boolean(t?.defaultModel),d({client:e,key:c,state:t,loading:!u&&a<5})};d({client:e,key:c,state:null,loading:!0});const f=e.onMessage(e=>{i||"session.model"!==e.type||e.sessionId!==s||(o++,clearTimeout(r),r=void 0,p(e),h())}),m=e.onClose(()=>{i=!0,clearTimeout(r),d({client:e,key:c,state:null,loading:!1})});async function g(){if(r=void 0,i||!e)return;l=!0,a++;const t=o;try{const r=await e.request({action:"model.status",id:e.makeId("model-status"),...s?{sessionId:s}:{cwd:n}},{timeoutMs:15e3});i||o!==t||p(r)}catch{i||o!==t||p(null)}finally{l=!1,h()}}return r=setTimeout(g,200),()=>{i=!0,clearTimeout(r),f(),m()}},[e,t,n,s,r,c]),"codex"!==t)return i;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 i.some(e=>""===e.value)?i.map(e=>""===e.value?{...e,...h}:e):[h,...i]}function ft({title:e,hint:t}){return i.jsxs("div",{className:"empty-state compact",children:[i.jsx(qe,{"aria-hidden":"true"}),i.jsx("h2",{children:e}),i.jsx("p",{children:t})]})}function mt(e,t){return!t.altKey&&(!(!t.metaKey&&!t.ctrlKey)||("enter"===e?!t.shiftKey:"shiftEnter"===e&&t.shiftKey))}const gt=/^[A-Za-z][A-Za-z0-9_-]*$/,vt=[{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 yt(e){return vt.filter(t=>!e||t.agents.includes(e))}function bt(e){return e.trim().toLowerCase()}function xt(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&&!gt.test(n)?null:{start:0,end:e.length,keyword:bt(n)}}function wt(e,t){return e.name===t?0:e.name.startsWith(t)?1:e.name.includes(t)?2:3}function St(e,t){const n=t.length>0,s=n&&!/^\s/.test(t),r=Boolean(e.argsHint&&!n);return`/${e.name}${r||s?" ":""}`}function kt(e,t){const n=e.trim();if(!n.startsWith("/")||n.startsWith("//"))return null;const s=/^\/([A-Za-z][A-Za-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(n);if(!s)return null;const r=bt(s[1]??""),i=yt(t).find(e=>e.name===r);if(!i)return null;const o=s[2]?.trim()??"";switch(i.commandName){case"clear":return{raw:n,command:{name:"clear"}};case"new":return{raw:n,command:{name:"new"}};case"exit":return{raw:n,command:{name:"exit"}};case"compact":return{raw:n,command:{name:"compact"}};case"goal":{const e=o.toLowerCase();return o&&"status"!==e&&"show"!==e&&"usage"!==e&&"help"!==e?"clear"===e||"reset"===e?{raw:n,command:{name:"goal",operation:"clear"}}:"pause"===e||"paused"===e?{raw:n,command:{name:"goal",operation:"pause"}}:"resume"===e||"active"===e?{raw:n,command:{name:"goal",operation:"resume"}}:{raw:n,command:{name:"goal",operation:"set",objective:o}}:{raw:n,command:{name:"goal",operation:"status"}}}}}function It(e){return"subscriptionRequired"===e?"Error: Agent commands require an active Pro subscription.":`Error: ${e||"Command failed."}`}const Ct=/^[A-Za-z_][A-Za-z0-9._:-]*$/,jt=/(?:^|\s)\$([A-Za-z_][A-Za-z0-9._:-]*|)$/;function Rt(e){return e.trim().toLowerCase()}function Et(e){const t=e.trim(),n=/^\$([A-Za-z_][A-Za-z0-9._:-]*)(?:\s+([\s\S]*))?$/.exec(t);return n?{name:Rt(n[1]??""),...n[2]?.trim()?{args:n[2].trim()}:{}}:null}function Mt(e){const t=jt.exec(e);if(!t||t.index+t[0].length!==e.length)return null;const n=t[1]??"";if(n&&!Ct.test(n))return null;const s=t[0].lastIndexOf("$");return{start:t.index+s,end:e.length,keyword:Rt(n)}}const Tt=new RegExp("((?:~/|/|\\.{1,2}/|[A-Za-z0-9._-]+/)[^\\n`<>\"')\\]},。!?;:、]*?\\.(?:png|jpg|jpeg|gif|webp|svg|heic|heif)(?::\\d+(?::\\d+)?|#[^\\s`<>\"')\\]},。!?;:、]+)?)","gi"),At=[".png",".jpg",".jpeg",".gif",".webp",".svg",".heic",".heif"],Nt="\\s`<>\"')\\]},。!?;:、",Pt="`<>\"')\\]},。!?;:、\\n\\r\\t",Dt=new RegExp(`(^|[\\s([{>])((?:~\\/|\\/|\\.{1,2}\\/)[^${Nt}]+|[A-Za-z0-9._-]+(?:\\/[A-Za-z0-9._-]+)+(?:\\.[A-Za-z0-9._-]+)?\\/?)`,"g"),Lt=new RegExp(`(^|[\\s([{>])((?=[^${Pt}]*\\/)[^${Pt}]+?\\.[A-Za-z0-9._-]+(?::\\d+(?::\\d+)?|#[^${Nt}]+)?)(?=$|[${Nt}])`,"g");function Ft(e){let t=e;for(;/[.,!?;:,。!?;:、]+$/.test(t);)t=t.slice(0,-1);return t}function qt(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 Ot(e){let t=Ft(e.trim());if(!t)return"";const n=t.indexOf("#");if(n>0){const e=t.slice(0,n);qt(e,{allowBareFilename:!0})&&(t=e)}const s=t.match(/^(.*?)(:\d+(?::\d+)?)$/);if(s){const e=s[1]??"";qt(e,{allowBareFilename:!0})&&(t=e)}return Ft(t)}function _t(e,t){return e.start<t.end&&t.start<e.end}function $t(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 zt(e){if($t(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($t(n))return{start:e.start+t,end:e.end,rawCandidate:n}}return e}function Ht(e,t){return qt(Ot(e),t)}function Bt(e){const t=Ot(e).toLowerCase();return Ht(t,{allowBareFilename:!0})&&At.some(e=>t.endsWith(e))}function Ut(e){return/^[a-zA-Z0-9._/@~-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Wt(e){return Boolean(e.sessionId.trim())&&!e.sessionId.startsWith("pending_")}function Kt(e,t={}){return Wt(e)?`cd ${Ut(e.cwd||".")} && ${function(e,t={}){if(!Wt(e))return"";const n=e.approvalMode??e.observedApprovalMode,s="claude"===e.agent?["claude","--resume",e.sessionId]:["codex","resume",e.sessionId],r=t.codexBackend??e.runtime?.codexBackend;return"codex"!==e.agent||"standalone"!==r&&(r||"@vibelet/cli"!==e.originator)||s.push("--no-daemon"),"autoApprove"===n?s.push("claude"===e.agent?"--dangerously-skip-permissions":"--dangerously-bypass-approvals-and-sandbox"):"claude"===e.agent&&"acceptEdits"===n&&s.push("--permission-mode","acceptEdits"),[...t.vibeletChannel?["npx",`vibelet@${t.vibeletChannel}`]:[],...s].map(Ut).join(" ")}(e,t)}`:""}const Vt="vibelet.web.notificationSettings",Qt={enabled:!1,approvals:!0,questions:!0,replies:!0,hiddenOnly:!0};function Gt(e=t()){try{const t=e.getItem(Vt);if(!t)return{...Qt};const n=JSON.parse(t);return Vn(n)?{enabled:"boolean"==typeof n.enabled?n.enabled:Qt.enabled,approvals:"boolean"==typeof n.approvals?n.approvals:Qt.approvals,questions:"boolean"==typeof n.questions?n.questions:Qt.questions,replies:"boolean"==typeof n.replies?n.replies:Qt.replies,hiddenOnly:"boolean"==typeof n.hiddenOnly?n.hiddenOnly:Qt.hiddenOnly}:{...Qt}}catch{return{...Qt}}}function Jt(e=("undefined"==typeof Notification?void 0:Notification)){return n().notifications?n().notifications.permission():e?.permission??"unsupported"}function Zt(e,t){return t?.length?e.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").trim():e}function Xt(e){return"user"===e.role?Zt(e.content,e.images):e.content}function Yt(e,t){return e.role===t.role&&(e.type??"message")===(t.type??"message")&&Xt(e)===Xt(t)&&JSON.stringify(e.images??[])===JSON.stringify(t.images??[])&&e.toolName===t.toolName&&JSON.stringify(e.toolInput)===JSON.stringify(t.toolInput)}function en(e,t){if(t.historyKey?.startsWith("client:")||!e.historyKey?.startsWith("client:")||!e.localClientMessageId||"user"!==e.role||"user"!==t.role||!Yt(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 tn(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??"")&&Yt(e,t)}function nn(e){for(let t=e.length-1;t>=0;t-=1)if("user"===e[t]?.role)return t;return-1}function sn(e,t,n){let s=e.slice();const r=new Set,i=s.flatMap((e,t)=>e.localClientMessageId&&e.historyKey?.startsWith("client:")?[t]:[]),o=new Map;i.length&&s.forEach((e,t)=>{const n=Date.parse(e.timestamp??"");if(e.historyKey?.startsWith("client:")||!Number.isFinite(n))return;const s=`${e.role}:${n}`,r=o.get(s)??[];r.push(t),o.set(s,r)});for(const d of t){const e=o.get(`${d.role}:${Date.parse(d.timestamp??"")}`)?.find(e=>tn(s[e],d))??-1;if(e<0||s[e].localClientMessageId)continue;const t=i.find(e=>!r.has(e)&&en(s[e],d)&&Date.parse(s[e].timestamp)<=Date.parse(d.timestamp));if(void 0===t)continue;const n=s[e].historyKey;s[e]={...s[t],...s[e],localDelivery:"delivered"},n||delete s[e].historyKey,r.add(t)}r.size&&(s=s.filter((e,t)=>!r.has(t)));const a=new Map,c=[];s.forEach((e,t)=>{e.historyKey&&!a.has(e.historyKey)&&a.set(e.historyKey,t),e.historyKey&&!e.historyKey.startsWith("client:")||c.push(t)});const l=new Set;for(const d of t){const e=d.historyKey?a.get(d.historyKey)??-1:-1;if(e>=0){d.delivery&&(s[e]={...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)&&(!!tn(t,d)||!!en(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===nn(s)&&s.slice(e+1).every(e=>"assistant"!==e.role||"info"===e.type||e.liveReply)&&Yt(t,d))))})??-1;if(t<0)d.historyKey&&a.set(d.historyKey,s.length),d.historyKey&&!d.historyKey.startsWith("client:")||c.push(s.length),s.push({...d});else{l.add(t);const e=s[t].historyKey;e&&e!==d.historyKey&&a.delete(e);const r=!d.historyKey&&en(s[t],d);s[t]={...s[t],...d},r&&(delete s[t].historyKey,s[t].localDelivery="delivered"),s[t].historyKey&&a.set(s[t].historyKey,t),s[t].localClientMessageId&&d.historyKey&&!d.historyKey.startsWith("client:")&&(s[t].localDelivery="delivered"),delete s[t].liveReply,n?.(d,s[t])}}return s}function rn(e){const t=e.at(-1);return"assistant"===t?.role&&"info"!==t.type?[...e.slice(0,-1),{...t,liveReply:!0}]:e.slice()}function on(e,t){if(!t?.trim())return e.slice();let n=-1;for(let a=e.length-1;a>=0;a--)if("user"===e[a]?.role){n=a;break}const s=[];for(let a=n+1;a<e.length;a++)"assistant"===e[a]?.role&&"info"!==e[a]?.type&&s.push(a);const r=s.at(-1),i=void 0!==r&&e.slice(r+1).some(e=>"tool"===e.role);let o=t;for(const a of s){if(a===r&&!i)break;const t=e[a].content;if(t.trim().startsWith(o.trim()))return e.slice();if(!t||!o.startsWith(t))break;if(o=o.slice(t.length),!o.trim())return e.slice()}if(void 0!==r&&!i){const t=e[r],n=t.content.trim().startsWith(o.trim())?t.content:o,s=e.slice();return s[r]={...t,content:n},rn(s)}return rn([...e,{role:"assistant",content:o,timestamp:(new Date).toISOString()}])}function an(e,t,n){const s=n?.[e.sessionId];return void 0!==s?s:"boolean"==typeof e.pinned?e.pinned:Boolean(t?.[e.sessionId])}function cn(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 ln(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 dn(e,t,n){if(0===t.length)return e;const s=new Set(t),r=[];for(const i of t){const e=n.get(i);e&&r.push(e)}for(const i of e)s.has(i.sessionId)||r.push(i);if(r.length!==e.length)return r;for(let i=0;i<e.length;i+=1)if(r[i]!==e[i])return r;return e}function un(e,t=Date.now(),n=l){if(!e)return n.timeUnknown;const s=Date.parse(e);if(!Number.isFinite(s))return n.timeUnknown;const r=t-s,i=36e5,o=24*i;return r<6e4?n.timeNow:r<i?n.timeMinutesAgo(Math.floor(r/6e4)):r<o?n.timeHoursAgo(Math.floor(r/i)):n.timeDaysAgo(Math.floor(r/o))}function hn(e,t){return"info"===e.type?t.messageInfoRole:{user:t.messageUserRole,assistant:t.messageAssistantRole,tool:t.messageToolRole}[e.role]}const pn="<oai-mem-citation>";function fn(e){let t,n=0;for(const s of e.split("\n")){const r=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(s);if(r){const e=r[1][0];t?e===t.marker&&r[1].length>=t.length&&!r[2].trim()&&(t=void 0):t={marker:e,length:r[1].length}}else if(!t){const t=s.replace(/^ {0,3}/,""),r=t.startsWith("<oai-mem")&&pn.startsWith(t);if(t.startsWith(pn)||r){const t=e.slice(n).trimStart(),s=t.indexOf("</oai-mem-citation>");if(s<0||!t.slice(s+19).trim())return e.slice(0,n).trimEnd()}}n+=s.length+1}return e}const mn=e=>e.replace(/\r\n?/g,"\n").trim(),gn=/^\[Attached image: ([^\n]+)\]$/gm;function vn(e){return"codex"===e?"Codex":"claude"===e?"Claude":e}function yn(e){const t=[],n=new Set;for(const s of e.matchAll(gn)){const e=s[1];e&&0!==e.trim().length&&!n.has(e)&&(n.add(e),t.push(e))}return t}function bn(e,t){if("assistant"===e.type)return mn(e.content);const n=mn(function(e){return e.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").replace(/\n{3,}/g,"\n\n").trim()}(e.content)),s=function(e){const t=new Set,n=[];for(const s of e)0===s.trim().length||t.has(s)||(t.add(s),n.push(s));return n}([...yn(e.content),...e.images??[]]).map(e=>`- ${t.attachedImage}: \`${e}\``);return n&&s.length>0?`${n}\n\n${s.join("\n")}`:n||s.join("\n")}const xn="pair",wn="vibelet.web.pairing",Sn="vibelet.web.deviceId";class kn extends Error{constructor(e,t){super(t),this.code=e,this.name="PairingCreateError"}}function In(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function Cn(e){const[t,n,s,r,i,o]=e;return!n||!Number.isFinite(s)||s<=0?null:{kind:"relay"===t?"relay":"direct",host:n,port:Math.floor(s),source:r,stability:i,...!0===o?{secure:!0}:{}}}function jn(e){if(!In(e))return null;const{kind:t,host:n,port:s,source:r,stability:i,secure:o}=e;return"direct"!==t&&"relay"!==t||"string"!=typeof n||!n.trim()||"number"!=typeof s||!Number.isFinite(s)||s<=0||"string"!=typeof r||"string"!=typeof i?null:{kind:t,host:n.trim(),port:Math.floor(s),source:r,stability:i,...!0===o?{secure:!0}:{}}}function Rn(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 En(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 Mn(e){return function(e){const t=e.trim().split(".");if(4!==t.length)return!1;const n=t.map(e=>/^\d+$/.test(e)?Number(e):Number.NaN);if(n.some(e=>!Number.isInteger(e)||e<0||e>255))return!1;const[s,r]=n;return 10===s||172===s&&r>=16&&r<=31||192===s&&168===r}(e.host)?0:"local_network"===e.source?1:"configured_host"===e.source?2:3}function Tn(e,t){const n=t?.port??e.port,s=t?.canonicalHost??e.canonicalHost;if(!s||"number"!=typeof n||!Number.isFinite(n))return[];const r=Math.floor(n);return[{kind:"direct",host:s,port:r,source:"fallback",stability:"stable"},...[...t?.fallbackHosts??[],...e.fallbackHosts??[]].map(e=>({kind:"direct",host:e,port:r,source:"fallback",stability:"stable"}))]}function An(e,t,n=window.location,s=!0){if(s&&Rn(n.hostname))return;const r=[...t?.connections??[],...e.connections??[],...Tn(e,t)].map(jn).filter(e=>Boolean(e)).filter(e=>"direct"===e.kind).sort((e,t)=>Mn(e)-Mn(t));for(const i of r){const e=En(i,n);if(e)return e}}function Nn(e=window.location.hash){const t=e.startsWith("#")?e.slice(1):e,n=new URLSearchParams(t).get(xn);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(!In(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(Cn).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 Pn(e){const t=e.getItem(wn);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 Dn(e){if("undefined"==typeof window)return null;try{return e===t()?window.sessionStorage:null}catch{return null}}function Ln(e=t(),n=Dn(e)){const s=Pn(e);if(s)return s;const r=n?Pn(n):null;return r?(e.setItem(wn,JSON.stringify(r)),n?.removeItem(wn),r):null}function Fn(e,n=t(),s=Dn(n)){n.setItem(wn,JSON.stringify(e)),s?.removeItem(wn)}function qn(e=t(),n=Dn(e)){e.removeItem(wn),n?.removeItem(wn)}async function On(e,n){try{return await async function(e,n=function(e=t()){const n=e.getItem(Sn);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(Sn,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 kn("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(In(e)&&"pair_window_expired"===e.error)return new kn("pair_window_expired","Pairing link expired.")}catch{}return new kn("pairing_failed",t||"Pairing failed.")}(s);const r=await s.json();return{daemonId:r.daemonId,displayName:r.displayName||e.displayName,deviceId:r.deviceId,pairToken:r.pairToken,pairedAt:(new Date).toISOString(),webSocketUrl:An(e,r,window.location,!0)}}(e,n?.deviceId)}catch(s){if(s instanceof kn&&"pair_window_expired"===s.code&&n?.daemonId===e.daemonId)return n;throw s}}class _n{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 $n extends Error{name="VibeletRequestRejectedError"}class zn extends Error{name="VibeletRequestTimeoutError"}function Hn(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}class Bn{heartbeat=new _n;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&&Rn(t.hostname)?s:e?.webSocketUrl?e.webSocketUrl:s}(e));let n;this.socket=t;const s=new Promise((e,s)=>{n=s,t.onopen=()=>e(),t.onerror=()=>s(new Error("WebSocket connection failed."))});if(t.onmessage=e=>{this.socket===t&&this.handleSocketMessage(e.data)},t.onclose=()=>{n(new Error("WebSocket disconnected.")),this.socket===t&&(this.heartbeat.stop(),this.authenticated=!1,this.authentication=null,this.socket=null,this.rejectPending(new Error("WebSocket disconnected.")),this.closeListeners.forEach(e=>e()))},await s,this.socket!==t)throw new Error("WebSocket disconnected.");const r=await this.requestOnSocket({action:"auth.hello",id:Hn("auth"),pairToken:e.pairToken,daemonId:e.daemonId,deviceId:e.deviceId,locale:navigator.language});if(this.socket!==t)throw new Error("WebSocket disconnected.");return this.authenticated=!0,this.capabilities=r.capabilities??{},this.heartbeat.start(()=>t.send(JSON.stringify({action:"ping"})),()=>t.close()),r}async request(e,t={}){const n=this.socket;if(!this.authenticated){if(!this.authentication)throw new Error("WebSocket is not connected.");await this.authentication}if(this.socket!==n||!this.isConnected)throw new Error("WebSocket disconnected.");return this.requestOnSocket(e,t)}requestOnSocket(e,t={}){return this.socket&&this.socket.readyState===WebSocket.OPEN?new Promise((n,s)=>{const r={action:e.action,resolve:n,reject:s};t.timeoutMs&&t.timeoutMs>0&&(r.timeoutId=setTimeout(()=>{this.pending.delete(e.id),s(new zn(t.timeoutMessage||`Request timed out (${e.action}).`))},t.timeoutMs)),this.pending.set(e.id,r),this.socket?.send(JSON.stringify(e))}):Promise.reject(new Error("WebSocket is not connected."))}send(e){this.isConnected&&this.socket?.send(JSON.stringify(e))}onMessage(e){return this.messageListeners.add(e),()=>this.messageListeners.delete(e)}onClose(e){return this.closeListeners.add(e),()=>this.closeListeners.delete(e)}get supportsSessionSteer(){return this.isConnected&&!0===this.capabilities.sessionSteer}get supportsQueueSendNow(){return this.isConnected&&!0===this.capabilities.queueSendNow}get supportsDirectoryWatch(){return this.isConnected&&!0===this.capabilities.directoryWatch}disconnect(){this.heartbeat.stop(),this.authenticated=!1,this.authentication=null,this.capabilities={},this.rejectPending(new Error("WebSocket disconnected."));const e=this.socket;this.socket=null,e?.close(1e3,"client disconnect")}get isConnected(){return this.authenticated&&this.socket?.readyState===WebSocket.OPEN}makeId(e){return Hn(e)}handleSocketMessage(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}if("pong"!==t.type){if("error"===t.type&&!t.sessionId){const e=/unsupported action "([^"]+)"/.exec(t.message)?.[1];if(e){let n=!1;for(const[s,r]of this.pending)r.action===e&&(this.pending.delete(s),r.timeoutId&&clearTimeout(r.timeoutId),r.reject(new $n(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 $n(t.error||"Request failed.")))}this.messageListeners.forEach(e=>e(t))}else this.heartbeat.acknowledge()}rejectPending(e){for(const t of this.pending.values())t.timeoutId&&clearTimeout(t.timeoutId),t.reject(e);this.pending.clear()}}function Un(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 Wn=".",Kn="normal";function Vn(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function Qn(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 Gn(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 Jn(e){const t=e;return{sessions:Array.isArray(t.sessions)?t.sessions:[],nextCursor:Un(t.nextCursor),inventoryVersion:t.inventoryVersion,inventoryBackfillInFlight:t.inventoryBackfillInFlight,folderCounts:t.folderCounts}}function Zn(e){return e.split("/").filter(Boolean).at(-1)??e}function Xn(e){return 0===Object.entries(e).length?"No structured input.":JSON.stringify(e,null,2)}function Yn(e){return Object.fromEntries(e.questions.map(e=>[e.id,e.options[0]?[e.options[0].label]:[]]))}function es(e){return e.trim()||void 0}function ts(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 ns(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 ss=0;function rs(e,t,n=(new Date).toISOString()){return{...e,sessionId:t,lastActivityAt:n}}function is(e,t,n){if(!t||!n||t===n||!Object.hasOwn(e,t))return e;const{[t]:s,...r}=e;return{...r,[n]:s}}function os(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 as(e,t){const n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n&&"."!==n?`${n}/${t}`:t}function cs(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 ls(e,t){return t.startsWith("image/")||/\.(png|jpe?g|gif|webp|heic|heif|svg)$/i.test(e)}function ds(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 us(e,t){return e.get(t)||void 0}function hs(e,t){if("subscriptionRequired"===e){const e="undefined"==typeof window?"en":s(r().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 ps="vibelet:image-gallery";function fs(e){window.dispatchEvent(new CustomEvent(ps,{detail:e}))}const ms=/^[a-z][a-z0-9+.-]*:/i,gs=/^[a-z]:[\\/]/i,vs=/\.(?:md|markdown)$/i,ys="https://vibelet.local",bs="/__vibelet_markdown__",xs=`${ys}${bs}`;function ws(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!==ys)return null;if(t.pathname!==bs)return null;const n=t.searchParams.get("path");return n&&vs.test(n)?n:null}(t);if(n)return n;if(ms.test(t)&&!gs.test(t))return null;const s=t.split(/[?#]/,1)[0]??"";return vs.test(s)?function(e){try{return decodeURIComponent(e)}catch{return e}}(s):null}function Ss(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=ks(e,n);t+=e.slice(n,s),n=s;continue}if("["===e[n]&&"!"!==e[n-1]){const s=Is(e,n);if(s){t+=s.text,n=s.end;continue}}t+=e[n],n+=1}return t}(e)}).join("\n")}function ks(e,t){let n=0;for(;"`"===e[t+n];)n+=1;const s="`".repeat(n),r=e.indexOf(s,t+n);return r<0?e.length:r+n}function Is(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,r=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(r<0)return null;const i=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 r=Cs(s.slice(1,e));return r?`${t}<${r}>${s.slice(e+1)}${n}`:null}const r=s.match(/^(\S+)([\s\S]*)$/);if(!r)return null;const i=Cs(r[1]);return i?`${t}${i}${r[2]}${n}`:null}(e.slice(s,r));return i?{text:`${e.slice(t,s)}${i})`,end:r+1}:null}function Cs(e){const t=ws(e);return t?`${xs}?path=${encodeURIComponent(t)}`:null}const js="https://vibelet.local/__vibelet_file__";function Rs(e){if(!e)return null;const t=ws(e);if(t)return t;let n=e.trim();if(n.startsWith(js))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=Ot(n),Ht(n,{allowBareFilename:!0})?n:null}const Es=e=>`${js}?path=${encodeURIComponent(e)}`;function Ms(e){return e.value??e.children?.map(Ms).join("")??""}function Ts(){return e=>{const t=e=>{if("link"===e.type||"image"===e.type){const t=Rs(e.url);return void(t&&(e.url=Es(t),Bt(t)&&(e.alt=e.alt||Ms(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)?(?=/))?${Tt.source}`,Tt.flags);let s=0;const r=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(Dt)){const e=n[1]??"",s=n[2]??"",r=(n.index??0)+e.length;t.push({start:r,end:r+s.length,rawCandidate:s})}for(const n of e.matchAll(Lt)){const e=n[1]??"",s=n[2]??"",r=(n.index??0)+e.length,i=zt({start:r,end:r+s.length,rawCandidate:s}),o=t.filter(e=>_t(e,i));if(0!==o.length){if($t(i.rawCandidate)){for(const e of o){const n=t.indexOf(e);n>=0&&t.splice(n,1)}t.push(i)}}else t.push(i)}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 r=Ft(s.rawCandidate),i=Ot(r),o=s.rawCandidate.slice(r.length);Ht(r)&&!Bt(r)?(t.push({type:"path",value:r,target:i||r}),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:Es(n.target??n.value),children:[{type:"text",value:n.value}]}:{type:"text",value:n.value})};for(const i of e.matchAll(n)){const n=Rs(i[0]);n&&Bt(n)&&(r(e.slice(s,i.index)),t.push({type:"image",url:Es(n),alt:n.split(/[\\/]/).at(-1)}),s=i.index+i[0].length)}return r(e.slice(s)),t}(e.value??""):(t(e),[e])))};t(e)}}const As=20971520,Ns=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[i,o]of this.entries)o.expires<=Date.now()&&this.remove(i,o);const s=this.entries.get(t);if(s)return this.entries.delete(t),this.entries.set(t,s),s.promise;const r={promise:Promise.resolve(new Blob),bytes:0,expires:1/0};return r.promise=Promise.resolve().then(n).then(e=>(this.entries.get(t)===r&&(r.bytes=e.size,r.expires=Date.now()+this.ttl,this.bytes+=e.size,this.trim()),e),e=>{throw this.remove(t,r),e}),this.entries.set(t,r),this.trim(),r.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 Ps(e,t){return Ns.get(t,e,()=>async function(e,t){for(let s=0;;s++){const r=new AbortController;let i;const o=()=>{clearTimeout(i),i=setTimeout(()=>r.abort(new DOMException("Image request timed out","TimeoutError")),3e4)};o();try{const n=await fetch(e,{headers:{authorization:`Bearer ${t}`},signal:r.signal});if(0===s&&[502,503,504].includes(n.status)){await(n.body?.cancel());continue}const i=n.headers.get("content-type")??"";if(!n.ok||Number(n.headers.get("content-length"))>As||!i.startsWith("image/"))throw await(n.body?.cancel()),new Error("Image unavailable");const a=n.body?.getReader();if(!a)throw new Error("Image unavailable");const c=[];let l=0;try{for(;;){o();const{value:e,done:t}=await a.read();if(t)break;if(l+=e.byteLength,l>As)throw await a.cancel(),new Error("Unsupported image");c.push(e)}}finally{a.releaseLock()}return new Blob(c,{type:i})}catch(n){if(0===s&&(n instanceof TypeError||r.signal.aborted))continue;throw n}finally{clearTimeout(i)}}}(e,t))}function Ds(e,t,n=1600){const s=Rs(e),r=Ln(),[i,a]=o.useState(null),[c,l]=o.useState(null);return o.useEffect(()=>{if(!s)return;const i=new AbortController;let o;return a(null),l(null),(async()=>{try{if(!r)throw new Error("No pairing");const c=new URL(ds(s,t));null!==n&&c.searchParams.set("w",String(n));const l=await Ps(c.toString(),r.pairToken);if(i.signal.aborted)return;o=URL.createObjectURL(l),a({src:e,url:o})}catch{i.signal.aborted||l(e)}})(),()=>{i.abort(),o&&URL.revokeObjectURL(o)}},[e,s,t,n,r?.pairToken,r?.webSocketUrl]),{url:s?i?.src===e?i.url:void 0:e,error:c===e,fail:()=>l(e)}}function Ls({src:e,alt:t,cwd:n,onOpen:o,gallery:a}){const c=Rs(e),{url:l,error:d,fail:h}=Ds(e,n),p=u[s(r().language)],f=t||Zn(c??e);return i.jsx("button",{className:"message-image-preview","data-image-src":e,"data-image-cwd":n,type:"button",title:c??e,"aria-label":`${p.preview}: ${f}`,onClick:async t=>{t.preventDefault(),t.stopPropagation();const s=await(a?.())??[{src:e,alt:f,cwd:n}],r=s.findIndex(t=>t.src===e||c&&Rs(t.src)===c);fs({images:r<0?[{src:e,alt:f,cwd:n}]:s,index:Math.max(0,r),onOpen:o})},children:d?i.jsxs("span",{className:"message-image-placeholder",children:[i.jsx(ue,{"aria-hidden":"true"}),f," · ",p.fileOpenFailed]}):l?i.jsx("img",{src:l,alt:f,loading:"lazy",onError:h}):i.jsxs("span",{className:"message-image-placeholder",children:[i.jsx(ve,{className:"session-running-icon","aria-hidden":"true"}),f]})})}function Fs({attachments:e,uploadBusy:t,onRemove:n,onOpen:s,t:r}){if(!e.length&&!t)return null;const o=e.filter(e=>e.type.startsWith("image/")||Bt(e.path)||Bt(e.name)),a=()=>o.map(e=>({src:e.path,alt:e.name||Zn(e.path)}));return i.jsxs("div",{className:"attachment-row composer-attachments",children:[e.length>0&&i.jsx("div",{className:"composer-attachment-images",children:e.map(e=>{const t=e.name||Zn(e.path),c=o.includes(e);return i.jsxs("div",{className:"composer-attachment-card "+(c?"composer-image-card":"composer-file-card"),children:[c?i.jsx(Ls,{src:e.path,alt:t,onOpen:s,gallery:a}):i.jsxs("button",{className:"composer-file-preview",type:"button",title:`${t} · ${Qn(e.size)}`,"aria-label":`${r.preview}: ${t}`,onClick:()=>s(e.path),children:[i.jsx(Ce,{"aria-hidden":"true"}),i.jsx("span",{children:t}),i.jsx("small",{children:Qn(e.size)})]}),i.jsx("button",{className:"composer-image-remove",type:"button",title:`${r.removeAttachment}: ${t}`,"aria-label":`${r.removeAttachment}: ${t}`,onClick:()=>n(e.path),children:i.jsx(Ve,{"aria-hidden":"true"})})]},e.path)})}),t&&i.jsxs("span",{className:"attachment-empty",role:"status",children:[i.jsx("span",{className:"loading-spinner small","aria-hidden":"true"}),r.uploading]})]})}function qs(e,t,n,s){const[r,i]=o.useState({left:16,top:16,maxHeight:240});return o.useLayoutEffect(()=>{if(!e)return;const r=()=>{const e=t.current?.getBoundingClientRect(),r=n.current;if(!e||!r)return;const o=r.getBoundingClientRect().width,a=Math.max(80,e.top-24),c=Math.min(r.scrollHeight,a);i({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})};r();const o="undefined"==typeof ResizeObserver?null:new ResizeObserver(r);return n.current&&o?.observe(n.current),window.addEventListener("resize",r),document.addEventListener("scroll",r,!0),()=>{o?.disconnect(),window.removeEventListener("resize",r),document.removeEventListener("scroll",r,!0)}},[e,t,n,s]),r}function Os({icon:e,label:t,menuLabel:n,options:s,value:r,onSelect:c,align:l="left",disabled:d,selected:u,wide:h,blendBackground:p,portal:f=!1,tooltipHoverDelay:m}){const[g,v]=o.useState(!1),y=o.useRef(null),b=o.useRef(null),x=o.useRef(null),w=qs(g&&f,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&&!y.current?.contains(e.target)&&!b.current?.contains(e.target)&&v(!1)};return document.addEventListener("pointerdown",n),()=>document.removeEventListener("pointerdown",n)},[g]);const k=g?i.jsx("div",{ref:b,style:f?w:void 0,"aria-label":n,className:`composer-option-popover ${f?"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===r;return i.jsxs("button",{"aria-checked":n,className:n?"selected":"",disabled:e.disabled,onClick:()=>{c(e.value),v(!1),x.current?.focus()},role:"menuitemradio","data-tooltip-delay":m,title:e.description??e.label,type:"button",children:[S&&i.jsx("span",{className:"composer-menu-icon",children:t?i.jsx(t,{"aria-hidden":"true"}):null}),i.jsxs("span",{className:"composer-menu-copy",children:[i.jsx("strong",{children:e.label}),e.description?i.jsx("small",{children:e.description}):null]}),i.jsx("span",{className:"composer-menu-indicator","aria-hidden":"true",children:n?i.jsx(_,{className:"composer-menu-check"}):null})]},e.value)})}):null;return i.jsxs("div",{className:"composer-menu",ref:y,onBlur:e=>{const t=e.relatedTarget;t&&(e.currentTarget.contains(t)||b.current?.contains(t))||v(!1)},onKeyDown:e=>{if("Escape"===e.key&&g&&(e.stopPropagation(),e.preventDefault(),v(!1),x.current?.focus()),!["ArrowDown","ArrowUp","Home","End"].includes(e.key))return;if(e.preventDefault(),!g)return void v(!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:[i.jsxs("button",{ref:x,"aria-expanded":g,"aria-haspopup":"menu",className:"composer-option-button "+(g||u?"selected":""),disabled:d,onClick:()=>v(e=>!e),title:n,type:"button",children:[i.jsx(e,{"aria-hidden":"true"}),i.jsx("span",{children:t}),g?i.jsx(H,{"aria-hidden":"true"}):i.jsx($,{"aria-hidden":"true"})]}),k&&f?a.createPortal(k,document.body):k]})}function _s(e,t,n){const s=o.useRef(null);return o.useEffect(()=>{n&&document.getElementById(`${e}-${t}`)?.scrollIntoView({block:"nearest"})},[e,t,n]),s}function $s({visible:e,listId:t,selectedIndex:n,onHighlight:s,skills:r,onClose:o,onSelect:a,t:c}){const l=_s(t,n,e);return e?i.jsxs("div",{className:"skill-suggestion-popover",children:[i.jsxs("header",{children:[i.jsx("strong",{children:c.skills}),i.jsx("button",{type:"button",className:"icon-button",onClick:o,title:c.closeSkills,children:i.jsx(Ve,{"aria-hidden":"true"})})]}),r.length?i.jsx("div",{className:"skill-suggestion-list",id:t,role:"listbox",ref:l,children:r.map((e,r)=>i.jsxs("button",{id:`${t}-${r}`,role:"option","aria-selected":n===r,onMouseEnter:()=>s(r),onClick:()=>a(e),title:e.description??e.name,type:"button",children:[i.jsxs("span",{children:[i.jsxs("strong",{children:["$",e.name]}),e.description?i.jsx("small",{children:e.description}):null]}),i.jsx("em",{children:e.source})]},`${e.source}:${e.name}`))}):i.jsx("p",{children:c.noSkillsFound})]}):null}function zs({visible:e,listId:t,selectedIndex:n,onHighlight:s,commands:r,onClose:o,onSelect:a,t:c}){const l=_s(t,n,e);return e?i.jsxs("div",{className:"skill-suggestion-popover command-suggestion-popover",children:[i.jsxs("header",{children:[i.jsx("strong",{children:c.commands}),i.jsx("button",{type:"button",className:"icon-button",onClick:o,title:c.closeCommands,children:i.jsx(Ve,{"aria-hidden":"true"})})]}),r.length?i.jsx("div",{className:"skill-suggestion-list",id:t,role:"listbox",ref:l,children:r.map((e,r)=>i.jsxs("button",{id:`${t}-${r}`,role:"option","aria-selected":n===r,onMouseEnter:()=>s(r),onClick:()=>a(e),title:e.description,type:"button",children:[i.jsxs("span",{children:[i.jsxs("strong",{children:["/",e.name]}),i.jsx("small",{children:e.argsHint?`${e.title} ${e.argsHint}`:e.title})]}),i.jsx("em",{children:e.source})]},e.name))}):i.jsx("p",{children:c.noCommandsFound})]}):null}function Hs({queue:e,controls:t,busy:n,t:s,onCancel:r}){const[c,l]=o.useState(new Set),[d,u]=o.useState(!1),h=o.useId(),p=o.useRef(null),f=o.useRef(0),m=o.useRef(!1),[g,v]=o.useState(null),y=o.useRef(null),b=()=>{y.current=null,v(null)},x=e=>{if(y.current===e)return;const t=e.getBoundingClientRect(),n=Math.min(280,window.innerWidth-16);y.current=e,v({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>f.current&&(m.current=!0,d&&u(!1)),f.current=e.length,!d&&m.current&&p.current&&(p.current.scrollTop=p.current.scrollHeight,m.current=!1)},[d,e.length]),e.length?i.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):y.current&&b()},onPointerLeave:b,onFocusCapture:e=>{e.target instanceof HTMLButtonElement&&e.target.dataset.queueHelp&&x(e.target)},onBlurCapture:b,onScrollCapture:b,onClickCapture:b,children:[i.jsxs("header",{className:"composer-queue-heading",children:[i.jsx("strong",{"aria-live":"polite",children:S}),i.jsxs("div",{className:"composer-queue-heading-actions",children:[!d&&i.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}),i.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?i.jsx($,{"aria-hidden":"true"}):i.jsx(H,{"aria-hidden":"true"})})]})]}),i.jsxs("div",{className:"composer-queue-details",id:h,hidden:d,children:[i.jsx("div",{className:"composer-queue-list",ref:p,children:e.map((e,n)=>i.jsxs("div",{className:"composer-queue-item","data-selected":!!e.clientMessageId&&c.has(e.clientMessageId)||void 0,children:[i.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:i.jsx("span",{children:e.content||s.queuedTurnFallback})}),i.jsxs("div",{className:"queue-row-actions",children:[i.jsxs("span",{className:"queue-remote-receipt",role:"status",title:s.queueRemoteReceivedHint,children:[i.jsx(K,{"aria-hidden":"true"}),s.queueRemoteReceived]}),i.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:i.jsx(G,{"aria-hidden":"true"})}),i.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:i.jsx(De,{"aria-hidden":"true"})}),i.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:()=>r(e),children:i.jsx(Ve,{"aria-hidden":"true"})})]})]},e.clientMessageId||`${e.enqueuedAt}:${n}`))}),i.jsxs("footer",{className:"queue-batch-actions",children:[I.length>0&&i.jsx("span",{children:s.queueSelectedCount(I.length)}),i.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:[i.jsx(me,{"aria-hidden":"true"}),s.queueCollect]}),i.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}),i.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(i.jsxs("div",{className:"composer-queue-tooltip",role:"tooltip",style:{left:g.left,top:g.top,transform:g.below?void 0:"translateY(-100%)"},children:[i.jsx("strong",{children:g.label}),i.jsx("span",{children:g.help})]}),document.body)]}):null}function Bs({replies:e,disabled:t,onSend:n,onChange:s,t:r}){const[a,c]=o.useState(!1),[l,d]=o.useState(""),u=()=>{const t=l.trim();!t||e.length>=20||(e.some(e=>h(e,r)===t)||s?.([...e,t]),d(""),c(!1))};return i.jsxs("div",{className:"quick-reply-row",children:[e.map(o=>{const a=h(o,r);return i.jsxs("span",{className:"quick-reply-item",children:[i.jsx("button",{className:"quick-reply-send",title:a,type:"button",disabled:t||!n,onClick:()=>{n?.(a)},children:a}),s&&i.jsx("button",{className:"quick-reply-remove",type:"button","aria-label":`${r.delete}: ${a}`,title:`${r.delete}: ${a}`,onClick:()=>s(e.filter(e=>e!==o)),children:i.jsx(Ve,{"aria-hidden":"true"})})]},o)}),s&&(a?i.jsxs("div",{className:"quick-reply-add-form",children:[i.jsx("input",{autoFocus:!0,"aria-label":r.quickReplyAdd,placeholder:r.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)))}}),i.jsx("button",{type:"button","aria-label":r.quickReplyAdd,disabled:!l.trim(),onClick:u,children:i.jsx(_,{"aria-hidden":"true"})}),i.jsx("button",{type:"button","aria-label":r.cancel,onClick:()=>c(!1),children:i.jsx(Ve,{"aria-hidden":"true"})})]}):i.jsx("button",{type:"button",className:"quick-reply-add","aria-label":r.quickReplyAdd,title:r.quickReplyAdd,disabled:e.length>=20,onClick:()=>c(!0),children:i.jsx(Me,{"aria-hidden":"true"})}))]})}const Us={en:{mode:"Default send mode",queue:"Queue",queueHelp:"Wait until the current turn finishes.",guide:"Guide",guideHelp:"Guide the active turn; queue when unavailable.",unsupported:"This daemon does not support guidance; the message remains queued."},zh:{mode:"默认发送方式",queue:"排队",queueHelp:"等待当前回合完成后发送。",guide:"引导",guideHelp:"引导当前回合,暂不可用时排队。",unsupported:"此服务不支持引导,消息已保留在队列。"},"zh-TW":{mode:"預設傳送方式",queue:"排隊",queueHelp:"等待目前回合完成後傳送。",guide:"引導",guideHelp:"引導目前回合,暫不可用時排隊。",unsupported:"此服務不支援引導,訊息已保留在佇列。"}};function Ws(){return Us[s(r().language)]}function Ks(){const e=Ws(),[t,n]=o.useState(()=>r().composer.sendMode);return o.useEffect(()=>{const e=()=>n(r().composer.sendMode);return window.addEventListener("vibelet.preferences.changed",e),()=>window.removeEventListener("vibelet.preferences.changed",e)},[]),i.jsx(Os,{portal:!0,icon:"guide"===t?G:ge,label:"guide"===t?e.guide:e.queue,menuLabel:e.mode,value:t,options:[{value:"queue",label:e.queue,description:e.queueHelp},{value:"guide",label:e.guide,description:e.guideHelp}],onSelect:e=>{const t=r();p({...t,composer:{...t.composer,sendMode:e}}),window.dispatchEvent(new Event("vibelet.preferences.changed"))},align:"right",wide:!0})}function Vs({shortcut:e,onChange:t,action:n,t:s}){const r="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?r?"建立":"create":r?s.send:"send",u="create"===n&&r&&!o?"创建":d,h="enter"===e?"Shift+Enter":"Enter",p=r?`${a} ${u};${h} ${o?"換行":"换行"}。${o?"點擊切換為":"点击切换为"} ${l} ${u}`:`${a} to ${d}; ${h} for a newline. Click to switch to ${l} to ${d}`;return i.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:[i.jsx(fe,{"aria-hidden":"true"}),i.jsx("span",{className:"submit-shortcut-tooltip","aria-hidden":"true",children:p})]})}function Qs({leading:e,controls:t,submit:n}){return i.jsxs("div",{className:"composer-toolbar",children:[i.jsxs("div",{className:"composer-scroll-controls",children:[i.jsx("div",{className:"composer-leading-controls",children:e}),i.jsx("div",{className:"composer-control-strip",children:t})]}),n]})}function Gs({label:e,disabled:t,onClick:n}){return i.jsx("button",{type:"button",className:"icon-button",title:e,"aria-label":e,disabled:t,onClick:n,children:i.jsx(Me,{"aria-hidden":"true"})})}function Js({children:e,...t}){return i.jsx("button",{...t,className:"send-button submit-action-button",children:e})}function Zs({connected:e,busy:t,sending:s,responding:o,hasDraft:a,uploadBusy:c=!1,shortcut:l,onStop:d,t:u}){const h=s?"sending":o?"replying":"ready",f=o&&!s&&!a,m=s?u.sendingMessage:f?u.stopGenerating:u.send,g=s?u.sendingMessage:o?u.replyingMessage:u.send,v=s?ve:f?ze:q;return i.jsxs("div",{className:"submit-button-group",children:["desktop"===n().kind&&i.jsx(Ks,{}),i.jsx(Vs,{shortcut:l,action:"send",t:u,onChange:e=>{const t=r();p({...t,composer:{...t.composer,sendShortcut:e}}),window.dispatchEvent(new Event("vibelet.preferences.changed"))}}),i.jsxs(Js,{type:f?"button":"submit","data-state":h,"data-action":f?"stop":"send",disabled:!e||t||s||!f&&(!a||c),"aria-label":m,"aria-description":g,title:f?`${g} · ${u.stopGenerating}`:s?g:`${o?`${g} · `:""}${u.send} · ${"enter"===l?u.sendShortcutEnter:"shiftEnter"===l?u.sendShortcutShiftEnter:u.sendShortcutModEnter}`,onClick:f?d:void 0,children:[o&&!s&&i.jsx("span",{className:"composer-send-progress","aria-hidden":"true"}),i.jsx(v,{className:s?"composer-send-spinner":f?"composer-send-stop":void 0,"aria-hidden":"true"}),i.jsx("span",{className:"composer-send-status",role:"status","aria-live":"polite",children:g})]})]})}function Xs({value:e,textareaRef:t,onValueChange:n,onKeyDown:s,autoFocus:r,disabled:a,...c}){const l=o.useRef(!1),d=o.useRef(!1);o.useEffect(()=>{if(!r||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)},[r,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]),i.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 Ys(e,t){const n=e.map(e=>({value:e.value,label:e.label,description:e.desc,icon:J}));return n.some(e=>""===e.value)||n.unshift({value:"",label:t.defaultOption,description:t.useDaemonDefaultModel,icon:J}),n}function er(e){return[{value:"normal",label:e.approvalNormal,description:e.approvalNormalDescription,icon:qe},{value:"plan",label:e.approvalPlan,description:e.approvalPlanDescription,icon:Oe},{value:"acceptEdits",label:e.approvalEdits,description:e.approvalEditsDescription,icon:ee},{value:"autoApprove",label:e.approvalAuto,description:e.approvalAutoDescription,icon:Qe}]}function tr(e){return[{value:"",label:e.effort,description:e.useDaemonDefault,icon:oe},{value:"minimal",label:e.effortMinimal,icon:oe},{value:"low",label:e.effortLow,icon:oe},{value:"medium",label:e.effortMedium,icon:oe},{value:"high",label:e.effortHigh,icon:oe},{value:"xhigh",label:e.effortXHigh,icon:oe},{value:"max",label:e.effortMax,icon:oe},{value:"ultra",label:e.effortUltra,icon:oe}]}function nr({label:e,triggerContent:t,className:n="",children:s}){const[r,c]=o.useState(!1),l=o.useRef(null),d=o.useId(),u=()=>{c(!1),l.current?.focus()},h=f(u,void 0,r),p=qs(r,l,h,"right");return o.useEffect(()=>{if(!r)return;const e=e=>{e.target instanceof Node&&!h.current?.contains(e.target)&&!l.current?.contains(e.target)&&c(!1)},t=e=>{e.target instanceof Node&&!h.current?.contains(e.target)&&!l.current?.contains(e.target)&&c(!1)};return document.addEventListener("pointerdown",e),document.addEventListener("focusin",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("focusin",t)}},[r]),i.jsxs("div",{className:`composer-menu ${n}`,onKeyDown:e=>{"Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),e.stopPropagation(),u())},children:[i.jsx("button",{ref:l,type:"button",className:"composer-option-button",title:e,"aria-label":e,"aria-haspopup":"dialog","aria-expanded":r,"aria-controls":r?d:void 0,onClick:()=>c(!r),children:t}),r&&a.createPortal(i.jsx("div",{ref:h,id:d,role:"dialog","aria-label":e,className:"composer-settings-popover",style:p,children:s(u)}),document.body)]})}function sr(e){const{t}=e;return i.jsxs(i.Fragment,{children:[e.fastMode&&i.jsxs("span",{className:"composer-fast-indicator",role:"status","aria-label":t.fastMode,title:t.fastMode,children:[i.jsx(Qe,{"aria-hidden":"true"}),i.jsx("span",{children:t.fast})]}),i.jsx(nr,{label:`${t.model} / ${t.effort}`,className:"composer-model-trigger",triggerContent:i.jsxs(i.Fragment,{children:[i.jsxs("span",{children:[e.modelLabel," · ",e.effort?e.effortLabel:t.defaultOption]}),i.jsx($,{"aria-hidden":"true"})]}),children:()=>i.jsxs("div",{className:"composer-model-settings",children:[i.jsx("strong",{children:t.model}),i.jsx(Os,{icon:J,label:e.modelLabel,menuLabel:t.model,tooltipHoverDelay:1500,options:e.modelOptions,value:e.model,onSelect:e.onModelChange,wide:!0}),i.jsx("strong",{children:t.effort}),i.jsx("div",{className:"composer-effort-options",role:"group","aria-label":t.effort,children:e.effortOptions.map(n=>i.jsx("button",{type:"button",disabled:n.disabled,"aria-pressed":e.effort===n.value,title:n.description??n.label,onClick:()=>e.onEffortChange(n.value),children:n.value?n.label:t.defaultOption},n.value))}),i.jsxs("button",{type:"button",role:"switch","aria-checked":e.fastMode,"aria-label":t.fastMode,className:"composer-fast-switch",onClick:()=>e.onFastModeChange(!e.fastMode),children:[i.jsx(oe,{"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:t.fastMode}),i.jsx("small",{children:t.preferFasterResponses})]}),i.jsx("span",{className:"composer-switch-track","aria-hidden":"true",children:i.jsx("span",{})})]})]})})]})}function rr(e){const{t}=e,n=[{label:t.uploadFiles,icon:Ce,action:e.onUpload,disabled:e.toolsDisabled},{label:t.skills,icon:Qe,action:e.onSkills,shortcut:"$",disabled:e.toolsDisabled},{label:t.commands,icon:$e,action:e.onCommands,shortcut:"/",disabled:e.toolsDisabled},...e.quickRepliesAvailable?[{label:e.quickRepliesOpen?t.hideQuickReplies:t.showQuickReplies,icon:_e,action:e.onQuickReplies,disabled:!1}]:[]];return i.jsxs("div",{className:"composer-toolbar desktop-composer-toolbar",children:[i.jsx(nr,{label:`${t.uploadFiles} / ${t.skills} / ${t.commands}`,className:"composer-tools-trigger",triggerContent:i.jsx(Me,{"aria-hidden":"true"}),children:e=>i.jsx("div",{className:"composer-tools-list",children:n.map(({label:t,icon:n,action:s,shortcut:r,disabled:o})=>i.jsxs("button",{type:"button",disabled:o,onClick:()=>{e(),s()},children:[i.jsx(n,{"aria-hidden":"true"}),i.jsx("span",{children:t}),r&&i.jsx("kbd",{children:r})]},t))})}),i.jsx("div",{className:"composer-permission "+("autoApprove"===e.approvalMode?"full-access":""),children:i.jsx(Os,{portal:!0,icon:qe,label:e.approvalLabel,menuLabel:t.approvalMode,options:e.approvalOptions,value:e.approvalMode,onSelect:e.onApprovalModeChange,wide:!0,blendBackground:!0})}),i.jsx("div",{className:"composer-toolbar-spacer"}),i.jsx(sr,{...e}),e.voice,e.submit]})}function ir({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),f=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[m,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 v=o.useRef(null),y=o.useRef(!0),b=o.useRef(e);b.current=e;const x=s(r().language),w="en"!==x;return o.useEffect(()=>(y.current=!0,()=>{y.current=!1,v.current?.stream.getTracks().forEach(e=>e.stop()),"recording"===v.current?.state&&v.current.stop()}),[]),m&&a.transcribeAudio&&"true"===t().getItem("vibelet.web.voice.enabled")?i.jsxs("span",{className:"voice-input-control","data-voice-state":c,children:[i.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"===v.current?.state&&v.current.stop():(async()=>{if(!f.current){f.current=!0,u(""),l("starting");try{const t=await navigator.mediaDevices.getUserMedia({audio:!0});if(!y.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}v.current=n;const s=[];let r=0;n.ondataavailable=e=>{s.push(e.data),r+=e.data.size,r>9437184&&"recording"===n.state&&n.stop()};const i=setTimeout(()=>{"recording"===n.state&&n.stop()},6e4);n.onstop=async()=>{if(clearTimeout(i),t.getTracks().forEach(e=>e.stop()),v.current=null,y.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),r=new DataView(s.buffer),i=(e,t)=>[...t].forEach((t,n)=>r.setUint8(e+n,t.charCodeAt(0)));i(0,"RIFF"),r.setUint32(4,s.length-8,!0),i(8,"WAVEfmt "),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,n.sampleRate,!0),r.setUint32(28,2*n.sampleRate,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,"data"),r.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));r.setInt16(44+2*e,t*(t<0?32768:32767),!0)}return s}finally{await t.close()}}(e):new Uint8Array(await e.arrayBuffer()),r=await a.transcribeAudio(n,"zh-TW"===x?"zh-TW":w?"zh":"en");if(y.current)if(r.trim()){u("");let e=r;const t=await(a.polishSettings?.status().catch(()=>{}));if(!y.current)return;if(t?.settings.enabled&&a.polishTranscript){l("polishing");try{const t=await a.polishTranscript(r);e=t.text,y.current&&"fallback"===t.status&&u(w?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}catch{y.current&&u(w?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}}y.current&&b.current(e)}else u(w?"没有识别到语音,请靠近麦克风重试。":"No speech detected. Try speaking closer to the microphone.")}catch{y.current&&u(w?"语音识别失败,请检查麦克风权限、语音设置和网络。":"Speech failed. Check microphone access, speech settings and connection.")}finally{f.current=!1,y.current&&l("idle")}}};try{n.start(1e3)}catch(e){throw clearTimeout(i),t.getTracks().forEach(e=>e.stop()),v.current=null,e}l("recording")}catch{f.current=!1,y.current&&(l("idle"),u(w?"无法开启麦克风,请检查系统权限。":"Microphone unavailable. Check system permissions."))}}})()},children:"recording"===c?i.jsx(ze,{"aria-hidden":"true"}):"idle"===c?i.jsx(we,{"aria-hidden":"true"}):i.jsx(ve,{className:"voice-input-spinner","aria-hidden":"true"})}),"idle"!==c&&i.jsxs("span",{className:"voice-input-progress",children:["recording"===c&&i.jsxs("span",{className:"voice-input-wave","aria-hidden":"true",children:[i.jsx("i",{}),i.jsx("i",{}),i.jsx("i",{})]}),i.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&&i.jsxs("span",{className:"voice-input-time","aria-hidden":"true",children:["00:",String(h).padStart(2,"0")]})]}),"idle"===c&&d&&i.jsx("span",{className:"voice-input-error",role:"alert",children:d})]}):null}function or({client:e,activeSessionId:t,activeQueue:s,queueControls:r,agent:a,attachments:c,approvalMode:l,activeModelOptions:d,busy:u,sending:h,responding:p,onStop:f,draft:m,effort:g,fastMode:v,model:y,phase:b,quickReplies:x,onQuickRepliesChange:w,quickRepliesOpen:S=!1,onQuickRepliesOpenChange:k,onSendQuickReply:I,sendShortcut:C,skills:j,uploadBusy:R,t:E,onApprovalModeChange:M,onCancelQueuedTurn:T,onDraftChange:A,onEffortChange:N,onFastModeChange:P,onModelChange:D,onRefreshSkills:L,onRemoveAttachment:F,onOpenRemoteFile:q,onSubmit:O,onUploadFiles:_}){const $=function(e,t,s,r){const i=o.useRef({draft:s,responding:r});i.current={draft:s,responding:r};const[a,c]=o.useState(null);o.useEffect(()=>{if(c(null),!e||!t||"desktop"!==n().kind)return;const s=e.onMessage(n=>{if("sessionId"in n&&n.sessionId===t)if("session.prediction"===n.type){if(i.current.draft||i.current.responding)return;c({client:e,sessionId:t,text:n.text?.trim().slice(0,2e3)??""})}else"text.delta"!==n.type&&"session.interrupted"!==n.type||c(null)}),r=e.onClose(()=>c(null));return()=>{s(),r()}},[e,t]),o.useEffect(()=>{(r||s)&&c(null)},[r,s]);const l=r||s||a?.client!==e||a?.sessionId!==t?"":a?.text??"";return{text:l,handleKeyDown:(e,t)=>!(!l||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||e.metaKey||e.ctrlKey||e.altKey||e.shiftKey||"Tab"!==e.key&&"Escape"!==e.key||(e.preventDefault(),"Tab"===e.key&&t(l),c(null),0))}}(e,t,m,p||h),z=o.useRef(null),H=o.useRef(null),[B]=o.useState(()=>"desktop"===n().kind||(window.matchMedia?.("(pointer: fine)").matches??!1)),[U,W]=o.useState(!1),[K,V]=o.useState(!1),[Q,G]=o.useState(!1),[Z,X]=o.useState(""),[Y,ee]=o.useState(""),te=o.useRef(null),ne=o.useRef(null),se="connected"===b,re=o.useMemo(()=>yt(a),[a]),ie=o.useMemo(()=>xt(m),[m]),ae=ie?`${ie.start}:${ie.end}:${ie.keyword}`:"",ce=Boolean(Q||ie&&Y!==ae),le=o.useMemo(()=>function(e,t,n=8){const s=bt(t);return(s?e.filter(e=>e.name.includes(s)||e.title.toLowerCase().includes(s)).sort((e,t)=>wt(e,s)-wt(t,s)):[...e]).slice(0,n)}(re,ie?.keyword??"",8),[re,ie?.keyword]),de=o.useMemo(()=>Mt(m),[m]),ue=de?`${de.start}:${de.end}:${de.keyword}`:"",he=Boolean(!ce&&(K||de&&Z!==ue)),pe=o.useMemo(()=>function(e,t,n=8){const s=Rt(t);return(s?e.filter(e=>Rt(e.name).includes(s)):e).slice(0,n)}(j,de?.keyword??"",8),[de?.keyword,j]),fe=o.useMemo(()=>er(E),[E]),me=o.useMemo(()=>tr(E),[E]),ge=d.find(e=>e.value===y),ve=ge?.label??(y||E.defaultOption),ye=fe.find(e=>e.value===l)?.label??l,be=me.find(e=>e.value===g)?.label??g,xe=Ys(d,E);o.useEffect(()=>{de||(te.current=null,X(""),V(!1))},[de]),o.useEffect(()=>{ie||(ne.current=null,ee(""),G(!1))},[ie]);const we=()=>{const e=function(e,t){if(!t)return e;const n=Mt(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}(m,te.current);te.current=null,e!==m&&A(e),ue&&X(ue),V(!1),H.current?.focus()},Se=()=>{const e=function(e,t){return t&&xt(e)?t.draftBeforeInsertion:e}(m,ne.current);ne.current=null,e!==m&&A(e),ae&&ee(ae),G(!1),H.current?.focus()},ke=()=>{ce?Se():(ee(""),xt(m)||0!==m.length||(ne.current={draftBeforeInsertion:m},A("/")),G(!0),H.current?.focus())},Ie=e=>{const t=xt(m),n=function(e,t,n){return t?function(e,t,n){return`${e.slice(0,t.start)}${St(n,"")}${e.slice(t.end)}`}(e,t,n):`${St(n,e)}${e}`}(m,t,e);A(n),ne.current=null,G(!1),ee(""),H.current?.focus()},Ce=()=>{if(he)we();else{if(L(),X(""),!Mt(m)){const e=0===m.length||/\s$/.test(m)?"":" ";te.current={draftBeforeInsertion:m,triggerStart:m.length+e.length},A(`${m}${e}$`)}V(!0),H.current?.focus()}},je=e=>{const t=Mt(m),n=t?function(e,t,n){return`${e.slice(0,t.start)}$${Rt(n)} ${e.slice(t.end)}`}(m,t,e.name):m.trim().length?`${m}${/\s$/.test(m)?"":" "}$${e.name} `:`$${e.name} `;A(n),te.current=null,V(!1),X(""),H.current?.focus()},Re=function({context:e,count:t,onSelect:n,onClose:s}){const r=o.useId(),[i,a]=o.useState({context:"",index:0}),c=i.context===e?Math.min(i.index,Math.max(0,t-1)):0,l=t=>a({context:e,index:t});return{listId:r,selectedIndex:c,selectIndex:l,handleKeyDown:r=>!(!e||r.nativeEvent.isComposing||229===r.nativeEvent.keyCode||r.metaKey||r.ctrlKey||r.altKey||r.shiftKey||("Escape"===r.key?(r.preventDefault(),r.stopPropagation(),s(),0):!t||("ArrowDown"===r.key||"ArrowUp"===r.key?(r.preventDefault(),r.stopPropagation(),l((c+("ArrowDown"===r.key?1:-1)+t)%t),0):"Enter"!==r.key&&"Tab"!==r.key||(r.preventDefault(),r.stopPropagation(),n(c),0))))}}({context:ce?`command:${ae}:${le.map(e=>e.name).join(",")}`:he?`skill:${ue}:${pe.map(e=>`${e.source}:${e.name}`).join(",")}`:"",count:ce?le.length:he?pe.length:0,onSelect:e=>ce?Ie(le[e]):je(pe[e]),onClose:ce?Se:we});return i.jsxs("form",{className:"composer "+(U?"dragging":""),onDragEnter:e=>{e.preventDefault(),W(!0)},onDragLeave:()=>W(!1),onDragOver:e=>e.preventDefault(),onDrop:e=>{(async e=>{e.preventDefault(),W(!1),se&&await _(e.dataTransfer.files)})(e)},onSubmit:e=>{e.preventDefault(),se&&O(e)},children:[i.jsx(Hs,{queue:s,controls:r,busy:u,t:E,onCancel:T}),S&&i.jsx(Bs,{replies:x,disabled:!se||u||h||R,onSend:I,onChange:w,t:E}),i.jsx($s,{visible:he,skills:pe,listId:Re.listId,selectedIndex:Re.selectedIndex,onHighlight:Re.selectIndex,onClose:we,onSelect:je,t:E}),i.jsx(zs,{visible:ce,commands:le,listId:Re.listId,selectedIndex:Re.selectedIndex,onHighlight:Re.selectIndex,onClose:Se,onSelect:Ie,t:E}),i.jsx(Xs,{textareaRef:H,autoFocus:B,"aria-controls":ce||he?Re.listId:void 0,"aria-activedescendant":ce&&le.length||he&&pe.length?`${Re.listId}-${Re.selectedIndex}`:void 0,"aria-autocomplete":"list",value:m,onValueChange:A,onPaste:e=>{(async e=>{se&&e.clipboardData.files.length&&await _(e.clipboardData.files)})(e)},onKeyDown:e=>{Re.handleKeyDown(e)||$.handleKeyDown(e,A)||"Enter"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||mt(C,e)&&(e.preventDefault(),se&&!e.repeat&&O())},placeholder:$.text?`${$.text} ⇥ Tab`:E.messagePlaceholder,rows:3}),i.jsx(Fs,{attachments:c,uploadBusy:R,onRemove:F,onOpen:q,t:E}),i.jsx("input",{ref:z,type:"file",multiple:!0,hidden:!0,onChange:e=>{(async(e,t)=>{await _(e),t.value=""})(e.currentTarget.files,e.currentTarget)}}),"desktop"===n().kind?i.jsx(rr,{t:E,approvalMode:l,approvalLabel:ye,approvalOptions:fe,onApprovalModeChange:M,model:y,modelLabel:ve,modelOptions:xe,onModelChange:D,effort:g,effortLabel:be||E.effort,effortOptions:me,onEffortChange:N,fastMode:v,onFastModeChange:P,toolsDisabled:!se||R,onUpload:()=>z.current?.click(),onSkills:Ce,onCommands:ke,quickRepliesAvailable:x.length>0||!!w,quickRepliesOpen:S,onQuickReplies:()=>k?.(!S),voice:i.jsx(ir,{onTranscript:e=>A(m?`${m} ${e}`:e)}),submit:i.jsx(Zs,{connected:se,busy:u,sending:h,responding:p,hasDraft:!!m.trim()||c.length>0,uploadBusy:R||c.some(e=>e.uploading),shortcut:C,onStop:f,t:E})}):i.jsx(Qs,{leading:i.jsxs(i.Fragment,{children:[i.jsx(ir,{onTranscript:e=>A(m?`${m} ${e}`:e)}),i.jsx(Gs,{label:E.uploadFiles,disabled:!se||R,onClick:()=>z.current?.click()}),x.length>0||w?i.jsx("button",{className:"icon-button quick-replies-toggle "+(S?"selected":""),type:"button",title:S?E.hideQuickReplies:E.showQuickReplies,"aria-label":S?E.hideQuickReplies:E.showQuickReplies,"aria-pressed":S,onClick:()=>k?.(!S),children:i.jsx(_e,{"aria-hidden":"true"})}):null,i.jsx("button",{className:"icon-button "+(he?"selected":""),type:"button",title:E.skills,"aria-label":E.skills,onClick:Ce,disabled:!se||R,children:i.jsx(Qe,{"aria-hidden":"true"})}),i.jsx("button",{className:"icon-button "+(ce?"selected":""),type:"button",title:E.commands,"aria-label":E.commands,onClick:ke,disabled:!se||R,children:i.jsx($e,{"aria-hidden":"true"})})]}),controls:i.jsxs(i.Fragment,{children:[i.jsx(Os,{portal:!0,icon:"autoApprove"===l?Qe:qe,label:ye,menuLabel:E.approvalMode,blendBackground:!0,options:fe,value:l,onSelect:M,wide:!0}),i.jsx(Os,{portal:!0,icon:J,label:ve,menuLabel:E.model,tooltipHoverDelay:1500,options:xe,value:y,onSelect:D,align:"right",wide:!0}),i.jsx(Os,{portal:!0,icon:oe,label:be||E.effort,menuLabel:E.effort,options:me,value:g,onSelect:N,align:"right"}),i.jsx(Os,{portal:!0,icon:Qe,label:v?E.fast:E.normal,menuLabel:E.fastMode,options:[{value:"off",label:E.normal,description:E.standardExecution,icon:oe},{value:"on",label:E.fast,description:E.preferFasterResponses,icon:Qe}],value:v?"on":"off",onSelect:e=>P("on"===e),align:"right",selected:v,wide:!0})]}),submit:i.jsx(Zs,{connected:se,busy:u,sending:h,responding:p,hasDraft:!!m.trim()||c.length>0,uploadBusy:R||c.some(e=>e.uploading),shortcut:C,onStop:f,t:E})})]})}function ar({terminals:e,t}){const[n,s]=o.useState(Date.now),r=e?.length??0;return o.useEffect(()=>{if(!r)return;s(Date.now());const e=window.setInterval(()=>s(Date.now()),1e3);return()=>window.clearInterval(e)},[r]),r?i.jsxs("details",{className:"background-terminals",children:[i.jsxs("summary",{children:[i.jsx(Be,{"aria-hidden":"true"}),i.jsx("span",{role:"status",children:t.backgroundTerminalsRunning(r)}),i.jsx($,{className:"background-terminal-chevron","aria-hidden":"true"})]}),i.jsx("p",{children:t.backgroundTerminalsHint}),i.jsx("ul",{children:e.map(e=>{const s=Date.parse(e.startedAt),r=Number.isFinite(s)?Math.max(0,Math.floor((n-s)/1e3)):0;return i.jsxs("li",{children:[i.jsxs("span",{children:[t.backgroundTerminalLabel," #",e.id]}),i.jsxs("time",{children:[Math.floor(r/60),":",String(r%60).padStart(2,"0")]})]},e.id)})})]}):null}async function cr(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,r=window.getSelection(),i=r?Array.from({length:r.rangeCount},(e,t)=>r.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),r){r.removeAllRanges();for(const e of i)r.addRange(e)}}}function lr(e,t){const[n,s]=o.useState(null),r=o.useRef(null);return o.useEffect(()=>()=>{null!==r.current&&window.clearTimeout(r.current)},[]),{copyText:o.useCallback(async n=>{try{await cr(n),s({message:e,tone:"success"})}catch{s({message:t,tone:"error"})}null!==r.current&&window.clearTimeout(r.current),r.current=window.setTimeout(()=>s(null),2400)},[t,e]),feedback:n}}function dr({feedback:e}){if(!e)return null;const t="success"===e.tone?_:Ve;return i.jsxs("div",{className:`copy-feedback ${e.tone}`,role:"status",children:[i.jsx(t,{"aria-hidden":"true"}),e.message]})}function ur({message:e,retryLabel:t,onRetry:n,onDismiss:s,closeLabel:r}){return i.jsxs("div",{className:"notice error chat-error-notice",role:"alert",children:[s?i.jsx("button",{type:"button",className:"chat-notice-dismiss","aria-label":r,title:r,onClick:s,children:i.jsx(Ve,{"aria-hidden":"true"})}):i.jsx(B,{"aria-hidden":"true"}),i.jsx("span",{children:e}),i.jsxs("button",{className:"chat-notice-retry",onClick:n,type:"button",children:[i.jsx(Te,{"aria-hidden":"true"}),t]})]})}function hr({label:e}){return i.jsxs("div",{className:"history-loading-state","aria-busy":"true","aria-label":e,role:"status",children:[i.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),i.jsxs("div",{className:"history-loading-copy",children:[i.jsx("strong",{children:e}),i.jsx("span",{"aria-hidden":"true"}),i.jsx("span",{"aria-hidden":"true"}),i.jsx("span",{"aria-hidden":"true"})]})]})}function pr({failedSend:e,onRetry:t,onDismiss:n,t:s}){const r={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 i.jsxs("div",{className:"failed-send-notice",role:"alert",children:[i.jsx(B,{"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:"timeout"===e.kind?s.sendUnconfirmed:s.sendFailed}),r,e.message&&i.jsx("blockquote",{className:"failed-send-content",children:e.message}),!!e.images?.length&&i.jsx("small",{children:s.failedSendImages(e.images.length)})]}),i.jsxs("button",{disabled:e.retrying,onClick:t,type:"button",children:[i.jsx(Te,{"aria-hidden":"true",className:e.retrying?"spin":void 0}),e.retrying?s.retrying:s.retrySend]}),n&&i.jsx("button",{className:"chat-notice-dismiss",onClick:n,type:"button","aria-label":s.close,title:s.close,children:i.jsx(Ve,{"aria-hidden":"true"})})]})}function fr({label:e,onClick:t}){return i.jsx("button",{className:"scroll-latest-button",type:"button","aria-label":e,title:e,onClick:t,children:i.jsx(D,{"aria-hidden":"true"})})}const mr=/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,gr=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\u00AD\u061C\u180E\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g,vr=new Set(["","{}","[]","null","undefined",'""']);function yr(e){return e.replace(/\s+/g," ").trim()}function br(e,t){return"string"==typeof e[t]?e[t]:""}function xr(e,t){return"number"==typeof e[t]?e[t]:void 0}function wr(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function Sr(e){const t=[],n=br(e,"file_path")||br(e,"filePath");n&&t.push({label:"Path",value:n,isFilePath:!0});const s=xr(e,"offset"),r=xr(e,"limit");if(void 0!==s||void 0!==r){const e=[];void 0!==s&&e.push(`line ${s+1}`),void 0!==r&&e.push(`to ${void 0!==s?s+r:r}`),t.push({label:"Range",value:e.join(" ")})}return t}function kr(e){const t=function(e){return"string"!=typeof e?"":e.replace(/\r\n?/g,"\n").replace(mr,"").replace(gr,"").trim()}(e);return vr.has(t)?"":t}function Ir(e){const t=kr(e);if(!t)return"";try{const e=JSON.parse(t);if(e&&"object"==typeof e&&!Array.isArray(e)){const t="string"==typeof e.query?yr(e.query):"";if(t)return t;const n="string"==typeof e.command?yr(e.command):"";if(n)return n;const s="string"==typeof e.description?yr(e.description):"";if(s)return s}}catch{}return yr(t)}function Cr(e){return"tool"===e.role||"info"===e.type&&!/^Error:/i.test(e.content.trim())}function jr(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=>Ir(e.content)).find(Boolean)??""}function Rr(e,t){return e.historyKey?e.historyKey:`${e.timestamp??e.toolName??e.content.slice(0,24)??"message"}:${t}`}function Er(e){for(let t=(e?.length??0)-1;t>=0;t-=1){const n=e[t];if("user"===n.role)return"failed"===n.localDelivery?n:void 0}}const Mr={en:{rewind:"Rewind to here",rewinding:"Rewinding conversation… The selected message will return to the composer when ready.",confirmRewind:"Continue in a new branch before this message? The original conversation will be archived and preserved. The selected message will become a draft; no message will be sent. Files will not change.",incompleteHistory:"This conversation has older history that is not loaded. Rewinding is unavailable to avoid selecting the wrong turn.",unavailable:"This message is no longer available.",rewindFailed:"Unable to rewind this conversation.",invalidResponse:"Invalid rewind response.",mediaError:"This format cannot be played here. Download the file to open it.",remoteSettings:"Sessions and remote devices",htmlPreview:"HTML preview",pdfPreview:"PDF preview",audioPreview:"Audio preview",videoPreview:"Video preview"},zh:{rewind:"回退到这里",rewinding:"正在回退会话…完成后,所选消息会回到输入框。",confirmRewind:"从这条消息之前建立新分支继续?原会话会归档保留,所选消息会填入草稿,不会自动发送,文件不会改变。",incompleteHistory:"此会话还有未加载的历史,暂时不能回退,以免选错消息位置。",unavailable:"这条消息已不可用。",rewindFailed:"无法回退此会话。",invalidResponse:"回退响应无效。",mediaError:"此格式无法在这里播放,请下载后打开。",remoteSettings:"会话与远程设备",htmlPreview:"HTML 预览",pdfPreview:"PDF 预览",audioPreview:"音频预览",videoPreview:"视频预览"},"zh-TW":{rewind:"回退到這裡",rewinding:"正在回退對話…完成後,所選訊息會回到輸入框。",confirmRewind:"從這則訊息之前建立新分支繼續?原對話會封存保留,所選訊息會填入草稿,不會自動傳送,檔案不會改變。",incompleteHistory:"此對話還有未載入的歷史,暫時不能回退,以免選錯訊息位置。",unavailable:"這則訊息已無法使用。",rewindFailed:"無法回退此對話。",invalidResponse:"回退回應無效。",mediaError:"此格式無法在這裡播放,請下載後開啟。",remoteSettings:"對話與遠端裝置",htmlPreview:"HTML 預覽",pdfPreview:"PDF 預覽",audioPreview:"音訊預覽",videoPreview:"影片預覽"}};function Tr(){return Mr[s(r().language)]}const Ar="vibelet:session-workspace-change",Nr="vibelet:session-workspace-before-remove",Pr="vibelet:session-workspace-removing";function Dr(e){window.dispatchEvent(new CustomEvent(Ar,{detail:e}))}function Lr(e,t){window.dispatchEvent(new CustomEvent(Pr,{detail:{...e,removing:t}}))}function Fr(e,t){let n;try{n=JSON.parse(e)}catch{return e}if(!Array.isArray(n)||2!==n.length)return e;if(n[0]===t.daemonId&&n[1]===t.sessionId)return"remove"===t.action?null:JSON.stringify([t.daemonId,t.nextSessionId]);if("string"!=typeof n[0])return e;const s=Fr(n[0],t);return null===s?null:s===n[0]?e:JSON.stringify([s,n[1]])}function qr(e,t){const{value:n,set:s}=Or(e,t);return[n,s]}function Or(e,t){const n=o.useRef(new Map),s=o.useRef([]),r=o.useCallback(e=>{let t=e;for(const n of s.current){if(null===t)break;t=Fr(t,n)}return t},[]),i=r(e),a=()=>"function"==typeof t?t():t;null===i||n.current.has(i)||n.current.set(i,a());const[c,l]=o.useState(()=>new Map),d=o.useRef(c),u=o.useCallback(e=>{d.current=e,l(e)},[]),h=null===i?a():c.has(i)?c.get(i):n.current.get(i),p=o.useCallback(t=>{const s=r(e);if(null===s)return;const i=d.current,o=i.has(s)?i.get(s):n.current.get(s),a="function"==typeof t?t(o):t;Object.is(o,a)||u(new Map(i).set(s,a))},[e,r,u]),f=o.useCallback((e,t)=>{const n=r(e);null===n||Object.is(d.current.get(n),t)||u(new Map(d.current).set(n,t))},[r,u]),m=o.useCallback(e=>{const t=r(e);return null===t?void 0:d.current.has(t)?d.current.get(t):n.current.get(t)},[r]),g=o.useCallback(()=>new Map([...n.current,...d.current]),[]),v=o.useCallback(e=>{const t=g();let n=!1;for(const[s,r]of t){const i=e(r,s);i!==r&&(t.set(s,i),n=!0)}n&&u(t)},[g,u]);return o.useEffect(()=>{const e=e=>{const t=e.detail;s.current.push(t);const r=e=>{const n=new Map(e);for(const[s,r]of e){const e=Fr(s,t);e!==s&&(n.delete(s),null!==e&&n.set(e,r))}return n};n.current=r(n.current),u(r(d.current))};return window.addEventListener(Ar,e),()=>window.removeEventListener(Ar,e)},[u]),{value:h,set:p,setForScope:f,getForScope:m,getAll:g,updateAll:v,resolveScope:r}}function _r(e,t){return JSON.stringify([e??null,t??null])}function $r(e,t){try{const[n,s]=JSON.parse(e),[r,i]=JSON.parse(t);return n===r&&null===s&&"string"==typeof i}catch{return!1}}const zr="vibelet:file-operation-before",Hr="vibelet:file-operation-done";function Br(e,t=""){const n=e.replace(/\\/g,"/"),s=/^(\/|[a-z]:\/|~)/i.test(n)?n:`${t.replace(/\\/g,"/")}/${n}`,r=[];for(const i of s.split("/"))i&&"."!==i&&(".."===i?r.pop():r.push(i));return`${s.startsWith("/")?"/":""}${r.join("/")}`}function Ur(e,t,n){const s=Br(e,n),r=Br(t,n);return s===r||s.startsWith(`${r}/`)}async function Wr(e,t){const n=new CustomEvent(zr,{cancelable:!0,detail:{...e,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd}});if(!window.dispatchEvent(n))throw new Error("unsaved_changes");const s=await fetch("/file-operation",{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.pairToken}`},body:JSON.stringify(e)}),r=await s.text();let i;try{i=JSON.parse(r)}catch{throw new Error(404===s.status||/^Vibelet Daemon v/.test(r)?"daemon_update_required":"operation_failed")}if(404===s.status&&"ENOENT"!==i.error)throw new Error("daemon_update_required");if(!s.ok)throw new Error(i.error??"operation_failed");return window.dispatchEvent(new CustomEvent(Hr,{detail:{...i,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd,source:e.path}})),i}const Kr=o.createContext(null),Vr=()=>o.useContext(Kr);function Qr({workspace:e,children:t}){const[s,r]=qr(_r(e.pairing?.daemonId,e.activeSessionId),void 0),a=o.useCallback((t,n=e.cwd)=>{const s=Br(t,n);r({path:s}),e.setControlTabAndOpen("files"),e.listDirectory(cs(s)??n,{updateRoute:!0})},[e.cwd,e.listDirectory,e.setControlTabAndOpen,r]),c=o.useMemo(()=>({request:s,reveal:a}),[s,a]);return i.jsx(Kr.Provider,{value:"desktop"===n().kind?c:null,children:t})}function Gr(e){return"en"===e?{title:"Image viewer",previous:"Previous image",next:"Next image",copy:"Copy image",copied:"Image copied",failed:"Could not copy image",open:"Open original in tab",close:"Close",unavailable:"Image unavailable"}:"zh-TW"===e?{title:"圖片檢視器",previous:"上一張",next:"下一張",copy:"複製圖片",copied:"圖片已複製",failed:"圖片複製失敗",open:"在 Tab 開啟原檔案",close:"關閉",unavailable:"無法載入圖片"}:{title:"图片查看器",previous:"上一张",next:"下一张",copy:"复制图片",copied:"图片已复制",failed:"图片复制失败",open:"在 Tab 打开原文件",close:"关闭",unavailable:"无法加载图片"}}function Jr({position:e,onClose:t,onCopy:n,onCopyImage:s,copyImageLabel:r,onRevealFile:c,revealFileLabel:l,onRewind:d,onToggleSource:u,sourceOpen:h,t:p}){const f=o.useRef(null),m=o.useRef(t);m.current=t,o.useLayoutEffect(()=>{const t=f.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 r=()=>m.current(),i=e=>{t.contains(e.target)||r()};return document.addEventListener("pointerdown",i),document.addEventListener("scroll",r,!0),window.addEventListener("resize",r),window.addEventListener("blur",r),()=>{document.removeEventListener("pointerdown",i),document.removeEventListener("scroll",r,!0),window.removeEventListener("resize",r),window.removeEventListener("blur",r),t.contains(document.activeElement)&&n?.focus({preventScroll:!0})}},[e]);const g=e=>{t(),e()};return a.createPortal(i.jsxs("div",{ref:f,role:"menu","aria-label":p.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(f.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&&i.jsxs("button",{type:"button",role:"menuitem",onClick:()=>g(s),children:[i.jsx(Q,{"aria-hidden":"true"}),r]}),c&&i.jsxs("button",{type:"button",role:"menuitem",onClick:()=>g(c),children:[i.jsx(se,{"aria-hidden":"true"}),l]}),d&&i.jsxs("button",{type:"button",role:"menuitem",onClick:()=>g(d),children:[i.jsx(Ae,{"aria-hidden":"true"}),Tr().rewind]}),i.jsxs("button",{type:"button",role:"menuitem",onClick:()=>g(n),children:[i.jsx(Q,{"aria-hidden":"true"}),p.copyMessage]}),i.jsxs("button",{type:"button",role:"menuitem",onClick:()=>g(u),children:[i.jsx(V,{"aria-hidden":"true"}),h?p.hideMarkdownSource:p.viewMarkdownSource]})]}),document.body)}function Zr({message:e,t}){return i.jsx("pre",{className:"message-markdown-source",role:"region","aria-label":t.markdownSource,children:e.content})}function Xr(e){if(!(e instanceof Element))return;const t=e.closest("[data-image-src], [data-file-path], a[href]");return t?Rs(t.dataset.imageSrc??t.dataset.filePath??t.getAttribute("href"))??void 0:void 0}function Yr(e){return"en"===e?"Show in file manager":"zh-TW"===e?"在檔案管理中顯示":"在文件管理中显示"}async function ei(e){const t=new Image;t.crossOrigin="anonymous",t.src=e,await t.decode();const n=document.createElement("canvas");n.width=t.naturalWidth,n.height=t.naturalHeight;const s=n.getContext("2d");if(!s)throw new Error("Canvas unavailable");return s.drawImage(t,0,0),await new Promise((e,t)=>n.toBlob(n=>n?e(n):t(new Error("Image conversion failed")),"image/png"))}async function ti(e){const t=n().writeClipboardImage;t?await t(new Uint8Array(await(await ei(e)).arrayBuffer())):await navigator.clipboard.write([new ClipboardItem({"image/png":ei(e)})])}function ni(e){if(!(e instanceof Element))return;const t=e.closest(".message-image-preview");return t?.dataset.imageSrc&&t.querySelector("img")?{src:t.dataset.imageSrc,cwd:t.dataset.imageCwd}:void 0}function si({field:e}){return e.isDiff?i.jsxs("div",{className:"tool-field diff",children:[i.jsx("span",{children:e.label}),e.diffOld?i.jsxs("pre",{className:"tool-diff old",children:[i.jsx("b",{children:"-"}),e.diffOld]}):null,e.diffNew?i.jsxs("pre",{className:"tool-diff new",children:[i.jsx("b",{children:"+"}),e.diffNew]}):null]}):i.jsxs("div",{className:`tool-field ${e.isCode?"code":""} ${e.isFilePath?"path":""}`,children:[i.jsx("span",{children:e.label}),i.jsx("pre",{children:e.value})]})}function ri({message:e,onCopy:t,t:n}){const s=function(e,t){if(!t)return[];switch((e??"").toLowerCase()){case"read":return Sr(t);case"write":{const e=Sr(t),n=br(t,"content");return n&&e.push({label:"Content",isDiff:!0,value:"",diffNew:wr(n,500)}),e}case"edit":{const e=Sr(t),n=br(t,"old_string")||br(t,"oldString"),s=br(t,"new_string")||br(t,"newString");return(n||s)&&e.push({label:"Change",isDiff:!0,value:"",diffOld:wr(n,300),diffNew:wr(s,300)}),e}case"bash":{const e=br(t,"command");return e?[{label:"Command",value:e,isCode:!0}]:[]}case"websearch":{const e=br(t,"query");return e?[{label:"Query",value:e}]:[]}case"webfetch":{const e=[],n=br(t,"url");n&&e.push({label:"URL",value:n});const s=br(t,"prompt");return s&&e.push({label:"Prompt",value:wr(s,200)}),e}case"glob":{const e=br(t,"pattern");return e?[{label:"Pattern",value:e}]:[]}case"grep":{const e=[],n=br(t,"pattern");n&&e.push({label:"Pattern",value:n,isCode:!0});const s=br(t,"path");return s&&e.push({label:"In",value:s,isFilePath:!0}),e}default:{const e=[],n=br(t,"command");if(n)return[{label:"Command",value:n,isCode:!0}];const s=br(t,"file_path")||br(t,"filePath");s&&e.push({label:"Path",value:s,isFilePath:!0});const r=br(t,"description");r&&e.push({label:"Description",value:wr(r,200)});const i=br(t,"query");i&&e.push({label:"Query",value:i});const o=br(t,"url");return o&&e.push({label:"URL",value:o}),e}}}(e.toolName,e.toolInput),r=Ir(e.content),o=kr(e.content),a=function(e){return kr(e).length>0}(e.content)&&!s.length,c=e.toolName??n.tool;return i.jsxs("section",{className:"tool-detail-card",children:[i.jsxs("header",{children:[i.jsx("span",{className:"tool-detail-icon",children:i.jsx(Be,{"aria-hidden":"true"})}),i.jsxs("div",{children:[i.jsx("strong",{children:c}),r?i.jsx("small",{title:r,children:r}):null]}),i.jsx("button",{className:"icon-button",onClick:()=>t(e.content),type:"button",title:n.copyOutput,children:i.jsx(Q,{"aria-hidden":"true"})})]}),s.length?i.jsx("div",{className:"tool-fields",children:s.map((e,t)=>i.jsx(si,{field:e},`${e.label}:${t}`))}):null,a?i.jsx("pre",{className:"json-box compact",children:o}):null]})}function ii({messages:e,showHeader:t=!0,onClose:n,onCopy:s,t:r}){if(!e.length)return null;const o=e.filter(e=>"tool"===e.role).length||e.length,a=r.toolCallCount(o),c=jr(e),l=e.map(e=>e.content).join("\n\n");return i.jsxs("section",{className:"tool-inline-panel","aria-label":r.toolDetails,children:[t?i.jsxs("header",{className:"inline-detail-header",children:[i.jsxs("div",{className:"inline-detail-title",children:[i.jsx("strong",{children:a}),i.jsx("span",{title:c,children:c||r.toolDetail})]}),i.jsxs("div",{className:"row-actions",children:[i.jsx("button",{className:"icon-button",onClick:()=>s(l),type:"button",title:r.copyOutput,children:i.jsx(Q,{"aria-hidden":"true"})}),i.jsx("button",{className:"icon-button",onClick:n,type:"button",title:r.closeToolDetails,children:i.jsx(Ve,{"aria-hidden":"true"})})]})]}):null,i.jsx("div",{className:"tool-detail-list",children:e.map((e,t)=>i.jsx(ri,{message:e,onCopy:s,t:r},`${e.historyKey??e.timestamp??e.toolName??"tool"}:${t}`))})]})}const oi=o.lazy(async()=>m(()=>import("./mermaid-O7DHMXV3-B3e3pugB.js").then(e=>e.a),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.MessageMarkdown})));function ai({label:e}){return i.jsxs("span",{className:"message-replying-indicator","aria-label":e,role:"status",children:[i.jsxs("span",{"aria-hidden":"true",className:"message-replying-dots",children:[i.jsx("i",{}),i.jsx("i",{}),i.jsx("i",{})]}),i.jsx("span",{children:e})]})}function ci({activeMatch:e,baseCwd:t,message:n,onCopy:a,onRewind:c,onCloseTool:l,onOpenRemoteFile:d,onToggleSource:u,onToggleTool:h,sourceOpen:p,toolOpen:f,replying:g,queued:v,t:y}){const b="assistant"===n.role?fn(n.content):n.content,[x,w]=o.useState(null),S=Vr(),[k,I]=o.useState(""),C=Gr(s(r().language)),j="user"===n.role&&"info"!==n.type?c:void 0,R=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 r="浏览器"===t.browser?{queued:t.queueRemoteReceived,interrupted:"已中断",sending:"发送中",delivered:"已送达",failed:"未确认送达",hint:"配对电脑已接收,可能仍在等待处理。"}:"瀏覽器"===t.browser?{queued:t.queueRemoteReceived,interrupted:"已中斷",sending:"傳送中",delivered:"已送達",failed:"未確認送達",hint:"配對電腦已接收,可能仍在等待處理。"}:{queued:t.queueRemoteReceived,interrupted:"Interrupted",sending:"Sending",delivered:"Delivered",failed:"Delivery unconfirmed",hint:"Received by the paired computer; processing may still be pending."};return{state:s,label:r[s],title:"queued"===s?t.queueRemoteReceivedHint:"delivered"===s?r.hint:r[s]}}(n,y,v),E=(n.images??[]).filter(e=>ls(e,"")||/^(?:data:image\/|https?:\/\/|blob:)/i.test(e)),M="tool"===n.role?Ir(n.content):"";return i.jsxs("article",{className:`message ${n.role} ${"info"===n.type?"info":""} ${e?"match":""}`,onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),w({x:e.clientX,y:e.clientY,image:ni(e.target),file:Xr(e.target)})},onKeyDown:e=>{if("ContextMenu"!==e.key&&(!e.shiftKey||"F10"!==e.key))return;e.preventDefault(),e.stopPropagation();const t=e.currentTarget.getBoundingClientRect();w({x:t.left+16,y:t.top+16,image:ni(e.target),file:Xr(e.target)})},children:[x&&i.jsx(Jr,{position:x,onClose:()=>w(null),onCopy:()=>a(n.content),onCopyImage:x.image?()=>{(async e=>{I("");try{await async function({src:e,cwd:t}){const n=Rs(e);if(!n)return ti(e);const s=Ln();if(!s)throw new Error("No pairing");const r=await Ps(ds(n,t),s.pairToken),i=URL.createObjectURL(r);try{await ti(i)}finally{URL.revokeObjectURL(i)}}(e),I(C.copied)}catch{I(C.failed)}})(x.image)}:void 0,copyImageLabel:C.copy,onRevealFile:x.file&&S?()=>S.reveal(x.file,t):void 0,revealFileLabel:Yr(s(r().language)),onRewind:j,onToggleSource:u,sourceOpen:p,t:y}),k&&i.jsx("div",{className:"message-image-copy-status",role:"status",children:k}),i.jsxs("div",{className:"message-meta",children:[i.jsx("span",{children:hn(n,y)}),i.jsxs("div",{className:"message-meta-side",children:[R&&i.jsx("span",{className:"message-delivery","data-state":R.state,role:"status",title:R.title,children:R.label}),i.jsx("time",{children:un(n.timestamp,Date.now(),y)})]})]}),p?i.jsx(Zr,{message:n,t:y}):"tool"===n.role?i.jsxs("button",{className:"tool-inline-summary","aria-expanded":f,onClick:h,type:"button",children:[i.jsxs("span",{children:[i.jsx(Ke,{"aria-hidden":"true"}),n.toolName??y.tool]}),M?i.jsx("small",{children:M}):null]}):"assistant"===n.role||"user"===n.role?i.jsx(o.Suspense,{fallback:i.jsx("pre",{children:b}),children:i.jsx(oi,{baseCwd:t,content:Zt(b,n.images),onOpenRemoteFile:d,additionalImages:E})}):i.jsx("pre",{children:n.content}),n.images?.length?i.jsx("div",{className:"message-image-attachments",children:n.images.map(e=>E.includes(e)?i.jsx(Ls,{src:e,cwd:t,onOpen:d,gallery:async()=>[...(await m(async()=>{const{collectMessageImages:e}=await import("./collectMessageImages-CUMbRGiF.js");return{collectMessageImages:e}},__vite__mapDeps([4,1,2]))).collectMessageImages(n.content,t),...E.map(e=>({src:e,cwd:t}))]},e):i.jsxs("button",{type:"button",className:"message-file-attachment",title:e,"data-file-path":e,onClick:()=>d(e,t),children:[i.jsx(Ce,{size:16,"aria-hidden":"true"}),Zn(e)]},e))}):null,"tool"===n.role&&f?i.jsx(ii,{messages:[n],onClose:l,onCopy:a,t:y}):null,g&&i.jsx(ai,{label:y.replyingMessage}),i.jsxs("div",{className:"message-actions","aria-label":y.messageActions,role:"group",children:[j&&i.jsx("button",{type:"button",onClick:j,title:Tr().rewind,"aria-label":Tr().rewind,children:i.jsx(Ae,{"aria-hidden":"true"})}),i.jsx("button",{"aria-label":y.copyMessage,onClick:()=>a(p?n.content:b),title:y.copyMessage,type:"button",children:i.jsx(Q,{"aria-hidden":"true"})}),i.jsx("button",{"aria-label":y.viewMarkdownSource,"aria-expanded":p,onClick:u,title:p?y.hideMarkdownSource:y.viewMarkdownSource,type:"button",children:i.jsx(V,{"aria-hidden":"true"})})]})]})}function li(e,t){return JSON.stringify([...Object.values(e),...Object.values(t)].map(e=>JSON.stringify([e.sessionId,e.requestId])).sort())}function di({activeMatch:e,expanded:t,messages:n,onToggle:s,t:r}){const o=jr(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 r of e.filter(e=>"tool"===e.role)){const e=r.toolName||"Tool",t=n[e.toLowerCase()]??e;s.set(t,(s.get(t)??0)+1)}return[...s].map(([e,t])=>t>1?`${e} × ${t}`:e).join(" · ")}(n,r)||o;return i.jsx("button",{className:`tool-group-bubble ${e?"match":""} ${t?"expanded":""}`,type:"button",onClick:s,"aria-expanded":t,"aria-label":o?`${a}: ${o}`:a,children:i.jsxs("span",{className:"tool-group-header",children:[i.jsxs("span",{className:"tool-group-title",children:[i.jsx(z,{className:"tool-group-chevron","aria-hidden":"true"}),i.jsx("strong",{children:a})]}),o?i.jsx("span",{className:"tool-group-summary",children:o}):null]})})}const ui=o.memo(function({message:e,index:t,actions:n,messageRefs:s,baseCwd:r,canRewind:o,activeMatch:a,replying:c,queued:l,sourceOpen:d,toolOpen:u,setOpenSourceKey:h,setOpenToolKey:p,copyText:f,failedSend:m,t:g}){const v=Rr(e,t);return i.jsxs("div",{className:`message-frame ${e.role} ${"info"===e.type?"info":""}`,"data-message-index":t,ref:e=>{s.current[t]=e},children:[i.jsx(ci,{activeMatch:a,baseCwd:r,message:e,replying:c,queued:l,onCopy:f,onRewind:o?()=>n.current.onRewindMessage(e):void 0,onCloseTool:()=>p(null),onOpenRemoteFile:(e,t)=>n.current.onOpenRemoteFile(e,t),onToggleSource:()=>h(e=>e===v?null:v),onToggleTool:()=>p(e=>e===v?null:v),sourceOpen:d,toolOpen:u,t:g}),m?i.jsx(pr,{failedSend:m,onRetry:()=>{n.current.retry()},onDismiss:()=>n.current.onDismissFailedSend?.(),t:g}):null]},v)}),hi=o.memo(function({items:e,activeQueue:t,actions:n,messageRefs:s,activeMatchedMessageIndex:r,baseCwd:o,canRewind:a,hiddenLaterItemCount:c,replyingMessageIndex:l,openSourceKey:d,openToolKey:u,setOpenSourceKey:h,setOpenToolKey:p,copyText:f,failedSend:m,t:g}){return i.jsx(i.Fragment,{children:e.map(e=>{if("toolGroup"===e.type){const t=e.entries.map(e=>e.message),n=e.entries.some(e=>r===e.index),o=u===e.id;return i.jsx("div",{className:"message-frame tool info",ref:t=>{for(const n of e.entries)s.current[n.index]=t},children:i.jsxs("div",{className:"inline-message-stack",children:[i.jsx(di,{t:g,activeMatch:n,expanded:o,messages:t,onToggle:()=>p(t=>t===e.id?null:e.id)}),o?i.jsx(ii,{messages:t,showHeader:!1,onClose:()=>p(null),onCopy:f,t:g}):null]})},e.id)}const{index:v,message:y}=e,b=Rr(y,v),x=d===b,w=u===b,S=m?.historyKey===y.historyKey?m:null;return i.jsx(ui,{message:y,queued:!!t?.some(e=>!!e.clientMessageId&&(y.historyKey===`client:${e.clientMessageId}`||y.localClientMessageId===e.clientMessageId)),index:v,actions:n,messageRefs:s,baseCwd:o,canRewind:a,activeMatch:r===v,replying:0===c&&v===l,sourceOpen:x,toolOpen:w,setOpenSourceKey:h,setOpenToolKey:p,copyText:f,failedSend:S,t:g},b)})})}),pi={cancelTimeout:"Cancellation is not confirmed. Vibelet still owns this session; retry to return it to the terminal.",releaseUnconfirmed:"The writer lock is not confirmed released. Retry handing back to the terminal.",handoffFailed:"Could not return the session to the terminal",resuming:"Resuming conversation",submitting:"Submitting message",waiting:"Message accepted · waiting for model",compacting:"Compacting context",responding:"Receiving reply",retrying:"Reconnecting to Codex…",noProgress:"No progress for",latestError:"Latest error: ",idle:"No active turn",error:"The turn encountered an error",releasing:"Cancelling and releasing…",released:"Session returned to the terminal",releasedHint:"To continue there, return to the original Codex terminal and press R. You can also send a message here to resume in Vibelet.",dismiss:"Got it",handoff:"Cancel and return to terminal",unavailable:"Execution status unavailable",waitHint:"No new output yet. You can cancel and return to the terminal."},fi={cancelTimeout:"尚未确认取消,会话仍由 Vibelet 占用。可重试交还终端。",releaseUnconfirmed:"尚未确认写锁释放,请重试交还终端。",handoffFailed:"尚未交还终端",resuming:"正在恢复会话",submitting:"正在提交消息",waiting:"消息已接收,等待模型",compacting:"正在压缩上下文",responding:"正在接收回复",retrying:"正在重连 Codex…",noProgress:"无进展",latestError:"最近错误:",idle:"当前没有运行中的轮次",error:"本轮执行出错",releasing:"正在取消并释放会话…",released:"已交还终端",releasedHint:"如需在终端继续,请回到原来的 Codex 终端按 R。也可以在这里发送消息,继续在 Vibelet 对话。",dismiss:"知道了",handoff:"取消并交还终端",unavailable:"暂时无法取得执行状态",waitHint:"尚无新输出,可取消本轮并交还终端。"},mi={cancelTimeout:"尚未確認取消,會話仍由 Vibelet 佔用。可重試交還終端。",releaseUnconfirmed:"尚未確認寫鎖釋放,請重試交還終端。",handoffFailed:"尚未交還終端",resuming:"正在恢復會話",submitting:"正在提交訊息",waiting:"訊息已接收,等待模型",compacting:"正在壓縮上下文",responding:"正在接收回覆",retrying:"正在重新連線 Codex…",noProgress:"無進展",latestError:"最近錯誤:",idle:"目前沒有執行中的輪次",error:"本輪執行出錯",releasing:"正在取消並釋放會話…",released:"已交還終端",releasedHint:"如需在終端繼續,請回到原來的 Codex 終端按 R。也可以在這裡傳送訊息,繼續在 Vibelet 對話。",dismiss:"知道了",handoff:"取消並交還終端",unavailable:"暫時無法取得執行狀態",waitHint:"尚無新輸出,可取消本輪並交還終端。"};function gi({client:e,sessionId:t,t:n}){const s=(e=>e===u.zh?fi:e===u["zh-TW"]?mi:pi)(n),[r,a]=o.useState(null),[c,l]=o.useState(""),[d,h]=o.useState(!1),[p,f]=o.useState(!1),[m,g]=o.useState(Date.now());o.useEffect(()=>{if(!e)return;let n,s=!1;const r=async()=>{try{const n=await e.request({action:"codex.session.status",id:e.makeId("execution"),sessionId:t},{timeoutMs:5e3});s||(a(n),g(Date.now()),["idle","error"].includes(n.phase)||f(!1))}catch{s||a(null)}s||(n=setTimeout(r,2e3))};r();const i=e.onMessage(e=>{"sessionId"in e&&e.sessionId===t&&["text.delta","session.queue"].includes(e.type)&&f(!1)});return()=>{s=!0,clearTimeout(n),i()}},[e,t]);const v=d?"releasing":p?"released":c?"error":r?.phase;return p||!c&&!d&&"error"!==r?.phase&&"retrying"!==r?.phase?null:i.jsxs("div",{className:"notice codex-session-control",role:"status","data-testid":"codex-session-control",style:{flexWrap:"wrap"},children:[i.jsxs("span",{style:{flex:1},children:[c?s.handoffFailed:v?s[v]:s.unavailable,r&&["compacting","waiting","submitting","retrying","responding"].includes(r.phase)&&!d&&!p&&i.jsxs("small",{style:{display:"block"},children:[s.noProgress," ",Math.max(0,Math.floor((m-(r.lastProgressAt??r.since))/1e3)),"s ·"," ",s.waitHint]}),!p&&!d&&"retrying"===r?.phase&&r.detail&&i.jsxs("small",{style:{display:"block"},children:[s.latestError,r.detail]}),c&&i.jsx("small",{role:"alert",style:{display:"block"},children:c})]}),i.jsx("button",{type:"button",className:"icon-text-button",disabled:!e?.isConnected||d,onClick:()=>{(async()=>{if(e&&!d){h(!0),f(!1),l("");try{const n=await e.request({action:"codex.session.handoff",id:e.makeId("handoff"),sessionId:t},{timeoutMs:25e3});if(!0!==n?.released)throw new Error(s.unavailable);f(!0)}catch(n){const e=n instanceof Error?n.message:String(n);l(e.includes("has not confirmed cancellation")?s.cancelTimeout:e.includes("Cannot confirm the Codex writer lock")?s.releaseUnconfirmed:e)}finally{h(!1)}}})()},children:d?s.releasing:s.handoff})]})}function vi({client:e,activeSession:t,busy:n,rewinding:s,errorText:r,failedSend:o,failedSendVisibleInConversation:a,onClearInterrupt:c,onDismissError:l,onDismissFailedSend:d,onRetry:u,onRetryFailedSend:h,t:p}){return i.jsxs("div",{className:"chat-notices","aria-live":"polite",children:[s&&i.jsx("div",{className:"notice",role:"status","aria-busy":"true",children:Tr().rewinding}),!s&&"codex"===t?.agent&&i.jsx(gi,{client:e,sessionId:t.sessionId,t:p},t.sessionId),r?i.jsx(ur,{message:r,retryLabel:e?.isConnected?p.refreshSessions:p.retry,onRetry:u,closeLabel:p.close,onDismiss:l}):null,o&&!a?i.jsx(pr,{failedSend:o,onRetry:h,onDismiss:d,t:p}):null,t?.interruptReason?i.jsxs("div",{className:"notice error",role:"alert",children:[i.jsx(Qe,{"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsx("strong",{children:p.replyStopped})," ",t.interruptReason.humanText||t.interruptReason.kind]}),i.jsx("button",{className:"icon-text-button",disabled:n,onClick:c,type:"button",children:p.clear})]}):null,t?.stallWarning?i.jsxs("div",{className:"notice warning",children:[i.jsx(W,{"aria-hidden":"true"}),i.jsx("span",{children:t.stallWarning.humanText||p.agentMayBeStalled}),i.jsx("button",{className:"chat-notice-dismiss",type:"button","aria-label":p.close,title:p.close,onClick:c,children:i.jsx(Ve,{"aria-hidden":"true"})})]}):null]})}function yi({title:e,draft:t,label:n,disabled:s,onDraftChange:r,onCommit:a}){const[c,l]=o.useState(!1),[d,u]=o.useState(t),h=o.useRef(null),p=o.useRef(null),f=o.useRef(!1),m=o.useRef(!1);o.useLayoutEffect(()=>{c?(h.current?.focus(),h.current?.select()):f.current&&(f.current=!1,p.current?.focus()),c||(m.current=!1)},[c]);const g=()=>{f.current=!0,l(!1)};return c?i.jsx("input",{ref:h,className:"inline-session-title-input","aria-label":n,value:d,onChange:e=>{u(e.target.value),r(e.target.value)},onBlur:()=>{m.current||(d.trim()&&d.trim()!==e&&a(d),l(!1))},onKeyDown:t=>{t.nativeEvent.isComposing||229===t.keyCode||("Enter"===t.key?(t.preventDefault(),m.current=!0,d.trim()&&d.trim()!==e&&a(d),g()):"Escape"===t.key&&(t.preventDefault(),t.stopPropagation(),m.current=!0,g()))}}):i.jsx("button",{ref:p,type:"button",className:"inline-session-title-button",title:e,"aria-label":`${n}: ${e}`,disabled:s,onClick:()=>{u(e),r(e),l(!0)},children:e})}const bi=o.createContext(null);function xi({matchCount:e,activeMatchIndex:t,query:n,onChange:s,onNext:r,onPrevious:o,onClose:a,t:c}){const l="浏览器"===c.browser?"上一个匹配项":"瀏覽器"===c.browser?"上一個匹配項":"Previous match",d="浏览器"===c.browser?"下一个匹配项":"瀏覽器"===c.browser?"下一個匹配項":"Next match";return i.jsxs("div",{className:"message-search-bar",id:"conversation-message-search",children:[i.jsx(Pe,{"aria-hidden":"true"}),i.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():r()),"Escape"===e.key&&(e.preventDefault(),a()))},placeholder:c.searchThisSession}),i.jsx("span",{className:"message-search-position","aria-live":"polite",title:c.messageSearchMatches(e),children:n.trim()?`${t} / ${e}`:c.allMessages}),i.jsx("button",{type:"button",className:"icon-button mini-button","aria-label":l,title:l,disabled:!e,onClick:o,children:i.jsx(q,{"aria-hidden":"true"})}),i.jsx("button",{type:"button",className:"icon-button mini-button","aria-label":d,title:d,disabled:!e,onClick:r,children:i.jsx(D,{"aria-hidden":"true"})}),i.jsx("button",{"aria-label":c.clearMessageSearch,title:c.clearMessageSearch,className:"icon-button mini-button",onClick:a,type:"button",children:i.jsx(Ve,{"aria-hidden":"true"})})]})}function wi({activeSession:e,agent:t,cwd:s,t:r,onOpenDetails:c,onScrollToStart:l,renameTitle:u,busy:h,onRename:p,onRenameTitleChange:f,onViewChanges:m,search:g}){const[v,y]=o.useState(!1),b=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{const e=()=>{y(!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&&y(!0)},[g.query]),o.useLayoutEffect(()=>{!v&&x.current&&(x.current=!1,b.current?.focus())},[v]);const w=e?d(e):r.newSession,S=e?.cwd??(s.trim().length>0&&"."!==s?s:""),k=e?.agent??t,I=o.useContext(bi),C=n().toolbarTarget?.("conversation")??I,j=i.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:[i.jsxs("div",{className:"chat-title-block",children:[i.jsxs("span",{className:"chat-title-line",children:[i.jsx("button",{className:`agent-status-pill chat-session-details-button ${k}`,type:"button",onClick:c,"aria-label":r.details,title:r.details,disabled:!e,children:"codex"===k?"Codex":"Claude"}),i.jsx("h1",{children:e?i.jsx(yi,{title:w,draft:u,label:r.rename,disabled:h,onDraftChange:f,onCommit:p},e.sessionId):w})]}),S?i.jsx("p",{title:S,children:S}):null,e?.branch||e?.diffStat?i.jsxs("div",{className:"header-metadata",children:[e.branch?i.jsx("span",{children:e.branch}):null,e.runtime.state?i.jsx("span",{children:r.runtimeState(e.runtime.state)}):null,e.terminal?.mode?i.jsx("span",{children:e.terminal.mode}):null]}):null]}),i.jsx("button",{"aria-label":r.scrollToConversationStart,className:"chat-scroll-start-target",onClick:l,title:r.scrollToConversationStart,type:"button"}),e&&!v?i.jsxs("button",{className:"chat-changes-button",type:"button","aria-label":r.viewChanges,title:r.viewChanges,onClick:()=>m(e.sessionId),children:[i.jsx(ae,{"aria-hidden":"true"}),e.diffStat&&(e.diffStat.additions>0||e.diffStat.deletions>0)?i.jsxs("span",{className:"chat-changes-summary","aria-hidden":"true",children:[i.jsxs("span",{className:"diff-add",children:["+",e.diffStat.additions]}),i.jsxs("span",{className:"diff-del",children:["−",e.diffStat.deletions]})]}):null]}):null,v?i.jsx(xi,{...g,t:r,onClose:()=>{x.current=!0,g.onChange(""),y(!1)}}):i.jsx("button",{ref:b,className:"icon-button chat-search-toggle",type:"button","aria-label":r.searchThisSession,title:ot(r.searchThisSession,"searchMessages"),"aria-expanded":!1,"aria-controls":"conversation-message-search",onClick:()=>y(!0),children:i.jsx(Pe,{"aria-hidden":"true"})})]});return i.jsx("header",{className:"chat-header chat-search-header "+(C?"chat-header-in-titlebar":""),children:C?a.createPortal(j,C):j})}const Si={};function ki(e,t){return Ii(e,"boolean"!=typeof Si.includeImageAlt||Si.includeImageAlt,"boolean"!=typeof Si.includeHtml||Si.includeHtml)}function Ii(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 Ci(e.children,t,n)}return Array.isArray(e)?Ci(e,t,n):""}function Ci(e,t,n){const s=[];let r=-1;for(;++r<e.length;)s[r]=Ii(e[r],t,n);return s.join("")}const ji=document.createElement("i");function Ri(e){const t="&"+e+";";ji.innerHTML=t;const n=ji.textContent;return(59!==n.charCodeAt(n.length-1)||"semi"===e)&&n!==t&&n}function Ei(e,t,n,s){const r=e.length;let i,o=0;if(t=t<0?-t>r?0:r+t:t>r?r:t,n=n>0?n:0,s.length<1e4)i=Array.from(s),i.unshift(t,n),e.splice(...i);else for(n&&e.splice(t,n);o<s.length;)i=s.slice(o,o+1e4),i.unshift(t,0),e.splice(...i),o+=1e4,t+=1e4}function Mi(e,t){return e.length>0?(Ei(e,e.length,0,t),e):t}const Ti={}.hasOwnProperty;function Ai(e){const t={};let n=-1;for(;++n<e.length;)Ni(t,e[n]);return t}function Ni(e,t){let n;for(n in t){const s=(Ti.call(e,n)?e[n]:void 0)||(e[n]={}),r=t[n];let i;if(r)for(i in r){Ti.call(s,i)||(s[i]=[]);const e=r[i];Pi(s[i],Array.isArray(e)?e:e?[e]:[])}}}function Pi(e,t){let n=-1;const s=[];for(;++n<t.length;)("after"===t[n].add?e:s).push(t[n]);Ei(e,0,0,s)}function Di(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 Li(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Fi=Qi(/[A-Za-z]/),qi=Qi(/[\dA-Za-z]/),Oi=Qi(/[#-'*+\--9=?A-Z^-~]/);function _i(e){return null!==e&&(e<32||127===e)}const $i=Qi(/\d/),zi=Qi(/[\dA-Fa-f]/),Hi=Qi(/[!-/:-@[-`{-~]/);function Bi(e){return null!==e&&e<-2}function Ui(e){return null!==e&&(e<0||32===e)}function Wi(e){return-2===e||-1===e||32===e}const Ki=Qi(new RegExp("\\p{P}|\\p{S}","u")),Vi=Qi(/\s/);function Qi(e){return function(t){return null!==t&&t>-1&&e.test(String.fromCharCode(t))}}function Gi(e,t,n,s){const r=s?s-1:Number.POSITIVE_INFINITY;let i=0;return function(s){return Wi(s)?(e.enter(n),o(s)):t(s)};function o(s){return Wi(s)&&i++<r?(e.consume(s),o):(e.exit(n),t(s))}}const Ji={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"),Gi(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,r(t)}function r(t){return null===t?(e.exit("chunkText"),e.exit("paragraph"),void e.consume(t)):Bi(t)?(e.consume(t),e.exit("chunkText"),s):(e.consume(t),r)}}},Zi={tokenize:function(e){const t=this,n=[];let s,r,i,o=0;return a;function a(s){if(o<n.length){const r=n[o];return t.containerState=r[1],e.attempt(r[0].continuation,c,l)(s)}return l(s)}function c(e){if(o++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,s&&y();const n=t.events.length;let r,i=n;for(;i--;)if("exit"===t.events[i][0]&&"chunkFlow"===t.events[i][1].type){r=t.events[i][1].end;break}v(o);let a=n;for(;a<t.events.length;)t.events[a][1].end={...r},a++;return Ei(t.events,i+1,0,t.events.slice(n)),t.events.length=a,l(e)}return a(e)}function l(r){if(o===n.length){if(!s)return h(r);if(s.currentConstruct&&s.currentConstruct.concrete)return f(r);t.interrupt=Boolean(s.currentConstruct&&!s._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Xi,d,u)(r)}function d(e){return s&&y(),v(o),h(e)}function u(e){return t.parser.lazy[t.now().line]=o!==n.length,i=t.now().offset,f(e)}function h(n){return t.containerState={},e.attempt(Xi,p,f)(n)}function p(e){return o++,n.push([t.currentConstruct,t.containerState]),h(e)}function f(n){return null===n?(s&&y(),v(0),void e.consume(n)):(s=s||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:s,contentType:"flow",previous:r}),m(n))}function m(n){return null===n?(g(e.exit("chunkFlow"),!0),v(0),void e.consume(n)):Bi(n)?(e.consume(n),g(e.exit("chunkFlow")),o=0,t.interrupt=void 0,a):(e.consume(n),m)}function g(e,n){const a=t.sliceStream(e);if(n&&a.push(null),e.previous=r,r&&(r.next=e),r=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<i&&(!s.events[e][1].end||s.events[e][1].end.offset>i))return;const n=t.events.length;let r,a,c=n;for(;c--;)if("exit"===t.events[c][0]&&"chunkFlow"===t.events[c][1].type){if(r){a=t.events[c][1].end;break}r=!0}for(v(o),e=n;e<t.events.length;)t.events[e][1].end={...a},e++;Ei(t.events,c+1,0,t.events.slice(n)),t.events.length=e}}function v(s){let r=n.length;for(;r-- >s;){const s=n[r];t.containerState=s[1],s[0].exit.call(t,e)}n.length=s}function y(){s.write([null]),r=void 0,s=void 0,t.containerState._closeFlow=void 0}}},Xi={tokenize:function(e,t,n){return Gi(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}};function Yi(e){return null===e||Ui(e)||Vi(e)?1:Ki(e)?2:void 0}function eo(e,t,n){const s=[];let r=-1;for(;++r<e.length;){const i=e[r].resolveAll;i&&!s.includes(i)&&(t=i(t,n),s.push(i))}return t}const to={name:"attention",resolveAll:function(e,t){let n,s,r,i,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};no(u,-a),no(h,a),i={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},r={type:a>1?"strongText":"emphasisText",start:{...e[n][1].end},end:{...e[d][1].start}},s={type:a>1?"strong":"emphasis",start:{...i.start},end:{...o.end}},e[n][1].end={...i.start},e[d][1].start={...o.end},c=[],e[n][1].end.offset-e[n][1].start.offset&&(c=Mi(c,[["enter",e[n][1],t],["exit",e[n][1],t]])),c=Mi(c,[["enter",s,t],["enter",i,t],["exit",i,t],["enter",r,t]]),c=Mi(c,eo(t.parser.constructs.insideSpan.null,e.slice(n+1,d),t)),c=Mi(c,[["exit",r,t],["enter",o,t],["exit",o,t],["exit",s,t]]),e[d][1].end.offset-e[d][1].start.offset?(l=2,c=Mi(c,[["enter",e[d][1],t],["exit",e[d][1],t]])):l=0,Ei(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,r=Yi(s);let i;return function(t){return i=t,e.enter("attentionSequence"),o(t)};function o(a){if(a===i)return e.consume(a),o;const c=e.exit("attentionSequence"),l=Yi(a),d=!l||2===l&&r||n.includes(a),u=!r||2===r&&l||n.includes(s);return c._open=Boolean(42===i?d:d&&(r||!u)),c._close=Boolean(42===i?u:u&&(l||!d)),t(a)}}};function no(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const so={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"),r};function r(t){return Fi(t)?(e.consume(t),i):64===t?n(t):c(t)}function i(e){return 43===e||45===e||46===e||qi(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||qi(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||_i(s)?n(s):(e.consume(s),a)}function c(t){return 64===t?(e.consume(t),l):Oi(t)?(e.consume(t),c):n(t)}function l(e){return qi(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||qi(t))&&s++<63){const n=45===t?u:d;return e.consume(t),n}return n(t)}}},ro={partial:!0,tokenize:function(e,t,n){return function(t){return Wi(t)?Gi(e,s,"linePrefix")(t):s(t)};function s(e){return null===e||Bi(e)?t(e):n(e)}}},io={continuation:{tokenize:function(e,t,n){const s=this;return function(t){return Wi(t)?Gi(e,r,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):r(t)};function r(s){return e.attempt(io,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"),r}return n(t)};function r(n){return Wi(n)?(e.enter("blockQuotePrefixWhitespace"),e.consume(n),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(n))}}},oo={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 Hi(s)?(e.enter("characterEscapeValue"),e.consume(s),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(s)}}},ao={name:"characterReference",tokenize:function(e,t,n){const s=this;let r,i,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"),r=31,i=qi,l(t))}function c(t){return 88===t||120===t?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(t),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),r=6,i=zi,l):(e.enter("characterReferenceValue"),r=7,i=$i,l(t))}function l(a){if(59===a&&o){const r=e.exit("characterReferenceValue");return i!==qi||Ri(s.sliceSerialize(r))?(e.enter("characterReferenceMarker"),e.consume(a),e.exit("characterReferenceMarker"),e.exit("characterReference"),t):n(a)}return i(a)&&o++<r?(e.consume(a),l):n(a)}}},co={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"),r)};function r(e){return s.parser.lazy[s.now().line]?n(e):t(e)}}},lo={concrete:!0,name:"codeFenced",tokenize:function(e,t,n){const s=this,r={partial:!0,tokenize:function(e,t,n){let r=0;return function(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),o};function o(t){return e.enter("codeFencedFence"),Wi(t)?Gi(e,c,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):c(t)}function c(t){return t===i?(e.enter("codeFencedFenceSequence"),l(t)):n(t)}function l(t){return t===i?(r++,e.consume(t),l):r>=a?(e.exit("codeFencedFenceSequence"),Wi(t)?Gi(e,d,"whitespace")(t):d(t)):n(t)}function d(s){return null===s||Bi(s)?(e.exit("codeFencedFence"),t(s)):n(s)}}};let i,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,i=t,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(t)}(t)};function c(t){return t===i?(a++,e.consume(t),c):a<3?n(t):(e.exit("codeFencedFenceSequence"),Wi(t)?Gi(e,l,"whitespace")(t):l(t))}function l(n){return null===n||Bi(n)?(e.exit("codeFencedFence"),s.interrupt?t(n):e.check(co,p,y)(n)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),d(n))}function d(t){return null===t||Bi(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),l(t)):Wi(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Gi(e,u,"whitespace")(t)):96===t&&t===i?n(t):(e.consume(t),d)}function u(t){return null===t||Bi(t)?l(t):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),h(t))}function h(t){return null===t||Bi(t)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),l(t)):96===t&&t===i?n(t):(e.consume(t),h)}function p(t){return e.attempt(r,y,f)(t)}function f(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),m}function m(t){return o>0&&Wi(t)?Gi(e,g,"linePrefix",o+1)(t):g(t)}function g(t){return null===t||Bi(t)?e.check(co,p,y)(t):(e.enter("codeFlowValue"),v(t))}function v(t){return null===t||Bi(t)?(e.exit("codeFlowValue"),g(t)):(e.consume(t),v)}function y(n){return e.exit("codeFenced"),t(n)}}},uo={name:"codeIndented",tokenize:function(e,t,n){const s=this;return function(t){return e.enter("codeIndented"),Gi(e,r,"linePrefix",5)(t)};function r(e){const t=s.events[s.events.length-1];return t&&"linePrefix"===t[1].type&&t[2].sliceSerialize(t[1],!0).length>=4?i(e):n(e)}function i(t){return null===t?a(t):Bi(t)?e.attempt(ho,i,a)(t):(e.enter("codeFlowValue"),o(t))}function o(t){return null===t||Bi(t)?(e.exit("codeFlowValue"),i(t)):(e.consume(t),o)}function a(n){return e.exit("codeIndented"),t(n)}}},ho={partial:!0,tokenize:function(e,t,n){const s=this;return r;function r(t){return s.parser.lazy[s.now().line]?n(t):Bi(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),r):Gi(e,i,"linePrefix",5)(t)}function i(e){const i=s.events[s.events.length-1];return i&&"linePrefix"===i[1].type&&i[2].sliceSerialize(i[1],!0).length>=4?t(e):Bi(e)?r(e):n(e)}}},po={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,r=3;if(!("lineEnding"!==e[r][1].type&&"space"!==e[r][1].type||"lineEnding"!==e[s][1].type&&"space"!==e[s][1].type))for(t=r;++t<s;)if("codeTextData"===e[t][1].type){e[r][1].type="codeTextPadding",e[s][1].type="codeTextPadding",r+=2,s-=2;break}for(t=r-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,r,i=0;return function(t){return e.enter("codeText"),e.enter("codeTextSequence"),o(t)};function o(t){return 96===t?(e.consume(t),i++,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?(r=e.enter("codeTextSequence"),s=0,l(t)):Bi(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||Bi(t)?(e.exit("codeTextData"),a(t)):(e.consume(t),c)}function l(n){return 96===n?(e.consume(n),s++,l):s===i?(e.exit("codeTextSequence"),e.exit("codeText"),t(n)):(r.type="codeTextData",c(n))}}};class fo{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 r=this.right.splice(this.right.length-s,Number.POSITIVE_INFINITY);return n&&mo(this.left,n),r.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),mo(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),mo(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);mo(this.right,t.reverse())}else{const t=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);mo(this.left,t.reverse())}}}function mo(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 go(e){const t={};let n,s,r,i,o,a,c,l=-1;const d=new fo(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,r=0,r<a.length&&"lineEndingBlank"===a[r][1].type&&(r+=2),r<a.length&&"content"===a[r][1].type))for(;++r<a.length&&"content"!==a[r][1].type;)"chunkText"===a[r][1].type&&(a[r][1]._isInFirstContentOfListItem=!0,r++);if("enter"===n[0])n[1].contentType&&(Object.assign(t,vo(d,l)),l=t[l],c=!0);else if(n[1]._container){for(r=l,s=void 0;r--;)if(i=d.get(r),"lineEnding"===i[1].type||"lineEndingBlank"===i[1].type)"enter"===i[0]&&(s&&(d.get(s)[1].type="lineEndingBlank"),i[1].type="lineEnding",s=r);else if("linePrefix"!==i[1].type&&"listItemIndent"!==i[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 Ei(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!c}function vo(e,t){const n=e.get(t)[1],s=e.get(t)[2];let r=t-1;const i=[];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,f=0,m=0;const g=[m];for(;p;){for(;e.get(++r)[1]!==p;);i.push(r),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&&(m=h+1,g.push(m),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=i.pop();c.push([n,n+t.length-1]),e.splice(n,2,t)}for(c.reverse(),h=-1;++h<c.length;)l[f+c[h][0]]=f+c[h][1],f+=c[h][1]-c[h][0]-1;return l}const yo={resolve:function(e){return go(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?r(t):Bi(t)?e.check(bo,i,r)(t):(e.consume(t),s)}function r(n){return e.exit("chunkContent"),e.exit("content"),t(n)}function i(t){return e.consume(t),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,s}}},bo={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"),Gi(e,r,"linePrefix")};function r(r){if(null===r||Bi(r))return n(r);const i=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&i&&"linePrefix"===i[1].type&&i[2].sliceSerialize(i[1],!0).length>=4?t(r):e.interrupt(s.parser.constructs.flow,n,t)(r)}}};function xo(e,t,n,s,r,i,o,a,c){const l=c||Number.POSITIVE_INFINITY;let d=0;return function(t){return 60===t?(e.enter(s),e.enter(r),e.enter(i),e.consume(t),e.exit(i),u):null===t||32===t||41===t||_i(t)?n(t):(e.enter(s),e.enter(o),e.enter(a),e.enter("chunkString",{contentType:"string"}),f(t))};function u(n){return 62===n?(e.enter(i),e.consume(n),e.exit(i),e.exit(r),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||Bi(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 f(r){return d||null!==r&&41!==r&&!Ui(r)?d<l&&40===r?(e.consume(r),d++,f):41===r?(e.consume(r),d--,f):null===r||32===r||40===r||_i(r)?n(r):(e.consume(r),92===r?m:f):(e.exit("chunkString"),e.exit(a),e.exit(o),e.exit(s),t(r))}function m(t){return 40===t||41===t||92===t?(e.consume(t),f):f(t)}}function wo(e,t,n,s,r,i){const o=this;let a,c=0;return function(t){return e.enter(s),e.enter(r),e.consume(t),e.exit(r),e.enter(i),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(i),e.enter(r),e.consume(u),e.exit(r),e.exit(s),t):Bi(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||Bi(t)||c++>999?(e.exit("chunkString"),l(t)):(e.consume(t),a||(a=!Wi(t)),92===t?u:d)}function u(t){return 91===t||92===t||93===t?(e.consume(t),c++,d):d(t)}}function So(e,t,n,s,r,i){let o;return function(t){return 34===t||39===t||40===t?(e.enter(s),e.enter(r),e.consume(t),e.exit(r),o=40===t?41:t,a):n(t)};function a(n){return n===o?(e.enter(r),e.consume(n),e.exit(r),e.exit(s),t):(e.enter(i),c(n))}function c(t){return t===o?(e.exit(i),a(o)):null===t?n(t):Bi(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),Gi(e,c,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),l(t))}function l(t){return t===o||null===t||Bi(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 ko(e,t){let n;return function s(r){return Bi(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),n=!0,s):Wi(r)?Gi(e,s,n?"linePrefix":"lineSuffix")(r):t(r)}}const Io={name:"definition",tokenize:function(e,t,n){const s=this;let r;return function(t){return e.enter("definition"),function(t){return wo.call(s,e,i,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(t)}(t)};function i(t){return r=Li(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 Ui(t)?ko(e,a)(t):a(t)}function a(t){return xo(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(t)}function c(t){return e.attempt(Co,l,l)(t)}function l(t){return Wi(t)?Gi(e,d,"whitespace")(t):d(t)}function d(i){return null===i||Bi(i)?(e.exit("definition"),s.parser.defined.push(r),t(i)):n(i)}}},Co={partial:!0,tokenize:function(e,t,n){return function(t){return Ui(t)?ko(e,s)(t):n(t)};function s(t){return So(e,r,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(t)}function r(t){return Wi(t)?Gi(e,i,"whitespace")(t):i(t)}function i(e){return null===e||Bi(e)?t(e):n(e)}}},jo={name:"hardBreakEscape",tokenize:function(e,t,n){return function(t){return e.enter("hardBreakEscape"),e.consume(t),s};function s(s){return Bi(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}},Ro={name:"headingAtx",resolve:function(e,t){let n,s,r=e.length-2,i=3;return"whitespace"===e[i][1].type&&(i+=2),r-2>i&&"whitespace"===e[r][1].type&&(r-=2),"atxHeadingSequence"===e[r][1].type&&(i===r-1||r-4>i&&"whitespace"===e[r-2][1].type)&&(r-=i+1===r?2:4),r>i&&(n={type:"atxHeadingText",start:e[i][1].start,end:e[r][1].end},s={type:"chunkText",start:e[i][1].start,end:e[r][1].end,contentType:"text"},Ei(e,i,r-i+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"),r(t)}(t)};function r(t){return 35===t&&s++<6?(e.consume(t),r):null===t||Ui(t)?(e.exit("atxHeadingSequence"),i(t)):n(t)}function i(n){return 35===n?(e.enter("atxHeadingSequence"),o(n)):null===n||Bi(n)?(e.exit("atxHeading"),t(n)):Wi(n)?Gi(e,i,"whitespace")(n):(e.enter("atxHeadingText"),a(n))}function o(t){return 35===t?(e.consume(t),o):(e.exit("atxHeadingSequence"),i(t))}function a(t){return null===t||35===t||Ui(t)?(e.exit("atxHeadingText"),i(t)):(e.consume(t),a)}}},Eo=["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"],Mo=["pre","script","style","textarea"],To={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 r,i,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),i=!0,p):63===a?(e.consume(a),r=3,s.interrupt?t:D):Fi(a)?(e.consume(a),o=String.fromCharCode(a),f):n(a)}function d(i){return 45===i?(e.consume(i),r=2,u):91===i?(e.consume(i),r=5,a=0,h):Fi(i)?(e.consume(i),r=4,s.interrupt?t:D):n(i)}function u(r){return 45===r?(e.consume(r),s.interrupt?t:D):n(r)}function h(r){return r==="CDATA[".charCodeAt(a++)?(e.consume(r),6===a?s.interrupt?t:j:h):n(r)}function p(t){return Fi(t)?(e.consume(t),o=String.fromCharCode(t),f):n(t)}function f(a){if(null===a||47===a||62===a||Ui(a)){const c=47===a,l=o.toLowerCase();return c||i||!Mo.includes(l)?Eo.includes(o.toLowerCase())?(r=6,c?(e.consume(a),m):s.interrupt?t(a):j(a)):(r=7,s.interrupt&&!s.parser.lazy[s.now().line]?n(a):i?g(a):v(a)):(r=1,s.interrupt?t(a):j(a))}return 45===a||qi(a)?(e.consume(a),o+=String.fromCharCode(a),f):n(a)}function m(r){return 62===r?(e.consume(r),s.interrupt?t:j):n(r)}function g(t){return Wi(t)?(e.consume(t),g):I(t)}function v(t){return 47===t?(e.consume(t),I):58===t||95===t||Fi(t)?(e.consume(t),y):Wi(t)?(e.consume(t),v):I(t)}function y(t){return 45===t||46===t||58===t||95===t||qi(t)?(e.consume(t),y):b(t)}function b(t){return 61===t?(e.consume(t),x):Wi(t)?(e.consume(t),b):v(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):Wi(t)?(e.consume(t),x):S(t)}function w(t){return t===c?(e.consume(t),c=null,k):null===t||Bi(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||Ui(t)?b(t):(e.consume(t),S)}function k(e){return 47===e||62===e||Wi(e)?v(e):n(e)}function I(t){return 62===t?(e.consume(t),C):n(t)}function C(t){return null===t||Bi(t)?j(t):Wi(t)?(e.consume(t),C):n(t)}function j(t){return 45===t&&2===r?(e.consume(t),T):60===t&&1===r?(e.consume(t),A):62===t&&4===r?(e.consume(t),L):63===t&&3===r?(e.consume(t),D):93===t&&5===r?(e.consume(t),P):!Bi(t)||6!==r&&7!==r?null===t||Bi(t)?(e.exit("htmlFlowData"),R(t)):(e.consume(t),j):(e.exit("htmlFlowData"),e.check(Ao,F,R)(t))}function R(t){return e.check(No,E,F)(t)}function E(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),M}function M(t){return null===t||Bi(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 Mo.includes(n)?(e.consume(t),L):j(t)}return Fi(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),L):45===t&&2===r?(e.consume(t),D):j(t)}function L(t){return null===t||Bi(t)?(e.exit("htmlFlowData"),F(t)):(e.consume(t),L)}function F(n){return e.exit("htmlFlow"),t(n)}}},Ao={partial:!0,tokenize:function(e,t,n){return function(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(ro,t,n)}}},No={partial:!0,tokenize:function(e,t,n){const s=this;return function(t){return Bi(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),r):n(t)};function r(e){return s.parser.lazy[s.now().line]?n(e):t(e)}}},Po={name:"htmlText",tokenize:function(e,t,n){const s=this;let r,i,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),y):Fi(t)?(e.consume(t),k):n(t)}function c(t){return 45===t?(e.consume(t),l):91===t?(e.consume(t),i=0,p):Fi(t)?(e.consume(t),v):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):Bi(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(i++)?(e.consume(t),6===i?f:p):n(t)}function f(t){return null===t?n(t):93===t?(e.consume(t),m):Bi(t)?(o=f,N(t)):(e.consume(t),f)}function m(t){return 93===t?(e.consume(t),g):f(t)}function g(t){return 62===t?A(t):93===t?(e.consume(t),g):f(t)}function v(t){return null===t||62===t?A(t):Bi(t)?(o=v,N(t)):(e.consume(t),v)}function y(t){return null===t?n(t):63===t?(e.consume(t),b):Bi(t)?(o=y,N(t)):(e.consume(t),y)}function b(e){return 62===e?A(e):y(e)}function x(t){return Fi(t)?(e.consume(t),w):n(t)}function w(t){return 45===t||qi(t)?(e.consume(t),w):S(t)}function S(t){return Bi(t)?(o=S,N(t)):Wi(t)?(e.consume(t),S):A(t)}function k(t){return 45===t||qi(t)?(e.consume(t),k):47===t||62===t||Ui(t)?I(t):n(t)}function I(t){return 47===t?(e.consume(t),A):58===t||95===t||Fi(t)?(e.consume(t),C):Bi(t)?(o=I,N(t)):Wi(t)?(e.consume(t),I):A(t)}function C(t){return 45===t||46===t||58===t||95===t||qi(t)?(e.consume(t),C):j(t)}function j(t){return 61===t?(e.consume(t),R):Bi(t)?(o=j,N(t)):Wi(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),r=t,E):Bi(t)?(o=R,N(t)):Wi(t)?(e.consume(t),R):(e.consume(t),M)}function E(t){return t===r?(e.consume(t),r=void 0,T):null===t?n(t):Bi(t)?(o=E,N(t)):(e.consume(t),E)}function M(t){return null===t||34===t||39===t||60===t||61===t||96===t?n(t):47===t||62===t||Ui(t)?I(t):(e.consume(t),M)}function T(e){return 47===e||62===e||Ui(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 Wi(t)?Gi(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)}}},Do={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&&Ei(e,0,e.length,n),e},resolveTo:function(e,t){let n,s,r,i,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(r){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&&(r=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[r][1].end}},d={type:"labelText",start:{...e[s+a+2][1].end},end:{...e[r-2][1].start}};return i=[["enter",c,t],["enter",l,t]],i=Mi(i,e.slice(s+1,s+a+3)),i=Mi(i,[["enter",d,t]]),i=Mi(i,eo(t.parser.constructs.insideSpan.null,e.slice(s+a+4,r-3),t)),i=Mi(i,[["exit",d,t],e[r-2],e[r-1],["exit",l,t]]),i=Mi(i,e.slice(r+1)),i=Mi(i,[["exit",c,t]]),Ei(e,s,e.length,i),e},tokenize:function(e,t,n){const s=this;let r,i,o=s.events.length;for(;o--;)if(("labelImage"===s.events[o][1].type||"labelLink"===s.events[o][1].type)&&!s.events[o][1]._balanced){r=s.events[o][1];break}return function(t){return r?r._inactive?d(t):(i=s.parser.defined.includes(Li(s.sliceSerialize({start:r.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(Lo,l,i?l:d)(t):91===t?e.attempt(Fo,l,i?c:d)(t):i?l(t):d(t)}function c(t){return e.attempt(qo,l,d)(t)}function l(e){return t(e)}function d(e){return r._balanced=!0,n(e)}}},Lo={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 Ui(t)?ko(e,r)(t):r(t)}function r(t){return 41===t?l(t):xo(e,i,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(t)}function i(t){return Ui(t)?ko(e,a)(t):l(t)}function o(e){return n(e)}function a(t){return 34===t||39===t||40===t?So(e,c,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(t):l(t)}function c(t){return Ui(t)?ko(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)}}},Fo={tokenize:function(e,t,n){const s=this;return function(t){return wo.call(s,e,r,i,"reference","referenceMarker","referenceString")(t)};function r(e){return s.parser.defined.includes(Li(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(e):n(e)}function i(e){return n(e)}}},qo={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)}}},Oo={name:"labelStartImage",resolveAll:Do.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"),r};function r(t){return 91===t?(e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelImage"),i):n(t)}function i(e){return 94===e&&"_hiddenFootnoteSupport"in s.parser.constructs?n(e):t(e)}}},_o={name:"labelStartLink",resolveAll:Do.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"),r};function r(e){return 94===e&&"_hiddenFootnoteSupport"in s.parser.constructs?n(e):t(e)}}},$o={name:"lineEnding",tokenize:function(e,t){return function(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),Gi(e,t,"linePrefix")}}},zo={name:"thematicBreak",tokenize:function(e,t,n){let s,r=0;return function(t){return e.enter("thematicBreak"),function(e){return s=e,i(e)}(t)};function i(i){return i===s?(e.enter("thematicBreakSequence"),o(i)):r>=3&&(null===i||Bi(i))?(e.exit("thematicBreak"),t(i)):n(i)}function o(t){return t===s?(e.consume(t),r++,o):(e.exit("thematicBreakSequence"),Wi(t)?Gi(e,i,"whitespace")(t):i(t))}}},Ho={continuation:{tokenize:function(e,t,n){const s=this;return s.containerState._closeFlow=void 0,e.check(ro,function(n){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,Gi(e,t,"listItemIndent",s.containerState.size+1)(n)},function(n){return s.containerState.furtherBlankLines||!Wi(n)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,r(n)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(Uo,t,r)(n))});function r(r){return s.containerState._closeFlow=!0,s.interrupt=void 0,Gi(e,e.attempt(Ho,t,n),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(r)}}},exit:function(e){e.exit(this.containerState.type)},name:"list",tokenize:function(e,t,n){const s=this,r=s.events[s.events.length-1];let i=r&&"linePrefix"===r[1].type?r[2].sliceSerialize(r[1],!0).length:0,o=0;return function(t){const r=s.containerState.type||(42===t||43===t||45===t?"listUnordered":"listOrdered");if("listUnordered"===r?!s.containerState.marker||t===s.containerState.marker:$i(t)){if(s.containerState.type||(s.containerState.type=r,e.enter(r,{_container:!0})),"listUnordered"===r)return e.enter("listItemPrefix"),42===t||45===t?e.check(zo,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 $i(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(ro,s.interrupt?n:l,e.attempt(Bo,u,d))}function l(e){return s.containerState.initialBlankLine=!0,i++,u(e)}function d(t){return Wi(t)?(e.enter("listItemPrefixWhitespace"),e.consume(t),e.exit("listItemPrefixWhitespace"),u):n(t)}function u(n){return s.containerState.size=i+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(n)}}},Bo={partial:!0,tokenize:function(e,t,n){const s=this;return Gi(e,function(e){const r=s.events[s.events.length-1];return!Wi(e)&&r&&"listItemPrefixWhitespace"===r[1].type?t(e):n(e)},"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5)}},Uo={partial:!0,tokenize:function(e,t,n){const s=this;return Gi(e,function(e){const r=s.events[s.events.length-1];return r&&"listItemIndent"===r[1].type&&r[2].sliceSerialize(r[1],!0).length===s.containerState.size?t(e):n(e)},"listItemIndent",s.containerState.size+1)}},Wo={name:"setextUnderline",resolveTo:function(e,t){let n,s,r,i=e.length;for(;i--;)if("enter"===e[i][0]){if("content"===e[i][1].type){n=i;break}"paragraph"===e[i][1].type&&(s=i)}else"content"===e[i][1].type&&e.splice(i,1),r||"definition"!==e[i][1].type||(r=i);const o={type:"setextHeading",start:{...e[n][1].start},end:{...e[e.length-1][1].end}};return e[s][1].type="setextHeadingText",r?(e.splice(s,0,["enter",o,t]),e.splice(r+1,0,["exit",e[n][1],t]),e[n][1].end={...e[r][1].end}):e[n][1]=o,e.push(["exit",o,t]),e},tokenize:function(e,t,n){const s=this;let r;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"),r=t,function(t){return e.enter("setextHeadingLineSequence"),i(t)}(t))};function i(t){return t===r?(e.consume(t),i):(e.exit("setextHeadingLineSequence"),Wi(t)?Gi(e,o,"lineSuffix")(t):o(t))}function o(s){return null===s||Bi(s)?(e.exit("setextHeadingLine"),t(s)):n(s)}}},Ko={tokenize:function(e){const t=this,n=e.attempt(ro,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,Gi(e,e.attempt(this.parser.constructs.flow,s,e.attempt(yo,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)}}},Vo={resolveAll:Zo()},Qo=Jo("string"),Go=Jo("text");function Jo(e){return{resolveAll:Zo("text"===e?Xo:void 0),tokenize:function(t){const n=this,s=this.parser.constructs[e],r=t.attempt(s,i,o);return i;function i(e){return c(e)?r(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"),r(e)):(t.consume(e),a)}function c(e){if(null===e)return!0;const t=s[e];let r=-1;if(t)for(;++r<t.length;){const e=t[r];if(!e.previous||e.previous.call(n,n.previous))return!0}return!1}}}}function Zo(e){return function(t,n){let s,r=-1;for(;++r<=t.length;)void 0===s?t[r]&&"data"===t[r][1].type&&(s=r,r++):t[r]&&"data"===t[r][1].type||(r!==s+2&&(t[s][1].end=t[r-1][1].end,t.splice(s+2,r-s-2),r=s+2),s=void 0);return e?e(t,n):t}}function Xo(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],r=t.sliceStream(s);let i,o=r.length,a=-1,c=0;for(;o--;){const e=r[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)i=!0,c++;else if(-1!==e){o++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(c=0),c){const r={type:n===e.length||i||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={...r.start},s.start.offset===s.end.offset?Object.assign(s,r):(e.splice(n,0,["enter",r,t],["exit",r,t]),n+=2)}n++}return e}const Yo={42:Ho,43:Ho,45:Ho,48:Ho,49:Ho,50:Ho,51:Ho,52:Ho,53:Ho,54:Ho,55:Ho,56:Ho,57:Ho,62:io},ea={91:Io},ta={[-2]:uo,[-1]:uo,32:uo},na={35:Ro,42:zo,45:[Wo,zo],60:To,61:Wo,95:zo,96:lo,126:lo},sa={38:ao,92:oo},ra={[-5]:$o,[-4]:$o,[-3]:$o,33:Oo,38:ao,42:to,60:[so,Po],91:_o,92:[jo,oo],93:Do,95:to,96:po},ia={null:[to,Vo]},oa=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:ea,disable:{null:[]},document:Yo,flow:na,flowInitial:ta,insideSpan:ia,string:sa,text:ra},Symbol.toStringTag,{value:"Module"})),aa=/[\0\t\n\r]/g,ca=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function la(e){return e.replace(ca,da)}function da(e,t,n){if(t)return t;if(35===n.charCodeAt(0)){const e=n.charCodeAt(1),t=120===e||88===e;return Di(n.slice(t?2:1),t?16:10)}return Ri(n)||e}function ua(e){return e&&"object"==typeof e?"position"in e||"type"in e?pa(e.position):"start"in e||"end"in e?pa(e):"line"in e||"column"in e?ha(e):"":""}function ha(e){return fa(e&&e.line)+":"+fa(e&&e.column)}function pa(e){return ha(e&&e.start)+"-"+ha(e&&e.end)}function fa(e){return e&&"number"==typeof e?e:1}const ma={}.hasOwnProperty;function ga(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:r(y),autolinkProtocol:d,autolinkEmail:d,atxHeading:r(m),blockQuote:r(function(){return{type:"blockquote",children:[]}}),characterEscape:d,characterReference:d,codeFenced:r(f),codeFencedFenceInfo:i,codeFencedFenceMeta:i,codeIndented:r(f,i),codeText:r(function(){return{type:"inlineCode",value:""}},i),codeTextData:d,data:d,codeFlowValue:d,definition:r(function(){return{type:"definition",identifier:"",label:null,title:null,url:""}}),definitionDestinationString:i,definitionLabelString:i,definitionTitleString:i,emphasis:r(function(){return{type:"emphasis",children:[]}}),hardBreakEscape:r(g),hardBreakTrailing:r(g),htmlFlow:r(v,i),htmlFlowData:d,htmlText:r(v,i),htmlTextData:d,image:r(function(){return{type:"image",title:null,url:"",alt:null}}),label:i,link:r(y),listItem:r(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:r(b,function(){this.data.expectingFirstListItemValue=!0}),listUnordered:r(b),paragraph:r(function(){return{type:"paragraph",children:[]}}),reference:function(){this.data.referenceType="collapsed"},referenceString:i,resourceDestinationString:i,resourceTitleString:i,setextHeading:r(m),strong:r(function(){return{type:"strong",children:[]}}),thematicBreak:r(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=Di(t,"characterReferenceMarkerNumeric"===n?10:16),this.data.characterReferenceType=void 0):s=Ri(t),this.stack[this.stack.length-1].value+=s},characterReference:function(e){this.stack.pop().position.end=va(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=Li(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=la(t),n.identifier=Li(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=va(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=Li(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()}};ya(t,(e||{}).mdastExtensions||[]);const n={};return function(e){let r={type:"root",children:[]};const a={stack:[r],tokenStack:[],config:t,enter:o,exit:c,buffer:i,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]];ma.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]||xa).call(a,void 0,e[0])}for(r.position={start:va(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:va(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},u=-1;++u<t.transforms.length;)r=t.transforms[u](r)||r;return r};function s(e,t,n){let s,r,i,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||i||(i=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(r=void 0;o--;){const t=e[o];if("lineEnding"===t[1].type||"lineEndingBlank"===t[1].type){if("exit"===t[0])continue;r&&(e[r][1].type="lineEndingBlank",l=!0),t[1].type="lineEnding",r=o}else if("linePrefix"!==t[1].type&&"blockQuotePrefix"!==t[1].type&&"blockQuotePrefixWhitespace"!==t[1].type&&"blockQuoteMarker"!==t[1].type&&"listItemIndent"!==t[1].type)break}i&&(!r||i<r)&&(s._spread=!0),s.end=Object.assign({},r?e[r][1].start:t[1].end),e.splice(r||a,0,["exit",s,t[2]]),a++,n++}if("listItemPrefix"===t[1].type){const r={type:"listItem",_spread:!1,start:Object.assign({},t[1].start),end:void 0};s=r,e.splice(a,0,["enter",r,t[2]]),a++,n++,i=void 0,o=!0}}}return e[t][1]._spread=l,n}function r(e,t){return function(n){o.call(this,e(n),n),t&&t.call(this,n)}}function i(){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:va(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+"` ("+ua({start:e.start,end:e.end})+"): it’s not open");s[0].type!==e.type&&(t?t.call(this,e,s[0]):(s[1]||xa).call(this,e,s[0])),n.position.end=va(e.end)}function l(){return ki(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:va(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=va(e.end)}function h(){this.data.atHardBreak=!0}function p(e){this.data.characterReferenceType=e.type}function f(){return{type:"code",lang:null,meta:null,value:""}}function m(){return{type:"heading",depth:0,children:[]}}function g(){return{type:"break"}}function v(){return{type:"html",value:""}}function y(){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(;!go(e););return e}(function(e){const t={constructs:Ai([oa,...(e||{}).extensions||[]]),content:n(Ji),defined:[],document:n(Zi),flow:n(Ko),lazy:{},string:n(Qo),text:n(Go)};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 r={},i=[];let o=[],a=[];const c={attempt:m(function(e,t){g(e,t.from)}),check:m(f),consume:function(e){Bi(e)?(s.line++,s.column=1,s.offset+=-3===e?2:1,v()):-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:m(f,{interrupt:!0})},l={code:null,containerState:{},defineSkip:function(e){r[e.line]=e.column,v()},events:[],now:h,parser:e,previous:null,sliceSerialize:function(e,t){return function(e,t){let n=-1;const s=[];let r;for(;++n<e.length;){const i=e[n];let o;if("string"==typeof i)o=i;else switch(i){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&&r)continue;o=" ";break;default:o=String.fromCharCode(i)}r=-2===i,s.push(o)}return s.join("")}(u(e),t)},sliceStream:u,write:function(e){return o=Mi(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=eo(i,l.events,l),l.events)}};let d=t.tokenize.call(l,c);return t.resolveAll&&i.push(t),l;function u(e){return function(e,t){const n=t.start._index,s=t.start._bufferIndex,r=t.end._index,i=t.end._bufferIndex;let o;if(n===r)o=[e[n].slice(s,i)];else{if(o=e.slice(n,r),s>-1){const e=o[0];"string"==typeof e?o[0]=e.slice(s):o.shift()}i>0&&o.push(e[r].slice(0,i))}return o}(o,e)}function h(){const{_bufferIndex:e,_index:t,line:n,column:r,offset:i}=s;return{_bufferIndex:e,_index:t,line:n,column:r,offset:i}}function p(e){d=d(e)}function f(e,t){t.restore()}function m(e,t){return function(n,r,i){let o,d,u,p;return Array.isArray(n)?f(n):"tokenize"in n?f([n]):function(e){return function(t){const n=null!==t&&e[t],s=null!==t&&e.null;return f([...Array.isArray(n)?n:n?[n]:[],...Array.isArray(s)?s:s?[s]:[]])(t)}}(n);function f(e){return o=e,d=0,0===e.length?i:m(e[d])}function m(e){return function(n){return p=function(){const e=h(),t=l.previous,n=l.currentConstruct,r=l.events.length,i=Array.from(a);return{from:r,restore:function(){s=e,l.previous=t,l.currentConstruct=n,l.events.length=r,a=i,v()}}}(),u=e,e.partial||(l.currentConstruct=e),e.name&&l.parser.constructs.disable.null.includes(e.name)?y():e.tokenize.call(t?Object.assign(Object.create(l),t):l,c,g,y)(n)}}function g(t){return e(u,p),r}function y(e){return p.restore(),++d<o.length?m(o[d]):i}}}function g(e,t){e.resolveAll&&!i.includes(e)&&i.push(e),e.resolve&&Ei(l.events,t,l.events.length-t,e.resolve(l.events.slice(t),l)),e.resolveTo&&(l.events=e.resolveTo(l.events,l))}function v(){s.line in r&&s.column<2&&(s.column=r[s.line],s.offset+=r[s.line]-1)}}(t,e,n)}}}(n).document().write(function(){let e,t=1,n="",s=!0;return function(r,i,o){const a=[];let c,l,d,u,h;for(r=n+("string"==typeof r?r.toString():new TextDecoder(i||void 0).decode(r)),d=0,n="",s&&(65279===r.charCodeAt(0)&&d++,s=void 0);d<r.length;){if(aa.lastIndex=d,c=aa.exec(r),u=c&&void 0!==c.index?c.index:r.length,h=r.charCodeAt(u),!c){n=r.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(r.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 va(e){return{line:e.line,column:e.column,offset:e.offset}}function ya(e,t){let n=-1;for(;++n<t.length;){const s=t[n];Array.isArray(s)?ya(e,s):ba(e,s)}}function ba(e,t){let n;for(n in t)if(ma.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 xa(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+ua({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+ua({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+ua({start:t.start,end:t.end})+") is still open")}const wa=new WeakMap;function Sa(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(ga(e))}function ka(e,t){const n=t.trim().toLowerCase();return n?e.flatMap((e,t)=>{if(Cr(e))return[];let s=wa.get(e);s?.content!==e.content&&(s={content:e.content,text:Sa(e.content).toLowerCase()},wa.set(e,s));const r=s.text,i=[];for(let o=r.indexOf(n);o>=0;o=r.indexOf(n,o+n.length))i.push({index:t,message:e,occurrence:i.length});return i}):[]}function Ia(e,t){const n=t.trim().toLowerCase();if(!n)return[];const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),r=[];let i="";for(;s.nextNode();){const e=s.currentNode;e.parentElement?.closest('button, [hidden], [aria-hidden="true"]')||(r.push({node:e,start:i.length,end:i.length+e.length}),i+=e.data)}const o=[],a=i.toLowerCase();for(let c=a.indexOf(n);c>=0;c=a.indexOf(n,c+n.length)){const e=c+n.length,t=r.find(e=>e.end>c),s=r.find(t=>t.end>=e);if(!t||!s)continue;const i=document.createRange();i.setStart(t.node,c-t.start),i.setEnd(s.node,e-s.start),o.push(i)}return o}const Ca=160;function ja(e){return Math.max(0,e-Ca)}const Ra=()=>null,Ea=()=>()=>{};function Ma({activeSession:e,activeUsage:t,messages:n,renameTitle:s,busy:r,t:a,onBrowseFiles:c,onClose:l,onExport:u,onJumpToMessage:h,onRename:p,onRenameTitleChange:m,onToggleArchived:v,onTogglePinned:y,onViewChanges:b}){const[x,w]=o.useState(""),{copyText:S,feedback:k}=lr(a.commandCopied,a.copyResumeFailed),I=o.useRef(null),C=f(l,I),j=o.useMemo(()=>Kt(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 i.jsxs("div",{"aria-labelledby":"session-detail-title","aria-modal":"true",className:"session-detail-drawer",ref:C,role:"dialog",tabIndex:-1,children:[i.jsx("div",{className:"drawer-backdrop",onClick:l,"aria-hidden":"true"}),i.jsxs("aside",{className:"session-detail-panel",children:[i.jsxs("header",{className:"drawer-header",children:[i.jsxs("div",{children:[i.jsx("span",{className:"eyebrow",children:e.agent}),i.jsx("strong",{id:"session-detail-title",title:d(e),children:i.jsx(yi,{title:d(e),draft:s,label:a.rename,disabled:r,onDraftChange:m,onCommit:p},e.sessionId)})]}),i.jsx("button",{"aria-label":a.closeSessionDetails,title:a.closeSessionDetails,className:"icon-button",onClick:l,ref:I,type:"button",children:i.jsx(Ve,{"aria-hidden":"true"})})]}),i.jsxs("div",{className:"detail-info-grid",children:[i.jsxs("div",{children:[i.jsx(ne,{"aria-hidden":"true"}),i.jsx("span",{children:a.workingDirectory}),i.jsx("strong",{title:e.cwd,children:e.cwd})]}),i.jsxs("div",{children:[i.jsx(be,{"aria-hidden":"true"}),i.jsx("span",{children:a.messages}),i.jsx("strong",{children:n.filter(e=>"user"===e.role||"assistant"===e.role).length})]}),i.jsxs("div",{children:[i.jsx(de,{"aria-hidden":"true"}),i.jsx("span",{children:a.session}),i.jsx("strong",{title:e.sessionId,children:e.sessionId})]}),i.jsxs("div",{children:[i.jsx(Be,{"aria-hidden":"true"}),i.jsx("span",{children:a.runtime}),i.jsx("strong",{children:a.runtimeState(e.runtime.state)})]})]}),e.branch||e.diffStat?i.jsxs("button",{className:"detail-command-card detail-changes-card",type:"button",onClick:b,children:[i.jsx(ae,{"aria-hidden":"true"}),i.jsx("span",{className:"detail-change-label",children:e.branch??a.changes}),i.jsx("span",{className:"detail-change-stats",role:"group","aria-label":a.changes,children:e.diffStat?i.jsxs(i.Fragment,{children:[i.jsxs("span",{className:"diff-add",children:["+",e.diffStat.additions]}),i.jsxs("span",{className:"diff-del",children:["-",e.diffStat.deletions]})]}):null})]}):null,i.jsxs("label",{className:"detail-search",children:[i.jsx(Pe,{"aria-hidden":"true"}),i.jsx("input",{value:x,onChange:e=>w(e.target.value),placeholder:a.searchMessages}),x.trim()?i.jsx("small",{children:a.searchResultCount(R.length)}):null]}),x.trim()&&R.length?i.jsx("div",{className:"detail-search-results",children:R.map(({message:e,index:t})=>i.jsxs("button",{type:"button",onClick:()=>{h(t,x),l()},children:[i.jsx("span",{children:hn(e,a)}),i.jsx("strong",{children:e.content})]},`${e.historyKey??e.timestamp??t}:${t}`))}):null,x.trim()?null:i.jsxs(i.Fragment,{children:[i.jsxs("button",{className:"detail-command-card",type:"button",onClick:c,children:[i.jsx(ne,{"aria-hidden":"true"}),i.jsx("span",{children:a.browseFiles})]}),j&&i.jsxs("button",{className:"detail-command-card",type:"button",onClick:()=>{S(j)},children:[i.jsx(U,{"aria-hidden":"true"}),i.jsx("span",{title:j,children:j})]}),i.jsx(dr,{feedback:k}),i.jsxs("div",{className:"detail-action-grid",children:[i.jsxs("button",{className:"icon-text-button",disabled:r,type:"button",onClick:y,children:[i.jsx(Re,{"aria-hidden":"true"}),e.pinned?a.unpin:a.pin]}),i.jsxs("button",{className:"icon-text-button",disabled:r,type:"button",onClick:v,children:[i.jsx(P,{"aria-hidden":"true"}),e.archived?a.unarchive:a.archive]}),i.jsxs("button",{className:"icon-text-button",type:"button",onClick:u,children:[i.jsx(g,{"aria-hidden":"true"}),a.exportSession]})]}),t?i.jsxs("p",{className:"detail-usage",children:[a.usage,": ",t.limits?.fiveHour?.usedPercent??"-","% 5h ·"," ",t.limits?.weekly?.usedPercent??"-","% weekly"]}):null,i.jsxs("p",{className:"detail-usage",children:[a.created," ",un(e.createdAt,Date.now(),a)]})]})]})]})}function Ta({activeSession:e,activeUsage:t,busy:n,messages:s,renameTitle:r,t:o,onBrowseFiles:a,onDetailsOpenChange:c,onExportActiveSession:l,onRenameSession:d,onRenameTitleChange:u,onToggleArchived:h,onTogglePinned:p,onViewChanges:f,onJumpToMessage:m}){return e?i.jsx(Ma,{activeSession:e,activeUsage:t,busy:n,messages:s,renameTitle:r,t:o,onBrowseFiles:()=>{c(!1),a()},onClose:()=>c(!1),onExport:l,onJumpToMessage:(e,t)=>{m(e,t)},onRename:d,onRenameTitleChange:u,onToggleArchived:h,onTogglePinned:p,onViewChanges:()=>{c(!1),f(e.sessionId)}}):null}function Aa({client:e,activeSession:t,activeSessionId:n,activeModelOptions:s,activeQueue:r,queueControls:a,activeUsage:c,agent:l,approvalMode:d,attachments:u,busy:h,rewinding:p,cwd:f,draft:m,effort:g,errorText:v,failedSend:y,onDismissFailedSend:b,fastMode:x,historyLoading:w,hasOlderHistory:S,olderHistoryLoading:k,onLoadOlderHistory:I,messages:C,messagesSessionId:j,model:R,phase:E,quickReplies:M,onQuickRepliesChange:T,quickRepliesOpen:A,onQuickRepliesOpenChange:N,onSendQuickReply:P,renameTitle:D,respondingSessionIds:L,sendShortcut:F,skills:q,uploadBusy:O,detailsOpen:_,t:$,onApprovalModeChange:z,onBrowseFiles:H,onCancelQueuedTurn:B,onClearInterrupt:U,onDraftChange:W,onDetailsOpenChange:K,onEffortChange:V,onExportActiveSession:Q,onRewindMessage:G,onFastModeChange:J,onRetryFailedSend:Z,onModelChange:X,onOpenRemoteFile:Y,onInterrupt:ee,onRetry:te,onDismissError:ne,onRefreshSkills:se,onRenameSession:re,onRenameTitleChange:ie,onRemoveAttachment:oe,onSubmit:ae,onToggleArchived:ce,onTogglePinned:le,onUploadFiles:de,onViewChanges:ue}){const he=pt(e,l,f,n,R,s,$),pe=function(e,t,n,s){const r=o.useSyncExternalStore(e.submission?.subscribe??Ea,e.submission?.getSnapshot??Ra,Ra),i=o.useRef(new Set),a=async e=>{if(!i.current.has(s)){i.current.add(s);try{await e()}finally{i.current.delete(s)}}};return{sending:!!r?.some(e=>e.sessionId===s),submit:t=>{if(t?.preventDefault(),n)return a(()=>e())},retry:()=>a(t)}}(ae,Z,"connected"===E&&!h&&!O&&!u.some(e=>e.uploading)&&(!!m.trim()||u.length>0),n),fe=function(e){const t=o.useRef(e);return o.useLayoutEffect(()=>{t.current=e}),t}({onRewindMessage:G,onOpenRemoteFile:Y,onDismissFailedSend:b,retry:pe.retry}),[me,ge]=o.useState(null),[ve,ye]=o.useState(null),[be,xe]=o.useState(!1),we=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 r=s?`${s.historyKey??s.timestamp}:${s.content.length}`:"",i=o.useRef({sessionId:e,revision:r}),[a,c]=o.useState(!1);return o.useEffect(()=>{i.current.sessionId===e&&n?r&&r!==i.current.revision&&c(!0):c(!1),i.current={sessionId:e,revision:r}},[e,r,n]),n&&i.current.sessionId===e&&a}(n,j===n?C:[],be),Se=o.useRef(null),ke=o.useRef([]),Ie=o.useRef(null),Ce=o.useRef(null),je=o.useRef(!1),Re=o.useRef(!1),Ee=o.useRef(!0),Me=o.useRef(0),Te=o.useRef(0),Ae=o.useMemo(()=>function(e){const t=[];for(let n=0;n<e.length;n+=1){const s=e[n];if(!Cr(s)){t.push({type:"message",index:n,message:s});continue}const r=[];let i=n;for(;i<e.length&&Cr(e[i]);)r.push({index:i,message:e[i]}),i+=1;t.push({type:"toolGroup",entries:r,id:`tool-group:${r.map(({index:e,message:t})=>Rr(t,e)).join("|")}`}),n=i-1}return t}(C),[C]),Ne=Boolean(n&&L.has(n)),Pe=Ne&&j===n&&!w,De=Pe&&"assistant"===C.at(-1)?.role&&"info"!==C.at(-1)?.type?C.length-1:-1,[Le,Fe]=o.useState(!1),{ensureMessageVisible:qe,hiddenItemCount:Oe,hiddenLaterItemCount:_e,revealAll:$e,revealEarlier:ze,revealLatest:He,revealStart:Be,visibleItems:Ue}=function(e,t,n=!1){const s=t.length,[r,i]=o.useState(()=>({sessionId:e,start:ja(s),total:s})),a=r.sessionId!==e?ja(s):n?0:-1===r.start?-1:s>r.total&&r.start+Ca>=r.total?ja(s):Math.min(r.start,ja(s));o.useLayoutEffect(()=>{r.sessionId===e&&r.start===a&&r.total===s||i({sessionId:e,start:a,total:s})},[e,a,r,s]);const c=o.useCallback(()=>{i(t=>({sessionId:e,start:Math.max(0,(t.sessionId===e?t.start:ja(s))-120),total:s}))},[e,s]),l=o.useCallback(n=>{const r=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||r<0||r>=a&&r<a+Ca)return!1;const o=Math.min(ja(s),Math.max(0,r-40));return i({sessionId:e,start:o,total:s}),!0},[t,e,a,s]),d=o.useCallback(()=>{i({sessionId:e,start:ja(s),total:s})},[e,s]),u=o.useCallback(()=>{i({sessionId:e,start:0,total:s})},[e,s]),h=Math.max(0,a),p=-1===a?s:Math.min(s,a+Ca);return{ensureMessageVisible:l,hiddenItemCount:h,hiddenLaterItemCount:Math.max(0,s-p),revealEarlier:c,revealLatest:d,revealStart:u,revealAll:()=>i({sessionId:e,start:-1,total:s}),visibleItems:o.useMemo(()=>t.slice(h,p),[t,h,p])}}(n,Ae,Le),We=o.useRef(!1),Ke=o.useRef(null),Ve=o.useMemo(()=>Boolean(y&&Ue.some(e=>"message"===e.type&&e.message.historyKey===y.historyKey)),[y,Ue]),Qe=o.useRef(null),{copyText:Ge,feedback:Je}=lr($.messageCopied,$.copyFailed),Ze=function(e,t,n,s){const[r,i]=o.useState(""),[a,c]=o.useState(0),l=o.useMemo(()=>ka(e,r),[e,r]),d=l.length?a%l.length:0,u=l[d],h=o.useRef(s);return h.current=s,o.useEffect(()=>{i(""),c(0)},[t]),o.useEffect(()=>{u&&h.current(u.index)},[r,d,u?.index]),o.useEffect(()=>{const e=n.current;if(!r.trim()||!e||"undefined"==typeof CSS||!CSS.highlights||"undefined"==typeof Highlight)return;let t=0,s=!1;const i=()=>{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 i=Ia(e,r);t.push(...i),Number(s.getAttribute("data-message-index"))===u?.index&&i[u.occurrence]&&n.push(i[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(),r=e.getBoundingClientRect();(t.top<r.top||t.bottom>r.bottom)&&(e.scrollTop+=t.top-r.top-r.height/2)}},o=()=>{cancelAnimationFrame(t),t=requestAnimationFrame(()=>{t=requestAnimationFrame(i)})},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")}},[r,d,u?.index,u?.occurrence,n]),{query:r,matchCount:l.length,activeMatchIndex:l.length?d+1:0,activeMessageIndex:u?.index,onChange:e=>{i(e),c(0)},onJump:(t,n)=>{i(n),c(Math.max(0,ka(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)}}(C,n,Se,e=>((e,t="smooth")=>{Ee.current=!1,Me.current=0;const n=qe(e),s=()=>ke.current[e]?.scrollIntoView({behavior:t,block:"center"});n?requestAnimationFrame(()=>requestAnimationFrame(s)):s()})(e,"instant")),Xe=o.useCallback(()=>{const e=Se.current;e&&(Ee.current=!0,Me.current=0,e.scrollTop=e.scrollHeight,xe(!1))},[]),Ye=o.useCallback(e=>{Ee.current=!0,Me.current=0,Re.current=!0,je.current=!1,Qe.current=null;const t=Se.current,n=t?t.scrollHeight-t.scrollTop-t.clientHeight:0,s=e??(0===_e&&t&&n<=t.clientHeight?"smooth":"auto"),r=()=>{const e=Se.current;e&&Re.current&&(e.scrollTo({top:e.scrollHeight,behavior:s}),xe(!1),requestAnimationFrame(()=>{Re.current=!1}))};_e>0?(He(),requestAnimationFrame(()=>requestAnimationFrame(r))):r()},[_e,He]),et=()=>{const e=Se.current;e&&(Qe.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,Ue))},tt=async()=>{if(!n||!S||!I||w||k||Ke.current)return;const e=n;Ke.current=e,We.current=!0,Ee.current=!1,je.current=!0,et(),Fe(!0);try{await I()}finally{Ke.current===e&&(Ke.current=null,Fe(!1))}},nt=()=>{const e=Se.current;if(!e)return;Me.current>0&&e.scrollTop<160&&j===n&&!je.current&&!Re.current&&(Oe>0?(je.current=!0,et(),ze()):tt());const t=e.scrollTop>Te.current;Te.current=e.scrollTop;const s=e.scrollHeight-e.scrollTop-e.clientHeight;Me.current>0&&!Re.current&&!je.current&&(Ee.current=t&&s<=2&&0===_e),xe(s>180||_e>0)};o.useLayoutEffect(()=>{_e>0&&xe(!0)},[_e]);const st=function(e,t,n,s,r,i,o,a=0){const c=()=>{const o=t.current||s.current;n.current=null,s.current=!1,t.current=!1,r.current=performance.now();const a=e.current;i.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,r.current=performance.now(),i.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()}}}(Se,Ee,Ce,Re,Me,Te,Be,Oe),rt=function(e){const t=e.at(-1);return t?`${e.length}:${t.historyKey??""}:${t.timestamp??""}:${t.content.length}`:"0"}(C);o.useLayoutEffect(()=>{Ie.current!==n&&(Qe.current=null,je.current=!1,We.current=!1,Ke.current=null,Fe(!1));const e=Qe.current,t=Se.current;if(e&&t){if(Le)return;return Oe>0&&We.current?void Be():(function(e,t,n,s){const r=t.message,i=r?n.findIndex(e=>e===r||(r.historyKey?e.historyKey===r.historyKey:e.role===r.role&&e.timestamp===r.timestamp&&e.content===r.content)):-1,o=i>=0?s[i]:t.element;e.scrollTop+=o?.isConnected?o.getBoundingClientRect().top-e.getBoundingClientRect().top-t.top:e.scrollHeight-t.height}(t,e,C,ke.current),Qe.current=null,je.current=!1,void(We.current=!1))}if(Ie.current!==n&&(Ie.current=n,Ce.current=n,ge(null),ye(null)),!Se.current)return;const s=j===n;if(null!==n&&Ce.current===n&&s&&(!w||C.length>0)){Xe();let e=0,t=-1,s=0;const r=performance.now(),i=()=>{if(Ce.current!==n)return;Xe();const o=Se.current?.scrollHeight??0;s=o===t?s+1:0,t=o;const a=performance.now()-r>=1400;!w&&s>=4||!w&&a?Ce.current=null:a||(e=requestAnimationFrame(i))};return e=requestAnimationFrame(i),xe(!1),()=>cancelAnimationFrame(e)}Ee.current&&0===_e&&Xe()},[n,Oe,_e,w,rt,Le,Be,C.length,j,E,Pe,Xe]),o.useLayoutEffect(()=>{const e=Se.current;if(!e)return;const t=new ResizeObserver(()=>{Ee.current&&0===_e&&Xe()});t.observe(e);for(const n of e.children)t.observe(n);return()=>t.disconnect()},[n,rt,Oe,_e,Pe,Xe]);const it=Ze.activeMessageIndex;return function(e,t,n){const s=o.useRef(n);s.current=n;const r=o.useRef(!1),[i,a]=o.useState(0);o.useLayoutEffect(()=>{r.current=!1;const t=t=>{"focusin"===t.type&&t.target instanceof Element&&t.target.contains(e.current)||(r.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=>{r.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(!r.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)},[i,e,t])}(Se,n,()=>{et(),$e()}),i.jsxs("section",{className:"chat-pane","aria-label":$.chat,children:[i.jsx(wi,{activeSession:t,agent:l,cwd:f,t:$,onOpenDetails:()=>t&&K(!0),onScrollToStart:st.toStart,renameTitle:D,busy:h,onRename:re,onRenameTitleChange:ie,onViewChanges:ue,search:Ze}),i.jsxs("div",{className:"message-scroll","data-session-id":j===n?n??void 0:void 0,"aria-busy":w,"data-history-loading":w?"true":"false","data-rendered-items":Ue.length,"data-hidden-items":Oe,"data-hidden-later-items":_e,"data-total-messages":C.length,ref:Se,onScroll:nt,...st,onWheel:e=>{st.onWheel(e),e.deltaY<0&&nt()},children:[w&&0===C.length?i.jsx(hr,{label:$.loadingHistory}):null,w||0!==C.length||Pe?null:i.jsx(ft,{title:t?$.noVisibleMessages:$.startDaemonSession,hint:$.emptyChatHint}),S&&0===Oe?i.jsx("div",{className:"conversation-window-gate",children:i.jsx("button",{type:"button",disabled:k,onClick:()=>{tt()},children:k?$.loadingHistory:$.loadEarlierMessages})}):null,Oe>0?i.jsx("div",{className:"conversation-window-gate",children:i.jsx("button",{type:"button",onClick:()=>{je.current=!0,et(),ze()},children:$.showEarlierMessages(Oe)})}):null,i.jsx(hi,{items:Ue,activeQueue:j===n?r:void 0,actions:fe,messageRefs:ke,activeMatchedMessageIndex:it,baseCwd:t?.cwd,canRewind:!h&&!Ne,hiddenLaterItemCount:_e,replyingMessageIndex:De,openSourceKey:me,openToolKey:ve,setOpenSourceKey:ge,setOpenToolKey:ye,copyText:Ge,failedSend:y,t:$}),Pe&&0===_e&&De<0?i.jsx("div",{className:"message-frame assistant","data-replying-placeholder":"true",children:i.jsx("div",{className:"message assistant replying-placeholder",children:i.jsx(ai,{label:$.replyingMessage})})}):null,_e>0?i.jsx("div",{className:"conversation-window-gate",children:i.jsx("button",{type:"button",onClick:()=>Ye("auto"),children:$.showLatestMessages(_e)})}):null,i.jsx("div",{"aria-hidden":"true",className:"message-latest-anchor"})]}),be?i.jsx(fr,{label:we?$.interactionNewReply:$.interactionLatest,onClick:()=>Ye()}):null,i.jsx(dr,{feedback:Je}),i.jsx(ar,{terminals:t?.runtime.backgroundTerminals,t:$},`terminals:${n}`),i.jsx(vi,{rewinding:p,client:e,activeSession:t,busy:h,errorText:v,failedSend:y,failedSendVisibleInConversation:Ve,onClearInterrupt:U,onDismissError:ne,onDismissFailedSend:b,onRetry:te,onRetryFailedSend:()=>{pe.retry()},t:$}),o.createElement(or,{client:e,activeSessionId:n,key:n,activeModelOptions:he,activeQueue:r,queueControls:{...a,onAction:(e,t)=>(Ye("auto"),a.onAction(e,t))},agent:l,approvalMode:d,attachments:u,busy:h,sending:pe.sending,responding:Ne,onStop:ee,draft:m,effort:g,fastMode:x,model:R,phase:E,quickReplies:M,onQuickRepliesChange:T,quickRepliesOpen:A,onQuickRepliesOpenChange:N,onSendQuickReply:P,sendShortcut:F,skills:q,uploadBusy:O,onApprovalModeChange:z,onCancelQueuedTurn:B,onDraftChange:W,onEffortChange:V,onFastModeChange:J,onModelChange:X,onRemoveAttachment:oe,onOpenRemoteFile:Y,onRefreshSkills:se,onSubmit:e=>(Ye("auto"),pe.submit(e)),onUploadFiles:de,t:$}),_?i.jsx(Ta,{activeSession:t,activeUsage:c,busy:h,messages:C,renameTitle:D,t:$,onBrowseFiles:H,onDetailsOpenChange:K,onExportActiveSession:Q,onRenameSession:re,onRenameTitleChange:ie,onToggleArchived:ce,onTogglePinned:le,onViewChanges:ue,onJumpToMessage:Ze.onJump}):null]})}const Na=["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"],Pa=["authorization","proxy-authorization"],Da=["cookie","set-cookie"],La=[...Pa,...Da],Fa=(e,t)=>t.length-e.length,qa=[...Na].sort(Fa).join("|"),Oa=Na.filter(e=>!La.includes(e)).sort(Fa).join("|"),_a=[...Pa].sort(Fa).join("|"),$a=[...Da].sort(Fa).join("|"),za=new RegExp(`(?:${qa}|credential|private[-_ ]?key|session[-_ ]?id|e-?mail|phone|mobile|address)`,"i"),Ha=new RegExp(`(["']?(?:${_a})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|(?:Basic|Bearer)\\s+[^\\s,;}]+|AWS4-HMAC-SHA256[^\\r\\n]*(?=\\r?$)|[^\\s,;}]+)`,"gim"),Ba=new RegExp(`(["']?(?:${$a})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\r\\n]+)`,"gi"),Ua=new RegExp(`(["']?(?:${Oa})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\s,;}&]+)`,"gi"),Wa=new RegExp(`([?&](?:${qa})=)[^&\\s]+`,"gi");function Ka(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 r='"'===s[0]||"'"===s[0]?s[0]:"";if(!r)return`${n}${t}`;const i=s.slice(1,-1).trim(),o=/^(Basic|Bearer)\b/i.exec(i)?.[1];return`${n}${r}${o?`${o} `:""}${t}${r}`};return e.replace(/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gi,t).replace(Ha,n).replace(Ba,n).replace(Ua,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(Wa,`$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 Va(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 Qa(e,t={}){const n=new AbortController,s=Number.isFinite(t.timeoutMs)&&(t.timeoutMs??0)>0?t.timeoutMs:15e3;let r;try{const i=(t.transport??Va)({url:t.endpoint??"https://service.lifeos.vip/feedback",method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:n.signal}),o=new Promise((e,t)=>{r=setTimeout(()=>{n.abort(),t(new Error("Feedback request timed out"))},s)}),a=await Promise.race([i,o]),c=function(e){try{const t=JSON.parse(e);return t&&"object"==typeof t?t:{}}catch{return{}}}(a.body);if(a.status<200||a.status>=300||0!==c.code)throw new Error(c.message||a.statusText||"Feedback request failed");if("string"!=typeof c.data?.id||!c.data.id||"string"!=typeof c.data.createdAt)throw new Error("Feedback response is invalid");return{id:c.data.id,createdAt:c.data.createdAt,issueFingerprint:"string"==typeof c.data?.issueFingerprint?c.data.issueFingerprint:void 0,issueOccurrence:"number"==typeof c.data?.issueOccurrence?c.data.issueOccurrence:void 0}}finally{r&&clearTimeout(r)}}const Ga=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 Ja(e){const t={contextSchemaVersion:1};if(e)for(const[n,s]of Object.entries(e))Ga.has(n)&&void 0!==s&&(t[n]=s);return function(e,t={}){if(!e)return{};const n=Math.max(0,t.characterBudget??6e4),s=Math.max(0,t.maxArrayEntries??50),r=Math.max(0,t.maxDepth??8),i=Math.max(0,t.maxObjectEntries??80),o=Math.max(0,t.maxStringLength??4e3),a={remaining:n},c=new WeakSet,l=(e,t)=>{if(a.remaining<=0)return"[TRUNCATED]";if(null===e||"boolean"==typeof e||"number"==typeof e)return e;if("bigint"==typeof e)return e.toString();if("string"==typeof e){const t=Ka(e).slice(0,Math.min(o,a.remaining));return a.remaining-=t.length,t}if(t>=r)return"[MAX_DEPTH]";if("object"!=typeof e)return Ka(String(e)).slice(0,Math.min(200,a.remaining));if(c.has(e))return"[Circular]";if(c.add(e),Array.isArray(e))return e.slice(0,s).map(e=>l(e,t+1));const n={};for(const[s,r]of Object.entries(e).slice(0,i)){if(a.remaining<=0)break;const e=Ka(s).slice(0,Math.min(120,a.remaining));a.remaining-=e.length,n[e]=za.test(s)?"[REDACTED]":l(r,t+1)}return n};return l(e,0)}(t)}const Za={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"},Xa={title:"意见反馈",subtitle:"报告问题,或告诉我们希望改进的地方。",bug:"问题",feature:"建议",description:"详细说明",descriptionPlaceholder:"发生了什么,或者你希望我们怎样改进?",email:"邮箱(选填)",emailPlaceholder:"便于我们回复你",includeDiagnostics:"附带经过隐私处理的诊断信息",privacyNotice:"仅在需要时附带诊断信息;发送前会移除已识别的凭据、个人标识和本地路径。",submit:"发送反馈",sending:"正在发送…",success:"感谢反馈,已经发送成功。",error:"发送失败,请稍后重试。",close:"关闭"},Ya={title:"意見回饋",subtitle:"回報問題,或告訴我們希望改善的地方。",bug:"問題",feature:"建議",description:"詳細說明",descriptionPlaceholder:"發生了什麼,或你希望我們如何改善?",email:"電子郵件(選填)",emailPlaceholder:"方便我們回覆你",includeDiagnostics:"附上經過隱私處理的診斷資訊",privacyNotice:"僅在需要時附上診斷資訊;傳送前會移除已識別的憑證、個人識別資訊和本機路徑。",submit:"傳送回饋",sending:"正在傳送…",success:"感謝回饋,已成功傳送。",error:"傳送失敗,請稍後再試。",close:"關閉"};function ec(e){const t=e?.trim().toLowerCase().replace(/_/g,"-")??"";return/^zh(?:-(?:tw|hk|mo|hant))(?:-|$)/u.test(t)?Ya:t.startsWith("zh")?Xa:Za}const tc=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function nc(e){if(!e?.length)return;if(e.length>4)throw new Error("Feedback supports at most 4 images");const t=e.map(e=>{if(!tc.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:Ka(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 sc({language:e,entry:t="web-settings"}){const r=s(e),a=o.useMemo(()=>ec(r),[r]),[c,l]=o.useState("bug"),[d,u]=o.useState(""),[h,p]=o.useState(""),[f,m]=o.useState("idle");return i.jsxs("section",{className:"control-section compact-section",children:[i.jsx("h2",{children:a.title}),i.jsx("p",{className:"empty-copy",children:a.subtitle}),i.jsxs("div",{className:"feedback-type-grid",children:[i.jsx("button",{className:"bug"===c?"primary-button":"",type:"button","aria-pressed":"bug"===c,onClick:()=>l("bug"),children:a.bug}),i.jsx("button",{className:"feature"===c?"primary-button":"",type:"button","aria-pressed":"feature"===c,onClick:()=>l("feature"),children:a.feature})]}),i.jsxs("label",{className:"field",children:[i.jsx("span",{children:a.description}),i.jsx("textarea",{rows:5,maxLength:8e3,value:d,placeholder:a.descriptionPlaceholder,onChange:e=>u(e.target.value)})]}),i.jsxs("label",{className:"field",children:[i.jsx("span",{children:a.email}),i.jsx("input",{type:"email",maxLength:320,value:h,placeholder:a.emailPlaceholder,onChange:e=>p(e.target.value)})]}),i.jsx("button",{className:"primary-button",type:"button",disabled:!d.trim()||"sending"===f,onClick:()=>{(async()=>{if(d.trim()&&"sending"!==f){m("sending");try{await Qa(function(e){const t=function(e){return Ka(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=Ka(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:Ja(e.metadata),images:nc(e.images)}}({product:"vibelet",source:"desktop"===n().kind?"desktop":"web",type:c,description:d,email:h,appVersion:n().appVersion||"web",locale:r,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(""),m("success")}catch{m("error")}}})()},children:"sending"===f?a.sending:a.submit}),"success"===f?i.jsx("p",{className:"empty-copy success-copy",children:a.success}):null,"error"===f?i.jsx("p",{className:"empty-copy error-copy",children:a.error}):null]})}const rc=[[0,.024],[.05,.078],[.25,.157],[.5,.243],[.75,.325],[.9,.4],[.97,.459],[.995,.506],[1,.533]];function ic(e,t,n){let s=374761393*e+668265263*t+2147483647*n|0;return s=Math.imul(s^s>>>13,1274126177),s^=s>>>16,(s>>>0)/4294967295}function oc(e,t,n,s){const r=Math.floor(e),i=Math.floor(t),o=e-r,a=t-i,c=o*o*o*(o*(6*o-15)+10),l=a*a*a*(a*(6*a-15)+10),d=e=>(e%n+n)%n,u=ic(d(r),i,s),h=ic(d(r+1),i,s),p=ic(d(r),i+1,s);return u+(h-u)*c+(p-u)*l+(u-h-p+ic(d(r+1),i+1,s))*c*l}function ac(e,t,n,s){const r=new Float32Array(e*e);for(let i=0;i<e;i++)for(let o=0;o<e;o++){let a=0,c=1,l=0;for(let r=0;r<n;r++){const n=t<<r;a+=c*oc(o/e*n,i/e*(n/2),n,s+97*r),l+=c,c*=.5}r[i*e+o]=a/l}return r}function cc(e,t,n){let s=0;for(const a of e)s+=a;const r=s/e.length;let i=0;for(const a of e)i+=(a-r)**2;const o=Math.sqrt(i/e.length)||1;return e.map(e=>t+(e-r)/o*n)}function lc(e,t,n){const s=Math.floor(6*e),r=6*e-s,i=n*(1-t),o=n*(1-r*t),a=n*(1-(1-r)*t);switch((s%6+6)%6){case 0:return[n,a,i];case 1:return[o,n,i];case 2:return[i,n,a];case 3:return[i,o,n];case 4:return[a,i,n];default:return[n,i,o]}}let dc=null;const uc=["fixed","gradient-2","gradient-3","spectrum"],hc=["none","brighten","flow","spotlight"],pc={color:"#b126ff",colorMode:"spectrum",color2:"#ff177c",color3:"#35d3ff",fixedColor:!1,speed:.7,paused:!1,phase:0,feather:95,projectionScale:174,intensity:1.15,grain:.035,seed:7},fc=(e,t,n,s)=>Math.min(s,Math.max(n,Number.isFinite(e)?e:t)),mc=e=>{let t=e.replace(/^#/,"");return/^[\da-f]{3}$/i.test(t)&&(t=Array.from(t,e=>e+e).join("")),/^[\da-f]{6}$/i.test(t)||(t="b126ff"),[0,2,4].map(e=>parseInt(t.slice(e,e+2),16)/255)};function gc({columns:e=1,rows:t=1,gap:n=0,colorSpread:s=0,centerProjectionScale:r,borderRadius:a,hoverEffect:c="none",...l}){const d=o.useRef(null),u=o.useRef(null),h=()=>({...pc,...Object.fromEntries(Object.entries(l).filter(([,e])=>void 0!==e)),colorMode:l.colorMode??(l.fixedColor?"fixed":"spectrum"),columns:e,rows:t,gap:n,colorSpread:s,centerProjectionScale:r,borderRadius:a,hoverEffect:c}),p=o.useRef(h());return o.useEffect(()=>{p.current=h(),u.current?.()}),o.useEffect(()=>{const e=d.current,t=e.parentElement instanceof HTMLButtonElement?e.parentElement:null,n=e.getContext("webgl",{alpha:!0,premultipliedAlpha:!0,antialias:!1});if(!n)return;let s=null,r=null,i=null,o=null,a=null,c=!1,l={},h=0,f=0,m=0,g=0,v=0,y=!1,b=!1,x=[0,0],w=!0,S=!1,k=!1,I=1,C=1;const j=matchMedia("(prefers-reduced-motion: reduce)"),R=(e,t)=>{const s=n.createShader(e);return n.shaderSource(s,t),n.compileShader(s),n.getShaderParameter(s,n.COMPILE_STATUS)?s:(n.deleteShader(s),null)},E=()=>{n.deleteBuffer(r),n.deleteProgram(s),n.deleteShader(i),n.deleteShader(o),n.deleteTexture(a),r=null,s=null,i=null,o=null,a=null},M=()=>{i=R(n.VERTEX_SHADER,"\nattribute vec2 a_position;\nvarying vec2 v_uv;\nvoid main() {\n v_uv = a_position * .5 + .5;\n gl_Position = vec4(a_position, 0., 1.);\n}");const t=!!n.getExtension("OES_standard_derivatives");k=t&&!!n.getExtension("EXT_shader_texture_lod");const d=(t?"#define USE_CHROMATIC_DERIVATIVES\n":"")+(k?"#define USE_CHROMATIC_TEXTURE_LOD\n":"");if(o=R(n.FRAGMENT_SHADER,d+"\n#ifdef USE_CHROMATIC_DERIVATIVES\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef USE_CHROMATIC_TEXTURE_LOD\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\nvarying vec2 v_uv;\nuniform vec2 u_size;\nuniform vec2 u_resolution;\nuniform vec2 u_grid;\nuniform float u_gap;\nuniform float u_time;\nuniform float u_phase;\nuniform float u_feather;\nuniform float u_projectionScale;\nuniform float u_centerProjectionScale;\nuniform float u_borderRadius;\nuniform float u_intensity;\nuniform float u_grain;\nuniform float u_spread;\nuniform float u_seed;\nuniform vec3 u_color;\nuniform float u_colorMode;\nuniform vec3 u_color2;\nuniform vec3 u_color3;\nuniform sampler2D u_field;\nuniform float u_hover;\nuniform float u_hoverEffect;\nuniform vec2 u_hoverPosition;\n\nfloat hash(vec3 p) {\n p = fract(p * .1031);\n p += dot(p, p.yzx + 33.33);\n return fract((p.x + p.y) * p.z);\n}\nvec3 hsv(vec3 c) {\n vec3 p = abs(fract(c.xxx + vec3(0., 2./3., 1./3.)) * 6. - 3.);\n return c.z * mix(vec3(1.), clamp(p - 1., 0., 1.), c.y);\n}\nvec3 rgbToHsv(vec3 c) {\n vec4 k = vec4(0., -1./3., 2./3., -1.);\n vec4 p = mix(vec4(c.bg, k.wz), vec4(c.gb, k.xy), step(c.b, c.g));\n vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r));\n float d = q.x - min(q.w, q.y);\n return vec3(abs(q.z + (q.w - q.y) / (6. * d + 1.e-8)), d / (q.x + 1.e-8), q.x);\n}\nmat2 rotate(float a) { return mat2(cos(a), -sin(a), sin(a), cos(a)); }\n\nvec3 rotatedField(vec2 source, float t, float tile) {\n vec2 uv = source * vec2(3.14159265, 1.57079633);\n vec3 sphere = vec3(cos(uv.y) * sin(uv.x), sin(uv.y), cos(uv.y) * cos(uv.x));\n sphere.xy = rotate(sin(t * .22 + tile * 3.1) * .55) * sphere.xy;\n sphere.yz = rotate(sin(t * .18 + tile * 2.4) * .55) * sphere.yz;\n sphere.xz = rotate(t * .16 + tile * 6.28) * sphere.xz;\n vec2 fieldUv = vec2(atan(sphere.x, sphere.z) / 6.283185 + .5, asin(clamp(sphere.y, -1., 1.)) / 3.141593 + .5);\n#ifdef USE_CHROMATIC_TEXTURE_LOD\n // Longitude wraps from 1 to 0 on the back meridian. Implicit derivatives see\n // that as a full-texture jump and pick the smallest mip, drawing dotted seams,\n // so select the mip from the wrapped (true) longitude change instead.\n vec2 dx = dFdx(fieldUv);\n vec2 dy = dFdy(fieldUv);\n dx.x -= floor(dx.x + .5);\n dy.x -= floor(dy.x + .5);\n return texture2DGradEXT(u_field, fieldUv, dx, dy).rgb;\n#else\n return texture2D(u_field, fieldUv).rgb;\n#endif\n}\nvec3 blurredField(vec2 source, float t, float tile) {\n // Blur the rotated field in the unprojected plane so compressed edges\n // remain soft after projection.\n float b = .045;\n vec3 c = rotatedField(source, t, tile) * .28;\n c += (rotatedField(source + vec2(b,0), t, tile) + rotatedField(source - vec2(b,0), t, tile)\n + rotatedField(source + vec2(0,b), t, tile) + rotatedField(source - vec2(0,b), t, tile)) * .12;\n c += (rotatedField(source + vec2(b,b), t, tile) + rotatedField(source - vec2(b,b), t, tile)\n + rotatedField(source + vec2(b,-b), t, tile) + rotatedField(source + vec2(-b,b), t, tile)) * .06;\n return c;\n}\nvec2 projectedSource(vec2 p, float fov) {\n vec2 angle = p * fov;\n float longitude = clamp(angle.x, -1.565, 1.565);\n float latitude = clamp(angle.y, -1.565, 1.565);\n return vec2(tan(longitude), tan(latitude) / max(.005, cos(longitude))) / tan(fov);\n}\nvec2 contourExtent() {\n vec2 halfSize = max(vec2(2.), (u_size / u_grid - u_gap) * .5);\n return halfSize / min(halfSize.x, halfSize.y);\n}\nfloat contourRadius(vec2 p) {\n // Intersect a ray with circular corners in physical coordinates. A wide\n // button retains straight sides and round end caps instead of becoming an ellipse.\n vec2 direction = abs(p) / max(length(p), .000001);\n vec2 extent = contourExtent();\n vec2 center = extent - u_borderRadius;\n if (direction.y * extent.x <= direction.x * center.y)\n return extent.x / max(direction.x, .000001);\n if (direction.x * extent.y <= direction.y * center.x)\n return extent.y / max(direction.y, .000001);\n float cross = direction.x * center.y - direction.y * center.x;\n return dot(direction, center)\n + sqrt(max(u_borderRadius * u_borderRadius - cross * cross, 0.));\n}\nfloat contourBoundary(vec2 p) {\n if (u_borderRadius < 0.) return max(abs(p.x), abs(p.y));\n vec2 physical = p * contourExtent();\n return length(physical) / max(contourRadius(physical), .000001);\n}\nvec2 materialSource(vec2 p, float fov, float centerFov) {\n if (u_borderRadius >= 0.) {\n // Project from the actual contour instead of clipping a square field.\n // Every point on the rounded/circular edge reaches the same source rim.\n float radius = contourBoundary(p);\n float angle = mix(centerFov, fov, smoothstep(.8, .95, radius));\n float projected = tan(min(radius * angle, 1.565)) / tan(angle);\n return p / max(length(p), .000001) * projected;\n }\n // The face can keep its own projection, which sets how the central gradient\n // moves, while the rim reflections keep the outer projection.\n float rim = smoothstep(.8, .95, max(abs(p.x), abs(p.y)));\n return mix(projectedSource(p, centerFov), projectedSource(p, fov), rim);\n}\nfloat projectedBoundary(vec2 p, float fov, float centerFov) {\n vec2 source = materialSource(p, fov, centerFov);\n return u_borderRadius < 0. ? max(abs(source.x), abs(source.y)) : length(source);\n}\nvoid main() {\n vec2 cellSize = u_size / u_grid;\n vec2 pixel = vec2(v_uv.x, 1. - v_uv.y) * u_size;\n vec2 id = floor(pixel / cellSize);\n vec2 halfSize = max(vec2(2.), (cellSize - u_gap) * .5);\n vec2 p = (mod(pixel, cellSize) - cellSize * .5) / halfSize;\n float tile = fract(dot(id, vec2(.754877666, .569840296)) + u_seed * .1031);\n float t = u_time + u_phase * 6.283185;\n if (u_hoverEffect > 1.5 && u_hoverEffect < 2.5) t += u_hover * 1.25;\n\n // Inverse of AE's Plane to Sphere: a 174 degree flat plane is mapped into\n // an equirectangular 360 x 180 degree frame. Most source pixels compress\n // into the perimeter; the colored rim is the projected field itself.\n float fov = radians(u_projectionScale * .5);\n float centerFov = radians(u_centerProjectionScale * .5);\n vec2 source = materialSource(p, fov, centerFov);\n float boundary = u_borderRadius < 0. ? max(abs(source.x), abs(source.y)) : length(source);\n float boxBoundary = contourBoundary(p);\n float edgeWidth;\n float boxWidth;\n#ifdef USE_CHROMATIC_DERIVATIVES\n edgeWidth = fwidth(boundary);\n boxWidth = fwidth(boxBoundary);\n#else\n // Match one framebuffer pixel even on devices without shader derivatives.\n vec2 dp = u_size / u_resolution / halfSize;\n vec2 dx = vec2(dp.x * .5, 0.);\n vec2 dy = vec2(0., dp.y * .5);\n edgeWidth = abs(projectedBoundary(p + dx, fov, centerFov) - projectedBoundary(p - dx, fov, centerFov))\n + abs(projectedBoundary(p + dy, fov, centerFov) - projectedBoundary(p - dy, fov, centerFov));\n boxWidth = abs(contourBoundary(p + dx) - contourBoundary(p - dx))\n + abs(contourBoundary(p + dy) - contourBoundary(p - dy));\n#endif\n edgeWidth = max(edgeWidth, .0001);\n boxWidth = max(boxWidth, .0001);\n float feather = clamp(u_feather / 360., .001, 1.);\n // Integrate coverage across the pixel footprint instead of cutting a\n // subpixel contour. Feather still controls the material's inner softness.\n float opacity = 1. - smoothstep(1. - feather - edgeWidth * .5, 1. + edgeWidth * .5, boundary);\n opacity *= 1. - smoothstep(1. - boxWidth * .5, 1. + boxWidth * .5, boxBoundary);\n\n // Rotate the already colored, softened source as a panoramic field, just\n // as VR Rotate Sphere precedes the Plane to Sphere adjustment layer.\n vec2 sampleSource = source;\n if (u_hoverEffect > 2.5) sampleSource -= u_hoverPosition * u_hover * .18;\n vec3 sourceColor = blurredField(sampleSource, t, tile);\n float intensity = u_intensity;\n if (u_hoverEffect > .5 && u_hoverEffect < 1.5) intensity *= 1. + u_hover * .3;\n if (u_hoverEffect > 2.5) {\n vec2 light = p - u_hoverPosition;\n intensity *= 1. + u_hover * .4 * exp(-dot(light, light) * 3.);\n }\n vec3 sourceHsv = rgbToHsv(sourceColor);\n vec3 base = rgbToHsv(u_color);\n float hue = sourceHsv.x + base.x - .81 + tile * u_spread + t * .075;\n vec3 color = hsv(vec3(hue, sourceHsv.y * base.y, min(1., sourceHsv.z * 1.75 * intensity * base.z)));\n if (u_colorMode < 2.5) {\n vec3 palette = u_color;\n if (u_colorMode > .5) {\n // Change the whole material's tint over time. Spatial coordinates\n // affect the reflections, never the selected palette's color.\n float flow = .5 - .5 * cos((tile * u_spread + t * .075) * 6.283185);\n palette = mix(u_color, u_color2, flow);\n if (u_colorMode > 1.5) {\n palette = flow < .5\n ? mix(u_color, u_color2, flow * 2.)\n : mix(u_color2, u_color3, flow * 2. - 1.);\n }\n }\n vec3 paletteHsv = rgbToHsv(palette);\n color = hsv(vec3(paletteHsv.xy, min(1., sourceHsv.z * 1.75 * intensity * paletteHsv.z)));\n }\n color += (hash(vec3(floor(pixel * 1.5), u_seed)) - .5) * u_grain * (.1 + length(color) * .15);\n gl_FragColor = vec4(max(color, 0.) * opacity, opacity);\n}"),!i||!o)return void E();if(s=n.createProgram(),n.attachShader(s,i),n.attachShader(s,o),n.linkProgram(s),!n.getProgramParameter(s,n.LINK_STATUS))return void E();n.useProgram(s),r=n.createBuffer(),n.bindBuffer(n.ARRAY_BUFFER,r),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),n.STATIC_DRAW);const u=n.getAttribLocation(s,"a_position");n.enableVertexAttribArray(u),n.vertexAttribPointer(u,2,n.FLOAT,!1,0,0),a=n.createTexture(),n.bindTexture(n.TEXTURE_2D,a),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MAG_FILTER,n.LINEAR),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.REPEAT),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([20,0,35,255])),l=Object.fromEntries(["size","resolution","grid","gap","time","phase","feather","projectionScale","centerProjectionScale","borderRadius","intensity","grain","spread","seed","color","colorMode","color2","color3","field","hover","hoverEffect","hoverPosition"].map(e=>[e,n.getUniformLocation(s,`u_${e}`)])),!c&&!S&&s&&a&&(n.bindTexture(n.TEXTURE_2D,a),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,128,128,0,n.RGBA,n.UNSIGNED_BYTE,function(){if(dc)return dc;const e=function(e,t){const n=Array.from(e.keys()).sort((t,n)=>e[t]-e[n]),s=new Float32Array(e.length);return n.forEach((n,r)=>{const i=r/(e.length-1);let o=1;for(;o<t.length-1&&t[o][0]<i;)o++;const[a,c]=t[o-1],[l,d]=t[o];s[n]=c+(i-a)/Math.max(1e-6,l-a)*(d-c)}),s}(ac(128,4,4,11),rc),t=cc(ac(128,3,3,29),.83,.05),n=cc(ac(128,5,2,53),.988,.03),s=new Uint8Array(65536);for(let r=0;r<16384;r++){const[i,o,a]=lc((t[r]%1+1)%1,Math.min(1,Math.max(.8,n[r])),e[r]);s[4*r]=Math.round(255*i),s[4*r+1]=Math.round(255*o),s[4*r+2]=Math.round(255*a),s[4*r+3]=255}return dc=s,s}()),k&&(n.generateMipmap(n.TEXTURE_2D),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_MIN_FILTER,n.LINEAR_MIPMAP_LINEAR)),e.dataset.renderer="webgl",$())},T=()=>!!s&&!S&&w&&!document.hidden&&!j.matches&&(!p.current.paused&&0!==p.current.speed||Math.abs(v-g)>.001),A=()=>{if(!s||S)return;const r=p.current,i=Math.round(fc(r.columns,1,1,24)),o=Math.round(fc(r.rows,1,1,24));n.viewport(0,0,e.width,e.height),n.uniform2f(l.size,I,C),n.uniform2f(l.resolution,e.width,e.height),n.uniform2f(l.grid,i,o),n.uniform1f(l.gap,fc(r.gap,0,0,Math.max(0,Math.min(I/i,C/o)-4))),n.uniform1f(l.time,m),n.uniform1f(l.hover,t?.disabled||"none"===r.hoverEffect?0:g),n.uniform1f(l.hoverEffect,Math.max(0,hc.indexOf(r.hoverEffect))),n.uniform2f(l.hoverPosition,...x),n.uniform1f(l.phase,fc(r.phase,0,-1e3,1e3)),n.uniform1f(l.feather,fc(r.feather,95,0,100));const c=fc(r.projectionScale,174,90,179.5);n.uniform1f(l.projectionScale,c),n.uniform1f(l.centerProjectionScale,fc(r.centerProjectionScale??c,c,90,179.5)),n.uniform1f(l.borderRadius,void 0===r.borderRadius?-1:fc(r.borderRadius,50,0,50)/50),n.uniform1f(l.intensity,fc(r.intensity,1.15,0,3)),n.uniform1f(l.grain,fc(r.grain,.035,0,.5)),n.uniform1f(l.spread,fc(r.colorSpread,0,0,2)),n.uniform1f(l.seed,fc(r.seed,7,0,65535)),n.uniform3fv(l.color,mc(r.color)),n.uniform1f(l.colorMode,uc.indexOf(r.colorMode)),n.uniform3fv(l.color2,mc(r.color2)),n.uniform3fv(l.color3,mc(r.color3)),n.activeTexture(n.TEXTURE0),n.bindTexture(n.TEXTURE_2D,a),n.uniform1i(l.field,0),n.drawArrays(n.TRIANGLES,0,6)},N=e=>{if(h=0,T()){if(f){const t=Math.min((e-f)/1e3,.1);p.current.paused||(m+=t*fc(p.current.speed,.7,0,4)),g+=(v-g)*(1-Math.exp(14*-t)),Math.abs(v-g)<=.001&&(g=v)}f=e,A(),T()&&(h=requestAnimationFrame(N))}else f=0},P=()=>{v=t&&!t.disabled&&"none"!==p.current.hoverEffect&&(y||b)?1:0,(j.matches||"none"===p.current.hoverEffect||t?.disabled)&&(g=v)},D=()=>{P(),h||(f=0,A(),T()&&(h=requestAnimationFrame(N)))},L=e=>{"touch"!==e.pointerType&&(y=!0,D())},F=()=>{y=!1,D()},q=()=>{b=!!t?.matches(":focus-visible"),b&&(x=[0,0]),D()},O=()=>{b=!1,D()},_=e=>{if(!t||t.disabled||"touch"===e.pointerType||"spotlight"!==p.current.hoverEffect)return;const n=t.getBoundingClientRect();x=[Math.max(-1,Math.min(1,(e.clientX-n.left)/Math.max(1,n.width)*2-1)),Math.max(-1,Math.min(1,(e.clientY-n.top)/Math.max(1,n.height)*2-1))],h||A()},$=()=>{cancelAnimationFrame(h),h=0,f=0,P(),A(),T()&&(h=requestAnimationFrame(N))},z=()=>{I=Math.max(1,e.clientWidth),C=Math.max(1,e.clientHeight);const t=Math.min(devicePixelRatio||1,2,Math.sqrt(15e5/(I*C)));e.width=Math.max(1,Math.round(I*t)),e.height=Math.max(1,Math.round(C*t)),$()},H=t=>{t.preventDefault(),S=!0,cancelAnimationFrame(h),delete e.dataset.renderer},B=()=>{S=!1,E(),M(),z()};M(),t?.addEventListener("pointerenter",L),t?.addEventListener("pointerleave",F),t?.addEventListener("pointercancel",F),t?.addEventListener("pointermove",_),t?.addEventListener("focus",q),t?.addEventListener("blur",O);const U=new ResizeObserver(z);U.observe(e);const W=new IntersectionObserver(([e])=>{w=e.isIntersecting,$()});return W.observe(e),document.addEventListener("visibilitychange",$),j.addEventListener("change",$),e.addEventListener("webglcontextlost",H),e.addEventListener("webglcontextrestored",B),u.current=$,z(),()=>{c=!0,u.current=null,cancelAnimationFrame(h),U.disconnect(),W.disconnect(),document.removeEventListener("visibilitychange",$),j.removeEventListener("change",$),e.removeEventListener("webglcontextlost",H),e.removeEventListener("webglcontextrestored",B),delete e.dataset.renderer,E(),t?.removeEventListener("pointerenter",L),t?.removeEventListener("pointerleave",F),t?.removeEventListener("pointercancel",F),t?.removeEventListener("pointermove",_),t?.removeEventListener("focus",q),t?.removeEventListener("blur",O)}},[]),i.jsx("canvas",{ref:d,className:"chromatic-surface","aria-hidden":"true",tabIndex:-1})}const vc={...pc,feather:100,projectionScale:174.7,intensity:1.4,grain:.105,borderRadius:50,hoverEffect:"brighten",entrance:"blur-up",entranceSpeed:1,entranceBlur:10,entranceDistance:20,entranceScale:.65},yc=o.forwardRef(function({children:e="Get started",className:t="",type:n="button",color:s=vc.color,colorMode:r,color2:a=vc.color2,color3:c=vc.color3,fixedColor:l,speed:d,paused:u,phase:h,feather:p=vc.feather,projectionScale:f=vc.projectionScale,intensity:m=vc.intensity,grain:g=vc.grain,borderRadius:v=vc.borderRadius,hoverEffect:y=vc.hoverEffect,entrance:b=vc.entrance,entranceSpeed:x=vc.entranceSpeed,entranceBlur:w=vc.entranceBlur,entranceDistance:S=vc.entranceDistance,entranceScale:k=vc.entranceScale,seed:I,style:C,...j},R){const E=o.useRef(null);o.useImperativeHandle(R,()=>E.current,[]),o.useEffect(()=>{const e=E.current,t=()=>{e.style.setProperty("--chromatic-button-short-side",`${Math.min(e.clientWidth,e.clientHeight)}px`)};t();const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]),o.useEffect(()=>{if("spotlight"!==y||j.disabled)return;const e=E.current,t=matchMedia("(prefers-reduced-motion: reduce)"),n=[0,0],s=[0,0],r=[0,0];let i=0,o=0,a=!1;const c=()=>Math.min(10,.18*Math.min(e.clientWidth,e.clientHeight)),l=()=>{cancelAnimationFrame(i),i=o=0,n.fill(0),s.fill(0),r.fill(0),e.style.removeProperty("--chromatic-pointer-transform")},d=a=>{if(i=0,t.matches||e.disabled||document.hidden)return void l();const u=o?Math.min((a-o)/1e3,1/30):1/60;o=a;const h=Math.max(1,Math.ceil(120*u)),p=u/h;for(let e=0;e<h;e++)for(let t=0;t<2;t++)s[t]+=(220*(r[t]-n[t])-16*s[t])*p,n[t]+=s[t]*p;const f=n.every((e,t)=>Math.abs(e-r[t])<.01&&Math.abs(s[t])<.05);if(f&&(n.splice(0,2,...r),s.fill(0),r.every(e=>0===e)))return void l();const m=Math.max(-1,Math.min(1,(Math.abs(n[0])-Math.abs(n[1]))/Math.max(1,c())));e.style.setProperty("--chromatic-pointer-transform",`translate(${n[0]}px, ${n[1]}px) scale(${1+.025*m}, ${1-.025*m})`),f?o=0:i=requestAnimationFrame(d)},u=()=>{i||(i=requestAnimationFrame(d))},h=e=>{"touch"===e.pointerType||t.matches||(a=!0)},p=s=>{if(!a||"touch"===s.pointerType||t.matches||e.disabled)return;const i=e.getBoundingClientRect(),o=[i.left+i.width/2-n[0],i.top+i.height/2-n[1]];r[0]=Math.max(-1,Math.min(1,(s.clientX-o[0])/Math.max(1,e.clientWidth/2)))*c(),r[1]=Math.max(-1,Math.min(1,(s.clientY-o[1])/Math.max(1,e.clientHeight/2)))*c(),u()},f=()=>{a=!1,r.fill(0),u()},m=()=>{a=!1,l()},g=()=>{document.hidden&&m()};return e.addEventListener("pointerenter",h),e.addEventListener("pointermove",p),e.addEventListener("pointerleave",f),e.addEventListener("pointercancel",f),t.addEventListener("change",m),document.addEventListener("visibilitychange",g),()=>{l(),e.removeEventListener("pointerenter",h),e.removeEventListener("pointermove",p),e.removeEventListener("pointerleave",f),e.removeEventListener("pointercancel",f),t.removeEventListener("change",m),document.removeEventListener("visibilitychange",g)}},[y,j.disabled]);const M=Math.min(50,Math.max(0,Number.isFinite(v)?v:vc.borderRadius)),T=function(e,t,n=!1){const s=e=>Math.SQRT2*(1-e/50)+e/50,r=s(Math.min(50,Math.max(0,Number.isFinite(t)?t:vc.borderRadius)))/s(vc.borderRadius),i=Math.min(179.5,Math.max(90,Number.isFinite(e)?e:174.7))*Math.PI/360;return Math.min(179.5,Math.max(90,360*Math.atan(Math.tan(i)*(n?1/r:r))/Math.PI))}(f,M),A=(e,t,n,s)=>Math.min(s,Math.max(n,Number.isFinite(e)?e:t));return i.jsxs("button",{...j,ref:E,type:n,"data-hover-effect":y,"data-entrance":b,className:`chromatic-button ${t}`.trim(),style:{"--chromatic-button-color":s,"--chromatic-button-radius":M/100,"--chromatic-entrance-speed":A(x,1,.1,4),"--chromatic-entrance-blur":`${A(w,10,0,40)}px`,"--chromatic-entrance-distance":`${A(S,20,0,120)}px`,"--chromatic-entrance-scale":A(k,.65,.05,1),...C},children:[i.jsx(gc,{color:s,colorMode:r,color2:a,color3:c,fixedColor:l,speed:d,paused:u,phase:h,feather:p,projectionScale:T,borderRadius:M,hoverEffect:y,centerProjectionScale:T-(vc.projectionScale-pc.projectionScale),intensity:m,grain:g,seed:I}),i.jsx("span",{className:"chromatic-button-content",children:e})]})}),bc=o.forwardRef(function({className:e="",style:t,...n},s){const[r,a]=o.useState(["#a87bb2","#c27ba0"]),[c,l]=o.useState(!1),[d,u]=o.useState(!1),h=o.useRef(null),p=e=>{h.current=e,"function"==typeof s?s(e):s&&(s.current=e)};return o.useEffect(()=>{u("undefined"!=typeof ResizeObserver&&"undefined"!=typeof IntersectionObserver&&"undefined"!=typeof WebGL2RenderingContext);const e=()=>{if(!h.current)return;const e=getComputedStyle(h.current);a([e.getPropertyValue("--accent").trim()||"#a87bb2",e.getPropertyValue("--accent-secondary").trim()||"#c27ba0"])};e();const t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme","class","style"]}),()=>t.disconnect()},[]),d?i.jsx(yc,{...n,ref:p,className:`product-chromatic-action ${e}`,style:t,color:r[0],color2:r[1],colorMode:"gradient-2",intensity:1.2,borderRadius:25,grain:.04,entrance:"none",hoverEffect:"brighten",paused:!c||n.disabled,speed:.25,onPointerEnter:e=>{l(!0),n.onPointerEnter?.(e)},onPointerLeave:e=>{l(!1),n.onPointerLeave?.(e)},onFocus:e=>{l(!0),n.onFocus?.(e)},onBlur:e=>{l(!1),n.onBlur?.(e)}}):i.jsx("button",{...n,ref:p,className:`product-chromatic-action chromatic-button ${e}`,style:t,children:i.jsx("span",{className:"chromatic-button-content",children:n.children})})}),xc={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 wc(){const e=xc[s(r().language)],[t,n]=o.useState(""),[a,c]=o.useState("");return i.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,r=s.searchParams.get("data");return r&&!s.hash&&"vibelet:"===s.protocol&&"pair"===s.hostname&&(s.hash=new URLSearchParams({pair:r}).toString(),s.searchParams.delete("data")),s}(e.trim()),n=Nn(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:[i.jsx("label",{htmlFor:"web-pairing-link",children:e.label}),i.jsx("p",{children:e.hint}),i.jsx("input",{id:"web-pairing-link",value:t,onChange:e=>{n(e.target.value),c("")},autoComplete:"off",spellCheck:!1,required:!0}),i.jsx(bc,{className:"primary-button",type:"submit",children:e.connect}),a&&i.jsx("p",{role:"alert",className:"connection-guide-error",children:a})]})}const Sc="vibelet --access=quick";function kc({errorText:e,t}){const[n,s]=o.useState("idle"),[a,c]=o.useState(!1),l=r().language,d=ec(l);return i.jsx("main",{className:"connection-guide",id:"vibelet-main-content",tabIndex:-1,children:i.jsxs("section",{className:"connection-guide-content","aria-labelledby":"connection-guide-title",children:[i.jsx("span",{className:"connection-guide-mark","aria-hidden":"true",children:i.jsx($e,{})}),i.jsx("span",{className:"connection-guide-eyebrow",children:"Vibelet"}),i.jsx("h1",{id:"connection-guide-title",children:t.openDaemonWebLink}),i.jsx("p",{children:t.openDaemonWebLinkHint}),i.jsx(wc,{}),i.jsxs("div",{className:"connection-command",children:[i.jsx("code",{children:Sc}),i.jsxs("button",{className:"primary-button",onClick:()=>{(async()=>{try{await cr(Sc),s("success")}catch{s("error")}window.setTimeout(()=>s("idle"),1800)})()},type:"button",children:["success"===n?i.jsx(_,{"aria-hidden":"true"}):i.jsx(Q,{"aria-hidden":"true"}),i.jsx("span",{children:"success"===n?t.commandCopied:"error"===n?t.copyFailed:t.copyStartCommand})]})]}),i.jsx("p",{className:"connection-guide-footnote",children:t.connectionGuideFootnote}),e?i.jsx("p",{className:"connection-guide-error",children:e}):null,i.jsxs("button",{className:"connection-feedback-toggle",type:"button","aria-expanded":a,onClick:()=>c(e=>!e),children:[i.jsx(be,{"aria-hidden":"true"}),d.title]}),a?i.jsx("div",{className:"connection-feedback-panel",children:i.jsx(sc,{language:l,entry:"connection-guide"})}):null]})})}const Ic=o.lazy(()=>m(()=>import("./ImageViewer-ChfsVDQe.js"),__vite__mapDeps([8,1,2,9,10])));function Cc(){const[e,t]=o.useState(null);return o.useEffect(()=>{const e=e=>t(e.detail);return window.addEventListener(ps,e),()=>window.removeEventListener(ps,e)},[]),e?i.jsx(o.Suspense,{fallback:null,children:i.jsx(Ic,{request:e,onClose:()=>t(null)},e.images[e.index].src)}):null}const jc=o.createContext(null);function Rc({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}),[r,i]=o.useState(0),[a,c]=o.useState([]),l=a.filter(t=>(t.scopeKey??"default")===e),[d,u]=qr(JSON.stringify([e,r]),null),[h,p]=qr(JSON.stringify([e,r]),()=>({}));o.useEffect(()=>{const e=e=>{const t=e.detail;c(e=>e.flatMap(e=>{const n=Fr(e.scopeKey??"default",t);return null===n?[]:n===(e.scopeKey??"default")?[e]:[{...e,scopeKey:n,session:e.session&&"remap"===t.action?{...e.session,sessionId:t.nextSessionId}:e.session}]}))};return window.addEventListener(Ar,e),()=>window.removeEventListener(Ar,e)},[]);const[f,m]=o.useState({}),g=o.useCallback((t,n,r,i,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:r,session:i,scope:o,path:a,location:d,scopeKey:e}]),"center"===d?u(l):p(e=>({...e,[t]:l})),l},[e,u,p]),v=o.useRef(new Set),y=o.useCallback((n,s)=>{const r=l.filter(e=>"browser"===e.kind&&"right"===e.location&&!e.url&&!e.currentUrl&&!v.current.has(e.id)),i=r.find(e=>e.id===h.browser)??r[0],o=i?.id??crypto.randomUUID();i&&v.current.add(o),c(t=>i?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=>{v.current.delete(t);const s=l.find(e=>e.id===t);if(!s)return;const r=l.find(e=>e.id!==t&&e.kind===s.kind&&e.location===s.location),i=r||"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),...i?[i]:[]]),r||"right"!==s.location||"diff"===s.kind||n.current?.(s.kind),d===t&&u(null),(i||h[s.kind]===t)&&p(e=>({...e,[s.kind]:i?.id??r?.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)=>m(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(()=>{v.current.clear(),c([]),u(null),p({}),i(e=>e+1)},[u,p]);return o.useMemo(()=>({scopeKey:e,allItems:a,openRight:t,closeRight:n,openBrowser:y,updateBrowserUrl:b,activate:S,epoch:r,items:l,center:d,right:h,hosts:f,add:g,move:x,close:w,rename:k,register:I,reset:C,setCenter:u,setRight:p}),[e,a,y,b,S,r,l,d,h,f,g,x,w,k,I,C])}(t);return i.jsx(jc.Provider,{value:n,children:e})}function Ec(){const e=o.useContext(jc);if(!e)throw new Error("Dock workspace provider missing");return e}function Mc(){return o.useContext(jc)}const Tc="application/x-vibelet-workspace-tab",Ac=o.createContext(null),Nc={browser:le,terminal:$e,diff:ae};function Pc(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 Dc({location:e,kind:t,t:n,cwd:s}){const r=Ec(),c=Pc(n),l=o.useRef(null),d=o.useRef(null),u=r.items.filter(n=>n.location===e&&(!t||n.kind===t)),h=function(e,t,n,s=""){const r=o.useContext(Ac),i=r?.element;t=t&&r?.kind===n;const[a,c]=o.useState(!1);return o.useLayoutEffect(()=>{const n=e.current,s=i?.querySelector(".control-tabs");if(!(t&&i&&n&&s))return;const r=()=>{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 r=t.getBoundingClientRect().width;t.remove();const o=i.clientWidth-s.getBoundingClientRect().width-8;c(e=>r>0?r<=o:e)},o=new ResizeObserver(r);return o.observe(i),o.observe(s),r(),()=>o.disconnect()},[t,i,e,s]),t&&a?i:null}(d,"right"===e&&u.length>1,t,u.map(e=>`${e.id}:${e.title}`).join("|"));if(o.useEffect(()=>{"right"===e&&t&&!r.items.some(e=>e.kind===t)&&r.add(t,n["browser"===t?"browser":"terminal"],s)},[e,t,r.epoch,r.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,r.right,u.map(e=>e.title).join("|")]),"right"===e&&t&&1===u.length)return null;const p=i.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&&r.right[t]&&i.jsx("button",{type:"button",className:"dock-move dock-move-first","aria-label":c.center,title:c.center,onClick:()=>r.move(r.right[t],"center"),children:i.jsx(L,{})}),i.jsx("div",{className:"dock-tab-items",ref:l,children:u.map(t=>{const s="center"===e?r.center===t.id:r.right[t.kind]===t.id,o=Nc[t.kind];return i.jsxs("div",{className:"document-tab dock-tab","data-active":s,"data-dock-id":t.id,draggable:!0,onDragStart:e=>{e.dataTransfer.setData(Tc,t.id),e.dataTransfer.effectAllowed="move"},children:[i.jsxs("button",{type:"button",role:"tab","aria-selected":s,title:t.title,onClick:()=>"center"===e?r.setCenter(t.id):r.setRight(e=>({...e,[t.kind]:t.id})),children:[i.jsx(o,{}),i.jsx("span",{children:t.title})]}),s&&"center"===e&&i.jsx("button",{type:"button",className:"dock-move","aria-label":c.right,title:c.right,onClick:()=>r.move(t.id,"right"),children:i.jsx(F,{})}),i.jsx("button",{type:"button",className:"document-tab-close","aria-label":`${n.close} ${t.title}`,title:n.close,onClick:()=>r.close(t.id),children:i.jsx(Ve,{})})]},t.id)})}),"right"===e&&t&&i.jsx("button",{type:"button",className:"dock-new","aria-label":c.create,title:ot(c.create,"newTab"),onClick:()=>r.add(t,n["browser"===t?"browser":"terminal"],s),children:i.jsx(Me,{})})]});return h?a.createPortal(p,h):p}function Lc({item:e,t}){const n=Ec(),s=Pc(t);return i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button","aria-label":s.center,title:s.center,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(Tc,e.id),t.dataTransfer.effectAllowed="move"},onClick:()=>n.move(e.id,"center"),children:i.jsx(L,{})}),i.jsx("button",{type:"button","aria-label":s.create,title:ot(s.create,"newTab"),onClick:()=>n.add(e.kind,t["browser"===e.kind?"browser":"terminal"],e.cwd),children:i.jsx(Me,{})})]})}function Fc({location:e,kind:t}){const n=Ec(),s="center"===e?"center":`right-${t}`,r=o.useCallback(e=>n.register(s,e),[n.register,s]);return i.jsx("div",{ref:r,className:"dock-slot","data-dock-location":e,"data-dock-kind":t})}function qc(e,t){const n=Mc();return n?{onDragOver:e=>{e.dataTransfer.types.includes(Tc)&&(e.preventDefault(),e.dataTransfer.dropEffect="move",e.currentTarget.classList.add("dock-drop-target"))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||e.currentTarget.classList.remove("dock-drop-target")},onDrop:s=>{s.currentTarget.classList.remove("dock-drop-target");const r=s.dataTransfer.getData(Tc),i=n.items.find(e=>e.id===r);i&&(s.preventDefault(),s.stopPropagation(),document.body.classList.remove("dock-dragging"),n.move(r,e),t?.(i.kind))}}:{}}const Oc=o.lazy(()=>m(()=>import("./BrowserControlPanel-DJHj2vwI.js"),__vite__mapDeps([11,1,2,9]))),_c=o.lazy(()=>m(()=>import("./SessionTerminalPanel-pCQpIA-I.js"),__vite__mapDeps([12,1,2]))),$c=o.lazy(()=>m(()=>Promise.resolve().then(()=>Zc),void 0).then(e=>({default:e.DiffDrawer})));function zc({item:e,...t}){const n=Ec(),[s]=o.useState(()=>({pairing:t.pairing,deviceName:t.deviceName})),r=o.useRef(t.client);t.daemonId===s.pairing?.daemonId&&(r.current=t.client);const c=qc(e.location),[l]=o.useState(()=>document.createElement("div")),d="right"===e.location,u=d&&1===n.items.filter(t=>"right"===t.location&&t.kind===e.kind).length,h=u?i.jsx(Lc,{item:e,t:t.t}):void 0,p=(e.scopeKey??"default")===n.scopeKey&&(d?"diff"===e.kind?n.right.diff===e.id:t.rightVisible&&t.controlTab===e.kind&&n.right[e.kind]===e.id:n.center===e.id),f=n.hosts[d?`right-${e.kind}`:"center"]??n.hosts.parking,m=n.hosts.parking;o.useLayoutEffect(()=>{m&&l.parentElement!==m&&m.appendChild(l)},[l,m]),o.useLayoutEffect(()=>{l.className="dock-surface",l.dataset.dockId=e.id,l.dataset.location=e.location,l.dataset.kind=e.kind,l.hidden=!p;const t=d&&"diff"===e.kind,n=()=>{const e=f?.getBoundingClientRect();Object.assign(l.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 f&&s.observe(f),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)}},[l,f,p,e.id,e.location,e.kind,d]),o.useLayoutEffect(()=>()=>l.remove(),[l]);const g=o.useCallback(t=>n.updateBrowserUrl(e.id,t),[n.updateBrowserUrl,e.id]);return a.createPortal(i.jsx("div",{className:"dock-surface-content",...c,children:i.jsx(o.Suspense,{fallback:i.jsx("p",{className:"control-panel-loading",children:t.t.loading}),children:"browser"===e.kind?i.jsx(Oc,{initialUrl:e.url,visible:p,onUrlChange:g,t:t.t,dockActions:h,onClose:u?()=>n.close(e.id):void 0,onTitleChange:t=>n.rename(e.id,t)}):"terminal"===e.kind?i.jsx(_c,{pairing:s.pairing,cwd:e.cwd??"",deviceName:s.deviceName,visible:p,autoOpen:!1!==e.autoOpenTerminal,onOpen:()=>n.activate(e.id),onCloseTab:()=>n.close(e.id),t:t.t,dockActions:h}):e.session&&r.current?i.jsx($c,{client:r.current,sessionId:e.session.sessionId,cwd:e.session.cwd,sessionTitle:e.title,t:t.t,onClose:()=>n.close(e.id),onDock:()=>n.move(e.id,d?"center":"right"),dockLabel:Pc(t.t).center,presentation:d?"drawer":"workspace",initialScope:e.scope,initialPath:e.path}):null})}),l)}function Hc(e){const t=Ec();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 i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"dock-parking",ref:s}),i.jsx("div",{className:"dock-overlay-slot",children:i.jsx(Fc,{location:"right",kind:"diff"})}),t.allItems.map(t=>i.jsx(zc,{item:t,...e},t.id))]})}function Bc({patch:e,truncated:t,truncatedLabel:n,loadingLabel:s}){const r=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,r.length]),i.jsxs("div",{className:"diff-patch-view",children:[r.slice(0,a).map((e,t)=>i.jsxs("div",{className:`diff-line ${e.kind}`,children:[i.jsx("span",{className:"diff-line-number","aria-hidden":"true",children:e.oldLine}),i.jsx("span",{className:"diff-line-number","aria-hidden":"true",children:e.newLine}),i.jsx("span",{className:"diff-line-sign","aria-hidden":"true",children:e.sign}),i.jsx("span",{className:"diff-line-text",children:e.text||" "})]},t)),a<r.length&&i.jsx("div",{ref:l,className:"diff-more",role:"status",children:s}),t&&i.jsx("p",{className:"diff-empty",children:n})]})}const Uc=new WeakMap;function Wc(e,t,n){let s=Uc.get(e);s||Uc.set(e,s=new Map);const r=JSON.stringify([t.sessionId,t.cwd,n]);let i=s.get(r);return i||(s.size>=12&&s.delete(s.keys().next().value),s.set(r,i={updated:0,patches:new Map})),i}function Kc(e,t,n){return Wc(e,t,n)}function Vc(e,t,n){const s=Wc(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 Qc(e,t,n,s){const r=Wc(e,t,n),i=r.patches.get(s);if(i?.pending)return i.pending;if(i?.data&&Date.now()-r.updated<5e3)return Promise.resolve(i.data);r.patches.size>=12&&r.patches.delete(r.patches.keys().next().value);const o={};return r.patches.set(s,o),o.pending=e.request({action:"session.gitDiff.file",id:e.makeId("gitDiffFile"),...t,scope:n,path:s}).then(e=>(o.data=e,e)).finally(()=>{o.pending=void 0}),o.pending}const Gc={loading:!1,files:null,error:null};function Jc({client:e,sessionId:t,cwd:n,sessionTitle:s,t:r,onClose:a,onDock:c,dockLabel:l,presentation:d="drawer",initialScope:u="unstaged",initialPath:h}){const p=o.useId(),m=o.useRef(null),[g,v]=o.useState(!1),y=o.useRef(void 0),b=o.useCallback(()=>{void 0===y.current&&("workspace"===d||window.matchMedia("(prefers-reduced-motion: reduce)").matches?a():(v(!0),y.current=window.setTimeout(a,180)))},[a,d]);o.useEffect(()=>()=>window.clearTimeout(y.current),[]);const x=f(b,m,"drawer"===d),w=Kc(e,{sessionId:t,cwd:n},u),[S,k]=o.useState(u),[I,C]=o.useState({unstaged:Gc,staged:Gc,[u]:{...Gc,files:w.data?.files??null}}),[j,R]=o.useState(h??w.data?.files[0]?.path??null),[E,M]=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,r=n.clientX,i=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-r,e.clientY-i)<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),F=I[S],q=o.useCallback(async s=>{C(e=>({...e,[s]:{loading:!0,files:e[s].files,error:null}}));try{const r=await Vc(e,{sessionId:t,cwd:n},s);C(e=>({...e,[s]:{loading:!1,files:r.files,error:null}}))}catch(r){C(e=>({...e,[s]:{loading:!1,files:null,error:r instanceof Error?r.message:String(r)}}))}},[e,t,n]);o.useEffect(()=>{q(S)},[S,q]),o.useEffect(()=>{const e=F.files;e&&(e.length?R(t=>e.some(e=>e.path===t)?t:e[0].path):R(null))},[F.files]),o.useEffect(()=>{if(!j)return M(null),void P(null);let s=!1;const r=Kc(e,{sessionId:t,cwd:n},S).patches.get(j)?.data;return M(e=>r??(e?.path===j?e:null)),A(!r&&E?.path!==j),P(null),Qc(e,{sessionId:t,cwd:n},S,j).then(e=>{s||(M(e),A(!1))}).catch(e=>{s||(P(e instanceof Error?e.message:String(e)),A(!1))}),()=>{s=!0}},[e,t,n,S,j,F.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 i.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&&i.jsx("div",{className:"diff-drawer-backdrop",onClick:b,"aria-hidden":"true"}),i.jsxs("div",{className:"diff-drawer-panel",children:[i.jsxs("header",{className:"diff-drawer-header",...D,children:[c&&"drawer"===d&&i.jsx("button",{type:"button",className:"icon-button","aria-label":l,title:l,onClick:()=>c({scope:S,path:j}),children:i.jsx(L,{})}),i.jsxs("div",{children:[i.jsx("strong",{id:p,children:r.changes}),i.jsx("span",{children:s})]}),i.jsx("button",{"aria-label":r.closeChanges,className:"icon-button",onClick:b,ref:m,type:"button",title:r.closeChanges,children:i.jsx(Ve,{"aria-hidden":"true"})})]}),i.jsx("div",{className:"diff-tabs",role:"tablist",children:["unstaged","staged"].map(e=>{const t=O[e],n=S===e;return i.jsxs("button",{type:"button",role:"tab","aria-selected":n,className:"diff-tab "+(n?"active":""),onClick:()=>{e!==S&&(R(null),M(null),P(null),k(e))},children:[i.jsx("span",{className:"diff-tab-label",children:"unstaged"===e?r.workingChanges:r.stagedChanges}),t.count>0?i.jsxs("span",{className:"diff-tab-meta",children:[i.jsxs("span",{className:"diff-add",children:["+",t.adds]}),i.jsxs("span",{className:"diff-del",children:["-",t.dels]})]}):null]},e)})}),i.jsxs("div",{className:"diff-body",children:[i.jsxs("aside",{className:"diff-files","aria-label":r.changedFiles,children:[F.loading&&!F.files?i.jsx("p",{className:"diff-empty",children:r.loading}):null,F.error?i.jsx("p",{className:"diff-empty diff-error",children:F.error}):null,F.files&&0===F.files.length?i.jsx("p",{className:"diff-empty",children:r.noChanges}):null,F.files?.map(e=>i.jsxs("button",{type:"button",className:`diff-file diff-file-${e.status} ${j===e.path?"active":""}`,onClick:()=>R(e.path),children:[i.jsx("span",{className:`diff-status diff-status-${e.status}`,children:e.status}),i.jsx("span",{className:"diff-file-path",title:e.path,children:e.path}),i.jsxs("span",{className:"diff-file-stats",children:[e.binary?i.jsx("span",{className:"diff-binary",children:"bin"}):null,!e.binary&&e.additions>0?i.jsxs("span",{className:"diff-add",children:["+",e.additions]}):null,!e.binary&&e.deletions>0?i.jsxs("span",{className:"diff-del",children:["-",e.deletions]}):null]})]},e.path))]}),i.jsx("section",{className:"diff-patch","aria-label":r.fileDiff,children:j?T?i.jsx("p",{className:"diff-empty",children:r.loadingPatch}):N?i.jsx("p",{className:"diff-empty diff-error",children:N}):E?.binary?i.jsx("p",{className:"diff-empty",children:r.binaryDiffUnavailable}):E?i.jsx(Bc,{patch:E.patch,truncated:E.truncated,truncatedLabel:r.patchTruncated,loadingLabel:r.loadingPatch},`${S}:${j}`):null:i.jsxs("div",{className:"diff-empty",children:[i.jsx(te,{"aria-hidden":"true"}),i.jsx("p",{children:r.selectFileForDiff})]})})]})]})]})}const Zc=Object.freeze(Object.defineProperty({__proto__:null,DiffDrawer:Jc},Symbol.toStringTag,{value:"Module"})),Xc=o.lazy(async()=>m(()=>import("./FilesControlPanel-B-pqZWgH.js"),__vite__mapDeps([13,1,2,14,15])).then(e=>({default:e.FilesControlPanel}))),Yc=o.lazy(async()=>m(()=>import("./LanguageSettingsPanel-P7H9JLtq.js"),__vite__mapDeps([16,1,2,17])).then(e=>({default:e.LanguageSettingsPanel}))),el=o.lazy(async()=>m(()=>import("./ThemeSettingsPanel-JUF7qFiS.js"),__vite__mapDeps([18,1,2,17])).then(e=>({default:e.ThemeSettingsPanel}))),tl=o.lazy(async()=>m(()=>import("./NotificationSettingsPanel-BAcpsROS.js"),__vite__mapDeps([19,1,2])).then(e=>({default:e.NotificationSettingsPanel})));function nl({t:e}){return i.jsxs("div",{className:"control-panel-loading","aria-live":"polite","aria-busy":"true",children:[i.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),i.jsx("span",{children:e.loadingControls})]})}function sl({client:e,id:t,activeSession:n,sessions:s,t:r,close:a}){const c=Mc(),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 Vc(e,t,"unstaged");n.files[0]&&await Qc(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?i.jsx(Jc,{client:e,sessionId:p.sessionId,cwd:p.cwd,sessionTitle:d(p),t:r,onClose:a,dockLabel:Pc(r).center,onDock:c?({scope:e,path:t})=>{c.add("diff",d(p),p.cwd,p,e,t),a()}:void 0},p.sessionId):null}function rl(e,t,n){return e.replace(/tailcat/gi,t).replace(/(?:https?:\/\/|wss?:\/\/)?\b127\.0\.0\.1\b(?::\d+)?/gi,n)}const il="vibelet.web.hideDeviceAddresses";function ol({activeDaemonId:e,busy:s,fallbackName:r,phase:a,statusText:c,t:l,targets:d,onConnect:u,onRename:h,onEditConnection:p}){const{hidden:f,toggle:m}=function(){const[e,n]=o.useState(()=>{try{return"true"===t().getItem(il)}catch{return!1}});return{hidden:e,toggle:()=>{const s=!e;n(s);try{t().setItem(il,String(s))}catch{}}}}(),g=e=>f?function(e){return e.replace(/([^\s]+):(\d+)(?=\s|$)/g,(e,t,n)=>{const s=t.split(".");if(4===s.length&&s.every(e=>/^\d{1,3}$/.test(e)))return`${s[0]}.***.${s[3]}:${n}`;const r=Math.min(3,Math.floor((t.length-1)/2));return`${r>0?`${t.slice(0,r)}***${t.slice(-r)}`:"***"}:${n}`})}(e):e,v=f?l.showDeviceAddresses:l.hideDeviceAddresses,[y,b]=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),E=d.find(t=>t.daemonId===e),M=g(E?.label||r||e?.slice(0,10)||"Vibelet");return o.useEffect(()=>{y||w(null),x&&C.current?.select()},[y,x]),o.useEffect(()=>{if(!y)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)}},[y]),i.jsxs("div",{className:"device-switcher",ref:I,children:[i.jsxs("button",{"aria-expanded":y,"aria-haspopup":"menu",className:"device-switcher-trigger",onClick:()=>b(e=>!e),title:M,type:"button",children:[i.jsx("strong",{children:M}),i.jsx($,{"aria-hidden":"true"})]}),i.jsxs("span",{className:`brand-connection ${a}`,children:[i.jsx("i",{"aria-hidden":"true"}),"connected"===a?l.connected:c]}),y?i.jsxs("div",{"aria-label":l.savedDevices,className:"device-switcher-menu",role:"menu",children:[i.jsxs("div",{className:"device-switcher-menu-header",children:[i.jsx("span",{children:l.savedDevices}),i.jsx("button",{type:"button",className:"device-rename-button","aria-label":v,title:v,onClick:m,children:f?i.jsx(X,{"aria-hidden":"true"}):i.jsx(Y,{"aria-hidden":"true"})})]}),R.map(t=>{const r=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 i.jsx("div",{className:"device-switcher-row"+(r?" is-active":""),children:x===t.daemonId?i.jsxs("form",{className:"device-rename-form",onSubmit:e=>{e.preventDefault(),x&&S.trim()&&(h(x,S),w(null))},children:[i.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}),i.jsx("button",{"aria-label":l.rename,title:l.rename,disabled:!S.trim(),type:"submit",children:i.jsx(_,{"aria-hidden":"true"})}),i.jsx("button",{"aria-label":l.cancel,title:l.cancel,type:"button",onClick:()=>w(null),children:i.jsx(Ve,{"aria-hidden":"true"})})]}):i.jsxs(i.Fragment,{children:[i.jsxs("button",{className:"device-connect-button",disabled:s||r,onClick:()=>{u(t),b(!1)},role:"menuitem","aria-current":r?"true":void 0,type:"button",children:[r?i.jsx(_,{"aria-hidden":"true"}):i.jsx(Ee,{"aria-hidden":"true"}),i.jsxs("span",{children:[i.jsxs("strong",{className:"device-target-heading",children:[i.jsx("span",{children:a}),r?i.jsx("em",{className:"device-active-label",children:l.active}):null]}),t.displayName&&t.displayName!==t.label?i.jsx("small",{children:g(t.displayName)}):null,j(t.daemonId)||!t.displayName?i.jsx("small",{children:j(t.daemonId)?l.currentDevice:g(t.daemonId)}):null,o?i.jsx("small",{className:"device-connection-endpoint",children:g(o)}):null]})]}),i.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:i.jsx(je,{"aria-hidden":"true"})}),p&&n().canEditConnection?.(t.daemonId)&&i.jsx("button",{"aria-label":`${l.editConnection} ${a}`,title:`${l.editConnection} ${a}`,className:"device-rename-button",onClick:()=>{p(t),b(!1)},type:"button",children:i.jsx(Le,{"aria-hidden":"true"})})]})},t.daemonId)}),0===d.length?i.jsx("p",{className:"empty-copy",children:l.noSavedDevices}):null]}):null]})}function al({label:e,value:t,options:n,onChange:s}){const r=o.useId();return i.jsxs("div",{className:"filter-section",children:[i.jsx("span",{className:"filter-section-label",id:r,children:e}),i.jsx("div",{className:"filter-choice-list",role:"radiogroup","aria-labelledby":r,children:n.map(e=>i.jsxs("label",{className:"filter-menu-row",children:[i.jsx("input",{type:"radio",name:r,value:e.value,checked:t===e.value,onChange:()=>s(e.value)}),i.jsx("span",{children:e.label}),i.jsx(_,{className:"filter-menu-check","aria-hidden":"true","data-checked":t===e.value})]},e.value))})]})}function cl({folder:e,initialValue:t,t:n,onClose:s,onSave:r}){const[c,l]=o.useState(t),d=o.useRef(null),u=f(s,d);return a.createPortal(i.jsxs("div",{"aria-labelledby":"folder-tag-dialog-title","aria-modal":"true",className:"folder-tag-dialog-layer",ref:u,role:"dialog",tabIndex:-1,children:[i.jsx("div",{"aria-hidden":"true",className:"folder-tag-dialog-backdrop",onClick:s}),i.jsxs("form",{className:"folder-tag-dialog",onSubmit:e=>{e.preventDefault(),r(c)},children:[i.jsxs("header",{children:[i.jsx("span",{className:"folder-tag-dialog-icon","aria-hidden":"true",children:i.jsx(He,{})}),i.jsxs("div",{children:[i.jsx("strong",{id:"folder-tag-dialog-title",children:n.editDirectoryTags}),i.jsx("span",{title:e,children:e})]}),i.jsx("button",{"aria-label":n.cancel,title:n.cancel,className:"mini-button",onClick:s,type:"button",children:i.jsx(Ve,{"aria-hidden":"true"})})]}),i.jsxs("label",{className:"folder-tag-dialog-field",children:[i.jsx("span",{children:n.directoryTags}),i.jsx("textarea",{"aria-describedby":"folder-tag-dialog-help",placeholder:n.directoryTagsPlaceholder,ref:d,rows:3,value:c,onChange:e=>l(e.target.value)})]}),i.jsx("p",{id:"folder-tag-dialog-help",children:n.directoryTagsDescription}),i.jsxs("footer",{children:[i.jsx("button",{className:"icon-text-button",onClick:s,type:"button",children:n.cancel}),i.jsx("button",{className:"primary-button",type:"submit",children:n.saveDirectoryTags})]})]})]}),document.body)}function ll({folderToggle:e,search:t,connected:n,filtersOpen:s,filtersActive:r,t:a,onSearchChange:c,onSearchCommit:l,onToggleFilters:d,onCreate:u}){const[h,p]=o.useState(Boolean(t)),f=h||t.length>0,m=o.useRef(null),g=o.useRef(null),v=o.useRef(!1),y=()=>{v.current=!0,l(),c(""),p(!1),g.current?.focus(),v.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)},[]),i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"rail-list-heading",children:[i.jsx("div",{className:"rail-heading-folders",children:e}),i.jsxs("div",{className:"rail-heading-actions",children:[i.jsx("button",{ref:g,"aria-label":a.searchSessions,"aria-expanded":f,className:"rail-create-button",title:ot(a.searchSessions,"searchSessions"),type:"button",onClick:()=>{p(!0),requestAnimationFrame(()=>m.current?.focus())},children:i.jsx(Pe,{"aria-hidden":"true"})}),i.jsx(bc,{"aria-label":a.newSession,className:"rail-create-button",disabled:!n,onClick:u,title:a.newSession,type:"button",children:i.jsx(Me,{"aria-hidden":"true"})}),i.jsx("button",{"aria-expanded":s,"aria-label":a.sessionFilters,className:"filter-toggle "+(s||r?"selected":""),onClick:d,title:a.sessionFilters,type:"button",children:i.jsx(ie,{"aria-hidden":"true"})})]})]}),f&&i.jsxs("div",{className:"search-box rail-search-overlay",onBlur:e=>{v.current||e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||(l(),p(Boolean(t)))},children:[i.jsx(Pe,{"aria-hidden":"true"}),i.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()}}),i.jsx("button",{className:"search-close","aria-label":a.cancel,title:a.cancel,type:"button",onClick:y,children:i.jsx(Ve,{"aria-hidden":"true"})})]})]})}function dl({menu:e,pending:t,t:n,onOpen:s,onDetails:r,onRename:o,onCopyResumeCommand:a,onResumeInTerminal:c,terminalBusy:l,onTogglePinned:d,onToggleArchived:u,onDelete:h}){return i.jsxs("div",{className:"session-context-menu",role:"menu",style:{left:e.x,top:e.y},onPointerDown:e=>e.stopPropagation(),children:[i.jsxs("button",{type:"button",role:"menuitem",onClick:s,children:[i.jsx(v,{"aria-hidden":"true"}),n.open]}),i.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:o,children:[i.jsx(je,{"aria-hidden":"true"}),n.rename]}),i.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:r,children:[i.jsx(he,{"aria-hidden":"true"}),n.details]}),i.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:a,children:[i.jsx(Q,{"aria-hidden":"true"}),n.copyResumeCommand]}),c&&i.jsxs("button",{type:"button",role:"menuitem",disabled:t||l,title:l?n.resumeTerminalBusy:n.resumeInTerminal,onClick:c,children:[i.jsx(Be,{"aria-hidden":"true"}),n.resumeInTerminal]}),i.jsx("span",{className:"context-menu-separator"}),i.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:d,children:[i.jsx(Re,{"aria-hidden":"true"}),e.session.pinned?n.unpin:n.pin]}),i.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:u,children:[i.jsx(P,{"aria-hidden":"true"}),e.session.archived?n.unarchive:n.archive]}),i.jsxs("button",{className:"danger",type:"button",role:"menuitem",onClick:h,children:[i.jsx(Ue,{"aria-hidden":"true"}),n.delete]})]})}function ul({title:e,t,onClose:n,onSave:s}){const[r,a]=o.useState(e),[c,l]=o.useState(!1),[d,u]=o.useState(!1),h=o.useRef(null),p=o.useRef(!1),f=o.useRef(!1),m=()=>{const e=h.current?.closest(".session-item")?.querySelector(".session-row");n(),f.current&&window.requestAnimationFrame(()=>e?.isConnected&&e.focus())};o.useLayoutEffect(()=>{h.current?.focus(),h.current?.select()},[]);const g=async()=>{if(p.current)return;const t=r.trim();if(t&&t!==e){p.current=!0,u(!0),l(!1);try{if(await s(t))return void m()}catch{}p.current=!1,u(!1),l(!0),h.current?.focus()}else m()};return i.jsxs("form",{className:"session-rename-inline",onSubmit:e=>{e.preventDefault(),g()},children:[i.jsx("input",{ref:h,"aria-label":t.rename,value:r,readOnly:d,onChange:e=>a(e.target.value),onBlur:()=>{g()},onKeyDown:e=>{e.stopPropagation(),e.nativeEvent.isComposing||229===e.keyCode||("Enter"===e.key&&(f.current=!0),"Escape"!==e.key||d||(e.preventDefault(),p.current=!0,f.current=!0,m()))}}),c&&i.jsx("small",{role:"alert",children:t.renameFailed})]})}function hl({session:e,renamingRowId:t,onRename:n,onCloseRename:s,active:r,selected:c=!1,responding:l,pending:u=!1,attentionReason:h,tagLabels:p,showFolder:f=!0,t:m,onSelect:g,onContextMenu:v,onToggleArchived:y,onTogglePinned:b}){const x=e.creationError,w=o.useId(),S=t===w,k=d(e),I=un(e.lastActivityAt,Date.now(),m),C=e.cwd?.split(/[\\/]/).filter(Boolean).at(-1)||e.cwd||".",j=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),[R,E]=o.useState(!1),M=o.useRef(null),T=o.useRef(null),A=o.useRef({x:0,y:0}),N=o.useRef(null),D=()=>{const e=T.current;if(!e)return;const{x:t,y:n}=A.current,s=e.getBoundingClientRect(),r=n+18+s.height<=window.innerHeight-8?n+18:n-s.height-12;e.style.left=`${Math.max(8,Math.min(t+14,window.innerWidth-s.width-8))}px`,e.style.top=`${Math.max(8,Math.min(r,window.innerHeight-s.height-8))}px`,e.style.visibility="visible"};o.useLayoutEffect(()=>{R&&D()},[R,k]);const L=()=>{null!==M.current&&window.clearTimeout(M.current),M.current=null,null!==N.current&&window.cancelAnimationFrame(N.current),N.current=null,E(!1)};return o.useEffect(()=>()=>{null!==M.current&&window.clearTimeout(M.current),null!==N.current&&window.cancelAnimationFrame(N.current)},[e.sessionId]),o.useEffect(()=>{if(!R)return;const e=()=>E(!1);return document.addEventListener("scroll",e,!0),()=>document.removeEventListener("scroll",e,!0)},[R]),i.jsxs("div",{className:"session-item","data-row-id":w,onContextMenu:e=>{L(),v?.(e)},"data-renaming":S||void 0,"data-active":r||void 0,"data-multi-selected":c||void 0,"data-statuses":Number(Boolean(e.pinned))+Number(Boolean(e.archived)),onMouseEnter:e=>{A.current={x:e.clientX,y:e.clientY},S||(e=>{null!==M.current&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{M.current=null,e.isConnected&&e.matches(":hover")&&E(!0)},2e3)})(e.currentTarget)},onMouseMove:e=>{A.current={x:e.clientX,y:e.clientY},R&&null===N.current&&(N.current=window.requestAnimationFrame(()=>{N.current=null,D()}))},onMouseLeave:L,onFocusCapture:e=>{if(!S&&e.target instanceof HTMLElement&&e.target.matches(":focus-visible")){null!==M.current&&window.clearTimeout(M.current),M.current=null;const t=e.currentTarget.getBoundingClientRect();A.current={x:t.left+t.width/2,y:t.bottom},E(!0)}},onBlurCapture:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||L()},children:[i.jsxs("button",{className:`session-row ${r?"active":""} ${e.archived?"archived":""} ${l?"responding":""}`,"data-session-id":e.sessionId,"data-row-id":w,disabled:S,"aria-current":r?"true":void 0,"aria-pressed":c,onClick:g,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},type:"button",children:[i.jsxs("span",{className:"session-row-head",children:[i.jsx("strong",{children:k}),i.jsx("span",{className:"session-row-metadata",children:i.jsx("span",{className:"session-row-time",title:I,children:I})}),l?i.jsx("span",{className:"session-running-indicator",role:"img","aria-label":m.agentResponding,title:m.agentResponding}):i.jsx("span",{className:"session-running-placeholder","aria-hidden":"true"})]}),x&&i.jsxs("span",{className:"session-attention-reason",title:x,children:[m.sessionCreateFailed,": ",x]}),h&&i.jsx("span",{className:"session-attention-reason",children:h}),e.runtime.backgroundTerminals?.length?i.jsx("span",{className:"session-terminal-count",children:m.backgroundTerminalsRunning(e.runtime.backgroundTerminals.length)}):null,p?.length?i.jsx("span",{className:"directory-tag-row",title:m.directoryTags,children:p.map(e=>i.jsx("em",{children:e},e))}):null,i.jsx("span",{className:"session-row-footer","aria-hidden":"true"})]}),S&&n&&s&&i.jsx(ul,{title:k,t:m,onClose:s,onSave:t=>n(e,t)}),i.jsxs("div",{className:"session-quick-actions",children:[i.jsx("button",{"aria-label":e.pinned?m.unpin:m.pin,className:e.pinned?"is-pinned":void 0,disabled:u,onClick:b,title:e.pinned?m.unpin:m.pin,type:"button",children:i.jsx(Re,{"aria-hidden":"true"})}),i.jsx("button",{"aria-label":e.archived?m.unarchive:m.archive,className:e.archived?"is-archived":void 0,disabled:u,onClick:y,title:e.archived?m.unarchive:m.archive,type:"button",children:i.jsx(P,{"aria-hidden":"true"})})]}),i.jsxs("div",{className:"session-git-links",children:[f&&i.jsx("span",{className:"session-git-folder",title:e.cwd,children:C}),e.branch&&(j&&r?i.jsx("a",{className:"session-branch-link",href:j,target:"_blank",rel:"noopener noreferrer",title:e.branch,children:e.branch}):i.jsx("span",{className:"session-branch-link",title:e.branch,children:e.branch})),e.pullRequest&&(r?i.jsxs("a",{className:"session-pr-link",href:e.pullRequest.url,target:"_blank",rel:"noopener noreferrer",title:e.pullRequest.title,children:["PR #",e.pullRequest.number]}):i.jsxs("span",{className:"session-pr-link",title:e.pullRequest.title,children:["PR #",e.pullRequest.number]})),e.pinned?i.jsx("span",{className:"session-row-status",children:m.pinned}):null,e.archived?i.jsx("span",{className:"session-row-status",children:m.archived}):null,i.jsx("span",{className:"session-row-agent",children:"codex"===e.agent?"Codex":"Claude"})]}),R&&a.createPortal(i.jsx("div",{"aria-hidden":"true",className:"session-title-tooltip",ref:T,style:{left:0,top:0,visibility:"hidden"},children:k}),document.body)]})}function pl(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 i.jsx(fl,{...e,...n})}const fl=o.memo(function({activeSessionId:e,renamingRowId:t,onRenameSession:n,onCloseRename:s,collapsedFolders:r,folderCounts:a,getFolderTags:c,groupFolders:l,groupedSessions:d,phase:u,attentionReasons:h,pendingSessionIds:p,respondingSessionIds:f,t:m,visibleSessions:g,onEditFolderTags:v,onOpenCreateMenu:y,onOpenSessionMenu:b,onSelectSession:x,onToggleSessionArchived:w,onToggleSessionPinned:S,onToggleFolder:k}){const I=o.useId(),[C,j]=o.useState(()=>new Set),R=o.useRef(null),E=o.useMemo(()=>{const e=l?d.flatMap(e=>r[e.folder]?[]:e.sessions):g;return[...new Set(e.map(e=>e.sessionId))]},[r,l,d,g]);o.useEffect(()=>{const e=new Set(E);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)},[E]),o.useEffect(()=>{0===C.size&&(R.current=e)},[e,C]);const M=(t,n)=>{if(n.shiftKey){const s=R.current??e??t,r=E.indexOf(s),i=E.indexOf(t),o=E.slice(Math.min(r<0?i:r,i),Math.max(r,i)+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?i.jsxs(i.Fragment,{children:[d.map(o=>{const l=!!r[o.folder],d=`${I}-${encodeURIComponent(o.folder)}`,g="folder"===o.kind?a[o.folder]??o.sessions.length:o.sessions.length,x="attention"===o.kind?m.needsAttentionSessionsGroup:"running"===o.kind?m.runningSessionsGroup:"pinned"===o.kind?m.pinnedSessionsGroup:o.folder;return i.jsxs("div",{className:"folder-group "+("folder"!==o.kind?"virtual-session-group":""),"data-group-kind":o.kind,"data-contains-active":o.sessions.some(t=>t.sessionId===e)||void 0,children:[i.jsxs("div",{className:"folder-heading",children:[i.jsxs("div",{className:"folder-header",children:[i.jsxs("button",{"aria-expanded":!l,"aria-controls":d,title:x,onClick:()=>k(o.folder),type:"button",children:[i.jsx(z,{className:"folder-disclosure","aria-hidden":"true"}),"attention"===o.kind?i.jsx(he,{"aria-hidden":"true"}):"running"===o.kind?i.jsx(A,{"aria-hidden":"true"}):"pinned"===o.kind?i.jsx(Re,{"aria-hidden":"true"}):l?i.jsx(re,{"aria-hidden":"true"}):i.jsx(ne,{"aria-hidden":"true"}),i.jsx("span",{children:"folder"===o.kind?o.folder.split(/[\\/]/).filter(Boolean).at(-1)||o.folder:x})]}),"folder"===o.kind?i.jsxs(i.Fragment,{children:[i.jsx("button",{"aria-label":c(o.folder).length?m.editDirectoryTags:m.addDirectoryTags,className:"mini-button folder-hover-action",onClick:()=>v(o.folder),title:c(o.folder).length?m.editDirectoryTags:m.addDirectoryTags,type:"button",children:i.jsx(He,{"aria-hidden":"true"})}),i.jsx("button",{"aria-label":m.newSession,className:"mini-button folder-hover-action",disabled:"connected"!==u,onClick:e=>y(e,o.folder),title:m.newSession,type:"button",children:i.jsx(Me,{"aria-hidden":"true"})})]}):null,i.jsx("small",{className:"folder-session-count",title:`${g} ${m.sessions}`,children:g})]}),"folder"===o.kind&&c(o.folder).length?i.jsx("div",{className:"folder-tag-row",children:c(o.folder).map(e=>i.jsx("span",{children:e},e))}):null]}),i.jsx("div",{className:"folder-session-list",id:d,hidden:l,children:l?null:o.sessions.map(r=>i.jsx(hl,{renamingRowId:t,onRename:n,onCloseRename:s,active:r.sessionId===e,selected:C.has(r.sessionId),responding:f.has(r.sessionId),attentionReason:h?.[r.sessionId],pending:p?.has(r.sessionId),session:r,showFolder:"folder"!==o.kind,tagLabels:c(r.cwd),t:m,onContextMenu:e=>b(e,r),onSelect:e=>M(r.sessionId,e),onToggleArchived:()=>w(r),onTogglePinned:()=>S(r)},r.sessionId))})]},o.folder)}),0===g.length?i.jsx("div",{className:"session-empty-state",children:i.jsx("p",{children:m.noSessionsMatch})}):null]}):i.jsxs(i.Fragment,{children:[g.map(r=>i.jsx(hl,{renamingRowId:t,onRename:n,onCloseRename:s,active:r.sessionId===e,selected:C.has(r.sessionId),responding:f.has(r.sessionId),attentionReason:h?.[r.sessionId],pending:p?.has(r.sessionId),session:r,tagLabels:c(r.cwd),t:m,onContextMenu:e=>b(e,r),onSelect:e=>M(r.sessionId,e),onToggleArchived:()=>w(r),onTogglePinned:()=>S(r)},r.sessionId)),0===g.length?i.jsx("div",{className:"session-empty-state",children:i.jsx("p",{children:m.noSessionsMatch})}):null]})});function ml({agentFilter:e,t,onAgentFilterChange:n}){return i.jsx(al,{label:t.agentFilterLabel,value:e,options:[{value:"all",label:t.agentFilterAll},{value:"claude",label:t.agentFilterClaude},{value:"codex",label:t.agentFilterCodex}],onChange:n})}function gl({groupFolders:e,hideArchived:t,separatePinnedGroup:n,showNeedsAttentionGroup:s,showRunningGroup:r,t:o,onToggleGroupFolders:a,onToggleHideArchived:c,onToggleNeedsAttentionGroup:l,onToggleRunningGroup:d,onToggleSeparatePinnedGroup:u}){const h=[[o.showNeedsAttentionGroup,s,l],[o.showRunningGroup,r,d],[o.separatePinnedGroup,n,u]];return i.jsxs("div",{className:"filter-section",children:[i.jsx("span",{className:"filter-section-label",children:o.filterViewOptions}),i.jsxs("div",{className:"filter-view-list",children:[i.jsxs("button",{"aria-pressed":e,className:"filter-menu-row",onClick:a,type:"button",children:[i.jsx("span",{children:o.groupByFolder}),i.jsx(_,{className:"filter-menu-check","aria-hidden":"true","data-checked":e})]}),h.map(([t,n,s])=>i.jsxs("button",{"aria-pressed":e&&n,className:"filter-menu-row nested-filter-option",disabled:!e,onClick:s,type:"button",children:[i.jsx("span",{children:t}),i.jsx(_,{className:"filter-menu-check","aria-hidden":"true","data-checked":e&&n})]},t)),i.jsxs("button",{"aria-pressed":t,className:"filter-menu-row",onClick:c,type:"button",children:[i.jsx("span",{children:o.hideArchived}),i.jsx(_,{className:"filter-menu-check","aria-hidden":"true","data-checked":t})]})]})]})}function vl({connectionIndicators:e,activeSessionId:t,busy:s,collapsedFolders:r,allFoldersCollapsed:c,currentCwd:l,activeDaemonId:d,displayName:u,savedTargets:h,directoryTags:p,folderCounts:f,groupFolders:m,sessionSort:g,onSessionSortChange:v,groupedSessions:y,hideArchived:b,separatePinnedGroup:x,showNeedsAttentionGroup:w,showRunningGroup:S,inventoryVersion:k,nextCursor:I,phase:C,attentionReasons:j,pendingSessionIds:R,respondingSessionIds:E,search:M,sessionAgentFilter:T,sessionsCount:A,sinceFilter:N,statusText:P,t:D,visibleSessions:L,onLoadMore:F,onCopyResumeCommand:q,onResumeInTerminal:O,onConnectTarget:_,onRequestNewSession:$,onDeleteSession:z,onRenameSession:H,onEditFolderTags:B,onOpenSessionDetails:U,onResetFilters:W,onRenameTarget:K,onEditConnection:V,onSearchChange:Q,onSearchCommit:G,onSelectSession:J,onToggleSessionArchived:Z,onToggleSessionPinned:X,onSessionAgentFilterChange:Y,onSinceFilterChange:ee,onToggleFolder:te,onToggleAllFolders:ne,onToggleGroupFolders:se,onToggleHideArchived:re,onToggleNeedsAttentionGroup:ie,onToggleRunningGroup:oe,onToggleSeparatePinnedGroup:ae}){const ce=function({activeSessionId:e,activeDaemonId:t,groupFolders:s,groupedSessions:r,collapsedFolders:i,onToggleFolder:a}){const c=o.useRef(null),l=o.useRef({key:"",revealed:!1});return o.useLayoutEffect(()=>{if("desktop"!==n().kind)return;const o=JSON.stringify([t,e]);if(l.current.key!==o&&(l.current={key:o,revealed:!1}),!e||l.current.revealed)return;if(s){const t=r.filter(t=>t.sessions.some(t=>t.sessionId===e)),n=t.find(e=>!i[e.folder])??t[0];if(n&&i[n.folder])return void(l.current.opening!==n.folder&&(l.current.opening=n.folder,a(n.folder)))}const d=c.current?.querySelector('.session-row[aria-current="true"]');if(!d)return;const u=requestAnimationFrame(()=>{d.isConnected&&l.current.key===o&&(d.scrollIntoView({block:"nearest",inline:"nearest",behavior:"instant"}),l.current.revealed=!0)});return()=>cancelAnimationFrame(u)},[t,e,i,s,r,a]),c}({activeSessionId:t,activeDaemonId:d,groupFolders:m,groupedSessions:y,collapsedFolders:r,onToggleFolder:te}),[le,de]=o.useState(null),[ue,he]=o.useState(!1),[pe,fe]=o.useState(null);o.useEffect(()=>{if(!pe)return;const e=window.setTimeout(()=>fe(null),2400);return()=>window.clearTimeout(e)},[pe]);const[me,ge]=o.useState(null),[be,xe]=o.useState(null),we=o.useRef(null),ke=o.useRef(null),[Ie,Ce]=o.useState(null),je="updated"!==g||"all"!==T||"30d"!==N||!m||m&&(w||S||x)||b,Re=function(e,t,n=!1){const s=o.useMemo(()=>e,[e?.lastActivityAt,e?.sessionId]),r=o.useRef(null),i=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=r.current;if(!e||!s||!u)return i.current=null,void l(null);const t=e.closest(".session-list");if(!(t instanceof HTMLElement))return;let o,c=!0;l(null);const d=()=>{i.current!==u&&(i.current=u,l(u),a.current(s).catch(()=>{c&&(o=window.setTimeout(()=>{c&&(i.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,i.current=null,void 0!==o&&window.clearTimeout(o),h?.disconnect()}},[u,s,n]),{canLoadMore:d,loading:d&&c===u,sentinelRef:r}}(I,F,"updated"!==g||!b),Ee=!!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]),Te=`${P} · ${"connected"===C?`${L.length}/${A} sessions · v${k??"-"}`:D.sameOriginAccess}`,Ae=n().toolbarTarget?.("left");o.useLayoutEffect(()=>{if(!ue)return;const e=()=>{const e=we.current?.getBoundingClientRect();if(!e)return;const t=Math.min(820,window.innerWidth-24);Ce({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)},[ue]),o.useEffect(()=>{if(!ue&&!be)return;const e=e=>{const t=e.target;t instanceof Node&&(we.current?.contains(t)||ke.current?.contains(t))||(he(!1),xe(null))},t=e=>{"Escape"===e.key&&(he(!1),xe(null))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[be,ue]);const Ne=(e,t)=>{xe(null),he(!1),$(t)},Pe=()=>xe(null),De=e=>{if(!be)return;const{session:t}=be;Pe(),e(t)},Le=i.jsxs("div",{className:"brand-block",title:Te,children:[i.jsx("div",{className:"brand-mark","aria-hidden":"true",children:i.jsx("img",{alt:"",className:"brand-logo",height:"40",src:"/web/assets/logo-CVsV06Wq.webp",width:"40"})}),i.jsx(ol,{activeDaemonId:d,busy:s,fallbackName:u,phase:C,statusText:P,t:D,targets:h,onConnect:_,onRename:K,onEditConnection:V})]});return i.jsxs("aside",{className:"session-rail","aria-label":D.sessions,children:[Ae?a.createPortal(Le,Ae):Le,i.jsxs("div",{className:"search-filter-wrap",ref:we,children:[i.jsx(ll,{folderToggle:m&&y.length>0&&i.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?i.jsx(ye,{"aria-hidden":"true"}):i.jsx(Se,{"aria-hidden":"true"})}),search:M,connected:"connected"===C,filtersOpen:ue,filtersActive:je,t:D,onSearchChange:Q,onSearchCommit:G,onToggleFilters:()=>he(e=>!e),onCreate:Ne}),ue&&Ie?a.createPortal(i.jsxs("div",{className:"filter-popover session-filter-popover",role:"dialog","aria-label":D.sessionFilters,ref:ke,style:{top:Ie.top,left:Ie.left},children:[i.jsx(al,{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:v}),i.jsx(ml,{agentFilter:T,t:D,onAgentFilterChange:Y}),i.jsx(al,{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}),i.jsx(gl,{groupFolders:m,hideArchived:b,separatePinnedGroup:x,showNeedsAttentionGroup:w,showRunningGroup:S,t:D,onToggleGroupFolders:se,onToggleHideArchived:re,onToggleNeedsAttentionGroup:ie,onToggleRunningGroup:oe,onToggleSeparatePinnedGroup:ae}),je?i.jsx("button",{className:"filter-reset-button",onClick:W,type:"button",children:D.resetFilters}):null]}),document.body):null]}),i.jsxs("div",{className:"session-list",ref:ce,children:[i.jsx(pl,{activeSessionId:t,renamingRowId:le,onRenameSession:H,onCloseRename:()=>de(null),collapsedFolders:r,folderCounts:f,getFolderTags:Me,groupFolders:m,groupedSessions:y,phase:C,attentionReasons:j,pendingSessionIds:R,respondingSessionIds:E,t:D,visibleSessions:L,onEditFolderTags:e=>{he(!1),xe(null),ge({folder:e,value:Me(e).join(", ")})},onOpenCreateMenu:Ne,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:X,onToggleFolder:te},d??"unconnected"),Re.canLoadMore?i.jsx("div",{"aria-live":"polite",className:"session-load-sentinel "+(Re.loading?"loading":""),ref:Re.sentinelRef,role:"status",children:Re.loading?i.jsxs(i.Fragment,{children:[i.jsx(ve,{className:"spin","aria-hidden":"true"}),i.jsx("span",{children:D.loadingMore})]}):null}):null]}),i.jsxs("div",{className:"session-rail-footer",children:[i.jsx("div",{className:"rail-footer-indicators",children:e}),n().openSettings&&i.jsxs("button",{"aria-label":D.settings,className:"icon-button rail-settings-button",onClick:()=>n().openSettings?.(),title:D.settings,type:"button",children:[i.jsx(Fe,{"aria-hidden":"true"}),n().settingsBadge]})]}),me?i.jsx(cl,{folder:me.folder,initialValue:me.value,t:D,onClose:()=>ge(null),onSave:e=>{me&&(B(me.folder,e),ge(null))}}):null,be?i.jsx(dl,{menu:be,pending:Ee,t:D,onOpen:()=>De(e=>J(e.sessionId)),onRename:()=>{de(be.rowId),Pe()},onDetails:()=>De(U),onCopyResumeCommand:()=>De(e=>{Promise.resolve(q(e)).then(()=>fe({message:D.commandCopied,tone:"success"})).catch(()=>fe({message:D.copyResumeFailed,tone:"error"}))}),onResumeInTerminal:O&&d&&n().resumeInTerminal&&n().isLocalDaemon?.(d)?()=>De(O):void 0,terminalBusy:E.has(be.session.sessionId),onTogglePinned:()=>De(X),onToggleArchived:()=>De(Z),onDelete:()=>De(z)}):null,i.jsx(dr,{feedback:pe})]})}function yl({collapsed:e,children:t,onExpand:s,onResize:r,t:o}){const c=n().toolbarTarget?.("left"),l=i.jsx("button",{"aria-label":e?o.expandSessionSidebar:o.collapseSessionSidebar,className:"sidebar-titlebar-toggle",onClick:s,title:ot(e?o.expandSessionSidebar:o.collapseSessionSidebar,"leftSidebar"),type:"button",children:i.jsx(ke,{"aria-hidden":"true"})});return i.jsxs(i.Fragment,{children:[c?a.createPortal(l,c):l,i.jsx("div",{className:"session-sidebar-motion",inert:e,"aria-hidden":e,children:t}),i.jsx("button",{"aria-label":o.resizeSessionSidebar,"aria-hidden":e,className:"resize-handle",disabled:e,onPointerDown:r,title:o.resizeSessionSidebar,type:"button",children:i.jsx("span",{})})]})}function bl({workspace:e,onSelect:t}){const a=o.useRef([]),c=o.useRef(new Map),[l,d]=o.useState(null),u=o.useRef({w:e,onSelect:t});u.current={w:e,onSelect:t};const h=o.useRef(null),p=o.useRef(null),f=s(r().language),m="en"===f?{title:"Recent conversations",hint:"Tab / Shift+Tab to preview · Release Ctrl to switch · Esc to cancel",empty:"No messages yet"}:"zh-TW"===f?{title:"最近會話",hint:"Tab / Shift+Tab 預覽 · 鬆開 Ctrl 切換 · Esc 取消",empty:"暫無訊息"}:{title:"最近会话",hint:"Tab / Shift+Tab 预览 · 松开 Ctrl 切换 · Esc 取消",empty:"暂无消息"};return o.useEffect(()=>{a.current=[],c.current.clear(),h.current=null,d(null)},[e.pairing?.daemonId]),o.useEffect(()=>{e.activeSessionId&&(a.current=[e.activeSessionId,...a.current.filter(t=>t!==e.activeSessionId)].slice(0,30))},[e.activeSessionId,e.pairing?.daemonId]),o.useEffect(()=>{const t=e.messagesSessionIdRef.current;if(t&&t===e.activeSessionId){c.current.set(t,e.messages.filter(e=>"user"===e.role||"assistant"===e.role).slice(-3).map(e=>({role:e.role,content:e.content.slice(0,360)})));for(const e of c.current.keys())a.current.includes(e)||c.current.delete(e)}},[e.messages,e.activeSessionId]),o.useEffect(()=>{p.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({block:"nearest",inline:"nearest"})},[l]),o.useEffect(()=>{if("desktop"!==n().kind)return;const e=e=>{h.current=e,d(e)},t=()=>e(null),s=()=>{const e=h.current?.sessions[h.current.index]?.sessionId;t(),e&&u.current.w.displaySessions.some(t=>t.sessionId===e&&!t.archived)&&u.current.onSelect(e)},r=n=>{if(n.isComposing||n.altKey||n.metaKey)return;if(h.current&&("Escape"===n.key||"Enter"===n.key))return n.preventDefault(),n.stopImmediatePropagation(),void("Escape"===n.key?t():s());if("Tab"!==n.key||!n.ctrlKey)return;if(document.querySelector('[data-shortcut-recording="true"], [role="dialog"], .desktop-workspace-container[hidden], .browser-settings-page'))return;n.preventDefault(),n.stopImmediatePropagation();const{w:r}=u.current;let i=h.current;if(!i){const e=r.displaySessions.filter(e=>!e.archived),t=[...new Set([r.activeSessionId,...a.current,...e.map(e=>e.sessionId)])].flatMap(t=>e.find(e=>e.sessionId===t)??[]);if(t.length<2)return;i={sessions:t,index:0}}e({...i,index:(i.index+(n.shiftKey?-1:1)+i.sessions.length)%i.sessions.length})},i=e=>{"Control"===e.key&&h.current&&s()},o=()=>{document.hidden&&t()};return window.addEventListener("keydown",r,!0),window.addEventListener("keyup",i,!0),window.addEventListener("blur",t),document.addEventListener("visibilitychange",o),()=>{window.removeEventListener("keydown",r,!0),window.removeEventListener("keyup",i,!0),window.removeEventListener("blur",t),document.removeEventListener("visibilitychange",o)}},[]),l?i.jsx("div",{className:"recent-session-backdrop",onPointerDown:()=>{h.current=null,d(null)},children:i.jsxs("section",{className:"recent-session-switcher","aria-label":m.title,onPointerDown:e=>e.stopPropagation(),children:[i.jsxs("div",{className:"recent-session-heading",children:[i.jsx("strong",{children:m.title}),i.jsxs("span",{children:[l.index+1," / ",l.sessions.length]})]}),i.jsx("div",{className:"recent-session-cards",role:"listbox","aria-label":m.title,ref:p,children:l.sessions.map((n,s)=>i.jsxs("button",{type:"button",role:"option","aria-selected":s===l.index,"data-session-id":n.sessionId,className:"recent-session-card",title:`${n.customTitle||n.title||e.t.chat} · ${n.cwd}`,onClick:()=>{h.current=null,d(null),t(n.sessionId)},children:[i.jsx("div",{className:"recent-session-preview","aria-hidden":"true",children:(c.current.get(n.sessionId)?.length?c.current.get(n.sessionId):[{role:"assistant",content:n.customTitle||n.title||m.empty}]).map((e,t)=>i.jsx("p",{className:e.role,children:e.content},t))}),i.jsxs("div",{className:"recent-session-title",children:[i.jsx(xe,{size:17}),i.jsx("strong",{children:n.customTitle||n.title||e.t.chat})]}),i.jsxs("div",{className:"recent-session-meta",children:[n.agent," · ",n.cwd.split("/").filter(Boolean).at(-1)||n.cwd]})]},n.sessionId))}),i.jsxs("div",{className:"recent-session-hint","aria-live":"polite",children:[i.jsxs("span",{className:"recent-session-announcement",children:[l.sessions[l.index]?.customTitle||l.sessions[l.index]?.title||e.t.chat,"."," "]}),m.hint]})]})}):null}const xl={version:"",latestVersion:"",loading:!1,error:null};function wl(e){const t=e.match(/^\d+/);return t?Number(t[0]):0}function Sl(e,t){return function(e,t){const n=e.split(/[+-]/,1)[0].split(".").map(wl),s=t.split(/[+-]/,1)[0].split(".").map(wl),r=Math.max(n.length,s.length);for(let i=0;i<r;i+=1){const e=n[i]??0,t=s[i]??0;if(e<t)return-1;if(e>t)return 1}return 0}(e,t)<0}function kl({busy:e,connected:t,dismissed:n,feedback:s,synced:r,t:o,onPull:a,onPushMerge:c,onPushReplace:l,onSkip:d}){const u=!t||null!==e;return i.jsxs("section",{className:"control-section compact-section archive-sync-panel",children:[i.jsx("h2",{children:o.archiveSyncTitle}),i.jsx("p",{className:"empty-copy",children:r?o.archiveSyncSynced:n?o.archiveSyncSkippedState:o.archiveSyncBody}),i.jsxs("div",{className:"action-grid archive-sync-actions",children:[i.jsxs("button",{className:"icon-text-button",disabled:u,onClick:c,type:"button",children:[i.jsx(ce,{"aria-hidden":"true"}),"pushMerge"===e?o.archiveSyncSyncing:o.archiveSyncPushMerge]}),i.jsxs("button",{className:"icon-text-button",disabled:u,onClick:a,type:"button",children:[i.jsx(g,{"aria-hidden":"true"}),"pull"===e?o.archiveSyncSyncing:o.archiveSyncPull]}),i.jsxs("button",{className:"icon-text-button",disabled:u,onClick:l,type:"button",children:[i.jsx(We,{"aria-hidden":"true"}),"pushReplace"===e?o.archiveSyncSyncing:o.archiveSyncPushReplace]}),i.jsxs("button",{className:"icon-text-button",disabled:u,onClick:d,type:"button",children:[i.jsx(N,{"aria-hidden":"true"}),o.archiveSyncSkip]})]}),s?i.jsx("p",{className:"empty-copy "+("error"===s.tone?"error-copy":"success-copy"),children:s.message}):null]})}const Il="__keep_current__";function Cl({connected:e,daemonId:t,t:n,listModels:s,apply:r}){const[a,c]=o.useState({codex:Il,claude:Il}),[l,d]=o.useState({codex:[],claude:[]}),[u,h]=o.useState(!0),[p,f]=o.useState(!1),[m,g]=o.useState(null),[v,y]=o.useState(!1),b=o.useRef(!1);return o.useEffect(()=>{let t=!1;if(d({codex:[],claude:[]}),c({codex:Il,claude:Il}),g(null),y(!1),e)for(const e of["codex","claude"])s(e).then(n=>{t||d(t=>({...t,[e]:n}))}).catch(()=>{});return()=>{t=!0}},[e,t,s]),i.jsxs("section",{className:"control-section bulk-session-settings",children:[i.jsx("h2",{children:n.bulkSessionTitle}),i.jsx("p",{className:"empty-copy",children:n.bulkSessionHint}),i.jsx("div",{className:"bulk-session-models",children:["codex","claude"].map(t=>{const s=[{value:Il,label:n.bulkSessionKeep},...l[t].map(e=>({value:e.value,label:e.label,description:e.desc}))];return i.jsxs("div",{className:"bulk-session-model",children:[i.jsx("span",{children:"codex"===t?"Codex":"Claude"}),i.jsx(Os,{portal:!0,wide:!0,icon:J,menuLabel:`${t} ${n.model}`,label:s.find(e=>e.value===a[t])?.label??n.bulkSessionKeep,options:s,value:a[t],disabled:p||!e,onSelect:e=>c(n=>({...n,[t]:e}))})]},t)})}),i.jsxs("div",{className:"bulk-session-speed",children:[i.jsxs("div",{children:[i.jsx("strong",{children:n.fastMode}),i.jsx("p",{className:"empty-copy",children:n.bulkSessionSpeedHint})]}),i.jsxs("button",{type:"button",className:"icon-text-button "+(u?"is-active":""),"aria-pressed":u,"aria-label":n.fastMode,disabled:p,onClick:()=>h(!u),children:[i.jsx(Qe,{"aria-hidden":"true"}),u?n.fast:n.bulkSessionNormal]})]}),i.jsx("button",{type:"button",className:"primary-button bulk-session-apply",disabled:!e||p,onClick:()=>{(async()=>{if(!b.current&&e){b.current=!0,f(!0),y(!1),g(null);try{g(await r({models:{codex:a.codex===Il?void 0:a.codex,claude:a.claude===Il?void 0:a.claude},fastMode:u},g))}catch{y(!0)}finally{b.current=!1,f(!1)}}})()},children:p?n.bulkSessionApplying:n.bulkSessionApply}),!e&&i.jsx("p",{className:"empty-copy",children:n.bulkSessionOffline}),m&&i.jsx("p",{role:"status",className:"empty-copy "+(m.failed?"error-copy":"success-copy"),children:n.bulkSessionResult.replace("{ok}",String(m.updated)).replace("{failed}",String(m.failed))}),v&&i.jsx("p",{role:"alert",className:"empty-copy error-copy",children:n.bulkSessionError})]})}function jl({pairing:e,label:t,phase:n,t:s,onForgetPairing:r}){const o="connected"===n?"connected":e?n:s.notPaired;return i.jsxs("section",{className:"control-section compact-section",children:[i.jsx("h2",{children:s.currentDevice}),i.jsxs("dl",{children:[i.jsxs("div",{children:[i.jsx("dt",{children:s.daemon}),i.jsxs("dd",{className:"connection-device-name",children:[i.jsx("strong",{children:t||e?.displayName||e?.daemonId||s.notPaired}),t&&e?.displayName&&t!==e.displayName?i.jsx("small",{children:e.displayName}):null]})]}),i.jsxs("div",{children:[i.jsx("dt",{children:s.status}),i.jsx("dd",{children:o})]})]}),i.jsx("div",{className:"action-grid",children:i.jsxs("button",{className:"danger-button",disabled:!e,onClick:r,type:"button",children:[i.jsx(pe,{"aria-hidden":"true"}),s.forget]})})]})}function Rl({connected:e,metadata:t,showUpdate:n,updateBusy:s,restartBusy:r,t:o,updateStatus:a,onUpdate:c,onRestart:l}){const d=t.version&&t.latestVersion&&n?`${t.version} -> ${t.latestVersion}`:t.version||o.unknown;return i.jsxs("section",{className:"control-section compact-section",children:[i.jsx("h2",{children:o.desktopConnector}),i.jsx("dl",{children:i.jsxs("div",{children:[i.jsx("dt",{children:o.version}),i.jsx("dd",{children:t.loading?o.checking:d})]})}),i.jsxs("div",{className:"action-grid",children:[n?i.jsxs("button",{className:"primary-button",disabled:!e||s||r,onClick:c,type:"button",children:[i.jsx(g,{"aria-hidden":"true"}),s?o.updating:o.update]}):null,i.jsxs("button",{className:"danger-button",disabled:!e||r,onClick:l,type:"button",children:[i.jsx(Te,{"aria-hidden":"true"}),r?o.restarting:o.restart]})]}),t.error?i.jsx("p",{className:"empty-copy",children:t.error}):null,a?i.jsx("p",{className:"empty-copy",children:a}):null]})}function El({activeDaemonId:e,busy:t,t:n,targets:s,onConnect:r,onForget:o}){return i.jsxs("section",{className:"control-section compact-section",children:[i.jsx("h2",{children:n.savedDevices}),i.jsxs("div",{className:"stack-list",children:[s.map(s=>i.jsxs("div",{className:"data-row target-row",children:[i.jsxs("div",{children:[i.jsxs("strong",{children:[s.label,s.daemonId===e?` · ${n.active}`:""]}),i.jsxs("span",{children:[s.displayName??s.daemonId," ·"," ",s.lastConnectedAt?un(s.lastConnectedAt,Date.now(),n):n.notConnectedRecently]})]}),i.jsxs("div",{className:"row-actions",children:[i.jsx("button",{"aria-label":`Connect to ${s.label}`,title:`Connect to ${s.label}`,className:"icon-button",disabled:t,onClick:()=>r(s),type:"button",children:i.jsx(Ee,{"aria-hidden":"true"})}),i.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:i.jsx(Ue,{"aria-hidden":"true"})})]})]},s.daemonId)),0===s.length?i.jsx("p",{className:"empty-copy",children:n.noSavedDevices}):null]})]})}function Ml({workspace:e,portalOnly:t=!1}){const s=()=>({general:n().settingsTarget?.()??null,sessions:n().settingsTarget?.("sessions")??null}),[r,c]=o.useState(s);o.useEffect(()=>{const e=()=>c(s());return window.addEventListener("vibelet.settings.target.changed",e),e(),()=>window.removeEventListener("vibelet.settings.target.changed",e)},[]);const l=e,d=i.jsx(Cl,{connected:"connected"===l.phase,daemonId:l.pairing?.daemonId,t:l.t,listModels:l.listSessionModels,apply:l.applyToAllSessions},l.pairing?.daemonId),u=i.jsxs(i.Fragment,{children:[!t&&i.jsxs(i.Fragment,{children:[i.jsx(jl,{pairing:l.pairing,label:l.savedTargets.find(e=>e.daemonId===l.pairing?.daemonId)?.label,phase:l.phase,t:l.t,onForgetPairing:l.clearPairing}),i.jsx(El,{activeDaemonId:l.pairing?.daemonId,busy:l.busy,t:l.t,targets:l.savedTargets,onConnect:l.connectSavedTarget,onForget:l.forgetSavedTarget})]}),!t&&d,i.jsx(kl,{busy:l.archiveSyncBusy,connected:"connected"===l.phase,dismissed:l.archiveSyncDismissed,feedback:l.archiveSyncStatus,synced:l.archiveSynced,t:l.t,onPull:()=>{l.runArchiveSync("pull")},onPushMerge:()=>{l.runArchiveSync("pushMerge")},onPushReplace:()=>{l.runArchiveSync("pushReplace")},onSkip:l.skipArchiveSync}),i.jsx(Rl,{connected:"connected"===l.phase,metadata:l.daemonMetadata,restartBusy:l.admin.loading&&"restart"===l.admin.action,showUpdate:Boolean(l.daemonMetadata.version&&l.daemonMetadata.latestVersion&&Sl(l.daemonMetadata.version,l.daemonMetadata.latestVersion)),t:l.t,updateBusy:l.admin.loading&&"update"===l.admin.action,updateStatus:l.admin.statusText,onRestart:()=>{l.runAdminAction("restart")},onUpdate:()=>{l.runAdminAction("update")}})]}),h=i.jsx("div",{className:"remote-workspace-settings",children:u});return t?i.jsxs(i.Fragment,{children:[r.sessions&&a.createPortal(d,r.sessions),r.general&&a.createPortal(h,r.general)]}):h}function Tl(){const e=n().polishSettings,t="en"!==s(r().language),[a,c]=o.useState(),[l,d]=o.useState({...y}),[u,h]=o.useState(""),[p,f]=o.useState(!1),[m,g]=o.useState(""),[v,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=>{f(!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{f(!1)}};return i.jsxs("section",{className:"control-section compact-section speech-polish-settings",children:[i.jsx("h2",{children:t?"语音润色":"Voice polishing"}),i.jsxs("label",{className:"speech-enabled",children:[i.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),f(!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{f(!1)}}}),t?"启用语音润色":"Enable voice polishing"]}),l.enabled&&i.jsxs("fieldset",{disabled:!a||p,className:"speech-polish-fields",children:[i.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."}),i.jsxs("label",{className:"field",children:[i.jsx("span",{children:t?"API 地址":"API URL"}),i.jsx("input",{type:"url",value:l.baseUrl,onChange:e=>d({...l,baseUrl:e.target.value}),autoComplete:"off"})]}),i.jsxs("label",{className:"field",children:[i.jsx("span",{children:t?"模型":"Model"}),i.jsx("input",{value:l.model,onChange:e=>d({...l,model:e.target.value}),autoComplete:"off"})]}),i.jsxs("label",{className:"field",children:[i.jsx("span",{children:t?"润色 API Key":"Polishing API Key"}),i.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"})]}),i.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()&&i.jsx("p",{className:"empty-copy",children:t?"请填写 API Key 并保存,润色才能生效。":"Enter and save an API key to use polishing."}),i.jsxs("details",{className:"speech-polish-advanced",children:[i.jsx("summary",{children:t?"自定义提示词":"Custom prompts"}),i.jsxs("label",{className:"field",children:[i.jsx("span",{children:t?"中文提示词":"Chinese prompt"}),i.jsx("textarea",{rows:5,value:l.promptZh,onChange:e=>d({...l,promptZh:e.target.value})})]}),i.jsxs("label",{className:"field",children:[i.jsx("span",{children:t?"英文提示词":"English prompt"}),i.jsx("textarea",{rows:5,value:l.promptEn,onChange:e=>d({...l,promptEn:e.target.value})})]}),i.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>d({...l,promptZh:y.promptZh,promptEn:y.promptEn}),children:t?"恢复默认提示词":"Reset prompts"})]}),i.jsxs("div",{className:"attention-actions",children:[i.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{x(u.trim()||void 0)},children:t?"保存润色设置":"Save polishing settings"}),a?.configured&&i.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{x("")},children:t?"移除润色密钥":"Remove polishing key"})]})]}),m&&i.jsx("p",{role:v?"alert":"status",className:v?"error-copy":"empty-copy",children:m})]})}const Al={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 Nl(){const e=n().speechSettings,a=Al[s(r().language)],[c,l]=o.useState(),[d,u]=o.useState(""),[h,p]=o.useState(!1),[f,m]=o.useState(""),[g,v]=o.useState("true"===t().getItem("vibelet.web.voice.enabled")),y=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&&m("Unable to load speech settings.")}),()=>{t=!1}},[e]);const b=e=>{v(e),t().setItem("vibelet.web.voice.enabled",String(e)),window.dispatchEvent(new Event("vibelet.speech.changed"))},x=async t=>{if(e&&!h){p(!0),m("");try{l(await e.saveKey(t)),u(""),t||b(!1),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch(n){m(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(r().language)?"Volcengine · ASR Flash":"火山引擎 · 录音识别"}];return i.jsxs(i.Fragment,{children:[i.jsxs("section",{className:"control-section compact-section speech-input-settings",children:[i.jsx("h2",{children:a.title}),i.jsxs("label",{className:"speech-enabled",children:[i.jsx("input",{type:"checkbox",role:"switch","aria-checked":g,className:"settings-switch",checked:g,disabled:!y,onChange:e=>b(e.target.checked)}),a.enabled]}),g&&i.jsxs(i.Fragment,{children:[e.setEngine&&i.jsxs("div",{className:"field speech-engine-field",children:[i.jsx("span",{children:"en"===s(r().language)?"Recognition engine":"识别引擎"}),i.jsx(Os,{icon:we,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),m(""),u("");try{l(await e.setEngine(t)),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch(n){m(n instanceof Error?n.message:String(n))}finally{p(!1)}}})]}),i.jsx("p",{className:"empty-copy",children:"system"===c?.engine?"en"===s(r().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(r().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&&i.jsxs(i.Fragment,{children:[i.jsx("p",{className:"empty-copy",children:"encrypted"===c?.persistence?a.secure:a.session}),i.jsxs("label",{className:"field",children:[i.jsx("span",{children:w?"火山引擎 API Key":"Deepgram API Key"}),i.jsx("input",{type:"password",autoComplete:"off",value:d,onChange:e=>u(e.target.value),placeholder:c?.configured?a.saved:"API Key"})]}),i.jsxs("div",{className:"attention-actions",children:[i.jsx("button",{type:"button",className:"icon-text-button",disabled:h||!d.trim(),onClick:()=>{x(d)},children:a.save}),c?.configured&&i.jsx("button",{type:"button",className:"icon-text-button",disabled:h,onClick:()=>{x("")},children:a.remove})]})]})]}),!y&&i.jsx("p",{className:"empty-copy",children:a.unsupported}),f&&i.jsx("p",{role:"alert",className:"error-copy",children:f})]}),g&&i.jsx(Tl,{})]})}async function Pl(e,t,n){for(let r=0;r<2&&n();r++)try{return await e.request(t(),{timeoutMs:135e3})}catch(s){if(!(s instanceof Error&&/timeout|timed out/i.test(s.message)))return}}function Dl(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 Ll(e){return e?"success":"warning"}function Fl(e,t){return e&&null!==t?t<150?"success":t<500?"warning":"danger":"warning"}function ql({connected:e,latencyMs:t,limits:n,t:s,failed:r={},loading:a=!1,onRetry:c}){const l=function(e){const t=[],n=Dl(e.codex),s=Dl(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}),[d,u]=o.useState(0);o.useEffect(()=>{if(u(0),l.length<2)return;const e=setInterval(()=>u(e=>(e+1)%l.length),4e3);return()=>clearInterval(e)},[l.length]);const h=l[d%l.length],p=h?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())}`}(h.resetsAt):null,f=h?`${h.label} ${h.availablePercent}%`:"",m=!!h&&r[h.agent],g=m?s.quotaUpdateFailed:h?"":a?s.loading:s.quotaUnavailable,v=`${s.remainingQuota}: ${f||g}${m?` · ${g}`:""} · ${p?s.quotaResetsAt.replace("{time}",p):s.quotaResetUnavailable}${e?"":` · ${s.latencyDisconnected}`}`,y=e?null===t?s.latencyMeasuring:`${t} ms`:s.latencyDisconnected;return i.jsxs("div",{className:"connection-indicators",children:[(h||c)&&i.jsxs("button",{type:"button",className:"connection-quota",disabled:!e||a||!c,onClick:c,title:`${v}${c?` · ${s.retry}`:""}`,"aria-label":`${v}${c?` · ${s.retry}`:""}`,"aria-busy":a,children:[i.jsx("span",{className:"connection-quota-dot",style:{background:`var(--${m||!h?"warning":Ll(e)})`}}),i.jsxs("span",{className:"connection-quota-text",children:[f||g,m?" ↻":""]})]}),i.jsxs("span",{role:"img",className:"connection-latency",style:{color:`var(--${Fl(e,t)})`},"aria-label":`${s.connectionLatency}: ${y}`,children:[i.jsx(A,{size:11,"aria-hidden":"true"}),i.jsx("span",{className:"connection-latency-text",children:y})]})]})}function Ol({workspace:e}){const{phase:t,clientRef:n,pairing:s,t:r}=e,[a,c]=o.useState(null),[l,d]=o.useState({}),[u,h]=o.useState({}),[p,f]=o.useState(!1),m=o.useRef(()=>{});return o.useEffect(()=>{h({}),d({})},[s?.daemonId]),o.useEffect(()=>{const e=n.current;if(c(null),f(!1),"connected"!==t||!e)return;let s=!0;const r=e.onLatency(c),i=new Set,o=new Map,a={codex:0,claude:0},l=()=>s&&n.current===e&&e.isConnected,u=(t,n=!1)=>{l()&&!i.has(t)&&(clearTimeout(o.get(t)),i.add(t),f(!0),Pl(e,()=>({action:"usage.limits.fetch",id:e.makeId("header-usage"),agent:t,force:n}),l).then(e=>{if(!l())return;const n=Boolean(e?.limits);a[t]=n?0:a[t]+1,h(e=>({...e,[t]:!n})),e?.limits&&d(n=>({...n,[t]:e}));const s=n?6e4:Math.min(6e4,15e3*2**Math.min(a[t]-1,2));o.set(t,setTimeout(()=>u(t),s))}).finally(()=>{i.delete(t),s&&f(i.size>0)}))},p=()=>{u("codex"),u("claude")};return m.current=()=>{u("codex",!0),u("claude",!0)},p(),window.addEventListener("online",p),window.addEventListener("focus",p),()=>{s=!1,m.current=()=>{},r();for(const e of o.values())clearTimeout(e);window.removeEventListener("online",p),window.removeEventListener("focus",p)}},[t,n,s?.daemonId]),i.jsx(ql,{connected:"connected"===t,latencyMs:a,limits:l,failed:u,loading:p,onRetry:()=>m.current(),t:r})}function _l({value:e,t,showSession:n=!0,onChange:s}){const r=[...n?[{tab:"session",label:t.session,Icon:Oe}]:[],{tab:"files",label:t.files,Icon:ne},{tab:"terminal",label:t.terminal,Icon:$e},{tab:"browser",label:t.browser,Icon:le}];return i.jsx("div",{className:"control-tabs",children:r.map(({tab:t,label:n,Icon:r})=>i.jsxs("button",{"aria-label":n,"aria-pressed":e===t,className:e===t?"selected":"",onClick:()=>s(t),title:n,type:"button",children:[i.jsx(r,{"aria-hidden":"true"}),i.jsx("span",{children:n})]},t))})}function $l(){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)},r=e=>{if(!(e instanceof Element))return null;const t=e.closest("button, a");return t?.closest(".control-pane, .control-tabs, .header-actions, .right-resize-handle")?t.textContent?.trim()?null:t:null},i=r=>{if(r===e)return;if(s(),!r)return;const i=r.getAttribute("title")||r.getAttribute("aria-label");if(!i)return;e=r,n=r.getAttribute("title"),null!==n&&r.removeAttribute("title");const o=r.getBoundingClientRect(),a=o.bottom+42>window.innerHeight,c=o.right>window.innerWidth-140?"end":o.left<140?"start":"center";t({label:i,left:"end"===c?o.right:"start"===c?o.left:o.left+o.width/2,top:a?o.top-7:o.bottom+7,above:a,align:c})},o=e=>i(r(e.target)),a=t=>{e&&t.relatedTarget instanceof Node&&e.contains(t.relatedTarget)||r(t.target)===e&&s()},c=e=>i(r(e.target)),l=t=>{r(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(i.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 zl({chinese:e}){const[s,r]=o.useState(rt),[a,c]=o.useState(null),[l,d]=o.useState(""),u=e=>{!function(e){t().setItem(st,JSON.stringify(e)),window.dispatchEvent(new Event(Ge))}(e),r(e),d("")};return i.jsxs("section",{className:"control-section compact-section workspace-shortcut-settings",children:[i.jsx("h2",{children:e?"应用内快捷键":"In-app shortcuts"}),i.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."}),Ze.map(t=>i.jsxs("div",{className:"workspace-shortcut-row",children:[i.jsx("span",{children:e?t.zh:t.en}),i.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:r=>{if(a!==t.id)return;if(r.preventDefault(),r.stopPropagation(),"Escape"===r.key)return c(null),void d("");if("Backspace"===r.key||"Delete"===r.key)return u({...s,[t.id]:""}),void c(null);const i=et(r.nativeEvent);if(!i)return;const o=function(e,t,s){return"browser"===n().kind?"mod+w"===t?"reserved":nt(e,t,{closeTab:"mod+alt+w",...s}):nt(e,t,s)}(t.id,i,s);if(o){const t=Ze.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]:i}),c(null)},children:a===t.id?e?"按下快捷键…":"Press shortcut…":tt(it(t.id,s))||(e?"未设置":"Not set")})]},t.id)),l&&i.jsx("p",{role:"alert",children:l}),i.jsx("div",{className:"attention-actions",children:i.jsx("button",{type:"button",onClick:()=>{u({}),c(null)},children:e?"恢复默认快捷键":"Restore defaults"})}),i.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 Hl({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(i.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],r=t.at(-1);e.shiftKey&&document.activeElement===s&&(e.preventDefault(),r?.focus()),e.shiftKey||document.activeElement!==r||(e.preventDefault(),s?.focus())},children:[i.jsxs("button",{ref:s,type:"button",className:"icon-text-button",onClick:n,children:["← ",t.chat]}),i.jsx("h1",{children:t.settings}),i.jsxs("div",{className:"browser-settings-body",children:[i.jsx(dt,{}),e,i.jsx(zl,{chinese:"Browser"!==t.browser})]})]}),document.body)}function Bl({children:e,collapsed:t,t:s,value:r,showSession:c,onChange:l,onResize:d}){const u=qc("right",e=>{"terminal"!==e&&"browser"!==e||l(e)}),h=n().toolbarTarget?.("controls"),[p,f]=o.useState(null),m=i.jsx("div",{className:"right-dock-toolbar",ref:f,children:i.jsx(_l,{value:r,t:s,showSession:c,onChange:l})});return"admin"===r&&"browser"===n().kind?i.jsx(Hl,{t:s,onClose:()=>l("files"),children:e}):i.jsxs(Ac.Provider,{value:{element:p,kind:r},children:[i.jsx($l,{}),h&&!t?a.createPortal(m,h):null,i.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:i.jsx("span",{})}),i.jsx("div",{className:"workspace-control-sidebar-motion",inert:t,"aria-hidden":t,children:i.jsxs("aside",{tabIndex:-1,"aria-label":s.controls,className:"control-pane",...u,children:[!h&&i.jsx("div",{className:"control-pane-toolbar",children:m}),e]})})]})}const Ul=new Set;function Wl(e){return Ul.add(e),()=>{Ul.delete(e)}}const Kl="vibelet.workspace.flush",Vl=e=>/^(https?:|data:|blob:)/i.test(e.path)?e.path:Br(e.path,e.cwd);function Ql(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function Gl(e=window.location.search){const t=new URLSearchParams(e),n=Ql(t.get("folder")),s=Ql(t.get("file")),r=Ql(t.get("cwd"));return{...n?{folder:n}:{},...s?{file:s}:{},...r?{cwd:r}:{}}}function Jl(e,t={}){const n=t.history??window.history,s=t.location??window.location,r=[];e.folder&&r.push("file","cwd"),e.file&&r.push("folder");const i=function(e,t,n=[]){const s=new URLSearchParams(e);for(const i of n)s.delete(i);for(const[i,o]of Object.entries(t))o?s.set(i,o):s.delete(i);const r=s.toString();return r?`?${r}`:""}(s.search,e,r),o=`${s.pathname}${i}${s.hash}`;t.replace?n.replaceState(null,"",o):n.pushState(null,"",o)}function Zl({path:e,label:t,zh:n}){const{copyText:s,feedback:r}=lr(n?"已复制路径":"Path copied",n?"复制失败,请重试":"Copy failed. Please try again."),o=r?.message??t;return i.jsx("button",{type:"button",title:o,"aria-label":o,onClick:()=>{s(e)},children:r?"success"===r.tone?i.jsx(_,{}):i.jsx(Ve,{}):i.jsx(Q,{})})}function Xl(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 Yl(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 ed(){const e=s(r().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 td({file:e}){const[t,c]=o.useState(!1),l=f(()=>c(!1),void 0,t),d=Tr(),u=s(r().language),h="en"===u?"Close":"zh-TW"===u?"關閉":"关闭",p=n().pdfPreviewUrl?.(e.path,e.cwd)??e.objectUrl;return i.jsxs(i.Fragment,{children:[i.jsxs("button",{className:"icon-text-button",type:"button",onClick:()=>c(!0),children:[i.jsx(te,{"aria-hidden":"true"}),d.pdfPreview]}),t&&a.createPortal(i.jsx("div",{className:"remote-document-layer",onPointerDown:e=>{e.target===e.currentTarget&&c(!1)},children:i.jsxs("div",{ref:l,className:"remote-document-dialog","aria-label":d.pdfPreview,role:"dialog","aria-modal":"true",tabIndex:-1,children:[i.jsxs("header",{children:[i.jsx("span",{children:e.path.split("/").pop()}),i.jsx("button",{className:"icon-button",type:"button","aria-label":h,title:h,onClick:()=>c(!1),children:i.jsx(Ve,{"aria-hidden":"true"})})]}),i.jsx("iframe",{title:d.pdfPreview,src:`${p}#toolbar=1&navpanes=0&view=Fit`})]})}),document.body)]})}function nd({file:e}){const[t,s]=o.useState(),r=e.objectUrl??e.path,a=()=>s(r),c=Tr(),l=Xl(e.path,e.contentType,"text"===e.kind);if(t===r)return i.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 i.jsx("iframe",{className:"remote-document-preview",sandbox:"allow-scripts",title:c.htmlPreview,src:t,srcDoc:t?void 0:Yl(e.text)})}return e.objectUrl?"image"===l?i.jsx("div",{className:"remote-media-viewer remote-image-viewer",children:i.jsx("img",{className:"remote-image",src:e.objectUrl,alt:e.path,onError:a})}):"audio"===l?i.jsx("audio",{"aria-label":c.audioPreview,controls:!0,preload:"metadata",src:e.objectUrl,onError:a}):"video"===l?i.jsx("div",{className:"remote-media-viewer remote-video-viewer",children:i.jsx("video",{"aria-label":c.videoPreview,controls:!0,playsInline:!0,preload:"metadata",src:e.objectUrl,onError:a},e.objectUrl)}):"pdf"===l?i.jsx(td,{file:e}):i.jsx("p",{className:"empty-copy",children:c.mediaError}):null}function sd(e){const t=e.split("#")[0];return/\.[^/\\.]+$/.test(t)?t:`${t}.md`}function rd(e,t){return cs(Br(e,t))??t??"."}function id(e,t,n){if(!e)return{path:Br(t,n),cwd:n??rd(t,n)};const s=e.includes("/")&&!/^\.\.?\//.test(e)?n??rd(t,n):rd(t,n);return{path:sd(e||t),cwd:s}}function od(e,t){if(!t)return;let n=t.replace(/^#/,"");try{n=decodeURIComponent(n)}catch{}const s=n.startsWith("^"),r=e.querySelectorAll(s?".block-id-superscript":"h1,h2,h3,h4,h5,h6"),i=Array.from(r).find(e=>e.textContent?.trim()===n||!s&&e.id===n),o=s?i?.closest(".milkdown-list-item-block, li, p, blockquote")??i:i;o?.scrollIntoView({block:"start"})}const ad=new Map;function cd(e,t,n){for(const[s,r]of ad)Date.now()-r.time>1e4&&ad.delete(s);n&&ad.set(Br(e,t),{hash:n,time:Date.now()})}function ld(e,t){const n=Br(e,t),s=ad.get(n);return ad.delete(n),s&&Date.now()-s.time<1e4?s.hash:""}const dd=o.lazy(()=>m(()=>import("./MarkdownModePanel-B4zGnWRC.js"),__vite__mapDeps([20,1,2,21])).then(e=>({default:e.MarkdownModePanel}))),ud=o.lazy(()=>m(()=>import("./file-editor-FileCodeEditor-Dn3f5PUl.js"),__vite__mapDeps([22,1,2,23,24])).then(e=>({default:e.FileCodeEditor}))),hd=o.lazy(()=>m(()=>import("./file-editor-ObsidianCodeEditor-BgXz3c5Z.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}))),pd=o.lazy(()=>m(()=>import("./file-editor-ObsidianFileEditor-CM9ucogo.js"),__vite__mapDeps([37,1,2,32,3,23,33,38,27,5,39,40,41,42])).then(e=>({default:e.ObsidianFileEditor})));function fd({file:e,client:t,onOpenRemoteFile:n,onTextChange:a}){const c=function(e,t){return o.useMemo(()=>{let n;return async(s,r)=>{const i=id(s,r,t),o={path:Br(i.path,i.cwd),cwd:t??i.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,r=s.replace(/\.(?:md|markdown)$/i,"").toLowerCase(),a=e.filter(e=>e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase()===r||e.basename.toLowerCase()===r||e.aliases?.includes(r)),c=Br(sd(s),i.cwd),l=a.find(e=>Br(e.relPath,t)===c)??a.find(e=>e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase()===r)??a.sort((e,t)=>e.relPath.localeCompare(t.relPath))[0];return l?{path:Br(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"===Xl(e.path,e.contentType,!0),p="en"!==s(r().language);return i.jsxs(i.Fragment,{children:[h&&i.jsxs("div",{className:"segmented editor-mode-tabs",children:[i.jsx("button",{type:"button",className:"edit"===d?"selected":"",onClick:()=>u("edit"),children:p?"编辑":"Edit"}),i.jsx("button",{type:"button",className:"preview"===d?"selected":"",onClick:()=>u("preview"),children:p?"预览":"Preview"})]}),l?i.jsx(o.Suspense,{fallback:i.jsx("pre",{className:"remote-editor",children:e.text}),children:i.jsx(dd,{text:e.text,modes:["edit","source"],initialMode:"edit",labels:ed(),renderVisual:s=>i.jsx(pd,{client:t,resolveFile:c,path:e.path,cwd:e.cwd,text:e.text,readOnly:s,onChange:a,onOpenFile:n}),renderCode:s=>i.jsx(hd,{client:t,cwd:e.cwd,path:e.path,resolveFile:c,onOpenFile:n,text:e.text,onChange:a,preview:s})})}):h&&"preview"===d?i.jsx(nd,{file:e}):i.jsx(o.Suspense,{fallback:i.jsx("pre",{className:"remote-editor",children:e.text}),children:i.jsx(ud,{path:e.path,text:e.text,onChange:a})})]})}function md({file:e,daemonId:t}){const[a,c]=o.useState(!1),[l,d]=o.useState(!1),u=n().openFile;if(!u||!t)return null;const h=s(r().language),p="en"===h?["Open in another app","Save changes before opening","Unable to open. Try again."]:"zh-TW"===h?["使用其他軟體開啟","請先儲存變更再開啟","無法開啟,請重試"]:["使用其他软件打开","请先保存更改再打开","无法打开,请重试"],f=e.dirty?p[1]:l?p[2]:p[0];return i.jsx("button",{type:"button",title:f,"aria-label":f,disabled:a||e.dirty,onClick:async()=>{c(!0),d(!1);try{await u({path:e.path,cwd:e.cwd,daemonId:t})}catch{d(!0)}finally{c(!1)}},children:i.jsx(v,{})})}function gd({workspace:e,children:t}){const a=Ec(),c=_r(e.pairing?.daemonId,e.activeSessionId),l=function(e){const{value:t,setForScope:n}=Or(e,!1);return o.useEffect(()=>{const e=e=>{const t=e.detail;n(_r(t.daemonId,t.sessionId),t.removing)};return window.addEventListener(Pr,e),()=>window.removeEventListener(Pr,e)},[n]),t}(c),d=qc("center"),{openFiles:u,setOpenFiles:h}=e,[p,f]=qr(c,null),[m,v]=o.useState(null),y=o.useRef({files:u,remoteFile:e.remoteFile,scopeKey:c});y.current={files:u,remoteFile:e.remoteFile,scopeKey:c};const w=o.useRef(new Map);o.useEffect(()=>{const e=e=>{const t=e.detail;for(const[n,s]of[...w.current]){const e=Fr(n,t);e!==n&&(w.current.delete(n),null!==e&&w.current.set(e,s))}};return window.addEventListener(Ar,e),()=>window.removeEventListener(Ar,e)},[]);const S="en"!==s(r().language);o.useEffect(()=>{if(!e.remoteFile)return w.current.set(c,null),void f(null);const t=e.remoteFile,n=Vl(t);w.current.get(c)!==n&&(f(n),a.setCenter(null)),w.current.set(c,n)},[e.remoteFile,c]);const k=t=>{a.setCenter(null),e.setRemoteFile(u[t]),f(t),Jl({file:u[t].path,cwd:u[t].cwd},{replace:!0})},I=()=>{f(null),e.setRemoteFile(null),a.setCenter(null),w.current.set(c,null),Jl({file:void 0},{replace:!0})},C=async t=>{const n=u[t];if(!n)return;const s=b();n.dirty&&!(await x({title:s.discard,message:t,confirmLabel:s.discardAction,danger:!0}))||y.current.scopeKey===c&&y.current.files[t]?.text===n.text&&(h(e=>{const n={...e};return delete n[t],n}),t===p&&(f(null),w.current.set(c,null),e.setRemoteFile(null),Jl({file:void 0},{replace:!0})))};o.useEffect(()=>{const e=e=>{const t=e.detail;if("closeTab"===t)return void(a.center?a.close(a.center):p&&C(p));const n=[null,...Object.keys(u),...a.items.filter(e=>"center"===e.location).map(e=>e.id)],s=n.indexOf(a.center||p),r=n[(Math.max(s,0)+("nextTab"===t?1:n.length-1))%n.length];r?u[r]?k(r):a.setCenter(r):I()};return window.addEventListener(Je,e),()=>window.removeEventListener(Je,e)},[u,p,a]);const j=p?u[p]:null;!function(e,t,n){const s=o.useRef({enabled:e,busy:t,save:n});s.current={enabled:e,busy:t,save:n},o.useEffect(()=>{const e=e=>{if(!s.current.enabled||e.defaultPrevented||e.isComposing||229===e.keyCode||"mod+s"!==et(e)||document.querySelector('[role="dialog"], [role="alertdialog"], .desktop-workspace-container[hidden]'))return;const t=e.target instanceof Element?e.target:document.activeElement;t?.closest(".document-file, .document-file-header")&&(e.preventDefault(),e.stopPropagation(),e.repeat||s.current.busy||s.current.save())};return window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)},[])}(!!j&&"text"===j.kind&&!a.center&&!l,e.busy,e.saveRemoteFile);const R=n().toolbarTarget?.("conversation"),E=j&&!a.center&&i.jsxs("header",{className:"document-file-header",role:"toolbar","aria-label":S?"文件操作":"File actions",children:[i.jsx("button",{type:"button",title:e.t.download,"aria-label":e.t.download,onClick:()=>{e.downloadRemoteFile()},children:i.jsx(g,{})}),i.jsx(md,{file:j,daemonId:e.pairing?.daemonId},`open:${j.path}`),i.jsx(Zl,{path:j.path,label:e.t.copyPath,zh:S},j.path),"text"===j.kind&&i.jsx("button",{type:"button",title:e.t.saveFile,"aria-label":e.t.saveFile,disabled:!j.dirty||e.busy,onClick:()=>{e.saveRemoteFile()},children:i.jsx(Ne,{})})]});return i.jsx(bi.Provider,{value:m,children:i.jsxs("div",{className:"workspace-documents",...d,children:[!R&&i.jsx("div",{className:"chat-header document-conversation-header",ref:v}),(Object.keys(u).length>0||a.items.some(e=>"center"===e.location))&&i.jsxs("div",{className:"document-tabs",children:[i.jsxs("div",{className:"document-tab-items",role:"tablist","aria-label":S?"工作区标签页":"Workspace tabs",children:[i.jsx("button",{role:"tab","aria-selected":!p&&!a.center,onClick:I,type:"button",children:e.t.chat}),Object.entries(u).map(([t,n])=>i.jsxs("div",{className:"document-tab","data-active":!a.center&&p===t,children:[i.jsxs("button",{type:"button",role:"tab","aria-selected":!a.center&&p===t,title:n.path,onClick:()=>k(t),children:[i.jsx(te,{}),i.jsxs("span",{className:"document-tab-label",children:[Zn(n.path),n.dirty?" ·":""]})]}),i.jsx("button",{type:"button",className:"document-tab-close",title:e.t.close,"aria-label":`${e.t.close} ${Zn(n.path)}`,onClick:()=>C(t),children:i.jsx(Ve,{})})]},t)),i.jsx(Dc,{location:"center",t:e.t})]}),E]}),i.jsx("div",{hidden:!!p||!!a.center,className:"document-chat",children:t}),i.jsx("div",{hidden:!a.center,className:"dock-center-content",children:i.jsx(Fc,{location:"center"})}),j&&!a.center&&i.jsxs("section",{className:"document-file",role:"tabpanel","aria-label":Zn(j.path),inert:l,"aria-busy":l,children:[e.errorText&&!e.remoteFileConflict&&i.jsx("div",{role:"alert",className:"inline-notice warning",children:i.jsx("span",{children:e.errorText})}),"text"===j.kind?i.jsx(fd,{client:e.clientRef?.current,file:j,onOpenRemoteFile:(t,n)=>{e.openRemoteFile(t,n,{updateRoute:!0})},onTextChange:t=>e.setRemoteFile(e=>e?{...e,text:t,dirty:!0}:e)},j.path):i.jsx(nd,{file:j},j.path),e.remoteFileConflict&&i.jsxs("div",{role:"alert",className:"inline-notice warning",children:[i.jsx("span",{children:e.t.remoteFileConflict(j.path)}),i.jsx("button",{type:"button",onClick:()=>{(async()=>{const t=e.remoteFile;t&&await x({message:e.t.confirmOverwrite(Zn(t.path)),danger:!0})&&y.current.remoteFile===t&&await e.saveRemoteFile({force:!0})})()},children:e.t.forceSave})]})]})]})})}function vd(e){const t=Ec();return()=>{const s=t.items.find(e=>e.id===t.right.browser&&"right"===e.location),r=s?.currentUrl??s?.url;e.rightSidebarCollapsed&&("session"===e.controlTab&&0===e.pendingActionsCount||"desktop"===n().kind&&"browser"===e.controlTab&&(!r||"about:blank"===r))&&e.setControlTab("files"),e.setRightSidebarCollapsed(e=>!e)}}const yd="vibelet.web.savedTargets";function bd(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 xd(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const s of e){const e=bd(s);if(e&&!t.has(e.daemonId)&&(t.add(e.daemonId),n.push(e),n.length>=12))break}return n}function wd(e=t()){const n=e.getItem(yd);if(!n)return[];try{return xd(JSON.parse(n))}catch{return[]}}function Sd(e,n=t()){n.setItem(yd,JSON.stringify(xd(e)))}const kd="vibelet.web.sessionListCache";function Id(e){return e instanceof Error&&"auth_failed"===e.message}const Cd="vibelet.web.composerDrafts",jd={draftsBySessionId:{},newSessionDraft:""};function Rd(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function Ed(e){return Rd(e)?{draftsBySessionId:Rd(e.draftsBySessionId)?Object.fromEntries(Object.entries(e.draftsBySessionId).filter(e=>"string"==typeof e[1])):{},newSessionDraft:"string"==typeof e.newSessionDraft?e.newSessionDraft:""}:jd}function Md(e=t()){const n=e.getItem(Cd);if(!n)return jd;try{return Ed(JSON.parse(n))}catch{return jd}}function Td(e,n=t()){n.setItem(Cd,JSON.stringify(Ed(e)))}function Ad(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 Nd(e,t){return t?e.draftsBySessionId[t]??"":e.newSessionDraft}function Pd(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 Dd(e){const t=e.toLowerCase();return/subscription|required|upgrade|billing/u.test(t)?"subscription":/skillnotfound|not found|missing/u.test(t)?"missing-resource":/permission|forbidden|unauthorized|denied/u.test(t)?"permission":/failed to reconnect|startup deadline exceeded/u.test(t)?"reconnect":/timeout|timed out/u.test(t)?"timeout":/process exited|reconnected concurrently/u.test(t)?"reconnect":/websocket|network|disconnect|connection|offline|closed/u.test(t)?"network":"unknown"}const Ld=13e4;function Fd(e,t){return Boolean(t)&&Object.hasOwn(e,t)}function qd(e,t,n){return t&&0!==n.length?{...e,[t]:sn(e[t]??[],n)}:e}function Od(e,t){const n=new Map,s=sn(e,t,(e,t)=>{t.localClientMessageId&&n.set(e,t)}),r=t.map(e=>{const t=n.get(e);return t?{...e,localClientMessageId:t.localClientMessageId,localDelivery:t.localDelivery}:{...e}}),i=new Set(r.map(e=>e.localClientMessageId));return function(e,t,n){const s=e.map(e=>{if(e.liveReply){const t=n.slice().reverse().find(t=>t.liveReply&&t.content.length>0&&(e.content.startsWith(t.content)||t.content.startsWith(e.content)));if(t?.timestamp)return{...e,timestamp:t.timestamp}}return e});for(const r of t){const e=Date.parse(r.timestamp??""),t=Number.isFinite(e)?s.findIndex(t=>{const s=Date.parse(t.timestamp??"");if(s!==e)return s>e;if("assistant"!==t.role)return!1;const i=n.findIndex(e=>t.historyKey&&e.historyKey===t.historyKey||t.liveReply&&e.liveReply&&e.timestamp===t.timestamp);return i<0||n.indexOf(r)<i}):-1;s.splice(t<0?s.length:t,0,r)}return s}(r,s.filter(e=>e.localClientMessageId&&e.historyKey?.startsWith("client:")&&!i.has(e.localClientMessageId)),e)}function _d(e,t,n){const s=new Set(e);return n?s.add(t):s.delete(t),s}async function $d(e){return{[e]:"desktop-free"}}async function zd(e,t,s,i){const o=r(),a="desktop"===n().kind&&"guide"===o.composer.sendMode,c=await e.request(t,s);if(!a||!Vn(c)||!0!==c.queued)return c;const l=Ws();try{if(!e.supportsSessionSteer)throw new Error(l.unsupported);await e.request({action:"session.steer",id:e.makeId("guide"),sessionId:"string"==typeof c.sessionId?c.sessionId:t.sessionId,clientMessageId:t.clientMessageId,message:t.message,images:t.images},s)}catch(d){i(`${l.guide}: ${d instanceof Error?d.message:String(d)}`)}return c}function Hd(){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 Bd(e,t,n){const s=Nd(e.composerDraftsRef.current,e.activeSessionId),r=s===t?s:[s,t].filter(Boolean).join("\n\n"),i=Ad(e.composerDraftsRef.current,e.activeSessionId,r);e.composerDraftsRef.current=i,e.setComposerDrafts(i),e.activeSessionIdRef.current===e.activeSessionId&&e.setDraft(r);try{Td(i)}catch{}e.setAttachments(e=>[...e,...n.filter(t=>!e.some(e=>e.path===t.path))])}const Ud=e=>e?.trim()?e:void 0,Wd="Session send timed out.";function Kd(e){return"string"==typeof e&&e.trim().length>0?e:void 0}const Vd="vibelet.web.sessionSettings";function Qd(e,t){o.useEffect(()=>{e.current=t},[e,t])}class Gd{constructor(e,t,n){this.storage=e,this.key=t,this.isReading=n;try{const n=JSON.parse(e?.getItem(t)??"null");if(n&&"object"==typeof n){const e=n,t=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[];if(this.observed=new Set(t(e.observed)),this.unseen=new Set(t(e.unseen)),Array.isArray(e.failed))for(const n of e.failed)Array.isArray(n)&&2===n.length&&n.every(e=>"string"==typeof e)&&this.failed.set(n[0],n[1])}}catch{}this.recovered=new Set(this.observed),this.snapshot=new Set([...this.unseen,...this.failed.values()])}observed=new Set;failed=new Map;unseen=new Set;recovered=new Set;suppressed=new Set;runtime=new Map;listeners=new Set;snapshot=new Set;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;save(){try{this.storage?.setItem(this.key,JSON.stringify({observed:[...this.observed].slice(-256),unseen:[...this.unseen].slice(-256),failed:[...this.failed].slice(-256)}))}catch{}const e=new Set([...this.unseen,...this.failed.values()]);this.snapshot.size===e.size&&[...e].every(e=>this.snapshot.has(e))||(this.snapshot=e,this.listeners.forEach(e=>e()))}deliveryChanged=(e,t,n)=>{if("failed"===n){if(this.failed.get(t)===e)return;this.failed.set(t,e)}else if(!this.failed.delete(t))return;this.save()};reconcileDeliveries=(e,t)=>{for(const[s,r]of this.failed)r===e&&this.failed.delete(s);const n=Er(t);n?.localClientMessageId&&this.failed.set(n.localClientMessageId,e),this.save()};deliveryRemoved=(e,t)=>{this.failed.delete(t)&&this.save()};observe=e=>{this.suppressed.delete(e),this.observed.has(e)||(this.observed.add(e),this.save())};complete=e=>{this.observed.delete(e)&&(this.suppressed.add(e),this.recovered.delete(e),this.isReading(e)?this.unseen.delete(e):this.unseen.add(e),this.save())};reconcile=(e,t)=>{const n=this.runtime.get(e);this.runtime.set(e,t),t?this.suppressed.has(e)||!0===n||this.observe(e):((!0===n||this.recovered.has(e))&&this.observed.has(e)&&this.complete(e),this.suppressed.delete(e))};acknowledgeOpened=e=>{this.unseen.delete(e)&&this.save()};acknowledgeVisible=()=>{let e=!1;for(const t of this.unseen)this.isReading(t)&&(this.unseen.delete(t),e=!0);e&&this.save()};remap=(e,t)=>{for(const n of[this.observed,this.unseen,this.suppressed,this.recovered])n.delete(e)&&n.add(t);this.runtime.has(e)&&(this.runtime.set(t,this.runtime.get(e)),this.runtime.delete(e));for(const[n,s]of this.failed)s===e&&this.failed.set(n,t);this.save()}}function Jd(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 Zd(e,t,n,s){const r=AbortSignal.timeout(12e4),i=await fetch(`/upload?name=${encodeURIComponent(e.name)}`,{method:"POST",signal:AbortSignal.any([n,r]),headers:{authorization:`Bearer ${t}`,"content-type":e.type||"application/octet-stream"},body:e});if(!i.ok)throw new Error(await i.text().catch(()=>s.uploadFailed)||s.uploadFailed);const o=function(e){const t=e;return"string"==typeof t.path?t.path:null}(await i.json());if(!o)throw new Error(s.uploadPathMissing);return{path:o,name:e.name,type:e.type||"application/octet-stream",size:e.size}}function Xd(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 Yd="vibelet.web.historyDiskCache.v1";function eu(){try{const e=JSON.parse(t().getItem(Yd)||"[]");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 tu(e,n){try{const s=eu().filter(t=>t.daemonId!==e||!Object.hasOwn(n,t.sessionId));for(const[t,i]of Object.entries(n)){if(!i)continue;const n={daemonId:e,sessionId:t,messages:i.slice(-1e3)};for(;n.messages.length&&(new TextEncoder).encode(JSON.stringify(n)).length>524288;)n.messages.shift();(n.messages.length||0===i.length)&&s.unshift(n)}const r=s.slice(0,40);for(;r.length&&(new TextEncoder).encode(JSON.stringify(r)).length>2097152;)r.pop();t().setItem(Yd,JSON.stringify(r))}catch{}}const nu=new Set(["attachmentCount","domNodes","durationMs","errorKind","failureKind","longTaskCount","maxLongTaskMs","online","phase","visibilityState"]);function su(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 ru(e,t){return t.has(e.sessionId)||!0===e.runtime?.isResponding||"daemonActive"===e.runtime?.state||"externalRunning"===e.runtime?.state}class iu{cleared=new Map;live(e,t,n){const s=new Set(n.map(e=>e.clientMessageId)),r=this.cleared.get(t)??new Set;for(const i of e[t]??[])i.clientMessageId&&!s.has(i.clientMessageId)&&r.add(i.clientMessageId);for(const i of s)i&&r.delete(i);return this.cleared.set(t,r),{...e,[t]:n}}confirmRemoval(e,t){const n=this.cleared.get(e)??new Set;t.forEach(e=>n.add(e)),this.cleared.set(e,n)}snapshot(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.filter(t=>!t.clientMessageId||!this.cleared.get(e)?.has(t.clientMessageId))]))}remap(e,t){const n=this.cleared.get(e);n&&(this.cleared.set(t,new Set([...this.cleared.get(t)??[],...n])),this.cleared.delete(e))}}const ou=o.lazy(()=>m(()=>import("./NewSessionDialog-Cw6WvtMR.js"),__vite__mapDeps([43,1,2,14,44]))),au=o.lazy(()=>m(()=>import("./GlobalPendingDialog-M2Dbntba.js"),__vite__mapDeps([45,1,2])));function cu({workspace:e}){const t=function(e){const[t,n]=o.useState(0),[s,r]=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=>{r(e=>e+1),e.activeSessionIdRef.current=t,e.setActiveSessionId(t),e.completionAttention?.acknowledgeOpened(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 i=e.clientRef.current;e.requestReconnectSnapshot().catch(n=>{e.clientRef.current===i&&e.activeSessionIdRef.current===t&&e.setErrorText(n instanceof Error?n.message:String(n))})},revealKey:t}}(e),[s,r]=o.useState(!0),[a,c]=o.useState(!1),[l,d]=o.useState(!1);!function(e){const t=Ec(),s=vd(e),[r,i]=o.useState(rt),a=o.useRef({workspace:e,dock:t,shortcuts:r,toggleRightSidebar:s});a.current={workspace:e,dock:t,shortcuts:r,toggleRightSidebar:s},o.useEffect(()=>{const e=()=>i(rt()),t=e=>e instanceof Element&&!!e.closest('.workspace-control-sidebar-motion, .dock-surface[data-location="right"], #desktop-toolbar-controls');let s=!1;const r=e=>{s=t(e.target)},o=(e,n,r=e.target)=>{if(e.defaultPrevented||e.isComposing||e.repeat||document.querySelector('[data-shortcut-recording="true"], [role="dialog"], [role="alertdialog"], .desktop-workspace-container[hidden], .browser-settings-page'))return;const i=et(e);if(!i&&!n)return;const{workspace:o,dock:c,shortcuts:l}=a.current,d=n??Ze.find(e=>it(e.id,l)===i)?.id;if(!d)return;if("searchMessages"===d&&(t(r)||!document.querySelector(".document-chat:not([hidden]) .chat-pane")))return;const u="terminal"===o.controlTab?"terminal":"browser",h=c.items.find(e=>e.id===c.center),p=!o.rightSidebarCollapsed&&(t(r)||r===document.body&&s),f=!p&&h?h:c.items.find(e=>e.id===c.right[u]);if("browserAddress"===d||"browserCopyUrl"===d){if("browser"!==f?.kind)return;const t=Array.from(document.querySelectorAll(".dock-surface")).find(e=>e.dataset.dockId===f.id&&!e.hidden)?.querySelector(".embedded-browser-panel");if(!t)return;return e.preventDefault(),e.stopPropagation(),void t.dispatchEvent(new CustomEvent("vibelet.browser.command",{detail:d}))}switch(e.preventDefault(),e.stopPropagation(),d){case"searchMessages":window.dispatchEvent(new Event("vibelet.message-search"));break;case"leftSidebar":o.setLeftSidebarCollapsed(e=>!e);break;case"rightSidebar":a.current.toggleRightSidebar();break;case"files":case"terminal":case"browser":o.setControlTabAndOpen(d);break;case"searchSessions":o.setLeftSidebarCollapsed(!1),window.dispatchEvent(new Event("vibelet.session-search"));break;case"newTab":{const e="terminal"===f?.kind||"browser"===f?.kind?f.kind:u;c.add(e,o.t[e],o.cwd),o.setControlTabAndOpen(e);break}case"moveTab":f&&c.move(f.id,"center"===f.location?"right":"center");break;case"diff":o.activeSession&&o.setDiffSessionId(o.activeSession.sessionId);break;case"closeTab":case"nextTab":case"previousTab":if(p)if("closeTab"===d)"files"===o.controlTab||!f||f.emptyPlaceholder?o.setRightSidebarCollapsed(!0):(document.querySelector(".control-pane")?.focus(),c.close(f.id));else{const e=c.items.filter(e=>"right"===e.location&&e.kind===u);e.length&&c.setRight(t=>({...t,[u]:e[(Math.max(0,e.findIndex(e=>e.id===f?.id))+("nextTab"===d?1:e.length-1))%e.length].id}))}else window.dispatchEvent(new CustomEvent(Je,{detail:d}))}},c=e=>o(e),l=n().subscribeCommand?.(e=>{"close-tab"===e&&o(new KeyboardEvent("keydown"),"closeTab",document.activeElement)});return window.addEventListener(Ge,e),window.addEventListener("focusin",r,!0),window.addEventListener("pointerdown",r,!0),window.addEventListener("keydown",c,!0),()=>{l?.(),window.removeEventListener(Ge,e),window.removeEventListener("focusin",r,!0),window.removeEventListener("pointerdown",r,!0),window.removeEventListener("keydown",c,!0)}},[])}(e);const u=vd(e),[h,p]=function(e){const[t,s]=o.useState(null);return o.useEffect(()=>{const t=()=>s(t=>t??{cwd:e}),r=n().subscribeCommand?.(e=>{"new-session"===e&&t()}),i=e=>{"browser"!==n().kind||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey||"n"!==e.key.toLowerCase()||(e.preventDefault(),t())};return window.addEventListener("keydown",i),()=>{r?.(),window.removeEventListener("keydown",i)}},[e]),[t,s]}(e.cwd);o.useEffect(()=>{"browser"===e.controlTab&&r(!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(Yn(e.activeQuestion))},[e.activeQuestion,e.setQuestionAnswers]);const{clientRef:f,phase:m,statusText:g,errorText:v,pairing:y,sessions:b,nextCursor:x,folderCounts:w,inventoryVersion:S,activeSessionId:k,diffSessionId:I,setDiffSessionId:C,respondingSessions:j,questionAnswers:R,agent:E,cwd:M,approvalMode:T,model:A,setModel:N,effort:P,setEffort:D,fastMode:L,setFastMode:F,renameTitle:q,setRenameTitle:O,draft:_,webPreferences:$,sessionSort:z,setSessionSort:H,search:B,setSearch:U,sinceFilter:W,setSinceFilter:K,hideArchived:V,setHideArchived:Q,groupFolders:G,setGroupFolders:J,showNeedsAttentionGroup:Z,setShowNeedsAttentionGroup:X,showRunningGroup:Y,setShowRunningGroup:ee,separatePinnedGroup:te,setSeparatePinnedGroup:ne,collapsedFolders:se,setCollapsedFolders:re,sessionAgentFilter:ie,setSessionAgentFilter:oe,directoryTags:ae,composerPreferences:ce,savedTargets:le,leftSidebarCollapsed:de,setLeftSidebarCollapsed:ue,rightSidebarCollapsed:he,setRightSidebarCollapsed:pe,workspaceClassName:fe,wideMainClassName:me,workspaceStyle:ge,beginPaneResize:ve,commitSearch:ye,saveTargets:be,setLanguagePreference:xe,setThemePreference:we,updateComposerPreferences:Se,t:ke,busy:Ie,rewindMessage:Ce,rewinding:je,controlTab:Re,setControlTab:Ee,detailsOpen:Me,setDetailsOpen:Te,setControlTabAndOpen:Ae,skills:Ne,admin:Pe,daemonMetadata:De,notificationSettings:Le,notificationPermission:Fe,archiveSyncBusy:qe,archiveSyncStatus:Oe,attachments:_e,setAttachments:$e,uploadBusy:ze,directory:He,newDirName:Be,setNewDirName:Ue,remoteFile:We,uploadFiles:Ke,openRemoteFile:Ve,listDirectory:Qe,listSessionDirectories:Xe,listFileTreeDirectory:Ye,createDirectory:tt,createSessionDirectory:nt,pendingActionsCount:st,activeQueue:ot,activeModelOptions:at,activeUsage:ct,activeApproval:lt,activeQuestion:dt,activeSession:ut,displaySessions:pt,groupedSessions:ft,pendingSessionIds:mt,visibleSessions:gt,historyLoading:vt,hasOlderHistory:yt,olderHistoryLoading:bt,requestHistory:xt,messages:wt,messagesSessionIdRef:St,updateDraft:kt,requestReconnectSnapshot:It,requestSessions:Ct,fetchAgentResources:jt,failedSend:Rt,dismissFailedSend:Et,retryFailedSend:Mt,stagePendingSession:Tt,listSessionModels:At,loadDirectoryGitMetadata:Nt,sendDraft:Pt,sendQuickReply:Dt,respondApproval:Lt,respondQuestion:Ft,cancelQuestion:qt,setQuestionChoice:Ot,requestActiveAction:_t,interruptActiveSession:$t,retrySessions:zt,updateApprovalMode:Ht,cancelQueuedTurn:Bt,setSessionPinned:Ut,setSessionArchived:Wt,deleteSession:Kt,updatePinned:Vt,updateArchived:Qt,renameSession:Gt,runArchiveSync:Jt,skipArchiveSync:Zt,runAdminAction:Xt,exportActiveSession:Yt,clearPairing:en,setNotificationsEnabled:tn,connectSavedTarget:nn,forgetSavedTarget:sn,openSessionDetails:rn,editFolderTags:on,copyResumeCommand:an,resumeInTerminal:cn,notificationsBlocked:ln,hasDaemonUpdate:dn,archiveSynced:un,archiveSyncDismissed:hn}=e,pn=o.useMemo(()=>function(e,t,n){const s={};for(const r of Object.values(e))s[r.sessionId]=`${n.interactionWaitingApproval} · ${r.description||r.toolName}`;for(const r of Object.values(t))s[r.sessionId]=`${n.interactionWaitingAnswer} · ${r.questions[0]?.question??""}`;return s}(e.pendingApprovals,e.pendingQuestions,ke),[e.pendingApprovals,e.pendingQuestions,ke]),fn=o.useMemo(()=>l?Object.fromEntries(ft.map(e=>[e.folder,!1!==se[e.folder]])):se,[l,se,ft]),mn=ft.length>0&&ft.every(e=>fn[e.folder]);return"missing-pair"===m?i.jsxs(i.Fragment,{children:[i.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:ke.skipToConversation}),i.jsx(kc,{errorText:v,t:ke})]}):i.jsxs("main",{className:fe,id:"vibelet-workspace",style:ge,children:[i.jsx(bl,{workspace:e,onSelect:t.selectSession}),h&&i.jsx(o.Suspense,{fallback:null,children:i.jsx(ou,{client:"connected"===m?f.current:null,onOpenRemoteFile:Ve,pairing:y,onLoadGitMetadata:Nt,cwd:h.cwd,agent:E,device:y?.daemonId??"disconnected",connected:"connected"===m,approvalMode:T,model:A,effort:P,fastMode:L,t:ke,onClose:()=>p(null),onCreate:Tt,onListModels:At,onListDirectories:Xe,onCreateDirectory:nt},y?.daemonId??"disconnected")}),i.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:ke.skipToConversation}),i.jsx(yl,{collapsed:de,onExpand:()=>ue(e=>!e),onResize:ve("left"),t:ke,children:i.jsx(vl,{connectionIndicators:i.jsx(Ol,{workspace:e}),activeDaemonId:y?.daemonId,activeSessionId:k,busy:Ie,collapsedFolders:fn,allFoldersCollapsed:mn,currentCwd:M,directoryTags:ae,displayName:y?.displayName,savedTargets:le,folderCounts:w,groupFolders:G,sessionSort:z,onSessionSortChange:H,groupedSessions:ft,hideArchived:V,separatePinnedGroup:te,showNeedsAttentionGroup:Z,showRunningGroup:Y,inventoryVersion:S,nextCursor:x,phase:m,respondingSessionIds:j,search:B,sessionAgentFilter:ie,sessionsCount:pt.length,sinceFilter:W,statusText:g,t:ke,visibleSessions:gt,onLoadMore:e=>Ct({append:!0,cursor:e}),onCopyResumeCommand:an,onResumeInTerminal:cn,onConnectTarget:nn,attentionReasons:pn,pendingSessionIds:mt,onRequestNewSession:e=>p({cwd:e??M}),onRenameSession:Gt,onDeleteSession:e=>{Kt(e)},onEditFolderTags:on,onOpenSessionDetails:rn,onResetFilters:()=>{H("updated"),oe("all"),K("30d"),Q(!1),J(!0),X(!1),ee(!1),ne(!1)},onRenameTarget:(e,t)=>be(function(e,t,n){const s=n.trim();return s?e.map(e=>e.daemonId===t?{...e,label:s}:e):e}(le,e,t)),onEditConnection:n().settingsTarget?e=>window.dispatchEvent(new CustomEvent("vibelet.desktop.edit-connection",{detail:e.pairToken})):void 0,onSearchChange:U,onSearchCommit:ye,onSelectSession:t.selectSession,onToggleSessionArchived:e=>{Wt(e,!e.archived)},onToggleSessionPinned:e=>{Ut(e,!e.pinned)},onSessionAgentFilterChange:oe,onSinceFilterChange:K,onToggleFolder:e=>re(t=>({...t,[e]:l?!1===t[e]:!t[e]})),onToggleAllFolders:()=>{d(!mn),re({})},onToggleGroupFolders:()=>J(e=>!e),onToggleHideArchived:()=>Q(e=>!e),onToggleNeedsAttentionGroup:()=>{e.toggleSessionViewGroup("needsAttention")},onToggleRunningGroup:()=>{e.toggleSessionViewGroup("running")},onToggleSeparatePinnedGroup:()=>{e.toggleSessionViewGroup("pinned")},onToggleCollapse:()=>ue(!0)})}),i.jsxs("section",{className:me,"aria-label":ke.vibeletWorkspace,id:"vibelet-main-content",tabIndex:-1,children:[i.jsx(gd,{workspace:e,children:i.jsx(Aa,{client:"connected"===m?f.current:null,activeSession:ut,activeSessionId:k,activeModelOptions:at,activeQueue:ot,activeUsage:ct,agent:E,approvalMode:T,attachments:_e,busy:Ie,cwd:M,draft:_,effort:P,errorText:v,failedSend:Rt,onDismissFailedSend:Et,fastMode:L,historyLoading:vt,hasOlderHistory:yt,olderHistoryLoading:bt,onLoadOlderHistory:()=>ut?xt(ut,{older:!0}):Promise.resolve(),messages:wt,messagesSessionId:St.current,model:A,phase:m,quickReplies:ce.quickReplies,onQuickRepliesChange:e=>Se(t=>({...t,quickReplies:e})),quickRepliesOpen:ce.quickRepliesOpen,onQuickRepliesOpenChange:e=>Se(t=>({...t,quickRepliesOpen:e})),renameTitle:q,respondingSessionIds:j,sendShortcut:ce.sendShortcut,skills:Ne,uploadBusy:ze,detailsOpen:Me,t:ke,onApprovalModeChange:e=>{Ht(e)},onBrowseFiles:()=>{const e=ut?.cwd||M||Wn;Ae("files"),Qe(e,{updateRoute:!0})},queueControls:e.queueControls,onCancelQueuedTurn:e=>{Bt(e)},onClearInterrupt:()=>{_t("session.clearInterrupt")},onDraftChange:kt,onDetailsOpenChange:Te,onEffortChange:D,onExportActiveSession:()=>{Yt()},rewinding:je,onRewindMessage:e=>{Ce(e)},onFastModeChange:F,onRetryFailedSend:Mt,onModelChange:N,onOpenRemoteFile:(e,t)=>{Ve(e,t,{updateRoute:!0})},onInterrupt:$t,onDismissError:()=>e.setErrorText(null),onRetry:()=>{zt(),jt(ut?.agent??E,M)},onRenameSession:e=>{Gt(void 0,e)},onRenameTitleChange:O,onRemoveAttachment:e=>$e(t=>t.filter(t=>t.path!==e)),onRefreshSkills:()=>{jt(ut?.agent??E,M)},onSubmit:Pt,onSendQuickReply:Dt,onToggleArchived:()=>{Qt()},onTogglePinned:()=>{Vt()},onUploadFiles:Ke,onViewChanges:C})}),i.jsxs(Bl,{collapsed:he,t:ke,value:Re,showSession:!1,onChange:Ee,onResize:ve("right"),children:[i.jsx("div",{hidden:"files"!==Re,style:{display:"files"===Re?"contents":"none"},children:i.jsx(o.Suspense,{fallback:i.jsx(nl,{t:ke}),children:i.jsx(Xc,{client:"connected"===m?f.current:null,watch:!he&&"files"===Re,onRefreshDirectory:()=>Qe(He.path,{background:!0}),busy:Ie,cwd:M,directory:He,onLoadChildren:Ye,newDirName:Be,remoteFile:We,t:ke,onCreateDirectory:()=>{tt()},onListDirectory:e=>{Qe(e,{updateRoute:!0})},onNewDirNameChange:Ue,onOpenRemoteFile:(e,t)=>{Ve(e,t,{updateRoute:!0})}},y?.daemonId)})}),a?i.jsxs("div",{hidden:"terminal"!==Re,className:"terminal-tab-content",children:[i.jsx(Dc,{location:"right",kind:"terminal",t:ke,cwd:M===Wn?He.path:M}),i.jsx(Fc,{location:"right",kind:"terminal"})]}):null,s?i.jsxs("div",{hidden:"browser"!==Re,className:"browser-tab-content",children:[i.jsx(Dc,{location:"right",kind:"browser",t:ke}),i.jsx(Fc,{location:"right",kind:"browser"})]}):null,"admin"===Re?i.jsxs(o.Suspense,{fallback:i.jsx(nl,{t:ke}),children:[i.jsx(Yc,{language:$.language,t:ke,onLanguageChange:xe}),!n().settingsTarget&&i.jsx(Nl,{}),i.jsx(el,{t:ke,theme:$.theme,onThemeChange:we}),i.jsx(tl,{notificationsBlocked:ln,permission:Fe,settings:Le,t:ke,onToggleEnabled:tn}),!n().settingsTarget&&i.jsx(Ml,{workspace:e})]}):null]})]}),n().settingsTarget&&i.jsx(Ml,{workspace:e,portalOnly:!0}),i.jsx("div",{className:"workspace-header-actions",children:i.jsx(ht,{client:"connected"===m?f.current:null,activeSession:ut,busy:Ie,controlsOpen:!he,pendingCount:st,t:ke,onOpenControls:u,onRefreshSessions:()=>{Ct({force:!0})},onRestoreSnapshot:()=>{It()},onToggleArchived:()=>{Qt()},onTogglePinned:()=>{Vt()},onViewChanges:C})}),i.jsx(o.Suspense,{fallback:null,children:i.jsx(au,{activeApproval:lt,activeQuestion:dt,pendingCount:st,requestKey:li(e.pendingApprovals,e.pendingQuestions),sessions:b,busy:Ie,errorText:v,questionAnswers:R,t:ke,onCancelQuestion:()=>{qt()},onQuestionChoice:Ot,onRespondApproval:e=>{Lt(e)},onRespondQuestion:()=>{Ft()},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)}),i.jsx(Cc,{}),i.jsx(Hc,{onOpenBrowserLink:e.applyBrowserDefaultWidth,onOpenRight:Ae,onCloseRight:()=>pe(!0),client:"connected"===m?f.current:null,daemonId:y?.daemonId,pairing:y,deviceName:y?.displayName??"",controlTab:Re,rightVisible:!he,t:ke}),i.jsx(sl,{activeSession:ut,client:f.current,close:()=>C(null),id:I,sessions:b,t:ke})]})}const lu=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),[i]=o.useState(()=>({permission:Jt(),notifications:Gt(),preferences:r(),drafts:Md(),targets:wd()})),a=o.useRef(i.permission),c=o.useRef(i.notifications),l=o.useRef(i.preferences),d=o.useRef(i.drafts),h=o.useRef(i.targets),f=o.useRef(a.current),m=o.useRef(c.current),g=o.useRef(d.current),v=o.useRef(null),y=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({}),E=o.useRef(!1),[M,T]=o.useState("connecting"),[A,N]=o.useState(()=>u[s(l.current.language)].preparingVibeletWeb),[P,D]=o.useState(null),[L,F]=o.useState(null),[q,O]=o.useState([]),[_,$]=o.useState({}),[z,H]=o.useState({}),[B,U]=o.useState(),[W,K]=o.useState({}),[V,Q]=o.useState(),[G,J]=o.useState(null),Z=_r(L?.daemonId,G),[X,Y]=o.useState(null),[ee,te]=o.useState(()=>new Set),[ne,se]=o.useState({}),[re,ie]=o.useState({}),[oe,ae]=o.useState({}),{pendingQueues:ce,setPendingQueues:le,setLivePendingQueue:de,remapPendingQueue:ue,confirmPendingQueueRemoval:he}=function(e){const t=o.useRef(new iu),n=o.useRef(e);n.current!==e&&(n.current=e,t.current=new iu);const[s,r]=o.useState({});return{pendingQueues:s,setPendingQueues:o.useCallback(e=>{r(n=>t.current.snapshot("function"==typeof e?e(n):e))},[]),setLivePendingQueue:o.useCallback((e,n)=>{r(s=>t.current.live(s,e,n))},[]),remapPendingQueue:o.useCallback((e,n)=>{t.current.remap(e,n)},[]),confirmPendingQueueRemoval:o.useCallback((e,n)=>{r(s=>(t.current.confirmRemoval(e,n),t.current.snapshot(s)))},[])}}(L?.daemonId),[pe,fe]=o.useState("claude"),[me,ge]=o.useState(Wn),[ve,ye]=o.useState(Kn),[be]=o.useState(!1),[xe,we]=o.useState(""),[Se,ke]=o.useState(""),[Ie,Ce]=o.useState(!1),[je,Re]=o.useState(""),[Ee,Me]=o.useState(d.current),[Te,Ae]=o.useState(()=>Nd(d.current,null)),{webPreferences:Ne,sessionSort:Pe,setSessionSort:De,setRightSidebarCollapsed:Le,search:Fe,setSearch:qe,sinceFilter:Oe,setSinceFilter:_e,hideArchived:$e,setHideArchived:ze,groupFolders:He,setGroupFolders:Be,showNeedsAttentionGroup:Ue,setShowNeedsAttentionGroup:We,showRunningGroup:Ke,setShowRunningGroup:Ve,separatePinnedGroup:Qe,setSeparatePinnedGroup:Ge,collapsedFolders:Je,setCollapsedFolders:Ze,sessionAgentFilter:Xe,setSessionAgentFilter:Ye,directoryTags:et,archiveSyncedDaemonIds:tt,archiveSyncCardDismissedDaemonIds:nt,composerPreferences:st,savedTargets:rt,setSavedTargets:it,leftSidebarCollapsed:ot,setLeftSidebarCollapsed:at,rightSidebarCollapsed:ct,workspaceClassName:lt,wideMainClassName:dt,workspaceStyle:ut,beginPaneResize:ht,applyBrowserDefaultWidth:pt,commitSearch:ft,saveTargets:mt,setLanguagePreference:gt,setThemePreference:vt,updateSessionListPreferences:yt,updateComposerPreferences:bt}=function(e,t,n="default"){const[s,i]=o.useState(e);o.useEffect(()=>{const e=()=>{const e=r();i(t=>({...t,theme:e.theme,language:e.language,composer:e.composer}))};return window.addEventListener("vibelet.preferences.changed",e),()=>window.removeEventListener("vibelet.preferences.changed",e)},[]);const[a,c]=o.useState(e.sessionList.sortOrder),[l,d]=o.useState(""),[u,h]=o.useState(e.sessionList.searchHistory),[f,m]=o.useState(e.sessionList.sinceFilter),[g,v]=o.useState(e.sessionList.hideArchived),[y,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,E]=o.useState(e.sessionList.collapsedFolders),[M,T]=o.useState(e.sessionList.agentFilter),[A,N]=o.useState(t),[P,D]=o.useState(e.layout.leftSidebarCollapsed),[L,F]=o.useState(e.layout.rightSidebarCollapsed),{leftPaneWidth:q,rightPaneWidth:O,beginPaneResize:_,applyBrowserDefaultWidth:$}=function(e,t,n="default"){const[s,r]=o.useState(288),[i,a]=qr(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 i?i:Math.round(h/("half"===i?2:3)),f=o.useCallback(()=>{a(e=>"number"==typeof e?e:"half")},[a]),m=o.useRef(null);o.useEffect(()=>()=>m.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,r=n+s,i=r>t?Math.max(0,t)/r:1;return{leftPaneWidth:e.leftCollapsed?e.leftPaneWidth:Math.floor(n*i),rightPaneWidth:e.rightCollapsed?e.rightPaneWidth:Math.floor(s*i)}}({leftCollapsed:e,rightCollapsed:t,leftPaneWidth:s,rightPaneWidth:p},c-96-64),v=o.useCallback(e=>t=>{if(0!==t.button||!1===t.isPrimary)return;t.preventDefault(),m.current?.();const n=t.currentTarget,s=t.pointerId;let i=!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),i=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?r(i):a(i)},p=()=>{if(i){i=!1,o.remove(),document.body.classList.remove("pane-resizing"),window.removeEventListener("pointermove",h,!0),window.removeEventListener("pointerup",f,!0),window.removeEventListener("pointercancel",f,!0),window.removeEventListener("blur",p),window.removeEventListener("keydown",v,!0),document.removeEventListener("visibilitychange",y),n.removeEventListener("lostpointercapture",f);try{n.hasPointerCapture?.(s)&&n.releasePointerCapture(s)}catch{}m.current===p&&(m.current=null)}},f=e=>{e.pointerId===s&&p()},v=e=>{"Escape"===e.key&&(e.preventDefault(),p())},y=()=>{"hidden"===document.visibilityState&&p()};m.current=p,document.body.classList.add("pane-resizing"),window.addEventListener("pointermove",h,!0),window.addEventListener("pointerup",f,!0),window.addEventListener("pointercancel",f,!0),window.addEventListener("blur",p),window.addEventListener("keydown",v,!0),document.addEventListener("visibilitychange",y),n.addEventListener("lostpointercapture",f);try{n.setPointerCapture?.(s)}catch{}},[g.leftPaneWidth,g.rightPaneWidth,a]);return{...g,beginPaneResize:v,applyBrowserDefaultWidth:f}}(P,L,n),z=s.sessionList.directoryTags,H=s.sessionList.archiveSyncedDaemonIds,B=s.sessionList.archiveSyncCardDismissedDaemonIds,U=s.composer,W=function(e){return{workspaceClassName:["workspace",e.leftCollapsed&&"left-sidebar-collapsed"].filter(Boolean).join(" "),wideMainClassName:["wide-main",e.rightCollapsed&&"right-sidebar-collapsed"].filter(Boolean).join(" "),style:{"--left-pane-width":`${e.leftPaneWidth}px`,"--right-pane-width":`${e.rightPaneWidth}px`}}}({leftCollapsed:P,rightCollapsed:L,leftPaneWidth:q,rightPaneWidth:O});o.useEffect(()=>{i(e=>{const t={...e,sessionList:{...e.sessionList,searchHistory:u,sortOrder:a,sinceFilter:f,hideArchived:g,groupFolders:y,showNeedsAttentionGroup:x,showRunningGroup:S,separatePinnedGroup:I,collapsedFolders:R,agentFilter:M},layout:{...e.layout,leftSidebarCollapsed:P,rightSidebarCollapsed:L}};return p(t),t})},[R,y,g,P,L,u,I,M,x,S,f,a]);const K=o.useCallback(()=>{h(e=>j(e,l))},[l]),V=o.useCallback(e=>{N(e),Sd(e)},[]),Q=o.useCallback(e=>{i(t=>{const n={...t,language:e};return p(n),n})},[]),G=o.useCallback(e=>{i(t=>{const n={...t,theme:e};return p(n),n})},[]),J=o.useCallback(e=>{i(t=>{const n={...t,sessionList:e(t.sessionList)};return p(n),n})},[]),Z=o.useCallback(e=>{i(t=>{const n={...t,composer:e(t.composer)};return p(n),n})},[]);return{webPreferences:s,sessionSort:a,setSessionSort:c,search:l,setSearch:d,sinceFilter:f,setSinceFilter:m,hideArchived:g,setHideArchived:v,groupFolders:y,setGroupFolders:b,showNeedsAttentionGroup:x,setShowNeedsAttentionGroup:w,showRunningGroup:S,setShowRunningGroup:k,separatePinnedGroup:I,setSeparatePinnedGroup:C,collapsedFolders:R,setCollapsedFolders:E,sessionAgentFilter:M,setSessionAgentFilter:T,directoryTags:z,archiveSyncedDaemonIds:H,archiveSyncCardDismissedDaemonIds:B,composerPreferences:U,savedTargets:A,setSavedTargets:N,leftSidebarCollapsed:P,setLeftSidebarCollapsed:D,rightSidebarCollapsed:L,setRightSidebarCollapsed:F,workspaceClassName:W.workspaceClassName,wideMainClassName:W.wideMainClassName,workspaceStyle:W.style,beginPaneResize:_,applyBrowserDefaultWidth:$,commitSearch:K,saveTargets:V,setLanguagePreference:Q,setThemePreference:G,updateSessionListPreferences:J,updateComposerPreferences:Z}}(l.current,h.current,Z),xt=s(Ne.language),wt=u[xt],[St,kt]=qr(Z,!1),[It,Ct]=qr(Z,!1),[jt,Rt]=qr(Z,"files"),[Et,Mt]=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])}(Ne.theme);const Tt=o.useCallback(e=>{Rt(e),Le(!1)},[Rt,Le]),[At,Nt]=o.useState({}),[Pt,Dt]=o.useState({}),[Lt,Ft]=o.useState([]),[qt,Ot]=o.useState({statusText:"",loading:!1,action:null}),[_t,$t]=o.useState(xl),[zt,Ht]=o.useState(c.current),[Bt,Ut]=o.useState(a.current),[Wt,Kt]=o.useState(null),[Vt,Qt]=o.useState(null);return{clientRef:e,connectWithPairingRef:t,activeSessionIdRef:n,initialNotificationPermissionRef:a,initialNotificationSettingsRef:c,initialPreferencesRef:l,initialComposerDraftsRef:d,initialSavedTargetsRef:h,notificationPermissionRef:f,notificationSettingsRef:m,composerDraftsRef:g,lastHistorySessionIdRef:v,historyCacheDaemonIdRef:y,historyPrefetchingSessionIdsRef:b,pairingRef:x,notifiedEventsRef:w,reconnectTimerRef:S,connectionAttemptIdRef:k,respondingSessionsRef:I,turnNotificationCountsRef:C,intentionalDisconnectRef:E,phase:M,setPhase:T,statusText:A,setStatusText:N,errorText:P?rl(P,wt.remoteDirectConnection,wt.localConnection):null,setErrorText:D,pairing:L,setPairing:F,sessions:q,setSessions:O,pendingSessions:_,setPendingSessions:$,optimisticSessions:z,setOptimisticSessions:H,nextCursor:B,setNextCursor:U,folderCounts:W,setFolderCounts:K,inventoryVersion:V,setInventoryVersion:Q,activeSessionId:G,setActiveSessionId:J,diffSessionId:X,setDiffSessionId:Y,respondingSessions:ee,setRespondingSessions:te,pendingApprovals:ne,setPendingApprovals:se,pendingQuestions:re,setPendingQuestions:ie,questionAnswers:oe,setQuestionAnswers:ae,pendingQueues:ce,setPendingQueues:le,setLivePendingQueue:de,remapPendingQueue:ue,confirmPendingQueueRemoval:he,agent:pe,setAgent:fe,cwd:me,setCwd:ge,approvalMode:ve,setApprovalMode:ye,continueSession:be,model:xe,setModel:we,effort:Se,setEffort:ke,fastMode:Ie,setFastMode:Ce,renameTitle:je,setRenameTitle:Re,composerDrafts:Ee,setComposerDrafts:Me,draft:Te,setDraft:Ae,webPreferences:Ne,sessionSort:Pe,setSessionSort:De,search:Fe,setSearch:qe,sinceFilter:Oe,setSinceFilter:_e,hideArchived:$e,setHideArchived:ze,groupFolders:He,setGroupFolders:Be,showNeedsAttentionGroup:Ue,setShowNeedsAttentionGroup:We,showRunningGroup:Ke,setShowRunningGroup:Ve,separatePinnedGroup:Qe,setSeparatePinnedGroup:Ge,collapsedFolders:Je,setCollapsedFolders:Ze,sessionAgentFilter:Xe,setSessionAgentFilter:Ye,directoryTags:et,archiveSyncedDaemonIds:tt,archiveSyncCardDismissedDaemonIds:nt,composerPreferences:st,savedTargets:rt,setSavedTargets:it,leftSidebarCollapsed:ot,setLeftSidebarCollapsed:at,rightSidebarCollapsed:ct,setRightSidebarCollapsed:Le,workspaceClassName:lt,wideMainClassName:dt,workspaceStyle:ut,beginPaneResize:ht,applyBrowserDefaultWidth:pt,commitSearch:ft,saveTargets:mt,setLanguagePreference:gt,setThemePreference:vt,updateSessionListPreferences:yt,updateComposerPreferences:bt,language:xt,t:wt,busy:St,setBusy:kt,rewinding:It,setRewinding:Ct,controlTab:jt,setControlTab:Rt,detailsOpen:Et,setDetailsOpen:Mt,setControlTabAndOpen:Tt,modelOptions:At,setModelOptions:Nt,usageLimits:Pt,setUsageLimits:Dt,skills:Lt,setSkills:Ft,admin:qt,setAdmin:Ot,daemonMetadata:_t,setDaemonMetadata:$t,notificationSettings:zt,setNotificationSettings:Ht,notificationPermission:Bt,setNotificationPermission:Ut,archiveSyncBusy:Wt,setArchiveSyncBusy:Kt,archiveSyncStatus:Vt,setArchiveSyncStatus:Qt}}(),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:i,activeSessionIdRef:a,notificationPermissionRef:c,notificationSettingsRef:l,composerDraftsRef:h,lastHistorySessionIdRef:f,historyPrefetchingSessionIdsRef:m,pairingRef:g,reconnectTimerRef:v,respondingSessionsRef:y,phase:b,setStatusText:x,setErrorText:S,pairing:k,setSessions:I,setOptimisticSessions:A,setNextCursor:N,setFolderCounts:P,setInventoryVersion:D,activeSessionId:L,setActiveSessionId:F,respondingSessions:q,setRespondingSessions:O,pendingApprovals:_,setPendingApprovals:$,pendingQuestions:z,setPendingQuestions:H,setQuestionAnswers:B,pendingQueues:U,setPendingQueues:W,agent:K,setAgent:V,cwd:Q,setCwd:G,setApprovalMode:J,composerDrafts:Z,setComposerDrafts:X,search:Y,sinceFilter:ee,hideArchived:te,sessionAgentFilter:ne,setRightSidebarCollapsed:se,t:re,controlTab:ie,setControlTab:oe,setControlTabAndOpen:ae,modelOptions:ce,setModelOptions:le,usageLimits:de,setUsageLimits:ue,setSkills:he,setDaemonMetadata:pe,notificationSettings:fe,setNotificationSettings:me,notificationPermission:ge,setNotificationPermission:ve,sessions:ye,pendingSessions:be,optimisticSessions:xe,setDraft:we,setBusy:Se}=e,ke=function(e){const{clientRef:t,pairing:n,cwd:s,phase:r,controlTab:i,setControlTab:a,setBusy:c,setErrorText:l,t:d,scopeKey:u="default"}=e,h=o.useRef(!1),p=o.useRef(null),f=p.current&&$r(p.current.key,u)?p.current:null,{value:m,set:g,setForScope:v,resolveScope:y,getAll:b}=Or(u,()=>[]),x=o.useCallback((e,t)=>{v(_r(n?.daemonId,e),t)},[n?.daemonId,v]);o.useEffect(()=>Wl(()=>[...b().values()].some(e=>e.length>0)),[b]);const[w,S]=o.useState(!1),k=o.useRef(new Map);o.useEffect(()=>{const e=new Set(m.map(e=>e.path));for(const[t,n]of k.current)(null===y(n.scope)||y(n.scope)===y(u)&&![...n.paths].some(t=>e.has(t)))&&(t.abort(),k.current.delete(t));S(k.current.size>0)},[m,u,y]);const[I,C]=qr(u,()=>({path:f?.directory.path||!h.current&&(Gl().folder||Gl().cwd)||s||Wn,entries:[],loading:!1,loaded:!1})),[j,R]=qr(u,""),{remoteFile:E,setRemoteFile:M,openFiles:T,setOpenFiles:A,acknowledgeSave:N}=function(e,t,n){const s=o.useRef(null),r=s.current&&$r(s.current.scope,e)?s.current:null,{value:i,set:a,getAll:c,updateAll:l}=Or(e,()=>r?.value??(n?{current:Vl(n),files:{[Vl(n)]:n}}:{current:null,files:{}}));s.current={scope:e,value:i},o.useEffect(()=>{r&&l((e,t)=>t===r.scope?{current:null,files:{}}:e)},[e]),o.useEffect(()=>{const e=e=>{const t=e.detail;for(const[n,s]of c())if(null===Fr(n,{...t,action:"remove"})&&Object.values(s.files).some(e=>e.dirty))return void e.preventDefault()};return window.addEventListener(Nr,e),()=>window.removeEventListener(Nr,e)},[c]),o.useEffect(()=>Wl(()=>[...c().values()].some(e=>Object.values(e.files).some(e=>e.dirty))),[c]);const d=o.useRef(new Set);o.useEffect(()=>{const e=new Set([...c().values()].flatMap(e=>Object.values(e.files).flatMap(e=>e.objectUrl?[e.objectUrl]:[])));for(const t of d.current)e.has(t)||URL.revokeObjectURL(t);d.current=e}),o.useEffect(()=>()=>{for(const e of d.current)URL.revokeObjectURL(e)},[]);const u=o.useCallback(e=>{a(t=>{const n=t.current?t.files[t.current]??null:null,s="function"==typeof e?e(n):e;if(!s)return null===t.current?t:{...t,current:null};const r=Vl(s),i=t.files[r],o=i?.dirty&&!s.dirty?i:s;return t.current===r&&i===o?t:{current:r,files:{...t.files,[r]:o}}})},[a]),h=o.useCallback(e=>{a(t=>{const n="function"==typeof e?e(t.files):e;return n===t.files?t:{current:t.current&&n[t.current]?t.current:null,files:n}})},[a]),p=o.useCallback((e,t)=>{a(n=>{const s=Vl(e),r=n.files[s];if(!r)return n;const i=function(e,t,n){return e&&e.path===t.path&&e.cwd===t.cwd&&e.etag===t.etag?{...e,dirty:e.text!==t.text,etag:"string"==typeof n.etag?n.etag:e.etag,lastModified:"string"==typeof n.lastModified?n.lastModified:e.lastModified,size:"number"==typeof n.size?n.size:e.size}:e}(r,e,t);return i!==r&&i?{...n,files:{...n.files,[s]:i}}:n})},[a]);return o.useEffect(()=>{const n=(n,s)=>{if(n===e)return t===s;try{return JSON.parse(n)[0]===s}catch{return!1}},s=e=>"move"===e.action||"delete"===e.action,r=(e,t)=>Ur(Vl(e),t.source??t.path,t.cwd),i=e=>{const{detail:t}=e;if(s(t))for(const[s,i]of c())if(n(s,t.daemonId)&&Object.values(i.files).some(e=>e.dirty&&r(e,t)))return void e.preventDefault()},o=e=>{const{detail:i}=e;if(!s(i))return;const o=Br(i.source??i.path,i.cwd),a=e=>`${Br(i.target,i.cwd)}${e.slice(o.length)}`;if(l((e,t)=>{if(!n(t,i.daemonId))return e;let s=e.current,o=!1;const c={};for(const[n,l]of Object.entries(e.files)){if(!r(l,i)){c[n]=l;continue}o=!0;const e="delete"===i.action?null:{...l,path:a(Vl(l))},t=e&&Vl(e);n===s&&(s=t),e&&t&&(c[t]=e)}return o?{current:s,files:c}:e}),t!==i.daemonId)return;const c=new URL(window.location.href),d=c.searchParams.get("file");d&&Ur(d,o,c.searchParams.get("cwd")??i.cwd)&&("delete"===i.action?c.searchParams.delete("file"):c.searchParams.set("file",a(Br(d,c.searchParams.get("cwd")??i.cwd))),window.history.replaceState(null,"",c.href))};return window.addEventListener(zr,i),window.addEventListener(Hr,o),()=>{window.removeEventListener(zr,i),window.removeEventListener(Hr,o)}},[e,t,c,l]),{remoteFile:i.current?i.files[i.current]??null:null,setRemoteFile:u,openFiles:i.files,setOpenFiles:h,acknowledgeSave:p}}(u,n?.daemonId,f?.file),[P,D]=qr(u,()=>new Set);p.current={key:u,file:E,directory:I};const L=e=>JSON.stringify([e.cwd,e.path,e.etag]),F=!!E&&P.has(L(E)),q=o.useRef(new Map),O=o.useRef(null);o.useEffect(()=>{C(e=>({...e,loaded:!1,loading:!1}))},[u]);const _=o.useRef(0),$=o.useRef(I.path);o.useEffect(()=>()=>{if(p.current&&$r(u,p.current.key)&&!p.current.file&&Gl().file&&(h.current=!1),_.current++,C(e=>e.loading?{...e,loading:!1}:e),y(u)!==y(p.current?.key??"")){O.current?.abort();for(const e of k.current.keys())e.abort();k.current.clear(),S(!1)}},[u]),o.useEffect(()=>{$.current!==I.path&&(_.current++,$.current=I.path)},[I.path]),o.useEffect(()=>(_.current++,C(e=>({...e,loading:!1,loaded:!1})),S(!1),()=>{_.current++;for(const e of k.current.keys())e.abort();k.current.clear(),O.current?.abort();for(const e of q.current.values())e.request.abort(),e.finish()}),[n?.pairToken]),o.useEffect(()=>{I.path!==Wn||Gl().folder||(_.current++,C(e=>({...e,entries:[],loaded:!1,loading:!1})))},[s]);const z=o.useCallback(async e=>{if(!e?.length||!n)return;const t=new AbortController;S(!0),l(null);const s=Array.from(e).map(e=>({file:e,path:URL.createObjectURL(e)}));k.current.set(t,{scope:u,paths:new Set(s.map(e=>e.path))}),g(e=>[...e,...s.map(({file:e,path:t})=>({path:t,name:e.name,type:e.type,size:e.size,uploading:!0}))]);try{await async function(e,t,n,s,r){let i=0;const o=[];if(await Promise.all(Array.from({length:Math.min(2,e.length)},async function(){for(;!n.aborted&&i<e.length;){const c=e[i++];try{const e=await Zd(c.file,t,n,s);n.aborted||r(c,e)}catch(a){o.push(a)}}})),!n.aborted&&o.length)throw o[0]}(s,n.pairToken,t.signal,d,({path:e},t)=>{g(n=>n.map(n=>n.path===e?t:n))})}catch(r){t.signal.aborted||l(r instanceof Error?r.message:String(r))}finally{const e=new Set(s.map(e=>e.path));g(t=>t.filter(t=>!e.has(t.path)));for(const t of e)URL.revokeObjectURL(t);k.current.delete(t)&&S(k.current.size>0)}},[n,l,d.uploadFailed,d.uploadPathMissing,u]),H=o.useCallback(async(e,t,s)=>{if(!n)return;O.current?.abort();const r=new AbortController;O.current=r,l(null);try{const i=/^(?:https?:\/\/|data:image\/|blob:)/i.test(e),o=await fetch(i?e:ds(e,t),{headers:i?{}:{authorization:`Bearer ${n.pairToken}`},signal:r.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(i&&!a.startsWith("image/"))throw new Error(d.fileOpenFailed);const c=Xl(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(r.signal.aborted)return;if(void 0!==u)M({path:e,cwd:t,kind:"text",contentType:a,text:u,etag:us(o.headers,"etag"),lastModified:us(o.headers,"last-modified"),size:Number(o.headers.get("content-length"))||void 0,dirty:!1});else{const n="pdf"===Xl(e,a,!1)?new Blob([l],{type:"application/pdf"}):l;M({path:e,cwd:t,kind:ls(e,a)?"image":"binary",contentType:a,text:"",objectUrl:URL.createObjectURL(n),etag:us(o.headers,"etag"),lastModified:us(o.headers,"last-modified"),size:l.size,dirty:!1})}s?.updateRoute&&Jl({file:e,...t?{cwd:t}:{}},{replace:s.replaceRoute})}catch(i){if(r.signal.aborted)return;l(i instanceof Error?i.message:String(i))}},[n,l,u]),B=o.useCallback(async e=>{if(!n||!E||"text"!==E.kind||q.current.has(u))return;const t=new AbortController,s={request:t,finish:()=>{q.current.get(u)===s&&(q.current.delete(u),c(!1))}};q.current.set(u,s),c(!0),l(null);try{const s=await fetch(ds(E.path,E.cwd),{method:"PUT",signal:t.signal,headers:{authorization:`Bearer ${n.pairToken}`,"content-type":"text/markdown; charset=utf-8",...E.etag&&!e?.force?{"if-match":E.etag}:{}},body:E.text});if(t.signal.aborted)return;if(!s.ok){if(409===s.status)throw D(e=>new Set(e).add(L(E))),new Error(d.remoteFileConflict(E.path));throw new Error(await s.text().catch(()=>d.fileSaveFailed)||d.fileSaveFailed)}const r=await s.json().catch(()=>null);if(t.signal.aborted)return;if(!r||"object"!=typeof r||!("etag"in r)||"string"!=typeof r.etag||!r.etag.trim())throw new Error(d.fileSaveFailed);D(e=>{const t=new Set(e);return t.delete(L(E)),t}),N(E,r)}catch(r){t.signal.aborted||p.current?.key!==u||l(r instanceof Error?r.message:String(r))}finally{s.finish()}},[n,E,c,l,u,N]),U=o.useCallback(async()=>{if(n&&E)try{const e=/^(?:https?:\/\/|data:image\/|blob:)/i.test(E.path),t=await fetch(e?E.path:ds(E.path,E.cwd),{headers:e?{}:{authorization:`Bearer ${n.pairToken}`}});if(!t.ok)throw new Error(d.downloadFailed);const s=URL.createObjectURL(await t.blob()),r=document.createElement("a");r.href=s,r.download=Zn(E.path),r.click(),URL.revokeObjectURL(s)}catch(e){l(e instanceof Error?e.message:String(e))}},[n,E,l,u]),W=o.useCallback(async(e=I.path,n)=>{const r=t.current;if(!r?.isConnected)return;if(n?.background&&$.current!==e)return;$.current=e;const i=++_.current;n?.background||C(t=>({...t,path:e,entries:e===t.path?t.entries:[],loading:!0,loaded:!1,error:void 0}));try{const t=await r.request({action:"dirs.list",id:r.makeId("dirs"),path:e,cwd:s||void 0},{timeoutMs:1e4,timeoutMessage:d.directoryListTimedOut});if(i!==_.current)return;C({path:e,entries:t.entries??[],loading:!1,loaded:!0}),n?.updateRoute&&Jl({folder:e},{replace:n.replaceRoute})}catch(o){if(i!==_.current)return;C(e=>({...e,loading:!1,loaded:!0,error:o instanceof Error?o.message:String(o)}))}},[t,s,I.path,u]),K=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]),V=o.useCallback(async e=>(await K(e)).filter(e=>e.isDirectory),[K]);o.useEffect(()=>{!h.current||"files"!==i||"connected"!==r||I.loading||I.loaded||W(I.path||s||Wn)},[i,s,I.loaded,I.loading,I.path,W,r]),o.useEffect(()=>{if("connected"!==r||h.current)return;const e=Gl();if(e.folder||e.file){if(h.current=!0,e.folder)return a("files"),void W(e.folder,{updateRoute:!1});e.file&&(e.cwd&&C(t=>({...t,path:e.cwd,loaded:!1})),H(e.file,e.cwd,{updateRoute:!1}))}else h.current=!0},[W,H,r,a]);const Q=o.useCallback(async()=>{const e=t.current;if(e?.isConnected&&0!==j.trim().length){c(!0),l(null);try{await e.request({action:"dirs.create",id:e.makeId("mkdir"),path:as(I.path,j),cwd:s||void 0}),R(""),await W(I.path)}catch(n){l(n instanceof Error?n.message:String(n))}finally{c(!1)}}},[t,s,I.path,W,j,c,l,u]),G=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:m,setAttachments:g,setSessionAttachments:x,uploadBusy:w,directory:I,setDirectory:C,newDirName:j,setNewDirName:R,remoteFile:E,setRemoteFile:M,openFiles:T,setOpenFiles:A,remoteFileConflict:F,uploadFiles:z,openRemoteFile:H,saveRemoteFile:B,downloadRemoteFile:U,listDirectory:W,listSessionDirectories:V,listFileTreeDirectory:K,createDirectory:Q,createSessionDirectory:G}}({scopeKey:_r(k?.daemonId,L),clientRef:i,pairing:k,cwd:Q,phase:b,controlTab:ie,setControlTab:ae,setBusy:Se,setErrorText:S,t:re}),Ie=Object.keys(_).length+Object.keys(z).length,Ce=function(e,t,n){return"codex"===n&&/^pending_(?:local_)?\d+(?:_\d+)?$/.test(t??"")?e.map(e=>void 0===e.waitingForStartup?{...e,waitingForStartup:!0}:e):e}(L?U[L]??[]:[],L,K),je=ce[K]??[],Re=de[K],{completionAttention:Ee,reviewSessionIds:Me}=function(e,t,n){const s=o.useMemo(()=>{let t;try{t=window.localStorage}catch{}return new Gd(t,`vibelet:completion-attention:${e??"disconnected"}`,Jd)},[e]),r=o.useSyncExternalStore(s.subscribe,s.getSnapshot),i=o.useRef(new Set);return o.useEffect(()=>{i.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)i.current.has(e)||s.observe(e);i.current=n},[s,n]),o.useEffect(()=>{if(!r.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,r]),{completionAttention:s,reviewSessionIds:r}}(k?.daemonId,ye,q),{historyCacheRef:Te,historyPageStartRef:Ae,hydrateVisibleHistory:Ne,messagesSessionIdRef:Pe,remapCachedHistory:De,appendCachedDelta:Le,appendCachedHistory:Fe,appendInfoMessage:qe,clearHistoryLoading:Oe,ensureCachedHistoryEntry:_e,setCachedMessageDelivery:$e,removeCachedMessage:ze,resolveCachedMessageSession:He,historyLoading:Be,hasOlderHistory:Ue,olderHistoryLoading:We,messages:Ke,mergeCachedHistoryPage:Ve,removeCachedHistory:Qe,renderCachedHistory:Ge,replaceCachedHistory:Je,requestHistory:Ze,setMessages:Xe}=function(e){const t=o.useRef({}),n=function(e){return o.useMemo(()=>{const t=new Map,n=t=>JSON.stringify([e?.current??null,t]);return{has:(e,s)=>t.get(n(e))?.has(s)??!1,add:(e,s)=>{const r=t.get(n(e))??new Set;r.add(s),t.set(n(e),r)},filter:(e,s)=>{const r=t.get(n(e));return s.filter(e=>{if("user"!==e.role)return!0;const t=e.localClientMessageId??(e.historyKey?.startsWith("client:")?e.historyKey.slice(7):void 0);return!t||!r?.has(t)})},remap:(e,s)=>{const r=t.get(n(e));r&&(t.set(n(s),new Set([...t.get(n(s))??[],...r])),t.delete(n(e)))}}},[e])}(e.historyCacheDaemonIdRef),s=function(e,t){const n=o.useRef(new Map),s=o.useRef(new Set),r=o.useRef(null),i=e=>JSON.stringify([t?.current,e]),a=o.useCallback(()=>{r.current&&clearTimeout(r.current),r.current=null;for(const[e,t]of n.current)tu(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 i=t?.current;i&&(n.current.set(i,{...n.current.get(i),[s]:e.current[s]}),r.current||(r.current=setTimeout(a,500)))},fresh:e=>s.current.delete(i(e)),isStale:e=>s.current.has(i(e)),restore:n=>{if(!t?.current||Object.hasOwn(e.current,n))return;const r=function(e,t){return eu().find(n=>n.daemonId===e&&n.sessionId===t)?.messages}(t.current,n);return r?(e.current={...e.current,[n]:r},s.current.add(i(n)),!0):void 0}}}(t,e.historyCacheDaemonIdRef),r=o.useRef(s);r.current=s;const i=o.useRef(null),a=o.useRef({}),c=o.useRef({}),l=o.useRef(new Map),[d,u]=o.useState(null),h=o.useRef(null),[p,f]=o.useState(!1),[m,g]=o.useState([]),v=o.useCallback(e=>!(e&&i.current&&i.current!==e||(i.current=null,f(!1),0)),[]),y=o.useCallback(n=>(r.current.restore(n)&&(delete a.current[n],delete c.current[n]),!!Fd(t.current,n)&&(h.current=n,e.onDeliveryHistoryChanged?.(n,t.current[n]??[]),g(t.current[n]??[]),!0)),[e.onDeliveryHistoryChanged]),b=o.useCallback((s,i,o)=>{t.current=function(e,t,n){return t?{...e,[t]:Od(e[t]??[],n)}:e}(t.current,s,n.filter(s,i)),r.current.changed(s),r.current.fresh(s);const a=t.current[s]??[];for(const t of a)t.localClientMessageId&&t.localDelivery&&e.onDeliveryChanged?.(s,t.localClientMessageId,t.localDelivery);return e.onDeliveryHistoryChanged?.(s,a),!1!==o?.renderActive&&s===e.activeSessionIdRef.current&&(h.current=s,g(a)),a},[e.activeSessionIdRef,e.onDeliveryChanged,e.onDeliveryHistoryChanged,n]),x=o.useCallback((n,s,r)=>{const i=l.current.get(n);i?.client===e.clientRef.current&&(void 0===i.before||r&&r.start<i.before)&&(i.received=!0),n===e.activeSessionIdRef.current&&e.setErrorText(t=>t===e.historyTimeoutMessage?null:t);const o=Fd(t.current,n)?c.current[n]:void 0;if(c.current[n]=r,"byte"===r?.cursorMode){const e=function(e,t,n,s){if(!n||"byte"!==n.cursorMode)return[...t];if(s.start<n.start){const n=new Set(t.map(Xd).filter(Boolean));return[...t,...e.filter(e=>{const t=Xd(e);return!t||!n.has(t)})]}const r=t[0],i=r?e.findIndex(e=>r.historyKey&&e.historyKey?r.historyKey===e.historyKey:Boolean(r.timestamp)&&r.timestamp===e.timestamp&&r.role===e.role&&r.type===e.type&&r.content===e.content&&JSON.stringify(r.images)===JSON.stringify(e.images)&&r.toolName===e.toolName&&JSON.stringify(r.toolInput)===JSON.stringify(e.toolInput)):-1;return i>=0?[...e.slice(0,i),...t]:[...t]}(t.current[n]??[],s,o,r);return"byte"===o?.cursorMode&&e.length>s.length&&r.start>=o.start&&(c.current[n]={...r,start:o.start,hasMore:o.hasMore}),a.current[n]=c.current[n]?.start,b(n,e)}if(!r)return a.current[n]=void 0,b(n,s);const d=a.current[n],u=t.current[n]??[],h=r.start+s.length;if(void 0===d||h<d||r.start>d+u.length)return a.current[n]=r.start,b(n,s);a.current[n]=Math.min(d,r.start),c.current[n]={...r,start:Math.min(d,r.start),hasMore:Math.min(d,r.start)>0};const p=u.slice(0,Math.max(0,r.start-d)),f=u.slice(Math.max(0,h-d),Math.max(0,r.total-d));return b(n,[...p,...s,...f])},[b,e.clientRef,e.activeSessionIdRef,e.setErrorText,e.historyTimeoutMessage]),w=o.useCallback((e,t)=>{delete c.current[e],a.current[e]=0;const n=b(e,t,{renderActive:!1});h.current=e,g(n)},[b]),S=o.useCallback((s,i)=>{t.current=qd(t.current,s,n.filter(s,i)),r.current.changed(s),e.onDeliveryHistoryChanged?.(s,t.current[s]??[]),s===e.activeSessionIdRef.current&&(h.current=s,g(t.current[s]??[]))},[e.activeSessionIdRef,e.onDeliveryHistoryChanged,n]),k=o.useCallback((s,i)=>{n.filter(s,[i]).length&&(t.current=function(e,t,n){return n.historyKey&&e[t]?.some(e=>e.historyKey===n.historyKey)?e:qd(e,t,[n])}(t.current,s,i),r.current.changed(s),e.onDeliveryHistoryChanged?.(s,t.current[s]??[]),s===e.activeSessionIdRef.current&&(h.current=s,g(t.current[s]??[])))},[e.activeSessionIdRef,e.onDeliveryHistoryChanged,n]),I=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),[]),C=o.useCallback((s,i,o,a)=>{if(s=I(s,i),n.has(s,i))return;if(!a&&!t.current[s]?.some(e=>e.localClientMessageId===i||e.historyKey===`client:${i}`))return;const c=function(e,t,n,s){const r=e.findIndex(e=>e.localClientMessageId===t||e.historyKey===`client:${t}`),i=e.slice();if(r<0)s&&i.push({role:"user",...s,timestamp:(new Date).toISOString(),historyKey:`client:${t}`,localClientMessageId:t,localDelivery:n});else{const s=e[r],o="delivered"===s.localDelivery||"accepted"===s.delivery||s.historyKey&&!s.historyKey.startsWith("client:");i[r]={...s,localClientMessageId:t,localDelivery:o&&"failed"===n?"delivered":n}}return i}(t.current[s]??[],i,o,a);t.current={...t.current,[s]:c},r.current.changed(s),s!==e.activeSessionIdRef.current&&s!==h.current||(h.current=s,g(t.current[s]??[]));const l=c.find(e=>e.localClientMessageId===i)?.localDelivery;return l&&e.onDeliveryChanged?.(s,i,l),e.onDeliveryHistoryChanged?.(s,c),l},[e.activeSessionIdRef,e.onDeliveryChanged,e.onDeliveryHistoryChanged,n]),j=o.useCallback((s,i)=>{s=I(s,i),n.add(s,i);const o=t.current[s];if(!o)return;const a=o.filter(e=>"user"!==e.role||e.localClientMessageId!==i&&e.historyKey!==`client:${i}`);a.length!==o.length&&(e.onDeliveryRemoved?.(s,i),e.onDeliveryHistoryChanged?.(s,a),t.current={...t.current,[s]:a},r.current.changed(s),s!==e.activeSessionIdRef.current&&s!==h.current||g(a))},[e.activeSessionIdRef,e.onDeliveryRemoved,e.onDeliveryHistoryChanged,I,n]),R=o.useCallback((n,s)=>{t.current=function(e,t,n){return t&&n?{...e,[t]:rn(Gn(e[t]??[],n))}:e}(t.current,n,s),r.current.changed(n),n===e.activeSessionIdRef.current&&(h.current=n,g(t.current[n]??[]))},[e.activeSessionIdRef,n]),E=o.useCallback((e,t)=>{S(e,[{role:"assistant",type:"info",content:t,timestamp:(new Date).toISOString()}])},[S]),M=o.useCallback(e=>{t.current=function(e,t){if(!Fd(e,t))return e;const n={...e};return delete n[t],n}(t.current,e),r.current.changed(e),delete a.current[e],delete c.current[e]},[]),T=o.useCallback((e,s)=>{n.remap(e,s),t.current=function(e,t,n){if(!t||!n||t===n||!Fd(e,t))return e;const s={...e};return s[n]=e[t],delete s[t],s}(t.current,e,s),r.current.changed(e),r.current.changed(s),a.current[s]=a.current[e],delete a.current[e],c.current[s]=c.current[e],delete c.current[e]},[n]),A=o.useCallback(async(t,{older:n=!1,refresh:s=!1}={})=>{const o=e.clientRef.current;if(!o?.isConnected)return;for(;l.current.get(t.sessionId)?.client===o;){if(!s)return;if(await l.current.get(t.sessionId).settled,e.clientRef.current!==o||!o.isConnected||e.activeSessionIdRef.current!==t.sessionId)return}const d=c.current[t.sessionId];if(n&&(!d?.hasMore||d.start<=0))return;let h;const p={client:o,received:!1,before:n?d?.start:void 0,settled:new Promise(e=>{h=e})};l.current.set(t.sessionId,p),n&&u(t.sessionId);const m=()=>e.clientRef.current===o,g=y(t.sessionId);g?v(t.sessionId):(i.current=t.sessionId,delete a.current[t.sessionId],f(!0),e.setErrorText(null));try{if(!n&&!s&&g&&!r.current.isStale(t.sessionId)){const n=await o.request({action:"reconnect.snapshot",id:o.makeId("snapshot"),activeSessionId:t.sessionId,activeAgent:t.agent,skipActiveSessionHistory:!0,skipGitMetadata:!0});if(!m())return;const s=n.snapshot.activeSession;if(s?.sessionId===t.sessionId){e.setPendingQueues(e=>({...e,[t.sessionId]:s.pendingQueue??[]}));for(const e of s.acceptedClientMessageIds??[])C(t.sessionId,e,"delivered")}return}if(await o.request({action:"session.history",id:o.makeId("history"),sessionId:t.sessionId,agent:t.agent,limit:n?100:20,...n&&"byte"!==d?.cursorMode?{before:d?.start}:{pageMode:"cursor",...n?{beforeCursor:d?.start}:{}}},{timeoutMessage:e.historyTimeoutMessage,timeoutMs:15e3}),!m())return}catch(b){!m()||e.activeSessionIdRef.current!==t.sessionId||b instanceof zn&&p.received||e.setErrorText(b instanceof Error?b.message:String(b))}finally{l.current.get(t.sessionId)===p&&l.current.delete(t.sessionId),h(),m()&&(n&&u(e=>e===t.sessionId?null:e),v(t.sessionId))}},[v,e.activeSessionIdRef,e.clientRef,e.historyTimeoutMessage,e.setErrorText,e.setPendingQueues,y,C]);return{hasOlderHistory:Boolean(c.current[e.activeSessionIdRef.current??""]?.hasMore),olderHistoryLoading:d===e.activeSessionIdRef.current&&null!==d,resolveCachedMessageSession:I,setCachedMessageDelivery:C,removeCachedMessage:j,appendCachedDelta:R,appendCachedHistory:S,appendInfoMessage:E,clearHistoryLoading:v,ensureCachedHistoryEntry:k,historyCacheRef:t,historyLoading:p,historyPageStartRef:a,hydrateVisibleHistory:w,messages:m,messagesSessionIdRef:h,mergeCachedHistoryPage:x,remapCachedHistory:T,removeCachedHistory:M,renderCachedHistory:y,replaceCachedHistory:b,requestHistory:A,setMessages:g}}({onDeliveryChanged:Ee.deliveryChanged,onDeliveryHistoryChanged:Ee.reconcileDeliveries,onDeliveryRemoved:Ee.deliveryRemoved,historyCacheDaemonIdRef:e.historyCacheDaemonIdRef,activeSessionIdRef:a,clientRef:i,historyTimeoutMessage:re.historyRequestTimedOut,setPendingQueues:W,setErrorText:S}),Ye=o.useMemo(()=>new Set(Object.entries(Te.current).filter(([,e])=>Er(e)).map(([e])=>e)),[Te.current]),{activeSession:et,activeApproval:tt,activeQuestion:nt,displaySessions:st,groupedSessions:rt,pendingSessionIds:it,visibleSessions:ot}=function(e){const t=o.useRef({protectedSessionIds:[]}),n=o.useMemo(()=>ns(ns(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]),r=o.useMemo(()=>n.find(t=>t.sessionId===e.activeSessionId)??null,[e.activeSessionId,n]),i=(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,r=[];for(const l of e)s.set(l.sessionId,l),(t[l.sessionId]||l.runtime.isResponding)&&r.push(l.sessionId);if(0===r.length)return 0===n.protectedSessionIds.length?{sessions:e,state:n}:{sessions:e,state:{protectedSessionIds:[]}};const i=new Set(r),o=n.protectedSessionIds.filter(e=>s.has(e)&&i.has(e)),a=new Set(o);let c=o.length!==n.protectedSessionIds.length;for(const l of r)a.has(l)||(a.add(l),o.push(l),c=!0);return{sessions:dn(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]),f=o.useMemo(()=>C(function(e,t={}){const n=e=>Object.fromEntries(Array.from(e??[],e=>[e,!0])),s=function(e,t,n,s={}){const r=new Map,i=[],o=[],a=[];for(const l of e){const e=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&&an(l,s.pinnedSessionIds,s.pendingPinnedSessionIds)&&n){i.push(l);continue}const c=r.get(e);c?c.push(l):r.set(e,[l])}const c=[];o.length&&c.push({folder:"@vibelet/needs-attention",kind:"attention",sessions:cn(o,s.regularSessionOrderById)}),a.length&&c.push({folder:"@vibelet/running",kind:"running",sessions:cn(a,s.regularSessionOrderById)}),i.length&&c.push({folder:"@vibelet/pinned",kind:"pinned",sessions:s.orderPinnedByLastActivity?ln(i):cn(i,s.regularSessionOrderById)});for(const[l,d]of r)c.push({folder:l,kind:"folder",sessions:d});return c}(e,n(t.respondingSessionIds),0,{...t,needsAttentionSessionIds:n(t.needsAttentionSessionIds),orderPinnedByLastActivity:!0}),r=new Map(t.runningSessionOrder?.map((e,t)=>[e,t]));if(r.size){const e=s.find(e=>"running"===e.kind);e?.sessions.sort((e,t)=>(r.get(e.sessionId)??1/0)-(r.get(t.sessionId)??1/0))}return s}(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:i,activeQuestion:a,activeSession:r,displaySessions:n,groupedSessions:f,pendingSessionIds:s,visibleSessions:p}}({activeSessionId:L,reviewSessionIds:Me,failedSessionIds:Ye,hideArchived:te,optimisticSessions:xe,pendingApprovals:_,pendingQuestions:z,pendingSessions:be,respondingSessionIds:q,search:Y,separatePinnedGroup:n.separatePinnedGroup,sessionAgentFilter:ne,sessionSort:e.sessionSort,sessions:ye,showNeedsAttentionGroup:n.showNeedsAttentionGroup,showRunningGroup:n.showRunningGroup});Qd(a,L),Qd(g,k),Qd(y,q),Qd(l,fe),Qd(c,ge),Qd(h,Z);const{updateNewSessionDraft:at,updateDraft:ct,updateSessionDraft:lt}=function({activeSessionIdRef:e,composerDraftsRef:t,setComposerDrafts:n,setDraft:s}){const r=o.useRef(null),i=o.useRef(null),a=o.useRef(!1);o.useEffect(()=>Wl(()=>a.current),[]);const c=o.useCallback(()=>{if(r.current&&clearTimeout(r.current),i.current&&clearTimeout(i.current),r.current=i.current=null,a.current){a.current=!1;try{Td(t.current)}catch{a.current=!0}}},[t]),l=o.useCallback(()=>{a.current=!0,r.current&&clearTimeout(r.current),r.current=setTimeout(c,300),i.current||(i.current=setTimeout(c,2e3))},[c]);o.useEffect(()=>{const e=()=>{"hidden"===document.visibilityState&&c()};return window.addEventListener(Kl,c),window.addEventListener("pagehide",c),window.addEventListener("beforeunload",c),document.addEventListener("visibilitychange",e),()=>{c(),window.removeEventListener(Kl,c),window.removeEventListener("pagehide",c),window.removeEventListener("beforeunload",c),document.removeEventListener("visibilitychange",e)}},[c]);const d=o.useCallback((r,i)=>{const o=Ad(t.current,r,i);t.current=o,n(o),e.current===r&&s(i),l()},[e,t,n,s,l]);return{updateDraft:o.useCallback(t=>d(e.current,t),[e,d]),updateNewSessionDraft:o.useCallback(e=>d(null,e),[d]),updateSessionDraft:d}}({activeSessionIdRef:a,composerDraftsRef:h,setComposerDrafts:X,setDraft:we});o.useEffect(()=>{E();const e=M();e&&(at(e),oe("session"),T())},[at]),o.useEffect(()=>{const e=()=>{me(Gt()),ve(Jt())};return window.addEventListener("vibelet.notifications.changed",e),()=>window.removeEventListener("vibelet.notifications.changed",e)},[]),o.useEffect(()=>{"admin"===ie&&ve(Jt())},[ie]),o.useEffect(()=>()=>{v.current&&window.clearTimeout(v.current)},[]);const dt=o.useCallback((e,n=!1)=>{I(t=>function(e,t,n=!1){const s=new Set(t.map(e=>e.sessionId));return ns(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(),r=(new Date).toISOString()){if(!e)return;const i={daemonId:e,page:{...n,sessions:n.sessions.slice(0,120)},cachedAt:r};s.setItem(kd,JSON.stringify(i))}(g.current?.daemonId,e),x(e.inventoryBackfillInFlight?re.connectedIndexing:re.connected)},[re.connected,re.connectedIndexing]),ut=function({clientRef:e,sessions:t,setSessions:n,activeSessionIdRef:s}){const r=o.useRef(new Map),i=o.useRef(t);i.current=t,o.useEffect(()=>()=>r.current.clear(),[]);const a=o.useCallback(async t=>{const i=e.current;if(!i?.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)r.current.set(e,l);try{const t=await i.request({action:"sessions.gitMetadata",id:i.makeId("git"),cwds:c});if(e.current!==i||!i.isConnected)return;n(n=>n.map(n=>{if(e.current!==i||!i.isConnected||r.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(i.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:i,sessions:ye,setSessions:I,activeSessionIdRef:a}),ht=o.useCallback((e,t=y.current)=>{const n=i.current;if(!n?.isConnected||0===e.length)return;const s=function(e,t,n,s,r=6){if(r<=0)return[];const i=[];for(const o of e){if(i.length>=r)break;o.sessionId&&ru(o,n)&&(Fd(t,o.sessionId)||s.has(o.sessionId)||i.push(o))}return i}(e,Te.current,t,m.current);for(const r of s)m.current.add(r.sessionId),n.request({action:"session.history",id:n.makeId("history_prefetch"),pageMode:"cursor",limit:20,sessionId:r.sessionId,agent:r.agent},{timeoutMessage:re.historyPrefetchTimedOut,timeoutMs:15e3}).catch(()=>{}).finally(()=>{m.current.delete(r.sessionId)})},[re.historyPrefetchTimedOut]),pt=o.useCallback(e=>{const t=function(e,t={}){const n=new Set,s={},r={},i={};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??[])r[p.sessionId]={type:"question.request",...p};let o,a,c,l,d,u,h=null;if(e.activeSession){const p=e.activeSession,f=e.sessions.find(e=>e.sessionId===p.sessionId);if(h=p.sessionId,o=p.agent,a=f?.cwd||t.currentCwd||Wn,c=p.approvalMode??f?.approvalMode??Kn,l=p.approvalMode??null,d=on(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};r[p.sessionId]=e,u=Yn(e)}p.pendingQueue?.length&&(i[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||Wn,c=s.approvalMode??Kn)}return{page:{sessions:e.sessions,nextCursor:Un(e.nextCursor),inventoryVersion:e.inventoryVersion,inventoryBackfillInFlight:e.inventoryBackfillInFlight},activeSessionId:h,activeAgent:o,activeCwd:a,activeApprovalMode:c,activeApprovalOverride:l,messages:d,respondingSessionIds:Array.from(n),pendingApprovals:s,pendingQuestions:r,pendingQueues:i,questionAnswers:u}}(e,{currentActiveSessionId:a.current,currentCwd:Q});dt(t.page,!1),N(t.page.nextCursor),D(t.page.inventoryVersion),void 0!==e.activeSession?.messages&&t.messages&&t.activeSessionId&&Ne(t.activeSessionId,t.messages);for(const n of e.activeSession?.acceptedClientMessageIds??[])$e(e.activeSession.sessionId,n,"delivered");e.activeSession&&void 0===e.activeSession.messages&&Ze(e.activeSession,{refresh:!0}),F(t.activeSessionId),t.activeAgent&&V(t.activeAgent),t.activeCwd&&G(t.activeCwd),t.activeApprovalMode&&J(t.activeApprovalMode),t.questionAnswers&&B(t.questionAnswers),y.current=new Set(t.respondingSessionIds),O(y.current),$(t.pendingApprovals),H(t.pendingQuestions),W(t.pendingQueues),ut(e.sessions),ht(e.sessions,new Set(t.respondingSessionIds))},[Q,ut,Ne,ht,Ze,dt,$e]),ft=function(e){const{clientRef:t,activeSessionIdRef:n,search:s,sinceFilter:r,hideArchived:i,sessionAgentFilter:a}=e,c=o.useMemo(()=>({}),[s,r,i,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,r=()=>t.current===e&&e.isConnected&&l.current.request===s;for(;r();){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:ts(o.sinceFilter),hideArchived:o.hideArchived,skipGitMetadata:!0,skipActiveSessionHistory:!0});if(!r())return;if(!c())continue;return void l.current.options.apply(t.snapshot)}catch(i){if(!r())return;if(c())throw i}}},[t,n])}({clientRef:i,activeSessionIdRef:a,activeAgent:et?.agent??K,sessionAgentFilter:ne,search:Y,sinceFilter:ee,hideArchived:te,apply:pt}),mt=function(e){const{clientRef:t,search:n,sinceFilter:s,hideArchived:r,sessionAgentFilter:i,viewKey:a}=e,c=o.useMemo(()=>({refresh:0}),[n,s,r,i,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"===i?void 0:i,search:n.trim()||void 0,sinceMs:ts(s),hideArchived:r,skipGitMetadata:!0,force:e?.force});if(!d())return;const a=Jn(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,r,i])}({clientRef:i,search:Y,sinceFilter:ee,hideArchived:te,sessionAgentFilter:ne,viewKey:[e.sessionSort,e.groupFolders,n.showNeedsAttentionGroup,n.showRunningGroup,n.separatePinnedGroup].join(":"),loadedCount:ye.length,setNextCursor:N,setSessionsFromPage:dt,setActiveSessionId:F,hydrateGitMetadata:ut,prefetchActiveHistories:ht}),gt=function({clientRef:e,setModelOptions:t,setUsageLimits:n,setSkills:s,setErrorText:r,t:i}){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",f=[],m=Promise.allSettled([d.request({action:"models.list",id:d.makeId("models"),agent:o},{timeoutMs:Ld}).then(e=>{h()&&t(t=>({...t,[o]:e.options??[]}))}).catch((e=>t=>{if(!h())return;const n=t instanceof Error?t.message:String(t);f.push(/timeout|timed out/i.test(n)?i.resourceLoadTimedOut(e):i.resourceLoadFailed(e,n)),r(f.join("\n"))})(`${p} · ${i.model}`)),Pl(d,()=>({action:"usage.limits.fetch",id:d.makeId("usage"),agent:o}),h).then(e=>{e&&h()&&n(t=>({...t,[o]:e}))}),Pl(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:m},m},[e,t,n,s,r,i])}({t:re,clientRef:i,setModelOptions:le,setUsageLimits:ue,setSkills:he,setErrorText:S}),vt=o.useCallback((e,t,n="info")=>{const s=i.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))nu.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:su(e.error)},"error")},r=e=>{n("web.telemetry.unhandled_rejection",{errorKind:su(e.reason)},"error")},i=window.setTimeout(()=>{n("web.telemetry.workspace_ready",{durationMs:performance.now()-t,domNodes:document.getElementsByTagName("*").length,online:navigator.onLine,visibilityState:document.visibilityState})},1500);let o=0,a=0,c=null;return"undefined"!=typeof PerformanceObserver&&PerformanceObserver.supportedEntryTypes.includes("longtask")&&(c=new PerformanceObserver(e=>{for(const t of e.getEntries())o+=1,a=Math.max(a,t.duration)}),c.observe({entryTypes:["longtask"]})),window.addEventListener("error",s),window.addEventListener("unhandledrejection",r),()=>{window.clearTimeout(i),window.removeEventListener("error",s),window.removeEventListener("unhandledrejection",r),c?.disconnect(),o>0&&n("web.telemetry.long_tasks",{longTaskCount:o,maxLongTaskMs:a},"warn")}},[e])}(vt);const yt=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:re.connectorVersionFailed}))}}else pe(xl)},[re.connectorVersionFailed]);o.useEffect(()=>{const e=()=>{me(Gt()),ve(Jt())};return window.addEventListener("vibelet.notifications.changed",e),()=>window.removeEventListener("vibelet.notifications.changed",e)},[]),o.useEffect(()=>{"admin"===ie&&"connected"===b&&yt()},[ie,b,yt]);const bt=o.useCallback(e=>{me(n=>{const s={...n,...e};return l.current=s,function(e,n=t()){n.setItem(Vt,JSON.stringify(e))}(s),s})},[]),xt=o.useCallback((t,n)=>{t&&n&&t!==n&&(Dr({action:"remap",daemonId:g.current?.daemonId??null,sessionId:t,nextSessionId:n}),a.current===t&&(a.current=n),F(e=>e===t?n:e),f.current===t&&(f.current=n),Pe.current===t&&(Pe.current=n),Ee.remap(t,n),De(t,n),y.current=os(y.current,t,n),O(e=>os(e,t,n)),$(e=>is(e,t,n)),H(e=>is(e,t,n)),e.remapPendingQueue(t,n),W(e=>is(e,t,n)),A(e=>{const s=e[t];if(!s)return e;const r={...e};return delete r[t],r[n]={...s,sessionId:n},r}),X(e=>{const s=function(e,t,n){if(!t||!n||t===n)return e;const s=e.draftsBySessionId[t];if(void 0===s)return e;const r={...e.draftsBySessionId};return delete r[t],s.trim()&&(r[n]=s),{...e,draftsBySessionId:r}}(e,t,n);if(s!==e){h.current=s;try{Td(s)}catch{}}return s}))},[Ee]);return{completionAttention:Ee,...e,...n,...ke,pendingActionsCount:Ie,activeQueue:Ce,activeModelOptions:je,activeUsage:Re,activeApproval:tt,activeQuestion:nt,activeSession:et,displaySessions:st,groupedSessions:rt,pendingSessionIds:it,visibleSessions:ot,appendCachedDelta:Le,appendCachedHistory:Fe,appendInfoMessage:qe,clearHistoryLoading:Oe,ensureCachedHistoryEntry:_e,setCachedMessageDelivery:$e,removeCachedMessage:ze,resolveCachedMessageSession:He,historyCacheRef:Te,historyLoading:Be,hasOlderHistory:Ue,olderHistoryLoading:We,historyPageStartRef:Ae,hydrateVisibleHistory:Ne,messages:Ke,messagesSessionIdRef:Pe,mergeCachedHistoryPage:Ve,remapCachedHistory:De,removeCachedHistory:Qe,renderCachedHistory:Ge,replaceCachedHistory:Je,requestHistory:Ze,setMessages:Xe,updateDraft:ct,updateNewSessionDraft:at,updateSessionDraft:lt,setSessionsFromPage:dt,hydrateGitMetadata:ut,prefetchActiveHistories:ht,applyReconnectSnapshot:pt,requestReconnectSnapshot:ft,requestSessions:mt,fetchAgentResources:gt,reportLog:vt,refreshDaemonMetadata:yt,updateNotificationSettings:bt,remapLocalSessionState:xt}}();!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 r=w(e.visibleSessions,"updated",!1)[0];r&&(t.current.initial&&e.activeSessionId||e.setActiveSessionId(r.sessionId),t.current.pending=!1)},[e.pairing?.daemonId,e.phase,e.activeSessionId,e.visibleSessions])}(e),function(e,t,n){const s=_r(e,t?.sessionId),[r,i]=qr(s,!1),a=o.useRef(null);o.useEffect(()=>{if(!t)return;const o=a.current?.daemonId===e?a.current?.scope:void 0;if(a.current={daemonId:e,scope:s},r)return;i(!0);const c=Gl();n(e=>function(e,t,n,s,r){if(t===n)return e;const i=!t&&r?r:s||Wn;return i===e.path?e:{path:i,entries:[],loading:!1,loaded:!1}}(e,o,s,t.cwd||Wn,c.folder||c.cwd))},[e,s,t?.sessionId,t?.cwd,r,i,n])}(e.pairing?.daemonId,e.activeSession,e.setDirectory);const i=function(e){const t=o.useRef(!1);return async n=>{const s=e.activeSession,r=e.clientRef.current;if(!s||!r?.isConnected||t.current||e.busy)return;const i=Tr(),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 r=t.rewindPoint;if(r)return e.findIndex(e=>JSON.stringify(e.rewindPoint)===JSON.stringify(r));const i=e.flatMap((e,n)=>e.role===t.role&&e.type===t.type&&e.content===t.content&&e.timestamp===t.timestamp&&JSON.stringify(e.images)===JSON.stringify(t.images)?[n]:[]);return 1===i.length?i[0]:-1}(o,n);if(a<0||"user"!==n.role||"info"===n.type)return void e.setErrorText(i.unavailable);if((e.historyPageStartRef.current[s.sessionId]??0)>0)return void e.setErrorText(i.incompleteHistory);t.current=!0;let c=!1;try{c=await x({message:i.confirmRewind})}finally{t.current=!1}if(c&&e.clientRef.current===r&&r.isConnected&&e.activeSessionIdRef.current===s.sessionId){t.current=!0,e.setBusy(!0),e.setRewinding(!0),e.setErrorText(null);try{const t=await $d("sessionRewind");if(e.clientRef.current!==r||!r.isConnected)return;const c=await r.request({action:"session.rewind",id:r.makeId("rewind"),sessionId:s.sessionId,agent:s.agent,targetUserMessageIndex:o.slice(0,a+1).filter(e=>"user"===e.role&&"info"!==e.type).length-1,featureEntitlements:t},{timeoutMs:15e4,timeoutMessage:i.rewindFailed});if(e.clientRef.current!==r)return;if(!c||"string"!=typeof c.sessionId||!c.sessionId||c.sessionId===s.sessionId||c.sourceSessionId!==s.sessionId||!0!==c.archivedSource||!Array.isArray(c.messages)||c.messages.some(e=>!e||"string"!=typeof e.content||!["user","assistant","tool"].includes(e.role)))throw new Error(i.invalidResponse);const l={...s,sessionId:c.sessionId,archived:!1};e.setOptimisticSessions(e=>{const t={...e};return delete t[s.sessionId],t[c.sessionId]=l,t}),e.setSessions(e=>[...e.filter(e=>e.sessionId!==c.sessionId).map(e=>e.sessionId===s.sessionId?{...e,archived:!0,pinned:!1}:e),l]),e.replaceCachedHistory(c.sessionId,c.messages),e.activeSessionIdRef.current===s.sessionId&&(e.lastHistorySessionIdRef.current=c.sessionId,e.activeSessionIdRef.current=c.sessionId,e.setActiveSessionId(c.sessionId),e.renderCachedHistory(c.sessionId)),e.updateSessionDraft(c.sessionId,Zt(n.content,n.images)),e.setSessionAttachments(c.sessionId,(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.clientRef.current===r&&e.setErrorText(l instanceof Error?l.message:i.rewindFailed)}finally{t.current=!1,e.setBusy(!1),e.setRewinding(!1)}}}}(e),{initialSavedTargetsRef:a,composerDraftsRef:c,lastHistorySessionIdRef:l,respondingSessionsRef:h,phase:f,setErrorText:m,pairing:g,setSessions:v,pendingSessions:y,activeSessionId:A,setActiveSessionId:N,setRespondingSessions:P,setPendingApprovals:D,setPendingQuestions:L,setPendingQueues:F,setLivePendingQueue:q,agent:O,setAgent:_,cwd:$,setCwd:z,setApprovalMode:H,setModel:B,setEffort:U,setFastMode:W,setRenameTitle:K,setDraft:V,archiveSyncedDaemonIds:Q,archiveSyncCardDismissedDaemonIds:G,setControlTabAndOpen:J,daemonMetadata:Z,notificationPermission:X,displaySessions:Y,appendInfoMessage:ee,clearHistoryLoading:te,messagesSessionIdRef:ne,renderCachedHistory:se,replaceCachedHistory:re,requestHistory:ie,setMessages:oe,requestSessions:ae,remapLocalSessionState:ce,attachments:le,setAttachments:de,listDirectory:ue,activeApproval:he,activeQuestion:pe,activeSession:fe,appendCachedDelta:me,appendCachedHistory:ge,ensureCachedHistoryEntry:ve,setCachedMessageDelivery:ye,resolveCachedMessageSession:be,historyCacheRef:xe,messages:we,mergeCachedHistoryPage:Se,removeCachedHistory:ke,updateDraft:Ie,setSessionsFromPage:Ce,requestReconnectSnapshot:je,fetchAgentResources:Re,reportLog:Ee,refreshDaemonMetadata:Me,updateNotificationSettings:Te,clientRef:Ae,connectWithPairingRef:Ne,activeSessionIdRef:Pe,notificationPermissionRef:De,notificationSettingsRef:Le,historyCacheDaemonIdRef:Fe,pairingRef:qe,notifiedEventsRef:Oe,reconnectTimerRef:_e,connectionAttemptIdRef:$e,turnNotificationCountsRef:ze,intentionalDisconnectRef:He,setPhase:Be,setStatusText:Ue,setPairing:We,setPendingSessions:Ke,setOptimisticSessions:Ve,questionAnswers:Qe,setQuestionAnswers:Ge,approvalMode:Je,continueSession:Ze,model:Xe,effort:Ye,fastMode:et,renameTitle:tt,setComposerDrafts:nt,draft:st,search:rt,sinceFilter:it,savedTargets:ot,setSavedTargets:at,saveTargets:ct,updateSessionListPreferences:lt,t:dt,busy:ut,setBusy:ht,setDetailsOpen:pt,setAdmin:ft,setDaemonMetadata:mt,setNotificationPermission:gt,archiveSyncBusy:vt,setArchiveSyncBusy:yt,setArchiveSyncStatus:bt}=e,xt=o.useCallback(async(e,t,n)=>{const s="string"==typeof n.sessionId?n.sessionId:e,r="string"==typeof n.oldSessionId?n.oldSessionId:e;r&&s&&r!==s&&ce(r,s),"clear"===t.name?(re(s,[]),F(e=>{const t={...e};return delete t[s],delete t[r],t}),D(e=>{const t={...e};return delete t[s],delete t[r],t}),L(e=>{const t={...e};return delete t[s],delete t[r],t}),N(s)):"new"===t.name?(N(s),ne.current=s,se(s)):"exit"===t.name?(v(e=>e.map(e=>e.sessionId===s?{...e,archived:!0}:e)),N(null),ne.current=null,l.current=null,oe([])):"goal"===t.name&&"goal"in n&&ee(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&&(h.current=new Set(h.current).add(s),P(e=>new Set(e).add(s))),await ae({force:!0})},[ee,ce,se,re,ae]),wt=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=t=>{e.setSessions(e=>e.map(e=>e.sessionId===t&&e.interruptReason?{...e,interruptReason:void 0,runtime:{...e.runtime,needsAttention:!1}}:e))},r=o.useCallback((t,s,r,i,o)=>{const a=e.notificationSettingsRef.current;a[i]&&!e.notifiedEventsRef.current.has(t)&&function(e,t,s={}){const r=s.notificationFactory??("undefined"==typeof Notification?void 0:Notification);if(!r&&!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??Jt(),s.visibilityState??("undefined"==typeof document?"visible":document.visibilityState)))return!1;if(n().notifications)return n().notifications.show(e,t,s.onClick),!0;const i=new r(e,{body:t,tag:s.tag});return s.onClick&&(i.onclick=s.onClick),!0}(s,r,{onClick:()=>{window.focus(),o&&e.setActiveSessionId(o)},permission:e.notificationPermissionRef.current,settings:a,tag:t,visibilityState:document.visibilityState})&&e.notifiedEventsRef.current.add(t)},[e]);return o.useCallback(n=>{switch(n.type){case"response":Vn(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 on(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(Yn(t))}else delete s[n.sessionId];return s})),e.setRespondingSessions(t=>{const s=_d(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":s(n.sessionId),e.completionAttention?.observe(n.sessionId),t(n.sessionId),e.appendCachedDelta(n.sessionId,n.content),e.respondingSessionsRef.current=_d(e.respondingSessionsRef.current,n.sessionId,!0),e.setRespondingSessions(e=>_d(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":s(n.sessionId),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${Xn(n.input)}`,timestamp:(new Date).toISOString()}]);break;case"tool.result":s(n.sessionId),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})),r(`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})),r(`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,r(`done:${n.sessionId}:${t}`,e.t.notificationReplyTitle,e.t.notificationReplyBody,"replies",n.sessionId)}e.respondingSessionsRef.current=_d(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(e=>_d(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=_d(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(e=>_d(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=_d(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(e=>_d(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,r])}({refreshInterruptedHistory:e=>{if(e!==Pe.current)return;const t=Y.find(t=>t.sessionId===e);t&&ie(t,{refresh:!0})},completionAttention:e.completionAttention,notificationSettingsRef:Le,notifiedEventsRef:Oe,notificationPermissionRef:De,activeSessionIdRef:Pe,respondingSessionsRef:h,turnNotificationCountsRef:ze,t:dt,setActiveSessionId:N,setErrorText:m,setPendingQueues:F,setLivePendingQueue:q,setPendingApprovals:D,setPendingQuestions:L,setQuestionAnswers:Ge,setRespondingSessions:P,setSessions:v,remapLocalSessionState:ce,requestSessions:ae,clearHistoryLoading:te,replaceCachedHistory:re,setCachedMessageDelivery:ye,mergeCachedHistoryPage:Se,appendCachedHistory:ge,appendCachedDelta:me});(function(e){const s=o.useRef(null),r=()=>{null!==s.current&&window.clearTimeout(s.current),s.current=null},i=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,i=!1)=>{const o=a.current;r(),o.reconnectTimerRef.current&&(window.clearTimeout(o.reconnectTimerRef.current),o.reconnectTimerRef.current=null),o.intentionalDisconnectRef.current=!1,o.setPhase("connecting"),o.setStatusText(i?o.t.reconnectingToDaemon:o.t.connectingToDaemon),o.setErrorText(null);const l=new Bn,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,r(),o.intentionalDisconnectRef.current||(o.setPhase("connecting"),o.setStatusText(o.t.reconnectingToDaemon),o.setErrorText(o.t.webSocketClosedRetrying),c(e)))});try{const r=await(n().prepareConnection?.(e))??e;if(!h())return;let c,d=r;try{c=await l.connect(r)}catch(f){if(!h()||!r.webSocketUrl||Id(f))throw f;d={...r,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},m=!!o.pairingRef.current&&o.pairingRef.current.daemonId!==u.daemonId;m&&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,Fn(u);const g=function(e,n=t()){if(!e)return null;try{const t=n.getItem(kd);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=Jn(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 Sd(t),t}),o.setPhase("connected"),o.setStatusText(o.t.connectedTo(c.displayName??e.displayName??"Vibelet Daemon")),o.refreshDaemonMetadata(u);let v=null;const y=async()=>{if(h())try{if(await a.current.requestReconnectSnapshot(),h()&&v){const e=v;o.setErrorText(t=>t===e?null:t)}}catch(f){if(!h())return;v=f instanceof Error?f.message:String(f),o.setErrorText(v),s.current=window.setTimeout(()=>{s.current=null,y()},1600)}};y();const b=a.current;b.fetchAgentResources(b.agent,m?Wn:b.cwd).catch(e=>{h()&&o.setErrorText(e instanceof Error?e.message:String(e))}),o.reportLog("web.connected",{reconnecting:i})}catch(f){if(!h())return;o.clientRef.current=null,l.disconnect(),Id(f)&&Ln()?.pairToken===e.pairToken&&qn(),o.setPhase("error"),o.setStatusText(o.t.connectionFailed),o.setErrorText(Id(f)?o.t.pairingAuthFailed:f instanceof Error?f.message:String(f)),Id(f)||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=Nn(),s=Ln()??e.rememberedTarget;if(!n&&!s)return e.setPhase("missing-pair"),void e.setStatusText(e.t.missingPair);try{e.setPhase("pairing"),n&&i.current?.pairNonce!==n.pairNonce&&(i.current={pairNonce:n.pairNonce,promise:On(n,s)});const r=n?await(i.current?.promise):s;if(!r||t)return;n&&(Fn(r),i.current=null,function(){if(!window.location.hash.includes(`${xn}=`))return;const e=`${window.location.pathname}${window.location.search}`;window.history.replaceState(null,"",e)}()),await e.connectWithPairingRef.current(r)}catch(r){if(t)return;n&&(i.current=null),e.setPhase("error"),e.setStatusText(e.t.pairingFailed),e.setErrorText(function(e,t){return e instanceof kn&&"pair_window_expired"===e.code?t.pairingLinkExpired:e instanceof Error?e.message:String(e)}(r,e.t))}}(),()=>{t=!0,r(),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:Ae,connectWithPairingRef:Ne,pairingRef:qe,reconnectTimerRef:_e,connectionAttemptIdRef:$e,intentionalDisconnectRef:He,historyCacheRef:xe,historyCacheDaemonIdRef:Fe,messagesSessionIdRef:ne,lastHistorySessionIdRef:l,rememberedTarget:a.current[0]??null,agent:O,cwd:$,phase:f,search:rt,sinceFilter:it,t:dt,handleServerMessage:wt,setPhase:Be,setStatusText:Ue,setErrorText:m,setMessages:oe,setPairing:We,setSavedTargets:at,setSessionsFromPage:Ce,resetDeviceWorkspace:()=>{Pe.current=null,N(null),z(Wn),v([]),Ke({}),Ve({}),e.setDiffSessionId(null),D({}),L({}),F({}),h.current=new Set,P(new Set),Jl({folder:void 0,file:void 0,cwd:void 0},{replace:!0})},refreshDaemonMetadata:Me,requestReconnectSnapshot:je,fetchAgentResources:Re,reportLog:Ee,requestSessions:ae}),o.useLayoutEffect(()=>{V(Nd(c.current,A))},[A,g?.daemonId]),o.useEffect(()=>{const e=Y.find(e=>e.sessionId===A);if(!e)return l.current=null,ne.current=null,te(),void oe([]);if(_(e.agent),z(e.cwd||Wn),K(e.customTitle??e.title??""),y[e.sessionId])return l.current=e.sessionId,te(),void(ne.current!==e.sessionId&&(ne.current=e.sessionId,oe([])));if(se(e.sessionId)){const t=l.current!==e.sessionId;return l.current=e.sessionId,te(e.sessionId),void(t&&ie(e,{refresh:!0}))}l.current!==e.sessionId&&(l.current=e.sessionId,ne.current!==e.sessionId&&(ne.current=e.sessionId,oe([])),ie(e,{refresh:!0}))},[A,te,Y,y,se,ie]);const St=function({daemonId:e,session:n,setModel:s,setEffort:r,setFastMode:i,setApprovalMode:a,setPendingSessions:c}){const l=o.useRef(null);l.current||(l.current=function(){try{const e=JSON.parse(t().getItem(Vd)||"{}");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??Kn},h=()=>{try{t().setItem(Vd,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")),r(p("effort")),i(p("fastMode")),a(p("approvalMode")),h())},[d,u.model,u.effort,u.fastMode,u.approvalMode]);const f=(e,t)=>{n&&(l.current[d]={...l.current[d],[e]:t},h(),c(s=>{const r=s[n.sessionId];if(!r)return s;const i="model"===e?es(t):"effort"===e?t||void 0:t;return{...s,[n.sessionId]:{...r,[e]:i}}})),"model"===e&&s(t),"effort"===e&&r(t),"fastMode"===e&&i(t),"approvalMode"===e&&a(t)};return{applyConfirmedSettings:(t,r)=>{const o=JSON.stringify([e??"",t]),a=l.current[o];a&&(delete a.fastMode,void 0!==r.model&&delete a.model,h()),n?.sessionId===t&&(i(r.fastMode),void 0!==r.model&&s(r.model))},setModel:e=>f("model",e),setEffort:e=>f("effort",e),setFastMode:e=>f("fastMode",e),setApprovalMode:e=>f("approvalMode",e)}}({daemonId:g?.daemonId,session:fe,setModel:B,setEffort:U,setFastMode:W,setApprovalMode:H,setPendingSessions:Ke}),{stagePendingSession:Ct,failedSend:jt,dismissFailedSend:Rt,retryFailedSend:Mt,sendDraft:Tt,sendQuickReply:At}=function(e){const[t]=o.useState(Hd),[n,s]=function(e,t,n){const s=Or(_r(n,e),{}),r=()=>{for(const[r,i]of s.getAll()){const[s,o]=JSON.parse(r);if(s===(n??null)&&o)for(const n of Object.values(i)){const s=t(o,n.clientMessageId);if(s===e)return{scope:r,failure:n.sessionId===s?n:{...n,sessionId:s}}}}return null},i=r();return[i?.failure??null,e=>{const o=i??r(),a=o?s.getForScope(o.scope):void 0,c=o?a?.[o.failure.clientMessageId]??null:null,l=c&&o?.failure.sessionId!==c.sessionId?{...c,sessionId:o.failure.sessionId}:c,d="function"==typeof e?e(l):e;if("function"!=typeof e||d!==l){if((null===e||"function"==typeof e)&&c&&o){if(d?.clientMessageId===c.clientMessageId)return void s.setForScope(o.scope,{...a,[d.clientMessageId]:d});const e={...a};delete e[c.clientMessageId],s.setForScope(o.scope,e)}if(d){const e=_r(n,t(d.sessionId,d.clientMessageId));s.setForScope(e,{...s.getForScope(e),[d.clientMessageId]:d})}}}]}(e.activeSessionId,e.resolveCachedMessageSession,e.daemonId),[r,i]=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 r=Kd(t)??Kd(e.cwd)??Wn,o=n??e.agent,a=function(e=Date.now()){return ss=(ss+1)%1e4,`pending_local_${e}_${ss}`}(),c=function(e){const t=e.now??(new Date).toISOString();return{sessionId:e.sessionId,agent:e.agent,cwd:e.cwd||Wn,...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:r,approvalMode:s?.approvalMode??e.approvalMode,model:es(s?.model??e.model),effort:(s?.effort??e.effort)||void 0,fastMode:s?.fastMode??e.fastMode,title:"codex"===o?e.t.newCodexSession:e.t.newClaudeSession}),l=s?.draft??(e.activeSessionIdRef.current?"":Nd(e.composerDraftsRef.current,null));return e.setPendingSessions(e=>({...e,[a]:c})),e.revealCreatedSession(r),e.setComposerDrafts(t=>{let n=Ad(t,a,l);return e.activeSessionIdRef.current||(n=Ad(n,null,"")),e.composerDraftsRef.current=n,Td(n),n}),e.setCwd(r),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)&&i({sessionId:a,attachments:s.attachments??[]}),e.setErrorText(null),e.reportLog("web.session.pending_create",{sessionId:a,agent:o,cwd:r}),a},[e]),l=function(e){return o.useCallback(async(t,n,s)=>{const r=e.clientRef.current;if(!r?.isConnected)return e.setErrorText(e.t.webSocketNotConnected),null;const i=s?e.pendingSessions[s]:void 0,o=Ud(t)??Ud(i?.cwd)??Ud(e.cwd)??Wn,a=n??i?.agent??e.agent,c=i?.approvalMode??e.approvalMode,l=i?i.model:es(e.model),d=i?i.effort:e.effort||void 0,u=i?.fastMode??e.fastMode;e.setErrorText(null),s&&e.setPendingSessions(e=>{const t=e[s];return t?{...e,[s]:{...t,creationError:void 0}}:e});try{const t=await r.request({action:"session.create",id:r.makeId("create"),agent:a,cwd:o,approvalMode:c,continueSession:e.continueSession,model:l,effort:d,fastMode:u,...s?{clientSessionId:s}:{}});if(e.clientRef.current!==r)return null;const n=function(e){const t=e;return"string"==typeof t.sessionId?t.sessionId:null}(t);if(!n)throw new Error(e.t.sessionIdMissing);const h=Vn(t)&&"string"==typeof t.oldSessionId?t.oldSessionId:s;if(e.activeSessionIdRef.current!==(s??null)&&e.activeSessionIdRef.current!==n||(e.setCwd(o),e.setAgent(a),e.activeSessionIdRef.current=n,e.setActiveSessionId(n),e.lastHistorySessionIdRef.current=n,e.messagesSessionIdRef.current=n,e.clearHistoryLoading()),s&&i){e.setPendingSessions(e=>{const t={...e};return delete t[s],h&&h!==s&&delete t[h],t});const{creationError:t,...r}=i;e.setOptimisticSessions(e=>({...e,[n]:rs(r,n)})),h&&h!==n&&e.remapLocalSessionState(h,n),s!==n&&e.remapLocalSessionState(s,n)}else await e.requestSessions({force:!0});return e.reportLog("web.session.create",{sessionId:n,clientSessionId:s,agent:a,cwd:o}),n}catch(h){if(e.clientRef.current!==r)return null;const t=h instanceof Error?h.message:String(h);return s&&e.setPendingSessions(e=>{const n=e[s];return n?{...e,[s]:{...n,creationError:t}}:e}),e.activeSessionIdRef.current===(s??null)&&e.setErrorText(t),null}},[e])}(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.clientRef.current===n&&(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,r,i)=>{n?.preventDefault();const o=(i??e.draft).trim(),u=r??e.attachments;if(u.some(e=>e.uploading))return;if(!o&&!u.length||e.busy||t.has(e.activeSessionId))return;const h=e.clientRef.current;if(!h?.isConnected)return void e.setErrorText(e.t.webSocketNotConnected);if(!e.activeSessionId)return void c(void 0,void 0,{draft:o,attachments:u});const p=t.start(e.activeSessionId);try{const t=Et(o)?"agentSkills":0===u.length&&kt(o,e.activeSession?.agent??e.agent)?"agentCommands":void 0;let n;if(t)try{n=await $d(t)}catch(f){if(e.clientRef.current!==h)return;return void e.setErrorText(f instanceof Error?f.message:String(f))}if(e.clientRef.current!==h||e.activeSessionIdRef.current!==e.activeSessionId)return;e.setErrorText(null),void 0===i&&e.updateDraft("");const r=u;void 0===i&&e.setAttachments([]);let c=e.activeSessionId,m=e.activeSession?.agent??e.agent;const g=c?e.pendingSessions[c]:void 0,v=g?.fastMode??e.fastMode,y=g?g.model:es(e.model),b=g?g.effort:e.effort||void 0;if(c&&e.pendingSessions[c]){const t=await l(e.pendingSessions[c].cwd,e.pendingSessions[c].agent,c);if(e.clientRef.current!==h)return;if(!t)return void(void 0===i&&Bd(e,o,r));c=t,m=e.pendingSessions[e.activeSessionId??""]?.agent??m}if(!c)return void(void 0===i&&Bd(e,o,r));p.remap(c);const x=0===r.length?kt(o,m):null;if(x){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"}(x.command),s=t?h.makeId("cmd_msg"):void 0;t&&(e.activeSessionIdRef.current===c&&(e.messagesSessionIdRef.current=c),e.appendCachedHistory(c,[{role:"user",content:t,timestamp:(new Date).toISOString()}]),e.activeSessionIdRef.current===c&&e.renderCachedHistory(c));try{if(t&&await d(c),e.clientRef.current!==h)return;const r=await h.request({action:"session.command",id:h.makeId("command"),sessionId:c,agent:m,command:x.command,...s?{clientMessageId:s}:{},featureEntitlements:n});if(e.clientRef.current!==h)return;await e.handleSessionCommandResponse(c,x.command,r)}catch(f){if(e.clientRef.current!==h)return;const t=f instanceof Error?f.message:String(f);e.appendInfoMessage(c,It(t)),e.activeSessionIdRef.current===c&&e.setErrorText(It(t))}return}const w=function(e){return e.startsWith("//")?e.slice(1):e}(o),S=r.map(e=>e.path),k=h.makeId("msg"),I=`client:${k}`;e.activeSessionIdRef.current===c&&(e.messagesSessionIdRef.current=c),e.setCachedMessageDelivery(c,k,"sending",{content:w,...S.length?{images:S}:{}}),e.activeSessionIdRef.current===c&&e.renderCachedHistory(c),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(c),e.setRespondingSessions(e=>new Set(e).add(c));const C=Et(w)??void 0,j=C?n:void 0;try{if(await d(c),e.clientRef.current!==h)return;const t=await zd(h,{action:"session.send",id:h.makeId("send"),sessionId:c,agent:m,message:w,clientMessageId:k,images:S.length?S:void 0,model:y,effort:b,fastMode:v,skillInvocation:C,featureEntitlements:j},{timeoutMs:Ld,timeoutMessage:Wd},t=>e.appendInfoMessage(c,t));if(e.clientRef.current!==h)return;Vn(t)&&"string"==typeof t.oldSessionId&&"string"==typeof t.sessionId&&(p.remap(t.sessionId),e.remapLocalSessionState(t.oldSessionId,t.sessionId)),e.setCachedMessageDelivery(Vn(t)&&"string"==typeof t.sessionId?t.sessionId:c,k,"delivered"),e.reportLog("web.telemetry.send_accepted",{attachmentCount:S.length}),s(e=>e?.historyKey===I?null:e)}catch(f){if(e.clientRef.current!==h)return;c=e.resolveCachedMessageSession(c,k);const t=Dd(hs(f instanceof Error?f.message:String(f),Boolean(C)));if("delivered"===e.setCachedMessageDelivery(c,k,"failed"))return;e.activeSessionIdRef.current===c&&e.setErrorText(null),s({sessionId:c,agent:m,message:w,clientMessageId:k,historyKey:I,kind:t,retrying:!1,...S.length?{images:S}:{},model:y,effort:b,fastMode:v,skillInvocation:C,featureEntitlements:j}),e.reportLog("web.telemetry.send_failed",{attachmentCount:S.length,failureKind:t},"warn"),a(c)}}finally{p.finish()}},[a,c,l,e,t,d]),h=o.useCallback(async()=>{if(!n||n.retrying||e.busy||t.has(e.activeSessionId))return;const r=e.clientRef.current;if(!r?.isConnected)return void s(e=>e?{...e,kind:"network"}:null);let i=e.resolveCachedMessageSession(n.sessionId,n.clientMessageId);const o=t.start(i);s(e=>e?{...e,retrying:!0}:null),e.ensureCachedHistoryEntry(i,{role:"user",content:n.message,historyKey:n.historyKey,...n.images?.length?{images:n.images}:{}}),e.setCachedMessageDelivery(i,n.clientMessageId,"sending"),e.setErrorText(null),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(i),e.setRespondingSessions(e=>new Set(e).add(i));try{await d(i);const t=n.skillInvocation?await $d("agentSkills"):void 0;if(e.clientRef.current!==r)return;const a=await zd(r,{action:"session.send",id:r.makeId("retry_send"),sessionId:i,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:t},{timeoutMs:Ld,timeoutMessage:Wd},t=>e.appendInfoMessage(i,t));if(e.clientRef.current!==r)return;Vn(a)&&"string"==typeof a.oldSessionId&&"string"==typeof a.sessionId&&(o.remap(a.sessionId),e.remapLocalSessionState(a.oldSessionId,a.sessionId)),e.setCachedMessageDelivery(Vn(a)&&"string"==typeof a.sessionId?a.sessionId:i,n.clientMessageId,"delivered"),e.reportLog("web.telemetry.retry_accepted",{attachmentCount:n.images?.length??0}),s(null)}catch(c){if(e.clientRef.current!==r)return;i=e.resolveCachedMessageSession(i,n.clientMessageId);const t=Dd(hs(c instanceof Error?c.message:String(c),Boolean(n.skillInvocation)));if("delivered"===e.setCachedMessageDelivery(i,n.clientMessageId,"failed"))return void s(null);s(e=>e?{...e,sessionId:i,kind:t,retrying:!1}:null),e.reportLog("web.telemetry.retry_failed",{attachmentCount:n.images?.length??0,failureKind:t},"warn"),a(i)}finally{s(e=>e?.clientMessageId===n.clientMessageId&&e.retrying?{...e,retrying:!1}:e),o.finish()}},[a,n,e,t,d]);return o.useEffect(()=>{!r||e.busy||t.has(e.activeSessionId)||(e.activeSessionId===r.sessionId&&e.pendingSessions[r.sessionId]?(i(null),u(void 0,r.attachments)):i(null))},[r,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)}}({daemonId:g?.daemonId,revealCreatedSession:t=>{e.setSearch(""),e.setSessionAgentFilter("all"),e.setCollapsedFolders(e=>({...e,[t]:!1}))},messages:we,sessions:Y,setSessions:v,clientRef:Ae,activeSessionIdRef:Pe,composerDraftsRef:c,lastHistorySessionIdRef:l,messagesSessionIdRef:ne,respondingSessionsRef:h,agent:O,cwd:$,approvalMode:Je,continueSession:Ze,model:Xe,effort:Ye,fastMode:et,activeSessionId:A,activeSession:fe,pendingSessions:y,draft:st,busy:ut,attachments:le,t:dt,setPendingSessions:Ke,setOptimisticSessions:Ve,setComposerDrafts:nt,setCwd:z,setAgent:_,setActiveSessionId:N,setMessages:oe,setDraft:V,setErrorText:m,setBusy:ht,setAttachments:de,setRespondingSessions:P,clearHistoryLoading:te,reportLog:Ee,remapLocalSessionState:ce,requestSessions:ae,updateDraft:Ie,appendCachedHistory:ge,ensureCachedHistoryEntry:ve,setCachedMessageDelivery:ye,resolveCachedMessageSession:be,renderCachedHistory:se,handleSessionCommandResponse:xt,appendInfoMessage:ee}),{respondApproval:Nt,respondQuestion:Pt,cancelQuestion:Dt,setQuestionChoice:Lt,requestActiveAction:Ft,interruptActiveSession:qt,retrySessions:Ot,updateApprovalMode:_t,setSessionPinned:$t,setSessionArchived:zt,deleteSession:Ht,updatePinned:Bt,updateArchived:Ut,renameSession:Wt}=function(e){const t=function(e){return o.useCallback(async t=>{const n=t.sessionId,s=e.clientRef.current,r=Boolean(e.pendingSessions[n]);if(!r&&!s?.isConnected)return!1;const i={daemonId:e.daemonId,sessionId:n},o=()=>r&&e.isSessionSubmitting(n)?(x({message:b().sessionStarting,notice:!0}),!1):!!function(e){return window.dispatchEvent(new CustomEvent(Nr,{cancelable:!0,detail:e}))}(i)||(x({message:b().saveSessionFiles,notice:!0}),!1);if(!o())return!1;if(!(await S(b().deleteSession(d(t)))))return!1;if(e.clientRef.current!==s||!r&&!s?.isConnected||!o())return!1;e.setBusy(!0),e.setErrorText(null),Lr(i,!0);try{if(r||await s.request({action:"session.delete",id:s.makeId("delete"),sessionId:n}),e.clientRef.current!==s)return!1;Dr({...i,action:"remove"}),e.removeCachedHistory(n);const t=e=>{if(!e[n])return e;const t={...e};return delete t[n],t};return e.setPendingSessions(t),e.setOptimisticSessions(t),e.setPendingQueues(t),e.setPendingApprovals(t),e.setPendingQuestions(t),e.setSessions(e=>e.filter(e=>e.sessionId!==n)),e.updateSessionDraft(n,""),e.respondingSessionsRef.current.delete(n),e.setRespondingSessions(e=>{const t=new Set(e);return t.delete(n),t}),e.activeSessionIdRef.current===n&&(e.activeSessionIdRef.current=null,e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([]),e.setDraft(Nd(e.composerDraftsRef.current,null)),e.setDetailsOpen(!1)),r||await e.requestSessions({force:!0,preserveLoaded:!0}),!0}catch(a){return e.clientRef.current!==s||x({message:a instanceof Error?a.message:String(a),notice:!0}),!1}finally{Lr(i,!1),e.setBusy(!1)}},[e])}(e),n=o.useCallback(async t=>{const n=e.clientRef.current,s=e.activeApproval;if(n?.isConnected&&s){e.setBusy(!0),e.setErrorText(null);try{if(await n.request({action:"session.approve",id:n.makeId("approve"),sessionId:s.sessionId,requestId:s.requestId,approved:t}),e.clientRef.current!==n)return;e.setPendingApprovals(e=>{const t={...e};return t[s.sessionId]?.requestId===s.requestId&&delete t[s.sessionId],t})}catch(r){if(e.clientRef.current!==n)return;const t=r instanceof Error?r.message:String(r);/session not found|session .* inactive/i.test(t)&&e.setPendingApprovals(e=>{if(e[s.sessionId]?.requestId!==s.requestId)return e;const t={...e};return delete t[s.sessionId],t}),e.setErrorText(t)}finally{e.setBusy(!1)}}},[e]),s=o.useCallback(async()=>{const t=e.clientRef.current;if(t?.isConnected&&e.activeQuestion){e.setBusy(!0),e.setErrorText(null);try{if(await t.request({action:"session.respondQuestion",id:t.makeId("question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId,answers:e.questionAnswers}),e.clientRef.current!==t)return;e.setPendingQuestions(t=>{const n={...t};return n[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete n[e.activeQuestion.sessionId],n})}catch(n){if(e.clientRef.current!==t)return;e.setErrorText(n instanceof Error?n.message:String(n))}finally{e.setBusy(!1)}}},[e]),r=o.useCallback(async()=>{const t=e.clientRef.current;if(t?.isConnected&&e.activeQuestion){e.setBusy(!0),e.setErrorText(null);try{if(await t.request({action:"session.cancelQuestion",id:t.makeId("cancel_question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId}),e.clientRef.current!==t)return;e.setPendingQuestions(t=>{const n={...t};return n[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete n[e.activeQuestion.sessionId],n})}catch(n){if(e.clientRef.current!==t)return;e.setErrorText(n instanceof Error?n.message:String(n))}finally{e.setBusy(!1)}}},[e]),i=o.useCallback((t,n,s)=>{e.setQuestionAnswers(e=>function(e,t,n,s=!1){if(!s)return{...e,[t]:[n]};const r=e[t]??[],i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,[t]:i}}(e,t,n,Boolean(s)))},[e]),a=o.useCallback(async n=>{const s=e.clientRef.current,r=e.activeSession,i=r?.sessionId??("session.interrupt"===n?e.activeSessionIdRef.current:null);if(!s?.isConnected||!i)return!1;if("session.interrupt"!==n&&!r)return!1;if("session.delete"===n)return t(r);if(e.clientRef.current!==s||!s.isConnected)return!1;e.setBusy(!0),e.setErrorText(null);try{if("session.resume"===n){if(await s.request({action:n,id:s.makeId("resume"),sessionId:i,agent:r.agent}),e.clientRef.current!==s)return!1}else if(await s.request({action:n,id:s.makeId(n.split(".").at(-1)??"session"),sessionId:i}),e.clientRef.current!==s)return!1;return"session.interrupt"!==n&&await e.requestSessions({force:!0,preserveLoaded:!0}),!0}catch(o){return e.clientRef.current!==s||e.setErrorText(o instanceof Error?o.message:String(o)),!1}finally{e.setBusy(!1)}},[e,t]),c=o.useCallback(async t=>{const n=e.clientRef.current;if(e.activeSession){if(n?.isConnected){e.setErrorText(null);try{if(await n.request({action:"session.setApprovalMode",id:n.makeId("approval_mode"),sessionId:e.activeSession.sessionId,approvalMode:t}),e.clientRef.current!==n)return;e.activeSessionIdRef.current===e.activeSession.sessionId&&e.setApprovalMode(t),e.setSessions(n=>n.map(n=>n.sessionId===e.activeSession.sessionId?{...n,approvalMode:t}:n))}catch(s){if(e.clientRef.current!==n)return;e.setErrorText(s instanceof Error?s.message:String(s))}}}else e.setApprovalMode(t)},[e]),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 r=n?Date.now():void 0;if(await s.request({action:"session.setPinned",id:s.makeId("pin"),sessionId:t.sessionId,pinned:n,...r?{pinnedAt:r}:{}}),e.clientRef.current!==s)return;e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,pinned:n,pinnedAt:r}:e)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(r){if(e.clientRef.current!==s)return;e.setErrorText(r instanceof Error?r.message:String(r))}finally{e.setBusy(!1)}}},[e]),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{if(await s.request({action:"session.setArchived",id:s.makeId("archive"),sessionId:t.sessionId,archived:n}),e.clientRef.current!==s)return;e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,archived:n}:e)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(r){if(e.clientRef.current!==s)return;e.setErrorText(r instanceof Error?r.message:String(r))}finally{e.setBusy(!1)}}},[e]),h=o.useCallback(async()=>{e.activeSession&&await l(e.activeSession,!e.activeSession.pinned)},[e.activeSession,l]),p=o.useCallback(async()=>{e.activeSession&&await u(e.activeSession,!e.activeSession.archived)},[e.activeSession,u]),f=o.useCallback(()=>{const t=e.activeSessionId;t&&a("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,a]),m=o.useCallback(()=>{e.setErrorText(null),"connected"===e.phase?e.requestSessions({force:!0,preserveLoaded:!0}):window.location.reload()},[e]),g=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 r=e.clientRef.current;if(!r?.isConnected||!t)return!1;e.setBusy(!0),e.setErrorText(null);try{return await r.request({action:"session.rename",id:r.makeId("rename"),sessionId:t.sessionId,title:s||void 0}),e.clientRef.current===r&&(e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,customTitle:s||void 0}:e)),!0)}catch(i){return e.clientRef.current!==r||e.setErrorText(i instanceof Error?i.message:String(i)),!1}finally{e.setBusy(!1)}},[e]);return{respondApproval:n,respondQuestion:s,cancelQuestion:r,setQuestionChoice:i,requestActiveAction:a,interruptActiveSession:f,retrySessions:m,updateApprovalMode:c,setSessionPinned:l,setSessionArchived:u,deleteSession:t,updatePinned:h,updateArchived:p,renameSession:g}}({daemonId:g?.daemonId??null,isSessionSubmitting:Tt.submission.has,updateSessionDraft:e.updateSessionDraft,clientRef:Ae,activeSessionIdRef:Pe,composerDraftsRef:c,lastHistorySessionIdRef:l,messagesSessionIdRef:ne,respondingSessionsRef:h,activeApproval:he,activeQuestion:pe,activeSession:fe,activeSessionId:A,questionAnswers:Qe,pendingSessions:y,phase:f,renameTitle:tt,setBusy:ht,setErrorText:m,setPendingApprovals:D,setPendingQuestions:L,setQuestionAnswers:Ge,setPendingQueues:F,setActiveSessionId:N,setMessages:oe,setApprovalMode:H,setSessions:v,setPendingSessions:Ke,setComposerDrafts:nt,setDraft:V,setAttachments:de,setDetailsOpen:pt,setRespondingSessions:P,setOptimisticSessions:Ve,removeCachedHistory:ke,requestSessions:ae,removeCachedMessage:e.removeCachedMessage}),{runArchiveSync:Qt,skipArchiveSync:Xt,runAdminAction:Yt,exportActiveSession:en,clearPairing:tn,setNotificationsEnabled:nn,connectSavedTarget:sn,forgetSavedTarget:un,openSessionDetails:hn,editFolderTags:pn,browseFolder:gn,copyResumeCommand:yn,resumeInTerminal:wn}=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 r="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,r,{timeout:e.t.archiveSyncFailedTimeout,disconnected:e.t.archiveSyncFailedDisconnected,generic:e.t.archiveSyncFailedGeneric})),!s.ok)return;const i=new Set(s.archivedSessionIds);e.setSessions(e=>e.map(e=>({...e,archived:i.has(e.sessionId)}))),e.pairingRef.current?.daemonId&&t(e.pairingRef.current.daemonId,"synced"),e.requestSessions({force:!0})},[t,e]),r=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]),i=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){return function(e,t){const n=d(e),{markdown:s}=function({title:e,session:t,messages:n,labels:s,exportedAt:r=new Date}){const i=[];for(const a of n){if("user"!==a.type&&"assistant"!==a.type)continue;const e=bn(a,s);e&&i.push(`## ${"user"===a.type?s.userMessage:s.assistantMessage}\n\n${e}`)}const o=[`# ${mn(e)||t.sessionId}`,"",`- ${s.agent}: ${vn(t.agent)}`,`- ${s.sessionId}: \`${t.sessionId}\``,`- ${s.workingDirectory}: \`${t.cwd}\``,`- ${s.createdAt}: ${t.createdAt}`,`- ${s.exportedAt}: ${r.toISOString()}`];return{markdown:i.length>0?`${o.join("\n")}\n\n${i.join("\n\n")}`:o.join("\n"),messageCount:i.length}}({title:n,session:e,messages:t.filter(e=>"info"!==e.type).map(e=>({type:e.role,content:"assistant"===e.role?fn(e.content):e.content,images:e.images})),labels:{agent:"Agent",sessionId:"Session",workingDirectory:"Working directory",createdAt:"Created",exportedAt:"Exported",userMessage:"User",assistantMessage:"Assistant",attachedImage:"Attachment"}});return{title:n,markdown:s}}(e,t).markdown}(e.activeSession,e.messages);!function(e,t){const n=URL.createObjectURL(new Blob([t],{type:"text/plain;charset=utf-8"})),s=document.createElement("a");s.href=n,s.download=e,s.click(),URL.revokeObjectURL(n)}(function(e,t){return`${e.replace(/[<>:"/\\|?*\u0000-\u001F]/g," ").replace(/\s+/g," ").trim().slice(0,80)||t.slice(0,12)||"session"}.txt`}(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,qn(),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(xl),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]),f=o.useCallback(t=>e.saveTargets(function(e,t){return e.filter(e=>e.daemonId!==t)}(e.savedTargets,t)),[e]),m=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]),v=o.useCallback(t=>{e.setControlTab("files"),e.listDirectory(t,{updateRoute:!0})},[e]),y=o.useCallback(async t=>{try{const n=Kt(t);if(!n)return;await cr(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:r,skipArchiveSync:i,runAdminAction:a,exportActiveSession:c,clearPairing:u,setNotificationsEnabled:h,connectSavedTarget:p,forgetSavedTarget:f,openSessionDetails:m,editFolderTags:g,browseFolder:v,copyResumeCommand:y,resumeInTerminal:o.useCallback(async t=>{if(x.current)return;const s=n(),r=e.pairingRef.current?.daemonId;if(r&&s.resumeInTerminal&&s.isLocalDaemon?.(r)){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:r,approvalMode:t.approvalMode??t.observedApprovalMode})}catch(i){e.setErrorText(String(i).includes("session_busy")?e.t.resumeTerminalBusy:e.t.resumeTerminalFailed)}finally{x.current=!1}}},[e])}}({clientRef:Ae,pairingRef:qe,connectWithPairingRef:Ne,notificationPermissionRef:De,intentionalDisconnectRef:He,connectionAttemptIdRef:$e,historyCacheRef:xe,historyCacheDaemonIdRef:Fe,messagesSessionIdRef:ne,lastHistorySessionIdRef:l,displaySessions:Y,pairing:g,t:dt,archiveSyncBusy:vt,daemonMetadata:Z,activeSession:fe,messages:we,notificationPermission:X,savedTargets:ot,setArchiveSyncBusy:yt,setArchiveSyncStatus:bt,setSessions:v,setAdmin:ft,setErrorText:m,setNotificationPermission:gt,setStatusText:Ue,setMessages:oe,setPairing:We,setDaemonMetadata:mt,setPhase:Be,setActiveSessionId:N,setRenameTitle:K,setDetailsOpen:pt,setControlTab:J,updateSessionListPreferences:lt,requestSessions:ae,refreshDaemonMetadata:Me,updateNotificationSettings:Te,saveTargets:ct,listDirectory:ue}),{listSessionModels:Sn,applyToAllSessions:In}=function(e,t,n){const s=o.useRef(n);return s.current=n,{listSessionModels:o.useCallback(async t=>{const n=e.current;return n?.isConnected?(await n.request({action:"models.list",id:n.makeId("models"),agent:t})).options??[]:[]},[e]),applyToAllSessions:async(n,r)=>{const i=e.current;if(!i?.isConnected)throw new Error("not_connected");let o=!1;const a=i.onClose(()=>{o=!0});try{return await async function(e,t){const n=new Map,s=new Set;let r;do{if(!t.isCurrentConnection())throw new Error("connection_changed");const e=await t.request({action:"sessions.list",id:t.nextId(),limit:500,cursor:r,skipGitMetadata:!0});if(!Array.isArray(e?.sessions))throw new Error("invalid_session_list");for(const t of e.sessions)t.sessionId.startsWith("pending_")||n.set(t.sessionId,t);if(r=e.nextCursor,r){const e=JSON.stringify(r);if(s.has(e))throw new Error("repeated_cursor");s.add(e)}}while(r);const i={updated:0,failed:0};for(const o of n.values()){const n=e.models[o.agent],s={...void 0!==n?{model:n}:{},fastMode:e.fastMode};try{if(!t.isCurrentConnection())throw new Error("connection_changed");if(await t.request({action:"session.configure",id:t.nextId(),sessionId:o.sessionId,...s}),!t.isCurrentConnection())throw new Error("connection_changed");t.onApplied(o,s),i.updated++}catch{i.failed++}t.onProgress?.({...i})}return i}(n,{nextId:()=>i.makeId("bulkcfg"),request:e=>i.request(e,{timeoutMs:15e3}),isCurrentConnection:()=>!o&&e.current===i&&i.isConnected,onProgress:r,onApplied:(e,n)=>{s.current(e.sessionId,n),t(t=>t.map(t=>t.sessionId===e.sessionId?{...t,...n}:t))}})}finally{a()}}}}(Ae,v,St.applyConfirmedSettings),Cn=o.useCallback(async e=>{const t=Ae.current;if(!t?.isConnected)throw new Error(dt.webSocketNotConnected);return t.request({action:"sessions.gitMetadata",id:t.makeId("directoryGit"),cwds:[e]})},[Ae,dt.webSocketNotConnected]),jn="denied"===X||"unsupported"===X,Rn=Boolean(Z.version&&Z.latestVersion&&Sl(Z.version,Z.latestVersion)),En=g?.daemonId,Mn=Boolean(En&&Q[En]),Tn=Boolean(En&&G[En]),An=function(e){const[t,n]=o.useState(null),s=e.clientRef.current,r=(t,n,s)=>{const r=n.map(t=>t.content||e.t.failedSendImages(t.images?.length??0)).join(" / ");return function(e,t,n,s){switch(Pd(s)){case"turn-changed":return e.queueGuideTurnChanged;case"no-active-turn":return e.queueGuideNoActiveTurn;case"not-ready":return e.queueSessionNotReady;case"stale-selection":return e.queueSelectionChanged;case"pending-request":return e.queuePendingRequest;case"unsupported":return e.queueGuideUnsupported}const r=s instanceof Error?s.message:String(s);return s instanceof $n?e.queueRequestRejected(t,n,r):e.queueRequestFailed(t,n,/timeout|timed out/i.test(r)?e.queueRequestTimeout:r)}(e.t,t,r,s)},i=e.activeSessionId,{busy:a,begin:c}=function(e,t){const n=o.useRef(new Set),[s,r]=o.useState([]),i=n=>n.client===e&&n.sessionId===t;return{busy:s.some(i),begin:()=>{if(!e||!t||[...n.current].some(i))return null;const s={client:e,sessionId:t};return n.current.add(s),r([...n.current]),()=>{n.current.delete(s),r([...n.current])}}}}(s,i),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===i&&t.action===n&&t.runtime===e.activeSession?.runtime,h="daemonActive"===e.activeSession?.runtime.state&&!e.activeQueue.some(e=>e.waitingForStartup),p=!i||Boolean(e.pendingApprovals[i]||e.pendingQuestions[i]),f=!p&&!0===s?.supportsSessionSteer&&!!i&&e.respondingSessions.has(i)&&h&&!0===e.activeSession?.runtime.isResponding&&!u("guide"),m=!p&&h&&!u("sendNow")&&!0===s?.supportsQueueSendNow,g=function(e){return o.useCallback(async t=>{const n=e.clientRef.current;if(!n?.isConnected||!e.activeSessionId||!t.clientMessageId)return;const s=e.activeSessionId,r=e.begin();if(r){e.setErrorText(null);try{const r=await n.request({action:"session.queue.cancel",id:n.makeId("queue_cancel"),sessionId:s,clientMessageId:t.clientMessageId},{timeoutMs:Ld});if(e.clientRef.current!==n)return;if(e.confirmPendingQueueRemoval(s,[t.clientMessageId]),0===r?.removed&&!r.interrupted)return await e.refreshState(),void(e.clientRef.current===n&&e.activeSessionIdRef.current===s&&x({message:e.t.queueSelectionChanged,notice:!0}));if(r?.interrupted||e.removeCachedMessage(s,t.clientMessageId),e.updateSessionDraft(s,[Nd(e.composerDraftsRef.current,s),t.content].filter(Boolean).join("\n\n")),t.images?.length){const n=[...new Set(t.images)];e.setAttachments(e=>{const t=new Set(e.map(e=>e.path));return[...e,...n.filter(e=>!t.has(e)).map(e=>({path:e,name:Zn(e),type:"image/*",size:0}))]})}r?.interrupted&&e.activeSessionIdRef.current===s&&x({message:e.t.queueWithdrawalInterrupted,notice:!0})}catch(i){if(e.clientRef.current!==n)return;await e.refreshState(),e.clientRef.current===n&&e.activeSessionIdRef.current===s&&e.setErrorText(i instanceof Error?i.message:String(i))}finally{r()}}},[e])}({...e,begin:c,refreshState:d});return{busy:a,canGuide:f,canSendNow:m,onAction:async(t,o)=>{if(!i||!s?.isConnected||!("guide"===o?f:m))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(i,n.clientMessageId,"sending",n);const g=t=>{p.add(t.clientMessageId),e.setCachedMessageDelivery(i,t.clientMessageId,"delivered"),e.confirmPendingQueueRemoval(i,[t.clientMessageId])};try{if("sendNow"===o){if(await s.request({action:"session.queue.sendNow",id:s.makeId("queue_now"),sessionId:i,clientMessageIds:u.map(e=>e.clientMessageId)},{timeoutMs:Ld}),!l())return;u.forEach(g)}else for(const e of u){if(!l())return;if(await s.request({action:"session.steer",id:s.makeId("queue_guide"),sessionId:i,clientMessageId:e.clientMessageId,message:e.content,images:e.images},{timeoutMs:Ld}),!l())return;g(e)}}catch(v){if(!l())return;const t=Pd(v);let s=!1;for(const n of u)p.has(n.clientMessageId)||(s="delivered"!==e.setCachedMessageDelivery(i,n.clientMessageId,"failed")||s);t&&("no-active-turn"===t&&e.setRespondingSessions(e=>{const t=new Set(e);return t.delete(i),t}),e.activeSession&&n({sessionId:i,action:o,runtime:e.activeSession.runtime}),await d()),s&&l()&&e.activeSessionIdRef.current===i&&e.setErrorText(r("guide"===o?e.t.queueGuide:e.t.queueSendNow,u.filter(e=>!p.has(e.clientMessageId)),v))}finally{h()}},onCollect:async t=>{if(!i||!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:i,clientMessageIds:o.map(e=>e.clientMessageId)},{timeoutMs:Ld});if(!l())return;const r=t.entries;if(!Array.isArray(r))throw new Error("Invalid queue collection response");const a=r.map(e=>e.content).filter(e=>e.trim()).join("\n\n"),c=e=>[e,a].filter(e=>e.trim()).join("\n\n");e.updateSessionDraft(i,c(Nd(e.composerDraftsRef.current,i)));const d=[...new Set(r.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:Zn(e),type:"image/*",size:0}))]}),e.confirmPendingQueueRemoval(i,[...n]);for(const n of r)n.clientMessageId&&e.removeCachedMessage(i,n.clientMessageId)}catch(u){if(!l())return;Pd(u)&&await d(),l()&&e.activeSessionIdRef.current===i&&e.setErrorText(r(e.t.queueCollectAll,o,u))}finally{a()}}},onCancel:g}}(e);return{...e,setModel:St.setModel,setEffort:St.setEffort,setFastMode:St.setFastMode,queueControls:An,listSessionModels:Sn,applyToAllSessions:In,loadDirectoryGitMetadata:Cn,rewindMessage:i,handleSessionCommandResponse:xt,handleServerMessage:wt,failedSend:jt,dismissFailedSend:Rt,retryFailedSend:Mt,stagePendingSession:Ct,sendDraft:Tt,sendQuickReply:At,respondApproval:Nt,respondQuestion:Pt,cancelQuestion:Dt,setQuestionChoice:Lt,requestActiveAction:Ft,interruptActiveSession:qt,retrySessions:Ot,updateApprovalMode:async e=>{St.setApprovalMode(e),fe&&!y[fe.sessionId]&&await _t(e)},cancelQueuedTurn:An.onCancel,setSessionPinned:$t,setSessionArchived:zt,deleteSession:Ht,updatePinned:Bt,updateArchived:Ut,renameSession:Wt,runArchiveSync:Qt,skipArchiveSync:Xt,runAdminAction:Yt,exportActiveSession:en,clearPairing:tn,setNotificationsEnabled:nn,connectSavedTarget:sn,forgetSavedTarget:un,openSessionDetails:hn,editFolderTags:pn,browseFolder:gn,copyResumeCommand:yn,resumeInTerminal:wn,notificationsBlocked:jn,hasDaemonUpdate:Rn,activeDaemonId:En,archiveSynced:Mn,archiveSyncDismissed:Tn}}();return i.jsx(Rc,{scopeKey:_r(e.pairing?.daemonId,e.activeSessionId),children:i.jsx(Qr,{workspace:e,children:i.jsx(cu,{workspace:e})})})}},Symbol.toStringTag,{value:"Module"}));export{te as $,pt as A,O as B,_ as C,as as D,Vs as E,sc as F,le as G,Js as H,ue as I,q as J,pe as K,ve as L,Mc as M,qr as N,Ln as O,je as P,Br as Q,cs as R,qe as S,Ue as T,Wr as U,Te as V,$ as W,Ve as X,z as Y,Qe as Z,re as _,Ts as a,Vr as a0,Vi as a1,Ki as a2,Li as a3,qi as a4,Fi as a5,Ui as a6,_i as a7,ro as a8,Gi as a9,lu as aA,Ei as aa,eo as ab,Yi as ac,Bi as ad,Wi as ae,Ai as af,rd as ag,ed as ah,Ls as ai,id as aj,ds as ak,od as al,cd as am,ld as an,ki as ao,ua as ap,Me as aq,fs as ar,la as as,Le as at,H as au,ze as av,D as aw,$e as ax,Bn as ay,Mi as az,Rs as b,Zn as c,Xn as d,Q as e,ga as f,cr as g,mt as h,Gr as i,Os as j,ne as k,Xs as l,Fs as m,Qs as n,Gs as o,Zd as p,er as q,Ss as r,ot as s,tr as t,Ds as u,Ys as v,ti as w,sr as x,J as y,oe as z};
|