vibelet 1.2.236 → 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-oOAXQU_U.js → ChipGroup-DCvI-4nb.js} +1 -1
- package/dist/web/assets/FilesControlPanel-B-pqZWgH.js +1 -0
- package/dist/web/assets/{GlobalPendingDialog-BRjrQWQb.js → GlobalPendingDialog-M2Dbntba.js} +1 -1
- package/dist/web/assets/{ImageViewer-BKLAZsx-.js → ImageViewer-ChfsVDQe.js} +1 -1
- package/dist/web/assets/{LanguageSettingsPanel-CaykSwtb.js → LanguageSettingsPanel-P7H9JLtq.js} +1 -1
- package/dist/web/assets/{MarkdownModePanel-MUsXqLwF.js → MarkdownModePanel-B4zGnWRC.js} +1 -1
- package/dist/web/assets/{NewSessionDialog-BY2zzDZo.css → NewSessionDialog-5JSvL7EJ.css} +1 -1
- package/dist/web/assets/NewSessionDialog-Cw6WvtMR.js +1 -0
- package/dist/web/assets/{NotificationSettingsPanel-BBUZhjoO.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-BgkL7mH7.js → ThemeSettingsPanel-JUF7qFiS.js} +1 -1
- package/dist/web/assets/{abnfDiagram-VRR7QNED-ODGFDhJw.js → abnfDiagram-VRR7QNED-BUn7dXdz.js} +1 -1
- package/dist/web/assets/{arc-BbkJgSU9.js → arc-BW2CYTF6.js} +1 -1
- package/dist/web/assets/{architectureDiagram-ZJ3FMSHR-Db8s926b.js → architectureDiagram-ZJ3FMSHR-QlFDuk3c.js} +1 -1
- package/dist/web/assets/{arrow-right-BCjDgKWi.js → arrow-right-BkDm1nz1.js} +1 -1
- package/dist/web/assets/{blockDiagram-677ZJIJ3-BavQ_vBo.js → blockDiagram-677ZJIJ3-Di1jkO8N.js} +1 -1
- package/dist/web/assets/{c4Diagram-LMCZKHZV-XWI6vuqV.js → c4Diagram-LMCZKHZV-BIE5S3xC.js} +1 -1
- package/dist/web/assets/channel-CgLW9Jd5.js +1 -0
- package/dist/web/assets/{chunk-2Q5K7J3B-B6hV61Y7.js → chunk-2Q5K7J3B-BZdVpYMm.js} +1 -1
- package/dist/web/assets/{chunk-32BRIVSS-DX3VKIDK.js → chunk-32BRIVSS-DniTjuKD.js} +1 -1
- package/dist/web/assets/{chunk-5VM5RSS4-CYMCskaD.js → chunk-5VM5RSS4-zU4WGQUt.js} +1 -1
- package/dist/web/assets/{chunk-EX3LRPZG-DBoGg_4O.js → chunk-EX3LRPZG-B_EGZWf3.js} +1 -1
- package/dist/web/assets/{chunk-JWPE2WC7-CRtoh7C6.js → chunk-JWPE2WC7-8R4xqfzd.js} +1 -1
- package/dist/web/assets/{chunk-MOJQB5TN-C-oFYT6N.js → chunk-MOJQB5TN-CmpQblce.js} +1 -1
- package/dist/web/assets/{chunk-RYQCIY6F-CH1nwWiv.js → chunk-RYQCIY6F-DrT9S-SZ.js} +1 -1
- package/dist/web/assets/{chunk-V7JOEXUC-BN4Ew-5h.js → chunk-V7JOEXUC-CEP012wY.js} +1 -1
- package/dist/web/assets/{chunk-VR4S4FIN-C2l6p76I.js → chunk-VR4S4FIN-DcSau3fK.js} +1 -1
- package/dist/web/assets/{chunk-XXDRQBXY-CqFQntEs.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-B29C7mI7.js → collectMessageImages-CUMbRGiF.js} +1 -1
- package/dist/web/assets/{cose-bilkent-JH36ORCC-e57V0sEJ.js → cose-bilkent-JH36ORCC-DKrqebqO.js} +1 -1
- package/dist/web/assets/{cynefin-VYW2F7L2-Bfk1s_pC.js → cynefin-VYW2F7L2-bQLn5vS2.js} +1 -1
- package/dist/web/assets/{cynefinDiagram-TSTJHNR4-D3quCWPS.js → cynefinDiagram-TSTJHNR4-ezXQFC9o.js} +1 -1
- package/dist/web/assets/{dagre-VKFMJZFB-g44y_PH_.js → dagre-VKFMJZFB-CDV8r_Bq.js} +1 -1
- package/dist/web/assets/{diagram-FQU43EPY-LnQzEtH4.js → diagram-FQU43EPY-BICapB67.js} +1 -1
- package/dist/web/assets/{diagram-G47NLZAW-CflyOpm5.js → diagram-G47NLZAW-TuVLjwN6.js} +1 -1
- package/dist/web/assets/{diagram-NH7WQ7WH-DBXAi8Ov.js → diagram-NH7WQ7WH-B3dBWl3F.js} +1 -1
- package/dist/web/assets/{diagram-OA4YK3LP-Dg_Dijvf.js → diagram-OA4YK3LP-DeIQlN-6.js} +1 -1
- package/dist/web/assets/{diagram-WEI45ONY-BuwomISz.js → diagram-WEI45ONY-DZcwYcod.js} +1 -1
- package/dist/web/assets/{ebnfDiagram-CCIWWBDH-BDsa6V-M.js → ebnfDiagram-CCIWWBDH-4KcDP5Zj.js} +1 -1
- package/dist/web/assets/{erDiagram-Q63AITRT-DjC-G50r.js → erDiagram-Q63AITRT-D4KIuggo.js} +1 -1
- package/dist/web/assets/{file-editor-FileCodeEditor-DMbYLQga.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-cHj5bINn.js → file-editor-ObsidianFileEditor-CM9ucogo.js} +1 -1
- package/dist/web/assets/{flowDiagram-23GEKE2U-BJQ8jmJz.js → flowDiagram-23GEKE2U-BeHvede_.js} +1 -1
- package/dist/web/assets/{folder-plus-CaEac9Pu.js → folder-plus-BVS_Q2fe.js} +1 -1
- package/dist/web/assets/{ganttDiagram-NO4QXBWP-C_Ep_sqX.js → ganttDiagram-NO4QXBWP-DrwEUqQX.js} +1 -1
- package/dist/web/assets/{gitGraphDiagram-IHSO6WYX-yqq5qCor.js → gitGraphDiagram-IHSO6WYX-Cm7T6TME.js} +1 -1
- package/dist/web/assets/{highlighted-body-TPN3WLV5-DsgrYxxe.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-CfjAw18S.js → index-CapF4a8Y.js} +1 -1
- package/dist/web/assets/{infoDiagram-FWYZ7A6U-BG84MMEG.js → infoDiagram-FWYZ7A6U-CgeulgC-.js} +1 -1
- package/dist/web/assets/{ishikawaDiagram-FXEZZL3T-BVbSAqPD.js → ishikawaDiagram-FXEZZL3T-x4glLaWe.js} +1 -1
- package/dist/web/assets/{journeyDiagram-5HDEW3XC-DR9u9PjY.js → journeyDiagram-5HDEW3XC-DHGcWBDR.js} +1 -1
- package/dist/web/assets/{kanban-definition-HUTT4EX6-BNL6Cjqp.js → kanban-definition-HUTT4EX6-CqYivdRn.js} +1 -1
- package/dist/web/assets/{linear-BABQawCG.js → linear-BKnAjtJN.js} +1 -1
- package/dist/web/assets/{mermaid-O7DHMXV3-D-nTO-tY.js → mermaid-O7DHMXV3-B3e3pugB.js} +2 -2
- package/dist/web/assets/{mermaid-O7DHMXV3-DQjp4PWc.css → mermaid-O7DHMXV3-CgN6EJ9a.css} +1 -1
- package/dist/web/assets/{mermaid.core-D1pd82vj.js → mermaid.core-CTf8qcol.js} +2 -2
- package/dist/web/assets/{mindmap-definition-LN4V7U3C-BjvItyAf.js → mindmap-definition-LN4V7U3C-NQnwG7IB.js} +1 -1
- package/dist/web/assets/{pegDiagram-2B236MQR-Bfs8YxC7.js → pegDiagram-2B236MQR-jfLjzzsG.js} +1 -1
- package/dist/web/assets/{pieDiagram-ENE6RG2P-DdELzb-R.js → pieDiagram-ENE6RG2P-CgxRYPCf.js} +1 -1
- package/dist/web/assets/{quadrantDiagram-ABIIQ3AL-AzJ5Sqrb.js → quadrantDiagram-ABIIQ3AL-0zHgV223.js} +1 -1
- package/dist/web/assets/{railroadDiagram-RFXS5EU6-s2d1tZs2.js → railroadDiagram-RFXS5EU6-CQqf55Rk.js} +1 -1
- package/dist/web/assets/{requirementDiagram-TGXJPOKE-OBPiuQUS.js → requirementDiagram-TGXJPOKE-Dm9cKzLN.js} +1 -1
- package/dist/web/assets/{sankeyDiagram-HTMAVEWB-B0z9UoWs.js → sankeyDiagram-HTMAVEWB-BRBxR71X.js} +1 -1
- package/dist/web/assets/{sequenceDiagram-DBY2YBRQ-B-eaTrbT.js → sequenceDiagram-DBY2YBRQ-DxVBmbfg.js} +1 -1
- package/dist/web/assets/{sizeCapture-X5ZJPWSS--cmYiv7G.js → sizeCapture-X5ZJPWSS-DNNwG-Sh.js} +1 -1
- package/dist/web/assets/{stateDiagram-2N3HPSRC-_MuFncei.js → stateDiagram-2N3HPSRC-C8KGcqhJ.js} +1 -1
- package/dist/web/assets/stateDiagram-v2-6OUMAXLB-Bk6KXy8V.js +1 -0
- package/dist/web/assets/{swimlanes-5IMT3BWC-c7JaTQfX.js → swimlanes-5IMT3BWC-CRe3WzWn.js} +2 -2
- package/dist/web/assets/swimlanesDiagram-G3AALYLV-DsL6VYKg.js +1 -0
- package/dist/web/assets/{timeline-definition-FHXFAJF6-CnOYde68.js → timeline-definition-FHXFAJF6-CQqiFe9j.js} +1 -1
- package/dist/web/assets/{vennDiagram-L72KCM5P-DZbkibLf.js → vennDiagram-L72KCM5P-C_5c80TB.js} +1 -1
- package/dist/web/assets/{wardleyDiagram-EHGQE667-go5O5Sd2.js → wardleyDiagram-EHGQE667-DJ2RRwLP.js} +1 -1
- package/dist/web/assets/{xychartDiagram-FW5EYKEG-B9THiMzF.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-C560TMeI.js +0 -2
- package/dist/web/assets/App-iPVf4ne3.css +0 -1
- package/dist/web/assets/BrowserControlPanel-7SS9C-wJ.js +0 -1
- package/dist/web/assets/FilesControlPanel-c4WfDaKU.js +0 -1
- package/dist/web/assets/NewSessionDialog-6g3uTjpL.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-bq0Spc3-.js +0 -2
- package/dist/web/assets/TerminalControlPanel-_G2RVzCv.js +0 -1
- package/dist/web/assets/channel-CVgTHrkc.js +0 -1
- package/dist/web/assets/classDiagram-OUVF2IWQ-CNwRwjLB.js +0 -1
- package/dist/web/assets/classDiagram-v2-EOCWNBFH-CNwRwjLB.js +0 -1
- package/dist/web/assets/clsx-pdz_ZVGy.js +0 -1
- package/dist/web/assets/file-editor-ObsidianCodeEditor-TJxlWj2j.js +0 -48
- package/dist/web/assets/index-BIOvx5-n.js +0 -2
- package/dist/web/assets/stateDiagram-v2-6OUMAXLB-B40jPaIC.js +0 -1
- package/dist/web/assets/swimlanesDiagram-G3AALYLV-9bT14x9O.js +0 -1
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid-O7DHMXV3-D-nTO-tY.js","assets/index-BIOvx5-n.js","assets/index-BBUiU9K_.css","assets/index-CfjAw18S.js","assets/collectMessageImages-B29C7mI7.js","assets/clsx-pdz_ZVGy.js","assets/index-1M7_HtDu.js","assets/mermaid-O7DHMXV3-DQjp4PWc.css","assets/ImageViewer-BKLAZsx-.js","assets/arrow-right-BCjDgKWi.js","assets/ImageViewer-Fya-Uufq.css","assets/BrowserControlPanel-7SS9C-wJ.js","assets/TerminalControlPanel-_G2RVzCv.js","assets/FilesControlPanel-c4WfDaKU.js","assets/folder-plus-CaEac9Pu.js","assets/FilesControlPanel-DQpsZVYc.css","assets/LanguageSettingsPanel-CaykSwtb.js","assets/ChipGroup-oOAXQU_U.js","assets/ThemeSettingsPanel-BgkL7mH7.js","assets/NotificationSettingsPanel-BBUZhjoO.js","assets/MarkdownModePanel-MUsXqLwF.js","assets/MarkdownModePanel-D73Xg4At.css","assets/file-editor-FileCodeEditor-DMbYLQga.js","assets/file-editor-index-C6CU7Fik.js","assets/FileCodeEditor-CW9KijoU.css","assets/file-editor-ObsidianCodeEditor-TJxlWj2j.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-bq0Spc3-.js","assets/RemoteLifeOSBlock-BGPY9LfG.css","assets/katex-uyR15voz.js","assets/marked.esm-BBjA1da9.js","assets/ObsidianCodeEditor-eECvmZRy.css","assets/file-editor-ObsidianFileEditor-cHj5bINn.js","assets/purify.es-BNLkGfTg.js","assets/isArrayLikeObject-C958pSF-.js","assets/_baseMerge-CwDZKfvJ.js","assets/_initCloneObject-C781OlVa.js","assets/ObsidianFileEditor-BM1om3jV.css","assets/NewSessionDialog-6g3uTjpL.js","assets/NewSessionDialog-BY2zzDZo.css","assets/GlobalPendingDialog-BRjrQWQb.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{c as e,i as t,h as n,b as s,d as i,j as r,r as o,f as a,S as c,m as l,t as d,n as u,o as h,p,_ as m,u as f,D as g,E as y,q as v,v as b,w as x,x as w,y as S,z as k,A as I,B as C,C as j,F as R,G as M,H as E,I as T}from"./index-BIOvx5-n.js";const N=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"}]]),A=e("archive-restore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]),P=e("archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]),D=e("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]),F=e("arrow-left-to-line",[["path",{d:"M3 19V5",key:"rwsyhb"}],["path",{d:"m13 6-6 6 6 6",key:"1yhaz7"}],["path",{d:"M7 12h14",key:"uoisry"}]]),L=e("arrow-right-to-line",[["path",{d:"M17 12H3",key:"8awo09"}],["path",{d:"m11 18 6-6-6-6",key:"8c2y43"}],["path",{d:"M21 5v14",key:"nzette"}]]),q=e("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),O=e("bell",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]]),$=e("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]),z=e("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),_=e("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),B=e("chevron-up",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]),H=e("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]),W=e("clipboard",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}]]),U=e("clock-3",[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]),K=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"}]]),V=e("corner-up-right",[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M4 20v-7a4 4 0 0 1 4-4h12",key:"1lu4f8"}]]),G=e("cpu",[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]]),J=e("ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]),Z=e("eye-off",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),Y=e("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),X=e("file-pen-line",[["path",{d:"m18.226 5.226-2.52-2.52A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-.351",key:"1k2beg"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}],["path",{d:"M8 18h1",key:"13wk12"}]]),ee=e("file-text",[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]),te=e("folder-open",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]),ne=e("folder-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"}]]),se=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"}]]),re=e("gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]),oe=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"}]]),ae=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"}]]),ce=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"}]]),le=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"}]]),de=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"}]]),ue=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"}]]),he=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"}]]),pe=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"}]]),fe=e("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),ge=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"}]]),ye=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"}]]),ve=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"}]]),be=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"}]]),xe=e("panel-left",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]),we=e("panel-right",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]),Se=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"}]]),ke=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"}]]),Ie=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"}]]),Ce=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"}]]),je=e("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),Re=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"}]]),Me=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"}]]),Ee=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"}]]),Te=e("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]),Ne=e("send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]),Ae=e("settings-2",[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]),Pe=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"}]]),De=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"}]]),Fe=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"}]]),Le=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"}]]),qe=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"}]]),Oe=e("square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]),$e=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"}]]),ze=e("terminal",[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]]),_e=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"}]]),Be=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"}]]),He=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"}]]),We=e("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),Ue=e("zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),Ke="vibelet.shortcuts.changed",Qe="vibelet.workspace.command",Ve=[{id:"leftSidebar",zh:"显示 / 隐藏左侧栏",en:"Toggle left sidebar",default:"mod+alt+["},{id:"rightSidebar",zh:"显示 / 隐藏右侧栏",en:"Toggle right sidebar",default:"mod+alt+]"},{id:"searchSessions",zh:"搜索会话",en:"Search sessions",default:"mod+shift+f"},{id:"searchMessages",zh:"搜索聊天内容",en:"Search conversation",default:"mod+f"},{id:"files",zh:"打开文件树",en:"Open files",default:"mod+alt+e"},{id:"terminal",zh:"打开终端",en:"Open terminal",default:"mod+j"},{id:"browser",zh:"打开浏览器",en:"Open browser",default:"mod+alt+b"},{id:"newTab",zh:"新建终端 / 浏览器标签",en:"New terminal / browser tab",default:"mod+t"},{id:"previousTab",zh:"上一个标签",en:"Previous tab",default:"mod+shift+["},{id:"nextTab",zh:"下一个标签",en:"Next tab",default:"mod+shift+]"},{id:"closeTab",zh:"关闭当前标签",en:"Close current tab",default:"mod+w"},{id:"moveTab",zh:"在中间区域与右侧栏间移动标签",en:"Move tab between workspace and sidebar",default:"mod+shift+m"},{id:"diff",zh:"查看 Git 变更",en:"View Git changes",default:"mod+alt+g"}];function Ge(){return/Mac|iPhone|iPad/.test(navigator.platform)}const Je={BracketLeft:"[",BracketRight:"]",Comma:",",Period:".",Slash:"/",Backslash:"\\",Minus:"-",Equal:"=",Space:"space"};function Ze(e,t=Ge()){const n=Je[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 Ye(e,t=Ge()){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 Xe(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":Ve.find(s=>s.id!==e&&function(e,t={}){return t[e]??Ve.find(t=>t.id===e).default}(s.id,n)===t)?.id??null:null}const et="vibelet.web.shortcuts";function tt(){try{const e=JSON.parse(t().getItem(et)||"{}");return Object.fromEntries(Ve.filter(t=>"string"==typeof e?.[t.id]).map(t=>[t.id,e[t.id]]))}catch{return{}}}function nt(e,t=tt()){return t[e]??("closeTab"===e&&"browser"===n().kind?"mod+alt+w":Ve.find(t=>t.id===e).default)}function st(e,t){const n=nt(t);return n?`${e} (${Ye(n)})`:e}const it="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",rt="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 ot(){const e=s(i().language);return"en"===e?{close:"Close",title:"Continue on your phone",free:"Mac and Web are free",description:"Step away from your desk. Check progress, respond to approvals and continue your sessions on your phone.",download:"Scan to install",ios:"Get the iPhone app",android:"Get the Android app",pairing:"Keep your computer running. On Mac, open Settings → Current device, enable phone access and generate a pairing code. Open Vibelet on your phone and scan it. For a CLI daemon, use the pairing code shown by npx vibelet.",pro:"Explore the mobile app first. Upgrade to Vibelet Pro on your phone when you need its advanced features. Existing mobile purchases can be restored there."}:"zh-TW"===e?{close:"關閉",title:"在手機上繼續",free:"Mac 與 Web 免費使用",description:"離開電腦,也能查看任務進度、處理審批,繼續同一段對話。",download:"掃碼安裝",ios:"取得 iPhone 版",android:"取得 Android 版",pairing:"保持電腦運行。在 Mac「設定 → 當前裝置」開啟手機存取並產生配對碼,再用手機 Vibelet 掃碼。使用 CLI 時,掃描 npx vibelet 顯示的配對碼。",pro:"先體驗手機端,需要進階功能時再於手機升級 Vibelet Pro。已有手機端購買可在手機恢復。"}:{close:"关闭",title:"在手机上继续",free:"Mac 与 Web 免费使用",description:"离开电脑,也能查看任务进度、处理审批,继续同一段对话。",download:"扫码安装",ios:"获取 iPhone 版",android:"获取 Android 版",pairing:"保持电脑运行。在 Mac「设置 → 当前设备」开启手机访问并生成配对码,再用手机 Vibelet 扫码。使用 CLI 时,扫描 npx vibelet 显示的配对码。",pro:"先体验手机端,需要高级功能时再在手机升级 Vibelet Pro。已有手机端购买可在手机恢复。"}}function at(){const e=ot();return r.jsxs("section",{className:"mobile-companion-panel control-section",children:[r.jsx("p",{className:"mobile-companion-free",children:e.free}),r.jsx("h2",{children:e.title}),r.jsx("p",{children:e.description}),r.jsx("div",{className:"mobile-companion-downloads",children:[{label:e.ios,qr:rt,url:"https://apps.apple.com/app/id6761245790"},{label:e.android,qr:it,url:"https://www.feishu.cn/file/RUnbb7INMocEFjxj5AWcC7WEn6d"}].map(t=>r.jsxs("div",{children:[r.jsx("img",{src:t.qr,alt:`${t.label} · ${e.download}`,width:"140",height:"140"}),r.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",children:t.label})]},t.url))}),r.jsx("p",{children:e.pairing}),r.jsx("p",{className:"mobile-companion-hint",children:e.pro})]})}function ct({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=ot().title;return a.createPortal(r.jsx("div",{className:"mobile-companion-backdrop",onClick:t=>{t.target===t.currentTarget&&e()},children:r.jsxs("section",{ref:t,className:"mobile-companion-dialog",role:"dialog","aria-modal":"true","aria-label":n,tabIndex:-1,onKeyDown:n=>{if("Escape"===n.key&&(n.preventDefault(),n.stopPropagation(),e()),"Tab"!==n.key)return;const s=Array.from(n.currentTarget.querySelectorAll("button,a[href]")),i=s[0],r=s.at(-1);!n.shiftKey||document.activeElement!==i&&document.activeElement!==t.current?n.shiftKey||document.activeElement!==r||(n.preventDefault(),i?.focus()):(n.preventDefault(),r?.focus())},children:[r.jsx("button",{type:"button",className:"icon-button mobile-companion-close","aria-label":ot().close,title:ot().close,onClick:e,children:r.jsx(We,{"aria-hidden":"true"})}),r.jsx(at,{})]})}),document.body)}function lt({activeSession:e,client:t,busy:s,controlsOpen:i,pendingCount:l=0,t:d,onOpenControls:u,onRefreshSessions:h,onRestoreSnapshot:p,onToggleArchived:m,onTogglePinned:f,onViewChanges:g}){const[y,v]=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=r.jsxs("div",{className:"header-actions",children:[e&&k.renderSessionShare?.(e,t),("desktop"!==k.kind||l>0)&&r.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:[r.jsx(O,{"aria-hidden":"true"}),l>0&&r.jsx("span",{className:"header-pending-count","aria-hidden":"true",children:l})]}),y&&r.jsx(ct,{onClose:()=>v(!1)}),e?null:r.jsx("button",{"aria-label":d.refreshSessions,className:"icon-button",onClick:h,title:d.refreshSessions,type:"button",children:r.jsx(Re,{"aria-hidden":"true"})}),r.jsx("button",{"aria-expanded":i,"aria-label":i?d.collapseControlsSidebar:d.workspaceTools,title:st(i?d.collapseControlsSidebar:d.workspaceTools,"rightSidebar"),className:"header-tool-button",onClick:u,type:"button",children:r.jsx(we,{"aria-hidden":"true"})}),e||k.openSettings?r.jsxs("div",{className:"header-more-wrap",ref:w,children:[r.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:r.jsx(J,{"aria-hidden":"true"})}),b?r.jsxs("div",{className:"header-action-menu",role:"menu",children:["desktop"===k.kind&&0===l&&r.jsxs("button",{role:"menuitem",type:"button",onClick:()=>S(()=>window.dispatchEvent(new Event("vibelet.pending.open"))),children:[r.jsx(O,{"aria-hidden":"true"}),r.jsx("span",{children:d.pendingActionCount(l)})]}),e&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:()=>S(()=>g(e.sessionId)),role:"menuitem",type:"button",children:[r.jsx(oe,{"aria-hidden":"true"}),r.jsx("span",{children:d.viewChanges})]}),r.jsxs("button",{disabled:s,onClick:()=>S(f),role:"menuitem",type:"button",children:[r.jsx(Ie,{"aria-hidden":"true"}),r.jsx("span",{children:e.pinned?d.unpin:d.pin})]}),r.jsxs("button",{disabled:s,onClick:()=>S(m),role:"menuitem",type:"button",children:[r.jsx(P,{"aria-hidden":"true"}),r.jsx("span",{children:e.archived?d.unarchive:d.archive})]}),r.jsxs("button",{onClick:()=>S(p),role:"menuitem",type:"button",children:[r.jsx(Me,{"aria-hidden":"true"}),r.jsx("span",{children:d.restoreSnapshot})]})]}),r.jsxs("button",{role:"menuitem",type:"button",onClick:()=>S(()=>v(!0)),children:[r.jsx(c,{"aria-hidden":"true"}),r.jsx("span",{children:ot().title})]}),r.jsxs("button",{onClick:()=>S(h),role:"menuitem",type:"button",children:[r.jsx(Re,{"aria-hidden":"true"}),r.jsx("span",{children:d.refreshSessions})]})]}):null]}):null]}),C=k.toolbarTarget?.("right");return C?a.createPortal(I,C):I}function dt({title:e,hint:t}){return r.jsxs("div",{className:"empty-state compact",children:[r.jsx(De,{"aria-hidden":"true"}),r.jsx("h2",{children:e}),r.jsx("p",{children:t})]})}function ut(e,t,n,s,i,r,a){const c=JSON.stringify([t,n,s,i]),[l,d]=o.useState(null);if(o.useEffect(()=>{if("codex"!==t||!e)return;let i,r=!1,o=0,a=0,l=!1,u=!1;const h=()=>{r||u||l||void 0!==i||a>=5||(i=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 m=e.onMessage(e=>{r||"session.model"!==e.type||e.sessionId!==s||(o++,clearTimeout(i),i=void 0,p(e),h())}),f=e.onClose(()=>{r=!0,clearTimeout(i),d({client:e,key:c,state:null,loading:!1})});async function g(){if(i=void 0,r||!e)return;l=!0,a++;const t=o;try{const i=await e.request({action:"model.status",id:e.makeId("model-status"),...s?{sessionId:s}:{cwd:n}},{timeoutMs:15e3});r||o!==t||p(i)}catch{r||o!==t||p(null)}finally{l=!1,h()}}return i=setTimeout(g,200),()=>{r=!0,clearTimeout(i),m(),f()}},[e,t,n,s,i,c]),"codex"!==t)return r;const u=l&&l.client===e&&l.key===c?l:null,h={value:"",label:`CLI · ${u?.state?.defaultModel||(!e||u&&!u.loading?a.unknown:a.remoteModelChecking)}`,desc:"config"===u?.state?.defaultSource?a.remoteModelConfig:"recommended"===u?.state?.defaultSource?a.remoteModelRecommended:a.unknown};return r.some(e=>""===e.value)?r.map(e=>""===e.value?{...e,...h}:e):[h,...r]}function ht(e,t){return!t.altKey&&(!(!t.metaKey&&!t.ctrlKey)||("enter"===e?!t.shiftKey:"shiftEnter"===e&&t.shiftKey))}const pt=/^[A-Za-z][A-Za-z0-9_-]*$/,mt=[{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 ft(e){return mt.filter(t=>!e||t.agents.includes(e))}function gt(e){return e.trim().toLowerCase()}function yt(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&&!pt.test(n)?null:{start:0,end:e.length,keyword:gt(n)}}function vt(e,t){return e.name===t?0:e.name.startsWith(t)?1:e.name.includes(t)?2:3}function bt(e,t){const n=t.length>0,s=n&&!/^\s/.test(t),i=Boolean(e.argsHint&&!n);return`/${e.name}${i||s?" ":""}`}function xt(e,t){const n=e.trim();if(!n.startsWith("/")||n.startsWith("//"))return null;const s=/^\/([A-Za-z][A-Za-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(n);if(!s)return null;const i=gt(s[1]??""),r=ft(t).find(e=>e.name===i);if(!r)return null;const o=s[2]?.trim()??"";switch(r.commandName){case"clear":return{raw:n,command:{name:"clear"}};case"new":return{raw:n,command:{name:"new"}};case"exit":return{raw:n,command:{name:"exit"}};case"compact":return{raw:n,command:{name:"compact"}};case"goal":{const e=o.toLowerCase();return o&&"status"!==e&&"show"!==e&&"usage"!==e&&"help"!==e?"clear"===e||"reset"===e?{raw:n,command:{name:"goal",operation:"clear"}}:"pause"===e||"paused"===e?{raw:n,command:{name:"goal",operation:"pause"}}:"resume"===e||"active"===e?{raw:n,command:{name:"goal",operation:"resume"}}:{raw:n,command:{name:"goal",operation:"set",objective:o}}:{raw:n,command:{name:"goal",operation:"status"}}}}}function wt(e){return"subscriptionRequired"===e?"Error: Agent commands require an active Pro subscription.":`Error: ${e||"Command failed."}`}const St=/^[A-Za-z_][A-Za-z0-9._:-]*$/,kt=/(?:^|\s)\$([A-Za-z_][A-Za-z0-9._:-]*|)$/;function It(e){return e.trim().toLowerCase()}function Ct(e){const t=e.trim(),n=/^\$([A-Za-z_][A-Za-z0-9._:-]*)(?:\s+([\s\S]*))?$/.exec(t);return n?{name:It(n[1]??""),...n[2]?.trim()?{args:n[2].trim()}:{}}:null}function jt(e){const t=kt.exec(e);if(!t||t.index+t[0].length!==e.length)return null;const n=t[1]??"";if(n&&!St.test(n))return null;const s=t[0].lastIndexOf("$");return{start:t.index+s,end:e.length,keyword:It(n)}}const Rt=new RegExp("((?:~/|/|\\.{1,2}/|[A-Za-z0-9._-]+/)[^\\n`<>\"')\\]},。!?;:、]*?\\.(?:png|jpg|jpeg|gif|webp|svg|heic|heif)(?::\\d+(?::\\d+)?|#[^\\s`<>\"')\\]},。!?;:、]+)?)","gi"),Mt=[".png",".jpg",".jpeg",".gif",".webp",".svg",".heic",".heif"],Et="\\s`<>\"')\\]},。!?;:、",Tt="`<>\"')\\]},。!?;:、\\n\\r\\t",Nt=new RegExp(`(^|[\\s([{>])((?:~\\/|\\/|\\.{1,2}\\/)[^${Et}]+|[A-Za-z0-9._-]+(?:\\/[A-Za-z0-9._-]+)+(?:\\.[A-Za-z0-9._-]+)?\\/?)`,"g"),At=new RegExp(`(^|[\\s([{>])((?=[^${Tt}]*\\/)[^${Tt}]+?\\.[A-Za-z0-9._-]+(?::\\d+(?::\\d+)?|#[^${Et}]+)?)(?=$|[${Et}])`,"g");function Pt(e){let t=e;for(;/[.,!?;:,。!?;:、]+$/.test(t);)t=t.slice(0,-1);return t}function Dt(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 Ft(e){let t=Pt(e.trim());if(!t)return"";const n=t.indexOf("#");if(n>0){const e=t.slice(0,n);Dt(e,{allowBareFilename:!0})&&(t=e)}const s=t.match(/^(.*?)(:\d+(?::\d+)?)$/);if(s){const e=s[1]??"";Dt(e,{allowBareFilename:!0})&&(t=e)}return Pt(t)}function Lt(e,t){return e.start<t.end&&t.start<e.end}function qt(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 Ot(e){if(qt(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(qt(n))return{start:e.start+t,end:e.end,rawCandidate:n}}return e}function $t(e,t){return Dt(Ft(e),t)}function zt(e){const t=Ft(e).toLowerCase();return $t(t,{allowBareFilename:!0})&&Mt.some(e=>t.endsWith(e))}function _t(e){return/^[a-zA-Z0-9._/@~-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function Bt(e){return Boolean(e.sessionId.trim())&&!e.sessionId.startsWith("pending_")}function Ht(e,t={}){return Bt(e)?`cd ${_t(e.cwd||".")} && ${function(e,t={}){if(!Bt(e))return"";const n=e.approvalMode??e.observedApprovalMode,s="claude"===e.agent?["claude","--resume",e.sessionId]:["codex","resume",e.sessionId],i=t.codexBackend??e.runtime?.codexBackend;return"codex"!==e.agent||"standalone"!==i&&(i||"@vibelet/cli"!==e.originator)||s.push("--no-daemon"),"autoApprove"===n?s.push("claude"===e.agent?"--dangerously-skip-permissions":"--dangerously-bypass-approvals-and-sandbox"):"claude"===e.agent&&"acceptEdits"===n&&s.push("--permission-mode","acceptEdits"),[...t.vibeletChannel?["npx",`vibelet@${t.vibeletChannel}`]:[],...s].map(_t).join(" ")}(e,t)}`:""}const Wt="vibelet.web.notificationSettings",Ut={enabled:!1,approvals:!0,questions:!0,replies:!0,hiddenOnly:!0};function Kt(e=t()){try{const t=e.getItem(Wt);if(!t)return{...Ut};const n=JSON.parse(t);return Bn(n)?{enabled:"boolean"==typeof n.enabled?n.enabled:Ut.enabled,approvals:"boolean"==typeof n.approvals?n.approvals:Ut.approvals,questions:"boolean"==typeof n.questions?n.questions:Ut.questions,replies:"boolean"==typeof n.replies?n.replies:Ut.replies,hiddenOnly:"boolean"==typeof n.hiddenOnly?n.hiddenOnly:Ut.hiddenOnly}:{...Ut}}catch{return{...Ut}}}function Qt(e=("undefined"==typeof Notification?void 0:Notification)){return n().notifications?n().notifications.permission():e?.permission??"unsupported"}function Vt(e){return"user"===e.role&&e.images?.length?e.content.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").trim():e.content}function Gt(e,t){return e.role===t.role&&(e.type??"message")===(t.type??"message")&&Vt(e)===Vt(t)&&JSON.stringify(e.images??[])===JSON.stringify(t.images??[])&&e.toolName===t.toolName&&JSON.stringify(e.toolInput)===JSON.stringify(t.toolInput)}function Jt(e,t){if(t.historyKey?.startsWith("client:")||!e.historyKey?.startsWith("client:")||!e.localClientMessageId||"user"!==e.role||"user"!==t.role||!Gt(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 Zt(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??"")&&Gt(e,t)}function Yt(e){for(let t=e.length-1;t>=0;t-=1)if("user"===e[t]?.role)return t;return-1}function Xt(e,t,n){let s=e.slice();const i=new Set,r=s.flatMap((e,t)=>e.localClientMessageId&&e.historyKey?.startsWith("client:")?[t]:[]),o=new Map;r.length&&s.forEach((e,t)=>{const n=Date.parse(e.timestamp??"");if(e.historyKey?.startsWith("client:")||!Number.isFinite(n))return;const s=`${e.role}:${n}`,i=o.get(s)??[];i.push(t),o.set(s,i)});for(const d of t){const e=o.get(`${d.role}:${Date.parse(d.timestamp??"")}`)?.find(e=>Zt(s[e],d))??-1;if(e<0||s[e].localClientMessageId)continue;const t=r.find(e=>!i.has(e)&&Jt(s[e],d)&&Date.parse(s[e].timestamp)<=Date.parse(d.timestamp));if(void 0===t)continue;const n=s[e].historyKey;s[e]={...s[t],...s[e],localDelivery:"delivered"},n||delete s[e].historyKey,i.add(t)}i.size&&(s=s.filter((e,t)=>!i.has(t)));const a=new Map,c=[];s.forEach((e,t)=>{e.historyKey&&!a.has(e.historyKey)&&a.set(e.historyKey,t),e.historyKey&&!e.historyKey.startsWith("client:")||c.push(t)});const l=new Set;for(const d of t){const e=d.historyKey?a.get(d.historyKey)??-1:-1;if(e>=0){d.delivery&&(s[e]={...s[e],...d,localDelivery:"delivered"}),n?.(d,s[e]);continue}const t=(d.historyKey?c:s.map((e,t)=>t)).find(e=>{const t=s[e];return!l.has(e)&&(!!Zt(t,d)||!!Jt(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===Yt(s)&&s.slice(e+1).every(e=>"assistant"!==e.role||"info"===e.type||e.liveReply)&&Gt(t,d))))})??-1;if(t<0)d.historyKey&&a.set(d.historyKey,s.length),d.historyKey&&!d.historyKey.startsWith("client:")||c.push(s.length),s.push({...d});else{l.add(t);const e=s[t].historyKey;e&&e!==d.historyKey&&a.delete(e);const i=!d.historyKey&&Jt(s[t],d);s[t]={...s[t],...d},i&&(delete s[t].historyKey,s[t].localDelivery="delivered"),s[t].historyKey&&a.set(s[t].historyKey,t),s[t].localClientMessageId&&d.historyKey&&!d.historyKey.startsWith("client:")&&(s[t].localDelivery="delivered"),delete s[t].liveReply,n?.(d,s[t])}}return s}function en(e){const t=e.at(-1);return"assistant"===t?.role&&"info"!==t.type?[...e.slice(0,-1),{...t,liveReply:!0}]:e.slice()}function tn(e,t){if(!t?.trim())return e.slice();let n=-1;for(let a=e.length-1;a>=0;a--)if("user"===e[a]?.role){n=a;break}const s=[];for(let a=n+1;a<e.length;a++)"assistant"===e[a]?.role&&"info"!==e[a]?.type&&s.push(a);const i=s.at(-1),r=void 0!==i&&e.slice(i+1).some(e=>"tool"===e.role);let o=t;for(const a of s){if(a===i&&!r)break;const t=e[a].content;if(t.trim().startsWith(o.trim()))return e.slice();if(!t||!o.startsWith(t))break;if(o=o.slice(t.length),!o.trim())return e.slice()}if(void 0!==i&&!r){const t=e[i],n=t.content.trim().startsWith(o.trim())?t.content:o,s=e.slice();return s[i]={...t,content:n},en(s)}return en([...e,{role:"assistant",content:o,timestamp:(new Date).toISOString()}])}function nn(e,t,n){const s=n?.[e.sessionId];return void 0!==s?s:"boolean"==typeof e.pinned?e.pinned:Boolean(t?.[e.sessionId])}function sn(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 rn(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 on(e,t,n){if(0===t.length)return e;const s=new Set(t),i=[];for(const r of t){const e=n.get(r);e&&i.push(e)}for(const r of e)s.has(r.sessionId)||i.push(r);if(i.length!==e.length)return i;for(let r=0;r<e.length;r+=1)if(i[r]!==e[r])return i;return e}function an(e,t=Date.now(),n=l){if(!e)return n.timeUnknown;const s=Date.parse(e);if(!Number.isFinite(s))return n.timeUnknown;const i=t-s,r=36e5,o=24*r;return i<6e4?n.timeNow:i<r?n.timeMinutesAgo(Math.floor(i/6e4)):i<o?n.timeHoursAgo(Math.floor(i/r)):n.timeDaysAgo(Math.floor(i/o))}function cn(e,t){return"info"===e.type?t.messageInfoRole:{user:t.messageUserRole,assistant:t.messageAssistantRole,tool:t.messageToolRole}[e.role]}const ln="<oai-mem-citation>";function dn(e){let t,n=0;for(const s of e.split("\n")){const i=/^ {0,3}(`{3,}|~{3,})(.*)$/.exec(s);if(i){const e=i[1][0];t?e===t.marker&&i[1].length>=t.length&&!i[2].trim()&&(t=void 0):t={marker:e,length:i[1].length}}else if(!t){const t=s.replace(/^ {0,3}/,""),i=t.startsWith("<oai-mem")&&ln.startsWith(t);if(t.startsWith(ln)||i){const t=e.slice(n).trimStart(),s=t.indexOf("</oai-mem-citation>");if(s<0||!t.slice(s+19).trim())return e.slice(0,n).trimEnd()}}n+=s.length+1}return e}const un=e=>e.replace(/\r\n?/g,"\n").trim(),hn=/^\[Attached image: ([^\n]+)\]$/gm;function pn(e){return"codex"===e?"Codex":"claude"===e?"Claude":e}function mn(e){const t=[],n=new Set;for(const s of e.matchAll(hn)){const e=s[1];e&&0!==e.trim().length&&!n.has(e)&&(n.add(e),t.push(e))}return t}function fn(e,t){if("assistant"===e.type)return un(e.content);const n=un(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}([...mn(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 gn="pair",yn="vibelet.web.pairing",vn="vibelet.web.deviceId";class bn extends Error{constructor(e,t){super(t),this.code=e,this.name="PairingCreateError"}}function xn(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function wn(e){const[t,n,s,i,r,o]=e;return!n||!Number.isFinite(s)||s<=0?null:{kind:"relay"===t?"relay":"direct",host:n,port:Math.floor(s),source:i,stability:r,...!0===o?{secure:!0}:{}}}function Sn(e){if(!xn(e))return null;const{kind:t,host:n,port:s,source:i,stability:r,secure:o}=e;return"direct"!==t&&"relay"!==t||"string"!=typeof n||!n.trim()||"number"!=typeof s||!Number.isFinite(s)||s<=0||"string"!=typeof i||"string"!=typeof r?null:{kind:t,host:n.trim(),port:Math.floor(s),source:i,stability:r,...!0===o?{secure:!0}:{}}}function kn(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 In(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 Cn(e){return function(e){const t=e.trim().split(".");if(4!==t.length)return!1;const n=t.map(e=>/^\d+$/.test(e)?Number(e):Number.NaN);if(n.some(e=>!Number.isInteger(e)||e<0||e>255))return!1;const[s,i]=n;return 10===s||172===s&&i>=16&&i<=31||192===s&&168===i}(e.host)?0:"local_network"===e.source?1:"configured_host"===e.source?2:3}function jn(e,t){const n=t?.port??e.port,s=t?.canonicalHost??e.canonicalHost;if(!s||"number"!=typeof n||!Number.isFinite(n))return[];const i=Math.floor(n);return[{kind:"direct",host:s,port:i,source:"fallback",stability:"stable"},...[...t?.fallbackHosts??[],...e.fallbackHosts??[]].map(e=>({kind:"direct",host:e,port:i,source:"fallback",stability:"stable"}))]}function Rn(e,t,n=window.location,s=!0){if(s&&kn(n.hostname))return;const i=[...t?.connections??[],...e.connections??[],...jn(e,t)].map(Sn).filter(e=>Boolean(e)).filter(e=>"direct"===e.kind).sort((e,t)=>Cn(e)-Cn(t));for(const r of i){const e=In(r,n);if(e)return e}}function Mn(e=window.location.hash){const t=e.startsWith("#")?e.slice(1):e,n=new URLSearchParams(t).get(gn);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(!xn(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(wn).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 En(e){const t=e.getItem(yn);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 Tn(e){if("undefined"==typeof window)return null;try{return e===t()?window.sessionStorage:null}catch{return null}}function Nn(e=t(),n=Tn(e)){const s=En(e);if(s)return s;const i=n?En(n):null;return i?(e.setItem(yn,JSON.stringify(i)),n?.removeItem(yn),i):null}function An(e,n=t(),s=Tn(n)){n.setItem(yn,JSON.stringify(e)),s?.removeItem(yn)}function Pn(e=t(),n=Tn(e)){e.removeItem(yn),n?.removeItem(yn)}async function Dn(e,n){try{return await async function(e,n=function(e=t()){const n=e.getItem(vn);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(vn,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 bn("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(xn(e)&&"pair_window_expired"===e.error)return new bn("pair_window_expired","Pairing link expired.")}catch{}return new bn("pairing_failed",t||"Pairing failed.")}(s);const i=await s.json();return{daemonId:i.daemonId,displayName:i.displayName||e.displayName,deviceId:i.deviceId,pairToken:i.pairToken,pairedAt:(new Date).toISOString(),webSocketUrl:Rn(e,i,window.location,!0)}}(e,n?.deviceId)}catch(s){if(s instanceof bn&&"pair_window_expired"===s.code&&n?.daemonId===e.daemonId)return n;throw s}}class Fn{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 Ln extends Error{name="VibeletRequestRejectedError"}function qn(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}class On{heartbeat=new Fn;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&&kn(t.hostname)?s:e?.webSocketUrl?e.webSocketUrl:s}(e));let n;this.socket=t;const s=new Promise((e,s)=>{n=s,t.onopen=()=>e(),t.onerror=()=>s(new Error("WebSocket connection failed."))});if(t.onmessage=e=>{this.socket===t&&this.handleSocketMessage(e.data)},t.onclose=()=>{n(new Error("WebSocket disconnected.")),this.socket===t&&(this.heartbeat.stop(),this.authenticated=!1,this.authentication=null,this.socket=null,this.rejectPending(new Error("WebSocket disconnected.")),this.closeListeners.forEach(e=>e()))},await s,this.socket!==t)throw new Error("WebSocket disconnected.");const i=await this.requestOnSocket({action:"auth.hello",id:qn("auth"),pairToken:e.pairToken,daemonId:e.daemonId,deviceId:e.deviceId,locale:navigator.language});if(this.socket!==t)throw new Error("WebSocket disconnected.");return this.authenticated=!0,this.capabilities=i.capabilities??{},this.heartbeat.start(()=>t.send(JSON.stringify({action:"ping"})),()=>t.close()),i}async request(e,t={}){const n=this.socket;if(!this.authenticated){if(!this.authentication)throw new Error("WebSocket is not connected.");await this.authentication}if(this.socket!==n||!this.isConnected)throw new Error("WebSocket disconnected.");return this.requestOnSocket(e,t)}requestOnSocket(e,t={}){return this.socket&&this.socket.readyState===WebSocket.OPEN?new Promise((n,s)=>{const i={action:e.action,resolve:n,reject:s};t.timeoutMs&&t.timeoutMs>0&&(i.timeoutId=setTimeout(()=>{this.pending.delete(e.id),s(new Error(t.timeoutMessage||`Request timed out (${e.action}).`))},t.timeoutMs)),this.pending.set(e.id,i),this.socket?.send(JSON.stringify(e))}):Promise.reject(new Error("WebSocket is not connected."))}send(e){this.isConnected&&this.socket?.send(JSON.stringify(e))}onMessage(e){return this.messageListeners.add(e),()=>this.messageListeners.delete(e)}onClose(e){return this.closeListeners.add(e),()=>this.closeListeners.delete(e)}get supportsSessionSteer(){return this.isConnected&&!0===this.capabilities.sessionSteer}get supportsQueueSendNow(){return this.isConnected&&!0===this.capabilities.queueSendNow}disconnect(){this.heartbeat.stop(),this.authenticated=!1,this.authentication=null,this.capabilities={},this.rejectPending(new Error("WebSocket disconnected."));const e=this.socket;this.socket=null,e?.close(1e3,"client disconnect")}get isConnected(){return this.authenticated&&this.socket?.readyState===WebSocket.OPEN}makeId(e){return qn(e)}handleSocketMessage(e){if("string"!=typeof e)return;let t;try{t=JSON.parse(e)}catch{return}if("pong"!==t.type){if("error"===t.type&&!t.sessionId){const e=/unsupported action "([^"]+)"/.exec(t.message)?.[1];if(e){let n=!1;for(const[s,i]of this.pending)i.action===e&&(this.pending.delete(s),i.timeoutId&&clearTimeout(i.timeoutId),i.reject(new Ln(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 Ln(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 $n(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 zn=".",_n="normal";function Bn(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function Hn(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 Wn(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 Un(e){const t=e;return{sessions:Array.isArray(t.sessions)?t.sessions:[],nextCursor:$n(t.nextCursor),inventoryVersion:t.inventoryVersion,inventoryBackfillInFlight:t.inventoryBackfillInFlight,folderCounts:t.folderCounts}}function Kn(e){return e.split("/").filter(Boolean).at(-1)??e}function Qn(e){return 0===Object.entries(e).length?"No structured input.":JSON.stringify(e,null,2)}function Vn(e){return Object.fromEntries(e.questions.map(e=>[e.id,e.options[0]?[e.options[0].label]:[]]))}function Gn(e){return e.trim()||void 0}function Jn(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 Zn(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 Yn=0;function Xn(e,t,n=(new Date).toISOString()){return{...e,sessionId:t,lastActivityAt:n}}function es(e,t,n){if(!t||!n||t===n||!Object.hasOwn(e,t))return e;const{[t]:s,...i}=e;return{...i,[n]:s}}function ts(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 ns(e,t){const n=e.replace(/\\/g,"/").replace(/\/+$/,"");return n&&"."!==n?`${n}/${t}`:t}function ss(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 is(e,t){return t.startsWith("image/")||/\.(png|jpe?g|gif|webp|heic|heif|svg)$/i.test(e)}function rs(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 os(e,t){return e.get(t)||void 0}function as(e,t){if("subscriptionRequired"===e){const e="undefined"==typeof window?"en":s(i().language);return"en"===e?"Computer features are free. Update Vibelet on the paired computer and reconnect.":"zh-TW"===e?"電腦端功能免費。請更新配對電腦上的 Vibelet,再重新連線。":"电脑端功能免费。请更新配对电脑上的 Vibelet,再重新连接。"}return"skillNotFound"===e?"Skill not found on the paired computer.":"skillResolveFailed"===e?"Could not load the skill on the paired computer.":e}const cs="vibelet:image-gallery";function ls(e){window.dispatchEvent(new CustomEvent(cs,{detail:e}))}const ds=/^[a-z][a-z0-9+.-]*:/i,us=/^[a-z]:[\\/]/i,hs=/\.(?:md|markdown)$/i,ps="https://vibelet.local",ms="/__vibelet_markdown__",fs=`${ps}${ms}`;function gs(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!==ps)return null;if(t.pathname!==ms)return null;const n=t.searchParams.get("path");return n&&hs.test(n)?n:null}(t);if(n)return n;if(ds.test(t)&&!us.test(t))return null;const s=t.split(/[?#]/,1)[0]??"";return hs.test(s)?function(e){try{return decodeURIComponent(e)}catch{return e}}(s):null}function ys(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=vs(e,n);t+=e.slice(n,s),n=s;continue}if("["===e[n]&&"!"!==e[n-1]){const s=bs(e,n);if(s){t+=s.text,n=s.end;continue}}t+=e[n],n+=1}return t}(e)}).join("\n")}function vs(e,t){let n=0;for(;"`"===e[t+n];)n+=1;const s="`".repeat(n),i=e.indexOf(s,t+n);return i<0?e.length:i+n}function bs(e,t){const n=function(e,t){let n=!1;for(let s=t+1;s<e.length;s+=1){const t=e[s];if(n)n=!1;else if("\\"!==t){if("]"===t)return s}else n=!0}return-1}(e,t);if(n<0||"("!==e[n+1])return null;const s=n+2,i=function(e,t){let n=!1;for(let s=t;s<e.length;s+=1){const t=e[s];if(n)n=!1;else if("\\"!==t){if(")"===t)return s}else n=!0}return-1}(e,s);if(i<0)return null;const r=function(e){const t=e.match(/^\s*/)?.[0]??"",n=e.match(/\s*$/)?.[0]??"",s=e.slice(t.length,e.length-n.length);if(s.startsWith("<")){const e=s.indexOf(">");if(e<0)return null;const i=xs(s.slice(1,e));return i?`${t}<${i}>${s.slice(e+1)}${n}`:null}const i=s.match(/^(\S+)([\s\S]*)$/);if(!i)return null;const r=xs(i[1]);return r?`${t}${r}${i[2]}${n}`:null}(e.slice(s,i));return r?{text:`${e.slice(t,s)}${r})`,end:i+1}:null}function xs(e){const t=gs(e);return t?`${fs}?path=${encodeURIComponent(t)}`:null}const ws="https://vibelet.local/__vibelet_file__";function Ss(e){if(!e)return null;const t=gs(e);if(t)return t;let n=e.trim();if(n.startsWith(ws))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=Ft(n),$t(n,{allowBareFilename:!0})?n:null}const ks=e=>`${ws}?path=${encodeURIComponent(e)}`;function Is(e){return e.value??e.children?.map(Is).join("")??""}function Cs(){return e=>{const t=e=>{if("link"===e.type||"image"===e.type){const t=Ss(e.url);return void(t&&(e.url=ks(t),zt(t)&&(e.alt=e.alt||Is(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)?(?=/))?${Rt.source}`,Rt.flags);let s=0;const i=e=>{for(const n of function(e){if(!e)return[];const t=[];let n=0;for(const s of function(e){const t=[];for(const n of e.matchAll(Nt)){const e=n[1]??"",s=n[2]??"",i=(n.index??0)+e.length;t.push({start:i,end:i+s.length,rawCandidate:s})}for(const n of e.matchAll(At)){const e=n[1]??"",s=n[2]??"",i=(n.index??0)+e.length,r=Ot({start:i,end:i+s.length,rawCandidate:s}),o=t.filter(e=>Lt(e,r));if(0!==o.length){if(qt(r.rawCandidate)){for(const e of o){const n=t.indexOf(e);n>=0&&t.splice(n,1)}t.push(r)}}else t.push(r)}return t.sort((e,t)=>e.start-t.start||e.end-t.end)}(e)){s.start>n&&t.push({type:"text",value:e.slice(n,s.start)});const i=Pt(s.rawCandidate),r=Ft(i),o=s.rawCandidate.slice(i.length);$t(i)&&!zt(i)?(t.push({type:"path",value:i,target:r||i}),o&&t.push({type:"text",value:o})):t.push({type:"text",value:s.rawCandidate}),n=s.end}return n<e.length&&t.push({type:"text",value:e.slice(n)}),t.length>0?t:[{type:"text",value:e}]}(e))t.push("path"===n.type?{type:"link",url:ks(n.target??n.value),children:[{type:"text",value:n.value}]}:{type:"text",value:n.value})};for(const r of e.matchAll(n)){const n=Ss(r[0]);n&&zt(n)&&(i(e.slice(s,r.index)),t.push({type:"image",url:ks(n),alt:n.split(/[\\/]/).at(-1)}),s=r.index+r[0].length)}return i(e.slice(s)),t}(e.value??""):(t(e),[e])))};t(e)}}const js=20971520,Rs=new class{constructor(e=128,t=67108864,n=3e4){this.maxEntries=e,this.maxBytes=t,this.ttl=n}scope="";bytes=0;entries=new Map;get(e,t,n){this.scope!==e&&(this.entries.clear(),this.bytes=0,this.scope=e);for(const[r,o]of this.entries)o.expires<=Date.now()&&this.remove(r,o);const s=this.entries.get(t);if(s)return this.entries.delete(t),this.entries.set(t,s),s.promise;const i={promise:Promise.resolve(new Blob),bytes:0,expires:1/0};return i.promise=Promise.resolve().then(n).then(e=>(this.entries.get(t)===i&&(i.bytes=e.size,i.expires=Date.now()+this.ttl,this.bytes+=e.size,this.trim()),e),e=>{throw this.remove(t,i),e}),this.entries.set(t,i),this.trim(),i.promise}remove(e,t){this.entries.get(e)===t&&(this.entries.delete(e),this.bytes-=t.bytes)}trim(){for(;this.entries.size>this.maxEntries||this.bytes>this.maxBytes;){const e=this.entries.entries().next().value;if(!e)return;this.remove(...e)}}};function Ms(e,t){return Rs.get(t,e,async()=>{const n=await fetch(e,{headers:{authorization:`Bearer ${t}`}});if(!n.ok||Number(n.headers.get("content-length"))>js)throw new Error("Image unavailable");const s=await n.blob();if(!s.type.startsWith("image/")||s.size>js)throw new Error("Unsupported image");return s})}function Es(e,t,n=1600){const s=Ss(e),i=Nn(),[r,a]=o.useState(null),[c,l]=o.useState(null);return o.useEffect(()=>{if(!s)return;const r=new AbortController;let o;return a(null),l(null),(async()=>{try{if(!i)throw new Error("No pairing");const c=new URL(rs(s,t));null!==n&&c.searchParams.set("w",String(n));const l=await Ms(c.toString(),i.pairToken);if(r.signal.aborted)return;o=URL.createObjectURL(l),a({src:e,url:o})}catch{r.signal.aborted||l(e)}})(),()=>{r.abort(),o&&URL.revokeObjectURL(o)}},[e,s,t,n,i?.pairToken,i?.webSocketUrl]),{url:s?r?.src===e?r.url:void 0:e,error:c===e,fail:()=>l(e)}}function Ts({src:e,alt:t,cwd:n,onOpen:o,gallery:a}){const c=Ss(e),{url:l,error:d,fail:h}=Es(e,n),p=u[s(i().language)],m=t||Kn(c??e);return r.jsx("button",{className:"message-image-preview","data-image-src":e,"data-image-cwd":n,type:"button",title:c??e,"aria-label":`${p.preview}: ${m}`,onClick:async t=>{t.preventDefault(),t.stopPropagation();const s=await(a?.())??[{src:e,alt:m,cwd:n}],i=s.findIndex(t=>t.src===e||c&&Ss(t.src)===c);ls({images:i<0?[{src:e,alt:m,cwd:n}]:s,index:Math.max(0,i),onOpen:o})},children:d?r.jsxs("span",{className:"message-image-placeholder",children:[r.jsx(de,{"aria-hidden":"true"}),m," · ",p.fileOpenFailed]}):l?r.jsx("img",{src:l,alt:m,loading:"lazy",onError:h}):r.jsxs("span",{className:"message-image-placeholder",children:[r.jsx(fe,{className:"session-running-icon","aria-hidden":"true"}),m]})})}function Ns({attachments:e,uploadBusy:t,onRemove:n,onOpen:s,t:i}){if(!e.length&&!t)return null;const o=e.filter(e=>e.type.startsWith("image/")||zt(e.path)||zt(e.name)),a=()=>o.map(e=>({src:e.path,alt:e.name||Kn(e.path)}));return r.jsxs("div",{className:"attachment-row composer-attachments",children:[e.length>0&&r.jsx("div",{className:"composer-attachment-images",children:e.map(e=>{const t=e.name||Kn(e.path),c=o.includes(e);return r.jsxs("div",{className:"composer-attachment-card "+(c?"composer-image-card":"composer-file-card"),children:[c?r.jsx(Ts,{src:e.path,alt:t,onOpen:s,gallery:a}):r.jsxs("button",{className:"composer-file-preview",type:"button",title:`${t} · ${Hn(e.size)}`,"aria-label":`${i.preview}: ${t}`,onClick:()=>s(e.path),children:[r.jsx(Se,{"aria-hidden":"true"}),r.jsx("span",{children:t}),r.jsx("small",{children:Hn(e.size)})]}),r.jsx("button",{className:"composer-image-remove",type:"button",title:`${i.removeAttachment}: ${t}`,"aria-label":`${i.removeAttachment}: ${t}`,onClick:()=>n(e.path),children:r.jsx(We,{"aria-hidden":"true"})})]},e.path)})}),t&&r.jsxs("span",{className:"attachment-empty",role:"status",children:[r.jsx("span",{className:"loading-spinner small","aria-hidden":"true"}),i.uploading]})]})}function As(e,t,n,s){const[i,r]=o.useState({left:16,top:16,maxHeight:240});return o.useLayoutEffect(()=>{if(!e)return;const i=()=>{const e=t.current?.getBoundingClientRect(),i=n.current;if(!e||!i)return;const o=i.getBoundingClientRect().width,a=Math.max(80,e.top-24),c=Math.min(i.scrollHeight,a);r({left:Math.max(16,Math.min("right"===s?e.right-o:e.left,innerWidth-o-16)),top:Math.max(16,e.top-c-8),maxHeight:a})};i();const o="undefined"==typeof ResizeObserver?null:new ResizeObserver(i);return n.current&&o?.observe(n.current),window.addEventListener("resize",i),document.addEventListener("scroll",i,!0),()=>{o?.disconnect(),window.removeEventListener("resize",i),document.removeEventListener("scroll",i,!0)}},[e,t,n,s]),i}function Ps({icon:e,label:t,menuLabel:n,options:s,value:i,onSelect:c,align:l="left",disabled:d,selected:u,wide:h,blendBackground:p,portal:m=!1,tooltipHoverDelay:f}){const[g,y]=o.useState(!1),v=o.useRef(null),b=o.useRef(null),x=o.useRef(null),w=As(g&&m,x,b,l),S=s.some(e=>e.icon);o.useEffect(()=>{if(!g)return;const e=b.current?.querySelectorAll('[role="menuitemradio"]:not(:disabled)'),t=[...e??[]].find(e=>"true"===e.getAttribute("aria-checked"));(t??e?.[0])?.focus();const n=e=>{e.target instanceof Node&&!v.current?.contains(e.target)&&!b.current?.contains(e.target)&&y(!1)};return document.addEventListener("pointerdown",n),()=>document.removeEventListener("pointerdown",n)},[g]);const k=g?r.jsx("div",{ref:b,style:m?w:void 0,"aria-label":n,className:`composer-option-popover ${m?"portal":""} ${p?"blend-background":""} ${S?"":"without-icons"} ${h?"wide":""} ${"right"===l?"align-right":""}`,role:"menu",children:s.map(e=>{const t=e.icon,n=e.value===i;return r.jsxs("button",{"aria-checked":n,className:n?"selected":"",disabled:e.disabled,onClick:()=>{c(e.value),y(!1),x.current?.focus()},role:"menuitemradio","data-tooltip-delay":f,title:e.description??e.label,type:"button",children:[S&&r.jsx("span",{className:"composer-menu-icon",children:t?r.jsx(t,{"aria-hidden":"true"}):null}),r.jsxs("span",{className:"composer-menu-copy",children:[r.jsx("strong",{children:e.label}),e.description?r.jsx("small",{children:e.description}):null]}),r.jsx("span",{className:"composer-menu-indicator","aria-hidden":"true",children:n?r.jsx($,{className:"composer-menu-check"}):null})]},e.value)})}):null;return r.jsxs("div",{className:"composer-menu",ref:v,onBlur:e=>{const t=e.relatedTarget;t&&(e.currentTarget.contains(t)||b.current?.contains(t))||y(!1)},onKeyDown:e=>{if("Escape"===e.key&&g&&(e.stopPropagation(),e.preventDefault(),y(!1),x.current?.focus()),!["ArrowDown","ArrowUp","Home","End"].includes(e.key))return;if(e.preventDefault(),!g)return void y(!0);const t=[...b.current?.querySelectorAll('[role="menuitemradio"]:not(:disabled)')??[]];if(!t.length)return;const n=t.indexOf(document.activeElement),s="Home"===e.key?0:"End"===e.key?t.length-1:(n+("ArrowDown"===e.key?1:-1)+t.length)%t.length;t[s]?.focus()},children:[r.jsxs("button",{ref:x,"aria-expanded":g,"aria-haspopup":"menu",className:"composer-option-button "+(g||u?"selected":""),disabled:d,onClick:()=>y(e=>!e),title:n,type:"button",children:[r.jsx(e,{"aria-hidden":"true"}),r.jsx("span",{children:t}),g?r.jsx(B,{"aria-hidden":"true"}):r.jsx(z,{"aria-hidden":"true"})]}),k&&m?a.createPortal(k,document.body):k]})}function Ds(e,t,n){const s=o.useRef(null);return o.useEffect(()=>{n&&document.getElementById(`${e}-${t}`)?.scrollIntoView({block:"nearest"})},[e,t,n]),s}function Fs({visible:e,listId:t,selectedIndex:n,onHighlight:s,skills:i,onClose:o,onSelect:a,t:c}){const l=Ds(t,n,e);return e?r.jsxs("div",{className:"skill-suggestion-popover",children:[r.jsxs("header",{children:[r.jsx("strong",{children:c.skills}),r.jsx("button",{type:"button",className:"icon-button",onClick:o,title:c.closeSkills,children:r.jsx(We,{"aria-hidden":"true"})})]}),i.length?r.jsx("div",{className:"skill-suggestion-list",id:t,role:"listbox",ref:l,children:i.map((e,i)=>r.jsxs("button",{id:`${t}-${i}`,role:"option","aria-selected":n===i,onMouseEnter:()=>s(i),onClick:()=>a(e),title:e.description??e.name,type:"button",children:[r.jsxs("span",{children:[r.jsxs("strong",{children:["$",e.name]}),e.description?r.jsx("small",{children:e.description}):null]}),r.jsx("em",{children:e.source})]},`${e.source}:${e.name}`))}):r.jsx("p",{children:c.noSkillsFound})]}):null}function Ls({visible:e,listId:t,selectedIndex:n,onHighlight:s,commands:i,onClose:o,onSelect:a,t:c}){const l=Ds(t,n,e);return e?r.jsxs("div",{className:"skill-suggestion-popover command-suggestion-popover",children:[r.jsxs("header",{children:[r.jsx("strong",{children:c.commands}),r.jsx("button",{type:"button",className:"icon-button",onClick:o,title:c.closeCommands,children:r.jsx(We,{"aria-hidden":"true"})})]}),i.length?r.jsx("div",{className:"skill-suggestion-list",id:t,role:"listbox",ref:l,children:i.map((e,i)=>r.jsxs("button",{id:`${t}-${i}`,role:"option","aria-selected":n===i,onMouseEnter:()=>s(i),onClick:()=>a(e),title:e.description,type:"button",children:[r.jsxs("span",{children:[r.jsxs("strong",{children:["/",e.name]}),r.jsx("small",{children:e.argsHint?`${e.title} ${e.argsHint}`:e.title})]}),r.jsx("em",{children:e.source})]},e.name))}):r.jsx("p",{children:c.noCommandsFound})]}):null}function qs({queue:e,controls:t,busy:n,t:s,onCancel:i}){const[c,l]=o.useState(new Set),[d,u]=o.useState(!1),h=o.useId(),p=o.useRef(null),m=o.useRef(0),f=o.useRef(!1),[g,y]=o.useState(null),v=o.useRef(null),b=()=>{v.current=null,y(null)},x=e=>{if(v.current===e)return;const t=e.getBoundingClientRect(),n=Math.min(280,window.innerWidth-16);v.current=e,y({label:e.dataset.queueLabel||"",help:e.dataset.queueHelp||"",left:Math.max(8,Math.min(t.left,window.innerWidth-n-8)),top:t.top<76?t.bottom+7:t.top-7,below:t.top<76})},w=e.length>0&&e.every(e=>e.waitingForStartup),S=w?s.sessionStartingMessage:s.queuedTurns(e.length),k=e.filter(e=>e.clientMessageId),I=k.filter(e=>c.has(e.clientMessageId)),C=n||t.busy,j=I.length?I:k;return o.useLayoutEffect(()=>{e.length>m.current&&(f.current=!0,d&&u(!1)),m.current=e.length,!d&&f.current&&p.current&&(p.current.scrollTop=p.current.scrollHeight,f.current=!1)},[d,e.length]),e.length?r.jsxs("section",{className:"composer-queue-banner","aria-label":S,onPointerMove:e=>{const t=e.target instanceof Element?e.target.closest("button[data-queue-help]"):null;t?x(t):v.current&&b()},onPointerLeave:b,onFocusCapture:e=>{e.target instanceof HTMLButtonElement&&e.target.dataset.queueHelp&&x(e.target)},onBlurCapture:b,onScrollCapture:b,onClickCapture:b,children:[r.jsxs("header",{className:"composer-queue-heading",children:[r.jsx("strong",{"aria-live":"polite",children:S}),r.jsxs("div",{className:"composer-queue-heading-actions",children:[!d&&r.jsx("button",{type:"button","data-queue-label":k.length>0&&I.length===k.length?s.queueClearSelection:s.queueSelectAll,"data-queue-help":s.queueSelectionHelp,disabled:C||!k.length,onClick:()=>l(k.length>0&&I.length===k.length?new Set:new Set(k.map(e=>e.clientMessageId))),children:k.length>0&&I.length===k.length?s.queueClearSelection:s.queueSelectAll}),r.jsx("button",{type:"button",className:"composer-queue-collapse","aria-controls":h,"aria-expanded":!d,"aria-label":d?s.queueExpand:s.queueCollapse,"data-queue-label":d?s.queueExpand:s.queueCollapse,"data-queue-help":d?s.queueExpandHelp:s.queueCollapseHelp,onClick:()=>u(e=>!e),children:d?r.jsx(z,{"aria-hidden":"true"}):r.jsx(B,{"aria-hidden":"true"})})]})]}),r.jsxs("div",{className:"composer-queue-details",id:h,hidden:d,children:[r.jsx("div",{className:"composer-queue-list",ref:p,children:e.map((e,n)=>r.jsxs("div",{className:"composer-queue-item","data-selected":!!e.clientMessageId&&c.has(e.clientMessageId)||void 0,children:[r.jsx("button",{type:"button",className:"queue-select-button","aria-label":s.selectQueuedTurn(n+1),"aria-pressed":!!e.clientMessageId&&c.has(e.clientMessageId),disabled:C||!e.clientMessageId,"data-queue-label":s.selectQueuedTurn(n+1),"data-queue-help":e.content?`${s.queueSelectionHelp}\n${e.content}`:s.queueSelectionHelp,onClick:()=>l(t=>{const n=new Set(t),s=e.clientMessageId;return n.has(s)?n.delete(s):n.add(s),n}),children:r.jsx("span",{children:e.content||s.queuedTurnFallback})}),r.jsxs("div",{className:"queue-row-actions",children:[r.jsx("button",{type:"button","data-queue-label":s.queueGuide,"data-queue-help":s.queueGuideHelp,"aria-label":s.guideQueuedTurn(n+1),disabled:C||!e.clientMessageId||!t.canGuide||w,onClick:()=>{t.onAction([e],"guide")},children:r.jsx(V,{"aria-hidden":"true"})}),r.jsx("button",{type:"button","data-queue-label":s.queueSendNow,"data-queue-help":s.queueSendNowHelp,"aria-label":s.sendQueuedTurnNow(n+1),disabled:C||!e.clientMessageId||!t.canSendNow||w,onClick:()=>{t.onAction([e],"sendNow")},children:r.jsx(Ne,{"aria-hidden":"true"})}),r.jsx("button",{type:"button",className:"queue-withdraw-button","data-queue-label":s.withdraw,"data-queue-help":s.queueWithdrawHelp,"aria-label":s.withdrawQueuedTurn(n+1),disabled:C||!e.clientMessageId,onClick:()=>i(e),children:r.jsx(We,{"aria-hidden":"true"})})]})]},e.clientMessageId||`${e.enqueuedAt}:${n}`))}),r.jsxs("footer",{className:"queue-batch-actions",children:[I.length>0&&r.jsx("span",{children:s.queueSelectedCount(I.length)}),r.jsxs("button",{type:"button","data-queue-label":I.length?s.queueCollectSelected:s.queueCollectAll,"aria-label":I.length?s.queueCollectSelected:s.queueCollectAll,"data-queue-help":s.queueCollectHelp,disabled:C||j.length<2,onClick:()=>{t.onCollect(j)},children:[r.jsx(me,{"aria-hidden":"true"}),s.queueCollect]}),r.jsx("button",{type:"button","data-queue-label":I.length?s.queueGuideSelected:s.queueGuideAll,"aria-label":I.length?s.queueGuideSelected:s.queueGuideAll,"data-queue-help":s.queueGuideHelp,disabled:C||!j.length||!t.canGuide||w,onClick:()=>{t.onAction(j,"guide")},children:s.queueGuide}),r.jsx("button",{type:"button","data-queue-label":I.length?s.queueSendSelected:s.queueSendAll,"aria-label":I.length?s.queueSendSelected:s.queueSendAll,"data-queue-help":s.queueSendNowHelp,disabled:C||!j.length||!t.canSendNow||w,onClick:()=>{t.onAction(j,"sendNow")},children:s.queueSendNow})]})]}),g&&a.createPortal(r.jsxs("div",{className:"composer-queue-tooltip",role:"tooltip",style:{left:g.left,top:g.top,transform:g.below?void 0:"translateY(-100%)"},children:[r.jsx("strong",{children:g.label}),r.jsx("span",{children:g.help})]}),document.body)]}):null}function Os({replies:e,disabled:t,onSend:n,onChange:s,t:i}){const[a,c]=o.useState(!1),[l,d]=o.useState(""),u=()=>{const t=l.trim();!t||e.length>=20||(e.some(e=>h(e,i)===t)||s?.([...e,t]),d(""),c(!1))};return r.jsxs("div",{className:"quick-reply-row",children:[e.map(o=>{const a=h(o,i);return r.jsxs("span",{className:"quick-reply-item",children:[r.jsx("button",{className:"quick-reply-send",title:a,type:"button",disabled:t||!n,onClick:()=>{n?.(a)},children:a}),s&&r.jsx("button",{className:"quick-reply-remove",type:"button","aria-label":`${i.delete}: ${a}`,title:`${i.delete}: ${a}`,onClick:()=>s(e.filter(e=>e!==o)),children:r.jsx(We,{"aria-hidden":"true"})})]},o)}),s&&(a?r.jsxs("div",{className:"quick-reply-add-form",children:[r.jsx("input",{autoFocus:!0,"aria-label":i.quickReplyAdd,placeholder:i.quickReplyAdd,value:l,maxLength:1e3,onChange:e=>d(e.target.value),onKeyDown:e=>{e.nativeEvent.isComposing||("Enter"===e.key&&(e.preventDefault(),e.stopPropagation(),u()),"Escape"===e.key&&(e.preventDefault(),e.stopPropagation(),c(!1)))}}),r.jsx("button",{type:"button","aria-label":i.quickReplyAdd,disabled:!l.trim(),onClick:u,children:r.jsx($,{"aria-hidden":"true"})}),r.jsx("button",{type:"button","aria-label":i.cancel,onClick:()=>c(!1),children:r.jsx(We,{"aria-hidden":"true"})})]}):r.jsx("button",{type:"button",className:"quick-reply-add","aria-label":i.quickReplyAdd,title:i.quickReplyAdd,disabled:e.length>=20,onClick:()=>c(!0),children:r.jsx(je,{"aria-hidden":"true"})}))]})}function $s({shortcut:e,onChange:t,action:n,t:s}){const i="New session"!==s.newSession,o="傳送快捷鍵"===s.sendShortcut,a="enter"===e?"Enter":"shiftEnter"===e?"Shift+Enter":"Cmd/Ctrl+Enter",c="enter"===e?"shiftEnter":"enter",l="enter"===c?"Enter":"Shift+Enter",d="create"===n?i?"建立":"create":i?s.send:"send",u="create"===n&&i&&!o?"创建":d,h="enter"===e?"Shift+Enter":"Enter",p=i?`${a} ${u};${h} ${o?"換行":"换行"}。${o?"點擊切換為":"点击切换为"} ${l} ${u}`:`${a} to ${d}; ${h} for a newline. Click to switch to ${l} to ${d}`;return r.jsxs("button",{type:"button",className:"submit-shortcut-toggle","data-shortcut":e,"aria-label":p,"aria-pressed":"enter"!==e,onMouseDown:e=>e.preventDefault(),onClick:()=>t(c),children:[r.jsx(pe,{"aria-hidden":"true"}),r.jsx("span",{className:"submit-shortcut-tooltip","aria-hidden":"true",children:p})]})}function zs({leading:e,controls:t,submit:n}){return r.jsxs("div",{className:"composer-toolbar",children:[r.jsxs("div",{className:"composer-scroll-controls",children:[r.jsx("div",{className:"composer-leading-controls",children:e}),r.jsx("div",{className:"composer-control-strip",children:t})]}),n]})}function _s({label:e,disabled:t,onClick:n}){return r.jsx("button",{type:"button",className:"icon-button",title:e,"aria-label":e,disabled:t,onClick:n,children:r.jsx(je,{"aria-hidden":"true"})})}function Bs({children:e,...t}){return r.jsx("button",{...t,className:"send-button submit-action-button",children:e})}function Hs({connected:e,busy:t,sending:n,responding:s,hasDraft:o,shortcut:a,onStop:c,t:l}){const d=n?"sending":s?"replying":"ready",u=s&&!n&&!o,h=n?l.sendingMessage:u?l.stopGenerating:l.send,m=n?l.sendingMessage:s?l.replyingMessage:l.send,f=n?fe:u?Oe:q;return r.jsxs("div",{className:"submit-button-group",children:[r.jsx($s,{shortcut:a,action:"send",t:l,onChange:e=>{const t=i();p({...t,composer:{...t.composer,sendShortcut:e}}),window.dispatchEvent(new Event("vibelet.preferences.changed"))}}),r.jsxs(Bs,{type:u?"button":"submit","data-state":d,"data-action":u?"stop":"send",disabled:!e||t||n||!u&&!o,"aria-label":h,"aria-description":m,title:u?`${m} · ${l.stopGenerating}`:n?m:`${s?`${m} · `:""}${l.send} · ${"enter"===a?l.sendShortcutEnter:"shiftEnter"===a?l.sendShortcutShiftEnter:l.sendShortcutModEnter}`,onClick:u?c:void 0,children:[s&&!n&&r.jsx("span",{className:"composer-send-progress","aria-hidden":"true"}),r.jsx(f,{className:n?"composer-send-spinner":u?"composer-send-stop":void 0,"aria-hidden":"true"}),r.jsx("span",{className:"composer-send-status",role:"status","aria-live":"polite",children:m})]})]})}function Ws({value:e,textareaRef:t,onValueChange:n,onKeyDown:s,autoFocus:i,disabled:a,...c}){const l=o.useRef(!1),d=o.useRef(!1);o.useEffect(()=>{if(!i||a||d.current)return;let e=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{const e=t.current;if(!e)return;d.current=!0;const n=document.activeElement;n&&n!==document.body&&n!==e||(e.focus({preventScroll:!0}),e.setSelectionRange(e.value.length,e.value.length),d.current=!0)})});return()=>cancelAnimationFrame(e)},[i,a,t]);const u=o.useMemo(()=>function(e){let t=0;for(let n=0;n<e.length;n++){const s=e.charCodeAt(n);if(t=s>32&&s<127?t+1:0,t>=4096)return"off"}return"soft"}(e),[e]);return o.useLayoutEffect(()=>{const n=t.current;n&&!l.current&&n.value!==e&&(n.value=e)},[e,t]),r.jsx("textarea",{...c,ref:t,disabled:a,wrap:l.current?t.current?.wrap:u,onCompositionStart:()=>{l.current=!0},onCompositionEnd:e=>{l.current=!1,n(e.currentTarget.value)},onChange:e=>n(e.currentTarget.value),onKeyDown:e=>{l.current||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||s?.(e)}})}function Us({label:e,triggerContent:t,className:n="",children:s}){const[i,c]=o.useState(!1),l=o.useRef(null),d=o.useRef(null),u=o.useId(),h=As(i,l,d,"right"),p=()=>{c(!1),l.current?.focus()};return o.useEffect(()=>{if(!i)return;d.current?.querySelector("button:not(:disabled)")?.focus();const e=e=>{e.target instanceof Node&&!d.current?.contains(e.target)&&!l.current?.contains(e.target)&&c(!1)},t=e=>{e.target instanceof Node&&!d.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)}},[i]),r.jsxs("div",{className:`composer-menu ${n}`,onKeyDown:e=>{"Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),e.stopPropagation(),p())},children:[r.jsx("button",{ref:l,type:"button",className:"composer-option-button",title:e,"aria-label":e,"aria-haspopup":"dialog","aria-expanded":i,"aria-controls":i?u:void 0,onClick:()=>c(!i),children:t}),i&&a.createPortal(r.jsx("div",{ref:d,id:u,role:"dialog","aria-label":e,className:"composer-settings-popover",style:h,children:s(p)}),document.body)]})}function Ks(e){const{t}=e,n=[{label:t.uploadFiles,icon:Se,action:e.onUpload,disabled:e.toolsDisabled},{label:t.skills,icon:Ue,action:e.onSkills,shortcut:"$",disabled:e.toolsDisabled},{label:t.commands,icon:qe,action:e.onCommands,shortcut:"/",disabled:e.toolsDisabled},...e.quickRepliesAvailable?[{label:e.quickRepliesOpen?t.hideQuickReplies:t.showQuickReplies,icon:Le,action:e.onQuickReplies,disabled:!1}]:[]];return r.jsxs("div",{className:"composer-toolbar desktop-composer-toolbar",children:[r.jsx(Us,{label:`${t.uploadFiles} / ${t.skills} / ${t.commands}`,className:"composer-tools-trigger",triggerContent:r.jsx(je,{"aria-hidden":"true"}),children:e=>r.jsx("div",{className:"composer-tools-list",children:n.map(({label:t,icon:n,action:s,shortcut:i,disabled:o})=>r.jsxs("button",{type:"button",disabled:o,onClick:()=>{e(),s()},children:[r.jsx(n,{"aria-hidden":"true"}),r.jsx("span",{children:t}),i&&r.jsx("kbd",{children:i})]},t))})}),r.jsx("div",{className:"composer-permission "+("autoApprove"===e.approvalMode?"full-access":""),children:r.jsx(Ps,{portal:!0,icon:De,label:e.approvalLabel,menuLabel:t.approvalMode,options:e.approvalOptions,value:e.approvalMode,onSelect:e.onApprovalModeChange,wide:!0,blendBackground:!0})}),r.jsx("div",{className:"composer-toolbar-spacer"}),e.fastMode&&r.jsxs("span",{className:"composer-fast-indicator",role:"status","aria-label":t.fastMode,title:t.fastMode,children:[r.jsx(Ue,{"aria-hidden":"true"}),r.jsx("span",{children:t.fast})]}),r.jsx(Us,{label:`${t.model} / ${t.effort}`,className:"composer-model-trigger",triggerContent:r.jsxs(r.Fragment,{children:[r.jsxs("span",{children:[e.modelLabel," · ",e.effort?e.effortLabel:t.defaultOption]}),r.jsx(z,{"aria-hidden":"true"})]}),children:()=>r.jsxs("div",{className:"composer-model-settings",children:[r.jsx("strong",{children:t.model}),r.jsx(Ps,{icon:G,label:e.modelLabel,menuLabel:t.model,tooltipHoverDelay:1500,options:e.modelOptions,value:e.model,onSelect:e.onModelChange,wide:!0}),r.jsx("strong",{children:t.effort}),r.jsx("div",{className:"composer-effort-options",role:"group","aria-label":t.effort,children:e.effortOptions.map(n=>r.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))}),r.jsxs("button",{type:"button",role:"switch","aria-checked":e.fastMode,"aria-label":t.fastMode,className:"composer-fast-switch",onClick:()=>e.onFastModeChange(!e.fastMode),children:[r.jsx(re,{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:t.fastMode}),r.jsx("small",{children:t.preferFasterResponses})]}),r.jsx("span",{className:"composer-switch-track","aria-hidden":"true",children:r.jsx("span",{})})]})]})}),e.voice,e.submit]})}function Qs({onTranscript:e}){const a=n(),[c,l]=o.useState("idle"),[d,u]=o.useState("");o.useEffect(()=>{if(!d||"idle"!==c)return;const e=setTimeout(()=>u(""),5e3);return()=>clearTimeout(e)},[d,c]);const[h,p]=o.useState(0),m=o.useRef(!1);o.useEffect(()=>{if("recording"!==c)return;const e=Date.now();p(0);const t=setInterval(()=>p(Math.floor((Date.now()-e)/1e3)),1e3);return()=>clearInterval(t)},[c]);const[f,g]=o.useState(!1);o.useEffect(()=>{let e=!0;const t=()=>{a.speechSettings?.status().then(t=>{e&&g(t.configured)}).catch(()=>{e&&g(!1)})};return t(),window.addEventListener("vibelet.speech.changed",t),()=>{e=!1,window.removeEventListener("vibelet.speech.changed",t)}},[]);const y=o.useRef(null),v=o.useRef(!0),b=o.useRef(e);b.current=e;const x=s(i().language),w="en"!==x;return o.useEffect(()=>(v.current=!0,()=>{v.current=!1,y.current?.stream.getTracks().forEach(e=>e.stop()),"recording"===y.current?.state&&y.current.stop()}),[]),f&&a.transcribeAudio&&"true"===t().getItem("vibelet.web.voice.enabled")?r.jsxs("span",{className:"voice-input-control","data-voice-state":c,children:[r.jsx("button",{className:"icon-button",type:"button",disabled:"idle"!==c&&"recording"!==c,"aria-label":w?"recording"===c?"停止录音":"语音输入":"recording"===c?"Stop recording":"Voice input",title:"recording"===c?w?"停止录音":"Stop recording":w?"语音输入(最长 60 秒)":"Voice input (up to 60 seconds)",onClick:()=>{"recording"===c?"recording"===y.current?.state&&y.current.stop():(async()=>{if(!m.current){m.current=!0,u(""),l("starting");try{const t=await navigator.mediaDevices.getUserMedia({audio:!0});if(!v.current)return void t.getTracks().forEach(e=>e.stop());let n;try{n=new MediaRecorder(t,{mimeType:"audio/webm"})}catch(e){throw t.getTracks().forEach(e=>e.stop()),e}y.current=n;const s=[];let i=0;n.ondataavailable=e=>{s.push(e.data),i+=e.data.size,i>9437184&&"recording"===n.state&&n.stop()};const r=setTimeout(()=>{"recording"===n.state&&n.stop()},6e4);n.onstop=async()=>{if(clearTimeout(r),t.getTracks().forEach(e=>e.stop()),y.current=null,v.current){l("transcribing");try{const e=new Blob(s,{type:"audio/webm"}),t=await(a.speechSettings?.status()),n="system"===t?.engine||"volcengine"===t?.engine?await async function(e){const t=new AudioContext;try{const n=await t.decodeAudioData(await e.arrayBuffer());if(n.duration>61||n.duration<=0)throw new Error("Invalid recording duration");const s=new Uint8Array(44+2*n.length),i=new DataView(s.buffer),r=(e,t)=>[...t].forEach((t,n)=>i.setUint8(e+n,t.charCodeAt(0)));r(0,"RIFF"),i.setUint32(4,s.length-8,!0),r(8,"WAVEfmt "),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,1,!0),i.setUint32(24,n.sampleRate,!0),i.setUint32(28,2*n.sampleRate,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),r(36,"data"),i.setUint32(40,s.length-44,!0);const o=Array.from({length:n.numberOfChannels},(e,t)=>n.getChannelData(t));for(let e=0;e<n.length;e++){const t=Math.max(-1,Math.min(1,o.reduce((t,n)=>t+n[e],0)/o.length));i.setInt16(44+2*e,t*(t<0?32768:32767),!0)}return s}finally{await t.close()}}(e):new Uint8Array(await e.arrayBuffer()),i=await a.transcribeAudio(n,"zh-TW"===x?"zh-TW":w?"zh":"en");if(v.current)if(i.trim()){u("");let e=i;const t=await(a.polishSettings?.status().catch(()=>{}));if(!v.current)return;if(t?.settings.enabled&&a.polishTranscript){l("polishing");try{const t=await a.polishTranscript(i);e=t.text,v.current&&"fallback"===t.status&&u(w?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}catch{v.current&&u(w?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}}v.current&&b.current(e)}else u(w?"没有识别到语音,请靠近麦克风重试。":"No speech detected. Try speaking closer to the microphone.")}catch{v.current&&u(w?"语音识别失败,请检查麦克风权限、语音设置和网络。":"Speech failed. Check microphone access, speech settings and connection.")}finally{m.current=!1,v.current&&l("idle")}}};try{n.start(1e3)}catch(e){throw clearTimeout(r),t.getTracks().forEach(e=>e.stop()),y.current=null,e}l("recording")}catch{m.current=!1,v.current&&(l("idle"),u(w?"无法开启麦克风,请检查系统权限。":"Microphone unavailable. Check system permissions."))}}})()},children:"recording"===c?r.jsx(Oe,{"aria-hidden":"true"}):"idle"===c?r.jsx(ve,{"aria-hidden":"true"}):r.jsx(fe,{className:"voice-input-spinner","aria-hidden":"true"})}),"idle"!==c&&r.jsxs("span",{className:"voice-input-progress",children:["recording"===c&&r.jsxs("span",{className:"voice-input-wave","aria-hidden":"true",children:[r.jsx("i",{}),r.jsx("i",{}),r.jsx("i",{})]}),r.jsx("span",{role:"status","aria-live":"polite",children:"recording"===c?w?"录音中":"Recording":"polishing"===c?w?"润色中":"Polishing":"transcribing"===c?w?"识别中":"Transcribing":w?"开启麦克风":"Opening microphone"}),"recording"===c&&r.jsxs("span",{className:"voice-input-time","aria-hidden":"true",children:["00:",String(h).padStart(2,"0")]})]}),"idle"===c&&d&&r.jsx("span",{className:"voice-input-error",role:"alert",children:d})]}):null}function Vs({activeQueue:e,queueControls:t,agent:s,attachments:i,approvalMode:a,activeModelOptions:c,busy:l,sending:d,responding:u,onStop:h,draft:p,effort:m,fastMode:f,model:g,phase:y,quickReplies:v,onQuickRepliesChange:b,quickRepliesOpen:x=!1,onQuickRepliesOpenChange:w,onSendQuickReply:S,sendShortcut:k,skills:I,uploadBusy:C,t:j,onApprovalModeChange:R,onCancelQueuedTurn:M,onDraftChange:E,onEffortChange:T,onFastModeChange:N,onModelChange:A,onRefreshSkills:P,onRemoveAttachment:D,onOpenRemoteFile:F,onSubmit:L,onUploadFiles:q}){const O=o.useRef(null),$=o.useRef(null),[z]=o.useState(()=>"desktop"===n().kind||(window.matchMedia?.("(pointer: fine)").matches??!1)),[_,B]=o.useState(!1),[H,W]=o.useState(!1),[U,K]=o.useState(!1),[Q,V]=o.useState(""),[J,Z]=o.useState(""),Y=o.useRef(null),ee=o.useRef(null),te="connected"===y,ne=o.useMemo(()=>ft(s),[s]),se=o.useMemo(()=>yt(p),[p]),ie=se?`${se.start}:${se.end}:${se.keyword}`:"",oe=Boolean(U||se&&J!==ie),ae=o.useMemo(()=>function(e,t,n=8){const s=gt(t);return(s?e.filter(e=>e.name.includes(s)||e.title.toLowerCase().includes(s)).sort((e,t)=>vt(e,s)-vt(t,s)):[...e]).slice(0,n)}(ne,se?.keyword??"",8),[ne,se?.keyword]),ce=o.useMemo(()=>jt(p),[p]),le=ce?`${ce.start}:${ce.end}:${ce.keyword}`:"",de=Boolean(!oe&&(H||ce&&Q!==le)),ue=o.useMemo(()=>function(e,t,n=8){const s=It(t);return(s?e.filter(e=>It(e.name).includes(s)):e).slice(0,n)}(I,ce?.keyword??"",8),[ce?.keyword,I]),he=o.useMemo(()=>function(e){return[{value:"normal",label:e.approvalNormal,description:e.approvalNormalDescription,icon:De},{value:"plan",label:e.approvalPlan,description:e.approvalPlanDescription,icon:Fe},{value:"acceptEdits",label:e.approvalEdits,description:e.approvalEditsDescription,icon:X},{value:"autoApprove",label:e.approvalAuto,description:e.approvalAutoDescription,icon:Ue}]}(j),[j]),pe=o.useMemo(()=>function(e){return[{value:"",label:e.effort,description:e.useDaemonDefault,icon:re},{value:"minimal",label:e.effortMinimal,icon:re},{value:"low",label:e.effortLow,icon:re},{value:"medium",label:e.effortMedium,icon:re},{value:"high",label:e.effortHigh,icon:re},{value:"xhigh",label:e.effortXHigh,icon:re},{value:"max",label:e.effortMax,icon:re},{value:"ultra",label:e.effortUltra,icon:re}]}(j),[j]),me=c.find(e=>e.value===g),fe=me?.label??(g||j.defaultOption),ge=he.find(e=>e.value===a)?.label??a,ye=pe.find(e=>e.value===m)?.label??m,ve=c.map(e=>({value:e.value,label:e.label,description:e.desc,icon:G}));ve.some(e=>""===e.value)||ve.unshift({value:"",label:j.defaultOption,description:j.useDaemonDefaultModel,icon:G}),o.useEffect(()=>{ce||(Y.current=null,V(""),W(!1))},[ce]),o.useEffect(()=>{se||(ee.current=null,Z(""),K(!1))},[se]);const be=()=>{const e=function(e,t){if(!t)return e;const n=jt(e);if(!n||n.start!==t.triggerStart)return e;const s=n.start>t.draftBeforeInsertion.length?" ":"";return e.slice(0,n.start)!==`${t.draftBeforeInsertion}${s}`?e:t.draftBeforeInsertion}(p,Y.current);Y.current=null,e!==p&&E(e),le&&V(le),W(!1),$.current?.focus()},xe=()=>{const e=function(e,t){return t&&yt(e)?t.draftBeforeInsertion:e}(p,ee.current);ee.current=null,e!==p&&E(e),ie&&Z(ie),K(!1),$.current?.focus()},we=()=>{oe?xe():(Z(""),yt(p)||0!==p.length||(ee.current={draftBeforeInsertion:p},E("/")),K(!0),$.current?.focus())},Se=e=>{const t=yt(p),n=function(e,t,n){return t?function(e,t,n){return`${e.slice(0,t.start)}${bt(n,"")}${e.slice(t.end)}`}(e,t,n):`${bt(n,e)}${e}`}(p,t,e);E(n),ee.current=null,K(!1),Z(""),$.current?.focus()},ke=()=>{if(de)be();else{if(P(),V(""),!jt(p)){const e=0===p.length||/\s$/.test(p)?"":" ";Y.current={draftBeforeInsertion:p,triggerStart:p.length+e.length},E(`${p}${e}$`)}W(!0),$.current?.focus()}},Ie=e=>{const t=jt(p),n=t?function(e,t,n){return`${e.slice(0,t.start)}$${It(n)} ${e.slice(t.end)}`}(p,t,e.name):p.trim().length?`${p}${/\s$/.test(p)?"":" "}$${e.name} `:`$${e.name} `;E(n),Y.current=null,W(!1),V(""),$.current?.focus()},Ce=function({context:e,count:t,onSelect:n,onClose:s}){const i=o.useId(),[r,a]=o.useState({context:"",index:0}),c=r.context===e?Math.min(r.index,Math.max(0,t-1)):0,l=t=>a({context:e,index:t});return{listId:i,selectedIndex:c,selectIndex:l,handleKeyDown:i=>!(!e||i.nativeEvent.isComposing||229===i.nativeEvent.keyCode||i.metaKey||i.ctrlKey||i.altKey||i.shiftKey||("Escape"===i.key?(i.preventDefault(),i.stopPropagation(),s(),0):!t||("ArrowDown"===i.key||"ArrowUp"===i.key?(i.preventDefault(),i.stopPropagation(),l((c+("ArrowDown"===i.key?1:-1)+t)%t),0):"Enter"!==i.key&&"Tab"!==i.key||(i.preventDefault(),i.stopPropagation(),n(c),0))))}}({context:oe?`command:${ie}:${ae.map(e=>e.name).join(",")}`:de?`skill:${le}:${ue.map(e=>`${e.source}:${e.name}`).join(",")}`:"",count:oe?ae.length:de?ue.length:0,onSelect:e=>oe?Se(ae[e]):Ie(ue[e]),onClose:oe?xe:be});return r.jsxs("form",{className:"composer "+(_?"dragging":""),onDragEnter:e=>{e.preventDefault(),B(!0)},onDragLeave:()=>B(!1),onDragOver:e=>e.preventDefault(),onDrop:e=>{(async e=>{e.preventDefault(),B(!1),te&&await q(e.dataTransfer.files)})(e)},onSubmit:e=>{L(e)},children:[r.jsx(qs,{queue:e,controls:t,busy:l,t:j,onCancel:M}),x&&r.jsx(Os,{replies:v,disabled:!te||l||d||C,onSend:S,onChange:b,t:j}),r.jsx(Fs,{visible:de,skills:ue,listId:Ce.listId,selectedIndex:Ce.selectedIndex,onHighlight:Ce.selectIndex,onClose:be,onSelect:Ie,t:j}),r.jsx(Ls,{visible:oe,commands:ae,listId:Ce.listId,selectedIndex:Ce.selectedIndex,onHighlight:Ce.selectIndex,onClose:xe,onSelect:Se,t:j}),r.jsx(Ws,{textareaRef:$,autoFocus:z,"aria-controls":oe||de?Ce.listId:void 0,"aria-activedescendant":oe&&ae.length||de&&ue.length?`${Ce.listId}-${Ce.selectedIndex}`:void 0,"aria-autocomplete":"list",value:p,onValueChange:E,onPaste:e=>{(async e=>{te&&e.clipboardData.files.length&&await q(e.clipboardData.files)})(e)},onKeyDown:e=>{Ce.handleKeyDown(e)||"Enter"!==e.key||e.nativeEvent.isComposing||229===e.nativeEvent.keyCode||ht(k,e)&&(e.preventDefault(),e.repeat||L())},placeholder:j.messagePlaceholder,rows:3,disabled:!te}),r.jsx(Ns,{attachments:i,uploadBusy:C,onRemove:D,onOpen:F,t:j}),r.jsx("input",{ref:O,type:"file",multiple:!0,hidden:!0,onChange:e=>{(async(e,t)=>{await q(e),t.value=""})(e.currentTarget.files,e.currentTarget)}}),"desktop"===n().kind?r.jsx(Ks,{t:j,approvalMode:a,approvalLabel:ge,approvalOptions:he,onApprovalModeChange:R,model:g,modelLabel:fe,modelOptions:ve,onModelChange:A,effort:m,effortLabel:ye||j.effort,effortOptions:pe,onEffortChange:T,fastMode:f,onFastModeChange:N,toolsDisabled:!te||C,onUpload:()=>O.current?.click(),onSkills:ke,onCommands:we,quickRepliesAvailable:v.length>0||!!b,quickRepliesOpen:x,onQuickReplies:()=>w?.(!x),voice:r.jsx(Qs,{onTranscript:e=>E(p?`${p} ${e}`:e)}),submit:r.jsx(Hs,{connected:te,busy:l,sending:d,responding:u,hasDraft:!!p.trim(),shortcut:k,onStop:h,t:j})}):r.jsx(zs,{leading:r.jsxs(r.Fragment,{children:[r.jsx(Qs,{onTranscript:e=>E(p?`${p} ${e}`:e)}),r.jsx(_s,{label:j.uploadFiles,disabled:!te||C,onClick:()=>O.current?.click()}),v.length>0||b?r.jsx("button",{className:"icon-button quick-replies-toggle "+(x?"selected":""),type:"button",title:x?j.hideQuickReplies:j.showQuickReplies,"aria-label":x?j.hideQuickReplies:j.showQuickReplies,"aria-pressed":x,onClick:()=>w?.(!x),children:r.jsx(Le,{"aria-hidden":"true"})}):null,r.jsx("button",{className:"icon-button "+(de?"selected":""),type:"button",title:j.skills,"aria-label":j.skills,onClick:ke,disabled:!te||C,children:r.jsx(Ue,{"aria-hidden":"true"})}),r.jsx("button",{className:"icon-button "+(oe?"selected":""),type:"button",title:j.commands,"aria-label":j.commands,onClick:we,disabled:!te||C,children:r.jsx(qe,{"aria-hidden":"true"})})]}),controls:r.jsxs(r.Fragment,{children:[r.jsx(Ps,{portal:!0,icon:"autoApprove"===a?Ue:De,label:ge,menuLabel:j.approvalMode,blendBackground:!0,options:he,value:a,onSelect:R,wide:!0}),r.jsx(Ps,{portal:!0,icon:G,label:fe,menuLabel:j.model,tooltipHoverDelay:1500,options:ve,value:g,onSelect:A,align:"right",wide:!0}),r.jsx(Ps,{portal:!0,icon:re,label:ye||j.effort,menuLabel:j.effort,options:pe,value:m,onSelect:T,align:"right"}),r.jsx(Ps,{portal:!0,icon:Ue,label:f?j.fast:j.normal,menuLabel:j.fastMode,options:[{value:"off",label:j.normal,description:j.standardExecution,icon:re},{value:"on",label:j.fast,description:j.preferFasterResponses,icon:Ue}],value:f?"on":"off",onSelect:e=>N("on"===e),align:"right",selected:f,wide:!0})]}),submit:r.jsx(Hs,{connected:te,busy:l,sending:d,responding:u,hasDraft:!!p.trim(),shortcut:k,onStop:h,t:j})})]})}function Gs({terminals:e,t}){const[n,s]=o.useState(Date.now),i=e?.length??0;return o.useEffect(()=>{if(!i)return;s(Date.now());const e=window.setInterval(()=>s(Date.now()),1e3);return()=>window.clearInterval(e)},[i]),i?r.jsxs("details",{className:"background-terminals",children:[r.jsxs("summary",{children:[r.jsx(ze,{"aria-hidden":"true"}),r.jsx("span",{role:"status",children:t.backgroundTerminalsRunning(i)}),r.jsx(z,{className:"background-terminal-chevron","aria-hidden":"true"})]}),r.jsx("p",{children:t.backgroundTerminalsHint}),r.jsx("ul",{children:e.map(e=>{const s=Date.parse(e.startedAt),i=Number.isFinite(s)?Math.max(0,Math.floor((n-s)/1e3)):0;return r.jsxs("li",{children:[r.jsxs("span",{children:[t.backgroundTerminalLabel," #",e.id]}),r.jsxs("time",{children:[Math.floor(i/60),":",String(i%60).padStart(2,"0")]})]},e.id)})})]}):null}async function Js(e){const t=n().writeClipboardText;if(t)return t(e);try{if(navigator.clipboard?.writeText)return void(await navigator.clipboard.writeText(e))}catch{}const s=document.activeElement,i=window.getSelection(),r=i?Array.from({length:i.rangeCount},(e,t)=>i.getRangeAt(t).cloneRange()):[],o=s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement?[s.selectionStart,s.selectionEnd,s.selectionDirection]:void 0,a=document.createElement("textarea");a.value=e,a.setAttribute("readonly",""),a.style.position="fixed",a.style.opacity="0",document.body.append(a);try{if(a.focus({preventScroll:!0}),a.select(),!document.execCommand("copy"))throw new Error("Clipboard copy was rejected")}finally{if(a.remove(),s instanceof HTMLElement&&s.focus({preventScroll:!0}),o&&(s instanceof HTMLInputElement||s instanceof HTMLTextAreaElement)&&null!==o[0]&&null!==o[1]&&s.setSelectionRange(o[0],o[1],o[2]??void 0),i){i.removeAllRanges();for(const e of r)i.addRange(e)}}}function Zs(e,t){const[n,s]=o.useState(null),i=o.useRef(null);return o.useEffect(()=>()=>{null!==i.current&&window.clearTimeout(i.current)},[]),{copyText:o.useCallback(async n=>{try{await Js(n),s({message:e,tone:"success"})}catch{s({message:t,tone:"error"})}null!==i.current&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>s(null),2400)},[t,e]),feedback:n}}function Ys({feedback:e}){if(!e)return null;const t="success"===e.tone?$:We;return r.jsxs("div",{className:`copy-feedback ${e.tone}`,role:"status",children:[r.jsx(t,{"aria-hidden":"true"}),e.message]})}function Xs({message:e,retryLabel:t,onRetry:n,onDismiss:s,closeLabel:i}){return r.jsxs("div",{className:"notice error chat-error-notice",role:"alert",children:[s?r.jsx("button",{type:"button",className:"chat-notice-dismiss","aria-label":i,title:i,onClick:s,children:r.jsx(We,{"aria-hidden":"true"})}):r.jsx(H,{"aria-hidden":"true"}),r.jsx("span",{children:e}),r.jsxs("button",{className:"chat-notice-retry",onClick:n,type:"button",children:[r.jsx(Re,{"aria-hidden":"true"}),t]})]})}function ei({label:e}){return r.jsxs("div",{className:"history-loading-state","aria-busy":"true","aria-label":e,role:"status",children:[r.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),r.jsxs("div",{className:"history-loading-copy",children:[r.jsx("strong",{children:e}),r.jsx("span",{"aria-hidden":"true"}),r.jsx("span",{"aria-hidden":"true"}),r.jsx("span",{"aria-hidden":"true"})]})]})}function ti({failedSend:e,onRetry:t,onDismiss:n,t:s}){const i={network:s.sendFailedNetwork,timeout:s.sendFailedTimeout,reconnect:s.sendFailedReconnect,permission:s.sendFailedPermission,subscription:s.sendFailedSubscription,"missing-resource":s.sendFailedMissingResource,unknown:s.sendFailedUnknown}[e.kind];return r.jsxs("div",{className:"failed-send-notice",role:"alert",children:[r.jsx(H,{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:"timeout"===e.kind?s.sendUnconfirmed:s.sendFailed}),i,e.message&&r.jsx("blockquote",{className:"failed-send-content",children:e.message}),!!e.images?.length&&r.jsx("small",{children:s.failedSendImages(e.images.length)})]}),r.jsxs("button",{disabled:e.retrying,onClick:t,type:"button",children:[r.jsx(Re,{"aria-hidden":"true",className:e.retrying?"spin":void 0}),e.retrying?s.retrying:s.retrySend]}),n&&r.jsx("button",{className:"chat-notice-dismiss",onClick:n,type:"button","aria-label":s.close,title:s.close,children:r.jsx(We,{"aria-hidden":"true"})})]})}function ni({label:e,onClick:t}){return r.jsx("button",{className:"scroll-latest-button",type:"button","aria-label":e,title:e,onClick:t,children:r.jsx(D,{"aria-hidden":"true"})})}const si=/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,ii=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\u00AD\u061C\u180E\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g,ri=new Set(["","{}","[]","null","undefined",'""']);function oi(e){return e.replace(/\s+/g," ").trim()}function ai(e,t){return"string"==typeof e[t]?e[t]:""}function ci(e,t){return"number"==typeof e[t]?e[t]:void 0}function li(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function di(e){const t=[],n=ai(e,"file_path")||ai(e,"filePath");n&&t.push({label:"Path",value:n,isFilePath:!0});const s=ci(e,"offset"),i=ci(e,"limit");if(void 0!==s||void 0!==i){const e=[];void 0!==s&&e.push(`line ${s+1}`),void 0!==i&&e.push(`to ${void 0!==s?s+i:i}`),t.push({label:"Range",value:e.join(" ")})}return t}function ui(e){const t=function(e){return"string"!=typeof e?"":e.replace(/\r\n?/g,"\n").replace(si,"").replace(ii,"").trim()}(e);return ri.has(t)?"":t}function hi(e){const t=ui(e);if(!t)return"";try{const e=JSON.parse(t);if(e&&"object"==typeof e&&!Array.isArray(e)){const t="string"==typeof e.query?oi(e.query):"";if(t)return t;const n="string"==typeof e.command?oi(e.command):"";if(n)return n;const s="string"==typeof e.description?oi(e.description):"";if(s)return s}}catch{}return oi(t)}function pi(e){return"tool"===e.role||"info"===e.type&&!/^Error:/i.test(e.content.trim())}function mi(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=>hi(e.content)).find(Boolean)??""}function fi(e,t){return e.historyKey?e.historyKey:`${e.timestamp??e.toolName??e.content.slice(0,24)??"message"}:${t}`}const gi={en:{rewind:"Rewind to here",confirmRewind:"Continue in a new branch before this message? The original conversation will be archived and preserved. The selected message will become a draft; no message will be sent. Files will not change.",incompleteHistory:"This conversation has older history that is not loaded. Rewinding is unavailable to avoid selecting the wrong turn.",unavailable:"This message is no longer available.",rewindFailed:"Unable to rewind this conversation.",invalidResponse:"Invalid rewind response.",mediaError:"This format cannot be played here. Download the file to open it.",remoteSettings:"Sessions and remote devices",htmlPreview:"HTML preview",pdfPreview:"PDF preview",audioPreview:"Audio preview",videoPreview:"Video preview"},zh:{rewind:"回退到这里",confirmRewind:"从这条消息之前建立新分支继续?原会话会归档保留,所选消息会填入草稿,不会自动发送,文件不会改变。",incompleteHistory:"此会话还有未加载的历史,暂时不能回退,以免选错消息位置。",unavailable:"这条消息已不可用。",rewindFailed:"无法回退此会话。",invalidResponse:"回退响应无效。",mediaError:"此格式无法在这里播放,请下载后打开。",remoteSettings:"会话与远程设备",htmlPreview:"HTML 预览",pdfPreview:"PDF 预览",audioPreview:"音频预览",videoPreview:"视频预览"},"zh-TW":{rewind:"回退到這裡",confirmRewind:"從這則訊息之前建立新分支繼續?原對話會封存保留,所選訊息會填入草稿,不會自動傳送,檔案不會改變。",incompleteHistory:"此對話還有未載入的歷史,暫時不能回退,以免選錯訊息位置。",unavailable:"這則訊息已無法使用。",rewindFailed:"無法回退此對話。",invalidResponse:"回退回應無效。",mediaError:"此格式無法在這裡播放,請下載後開啟。",remoteSettings:"對話與遠端裝置",htmlPreview:"HTML 預覽",pdfPreview:"PDF 預覽",audioPreview:"音訊預覽",videoPreview:"影片預覽"}};function yi(){return gi[s(i().language)]}function vi(e,t){const n=o.useRef(new Map);n.current.has(e)||n.current.set(e,"function"==typeof t?t():t);const[s,i]=o.useState(()=>new Map);return[s.has(e)?s.get(e):n.current.get(e),o.useCallback(t=>{i(s=>{const i=s.has(e)?s.get(e):n.current.get(e),r="function"==typeof t?t(i):t;return Object.is(i,r)?s:new Map(s).set(e,r)})},[e])]}function bi(e,t){return JSON.stringify([e??null,t??null])}function xi(e,t){try{const[n,s]=JSON.parse(e),[i,r]=JSON.parse(t);return n===i&&null===s&&"string"==typeof r}catch{return!1}}const wi="vibelet:file-operation-before",Si="vibelet:file-operation-done";function ki(e,t=""){const n=e.replace(/\\/g,"/"),s=/^(\/|[a-z]:\/|~)/i.test(n)?n:`${t.replace(/\\/g,"/")}/${n}`,i=[];for(const r of s.split("/"))r&&"."!==r&&(".."===r?i.pop():i.push(r));return`${s.startsWith("/")?"/":""}${i.join("/")}`}function Ii(e,t,n){const s=ki(e,n),i=ki(t,n);return s===i||s.startsWith(`${i}/`)}async function Ci(e,t){const n=new CustomEvent(wi,{cancelable:!0,detail:{...e,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd}});if(!window.dispatchEvent(n))throw new Error("unsaved_changes");const s=await fetch("/file-operation",{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.pairToken}`},body:JSON.stringify(e)}),i=await s.text();let r;try{r=JSON.parse(i)}catch{throw new Error(404===s.status||/^Vibelet Daemon v/.test(i)?"daemon_update_required":"operation_failed")}if(404===s.status&&"ENOENT"!==r.error)throw new Error("daemon_update_required");if(!s.ok)throw new Error(r.error??"operation_failed");return Nn()?.daemonId===t.daemonId&&window.dispatchEvent(new CustomEvent(Si,{detail:{...r,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd,source:e.path}})),r}const ji=o.createContext(null),Ri=()=>o.useContext(ji);function Mi({workspace:e,children:t}){const[s,i]=vi(bi(e.pairing?.daemonId,e.activeSessionId),void 0);return r.jsx(ji.Provider,{value:"desktop"===n().kind?{request:s,reveal:(t,n=e.cwd)=>{const s=ki(t,n);i({path:s}),e.setControlTabAndOpen("files"),e.listDirectory(ss(s)??n,{updateRoute:!0})}}:null,children:t})}function Ei(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 Ti({position:e,onClose:t,onCopy:n,onCopyImage:s,copyImageLabel:i,onRevealFile:c,revealFileLabel:l,onRewind:d,onToggleSource:u,sourceOpen:h,t:p}){const m=o.useRef(null),f=o.useRef(t);f.current=t,o.useLayoutEffect(()=>{const t=m.current,n=document.activeElement,s=t.getBoundingClientRect();t.style.left=`${Math.max(8,Math.min(e.x,innerWidth-s.width-8))}px`,t.style.top=`${Math.max(8,Math.min(e.y,innerHeight-s.height-8))}px`,t.querySelector("button")?.focus({preventScroll:!0});const i=()=>f.current(),r=e=>{t.contains(e.target)||i()};return document.addEventListener("pointerdown",r),document.addEventListener("scroll",i,!0),window.addEventListener("resize",i),window.addEventListener("blur",i),()=>{document.removeEventListener("pointerdown",r),document.removeEventListener("scroll",i,!0),window.removeEventListener("resize",i),window.removeEventListener("blur",i),t.contains(document.activeElement)&&n?.focus({preventScroll:!0})}},[e]);const g=e=>{t(),e()};return a.createPortal(r.jsxs("div",{ref:m,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(m.current.querySelectorAll("button:not(:disabled)")),s=n.indexOf(document.activeElement);["Escape","Tab","ArrowDown","ArrowUp","Home","End"].includes(e.key)&&e.preventDefault(),"Escape"!==e.key&&"Tab"!==e.key||t(),"ArrowDown"===e.key&&n[(s+1)%n.length]?.focus(),"ArrowUp"===e.key&&n[(s-1+n.length)%n.length]?.focus(),"Home"===e.key&&n[0]?.focus(),"End"===e.key&&n.at(-1)?.focus()},children:[s&&r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>g(s),children:[r.jsx(Q,{"aria-hidden":"true"}),i]}),c&&r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>g(c),children:[r.jsx(ne,{"aria-hidden":"true"}),l]}),d&&r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>g(d),children:[r.jsx(Me,{"aria-hidden":"true"}),yi().rewind]}),r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>g(n),children:[r.jsx(Q,{"aria-hidden":"true"}),p.copyMessage]}),r.jsxs("button",{type:"button",role:"menuitem",onClick:()=>g(u),children:[r.jsx(K,{"aria-hidden":"true"}),h?p.hideMarkdownSource:p.viewMarkdownSource]})]}),document.body)}function Ni({message:e,t}){return r.jsx("pre",{className:"message-markdown-source",role:"region","aria-label":t.markdownSource,children:e.content})}function Ai(e){if(!(e instanceof Element))return;const t=e.closest("[data-image-src], [data-file-path], a[href]");return t?Ss(t.dataset.imageSrc??t.dataset.filePath??t.getAttribute("href"))??void 0:void 0}function Pi(e){return"en"===e?"Show in file manager":"zh-TW"===e?"在檔案管理中顯示":"在文件管理中显示"}async function Di(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 Fi(e){const t=n().writeClipboardImage;t?await t(new Uint8Array(await(await Di(e)).arrayBuffer())):await navigator.clipboard.write([new ClipboardItem({"image/png":Di(e)})])}function Li(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 qi({field:e}){return e.isDiff?r.jsxs("div",{className:"tool-field diff",children:[r.jsx("span",{children:e.label}),e.diffOld?r.jsxs("pre",{className:"tool-diff old",children:[r.jsx("b",{children:"-"}),e.diffOld]}):null,e.diffNew?r.jsxs("pre",{className:"tool-diff new",children:[r.jsx("b",{children:"+"}),e.diffNew]}):null]}):r.jsxs("div",{className:`tool-field ${e.isCode?"code":""} ${e.isFilePath?"path":""}`,children:[r.jsx("span",{children:e.label}),r.jsx("pre",{children:e.value})]})}function Oi({message:e,onCopy:t,t:n}){const s=function(e,t){if(!t)return[];switch((e??"").toLowerCase()){case"read":return di(t);case"write":{const e=di(t),n=ai(t,"content");return n&&e.push({label:"Content",isDiff:!0,value:"",diffNew:li(n,500)}),e}case"edit":{const e=di(t),n=ai(t,"old_string")||ai(t,"oldString"),s=ai(t,"new_string")||ai(t,"newString");return(n||s)&&e.push({label:"Change",isDiff:!0,value:"",diffOld:li(n,300),diffNew:li(s,300)}),e}case"bash":{const e=ai(t,"command");return e?[{label:"Command",value:e,isCode:!0}]:[]}case"websearch":{const e=ai(t,"query");return e?[{label:"Query",value:e}]:[]}case"webfetch":{const e=[],n=ai(t,"url");n&&e.push({label:"URL",value:n});const s=ai(t,"prompt");return s&&e.push({label:"Prompt",value:li(s,200)}),e}case"glob":{const e=ai(t,"pattern");return e?[{label:"Pattern",value:e}]:[]}case"grep":{const e=[],n=ai(t,"pattern");n&&e.push({label:"Pattern",value:n,isCode:!0});const s=ai(t,"path");return s&&e.push({label:"In",value:s,isFilePath:!0}),e}default:{const e=[],n=ai(t,"command");if(n)return[{label:"Command",value:n,isCode:!0}];const s=ai(t,"file_path")||ai(t,"filePath");s&&e.push({label:"Path",value:s,isFilePath:!0});const i=ai(t,"description");i&&e.push({label:"Description",value:li(i,200)});const r=ai(t,"query");r&&e.push({label:"Query",value:r});const o=ai(t,"url");return o&&e.push({label:"URL",value:o}),e}}}(e.toolName,e.toolInput),i=hi(e.content),o=ui(e.content),a=function(e){return ui(e).length>0}(e.content)&&!s.length,c=e.toolName??n.tool;return r.jsxs("section",{className:"tool-detail-card",children:[r.jsxs("header",{children:[r.jsx("span",{className:"tool-detail-icon",children:r.jsx(ze,{"aria-hidden":"true"})}),r.jsxs("div",{children:[r.jsx("strong",{children:c}),i?r.jsx("small",{title:i,children:i}):null]}),r.jsx("button",{className:"icon-button",onClick:()=>t(e.content),type:"button",title:n.copyOutput,children:r.jsx(Q,{"aria-hidden":"true"})})]}),s.length?r.jsx("div",{className:"tool-fields",children:s.map((e,t)=>r.jsx(qi,{field:e},`${e.label}:${t}`))}):null,a?r.jsx("pre",{className:"json-box compact",children:o}):null]})}function $i({messages:e,showHeader:t=!0,onClose:n,onCopy:s,t:i}){if(!e.length)return null;const o=e.filter(e=>"tool"===e.role).length||e.length,a=i.toolCallCount(o),c=mi(e),l=e.map(e=>e.content).join("\n\n");return r.jsxs("section",{className:"tool-inline-panel","aria-label":i.toolDetails,children:[t?r.jsxs("header",{className:"inline-detail-header",children:[r.jsxs("div",{className:"inline-detail-title",children:[r.jsx("strong",{children:a}),r.jsx("span",{title:c,children:c||i.toolDetail})]}),r.jsxs("div",{className:"row-actions",children:[r.jsx("button",{className:"icon-button",onClick:()=>s(l),type:"button",title:i.copyOutput,children:r.jsx(Q,{"aria-hidden":"true"})}),r.jsx("button",{className:"icon-button",onClick:n,type:"button",title:i.closeToolDetails,children:r.jsx(We,{"aria-hidden":"true"})})]})]}):null,r.jsx("div",{className:"tool-detail-list",children:e.map((e,t)=>r.jsx(Oi,{message:e,onCopy:s,t:i},`${e.historyKey??e.timestamp??e.toolName??"tool"}:${t}`))})]})}const zi=o.lazy(async()=>m(()=>import("./mermaid-O7DHMXV3-D-nTO-tY.js").then(e=>e.a),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.MessageMarkdown})));function _i({label:e}){return r.jsxs("span",{className:"message-replying-indicator","aria-label":e,role:"status",children:[r.jsxs("span",{"aria-hidden":"true",className:"message-replying-dots",children:[r.jsx("i",{}),r.jsx("i",{}),r.jsx("i",{})]}),r.jsx("span",{children:e})]})}function Bi({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:y,t:v}){const b="assistant"===n.role?dn(n.content):n.content,[x,w]=o.useState(null),S=Ri(),[k,I]=o.useState(""),C=Ei(s(i().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 i="浏览器"===t.browser?{queued:"排队中",interrupted:"已中断",sending:"发送中",delivered:"已送达",failed:"未确认送达",hint:"配对电脑已接收,可能仍在等待处理。"}:"瀏覽器"===t.browser?{queued:"排隊中",interrupted:"已中斷",sending:"傳送中",delivered:"已送達",failed:"未確認送達",hint:"配對電腦已接收,可能仍在等待處理。"}:{queued:"Queued",interrupted:"Interrupted",sending:"Sending",delivered:"Delivered",failed:"Delivery unconfirmed",hint:"Received by the paired computer; processing may still be pending."};return{state:s,label:i[s],title:"delivered"===s?i.hint:i[s]}}(n,v,y),M=(n.images??[]).filter(e=>is(e,"")||/^(?:data:image\/|https?:\/\/|blob:)/i.test(e)),E="tool"===n.role?hi(n.content):"";return r.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:Li(e.target),file:Ai(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:Li(e.target),file:Ai(e.target)})},children:[x&&r.jsx(Ti,{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=Ss(e);if(!n)return Fi(e);const s=Nn();if(!s)throw new Error("No pairing");const i=await Ms(rs(n,t),s.pairToken),r=URL.createObjectURL(i);try{await Fi(r)}finally{URL.revokeObjectURL(r)}}(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:Pi(s(i().language)),onRewind:j,onToggleSource:u,sourceOpen:p,t:v}),k&&r.jsx("div",{className:"message-image-copy-status",role:"status",children:k}),r.jsxs("div",{className:"message-meta",children:[r.jsx("span",{children:cn(n,v)}),r.jsxs("div",{className:"message-meta-side",children:[R&&r.jsx("span",{className:"message-delivery","data-state":R.state,role:"status",title:R.title,children:R.label}),r.jsx("time",{children:an(n.timestamp,Date.now(),v)})]})]}),p?r.jsx(Ni,{message:n,t:v}):"tool"===n.role?r.jsxs("button",{className:"tool-inline-summary","aria-expanded":f,onClick:h,type:"button",children:[r.jsxs("span",{children:[r.jsx(He,{"aria-hidden":"true"}),n.toolName??v.tool]}),E?r.jsx("small",{children:E}):null]}):"assistant"===n.role||"user"===n.role?r.jsx(o.Suspense,{fallback:r.jsx("pre",{children:b}),children:r.jsx(zi,{baseCwd:t,content:n.images?.length?b.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").trim():b,onOpenRemoteFile:d,additionalImages:M})}):r.jsx("pre",{children:n.content}),n.images?.length?r.jsx("div",{className:"message-image-attachments",children:n.images.map(e=>M.includes(e)?r.jsx(Ts,{src:e,cwd:t,onOpen:d,gallery:async()=>[...(await m(async()=>{const{collectMessageImages:e}=await import("./collectMessageImages-B29C7mI7.js");return{collectMessageImages:e}},__vite__mapDeps([4,1,2]))).collectMessageImages(n.content,t),...M.map(e=>({src:e,cwd:t}))]},e):r.jsxs("button",{type:"button",className:"message-file-attachment",title:e,"data-file-path":e,onClick:()=>d(e,t),children:[r.jsx(Se,{size:16,"aria-hidden":"true"}),Kn(e)]},e))}):null,"tool"===n.role&&f?r.jsx($i,{messages:[n],onClose:l,onCopy:a,t:v}):null,g&&r.jsx(_i,{label:v.replyingMessage}),r.jsxs("div",{className:"message-actions","aria-label":v.messageActions,role:"group",children:[j&&r.jsx("button",{type:"button",onClick:j,title:yi().rewind,"aria-label":yi().rewind,children:r.jsx(Me,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":v.copyMessage,onClick:()=>a(p?n.content:b),title:v.copyMessage,type:"button",children:r.jsx(Q,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":v.viewMarkdownSource,"aria-expanded":p,onClick:u,title:p?v.hideMarkdownSource:v.viewMarkdownSource,type:"button",children:r.jsx(K,{"aria-hidden":"true"})})]})]})}function Hi(e,t){return JSON.stringify([...Object.values(e),...Object.values(t)].map(e=>JSON.stringify([e.sessionId,e.requestId])).sort())}function Wi({activeMatch:e,expanded:t,messages:n,onToggle:s,t:i}){const o=mi(n),a=function(e,t){const n={read:t.interactionRead,read_file:t.interactionRead,edit:t.interactionEdit,write:t.interactionEdit,apply_patch:t.interactionEdit,grep:t.interactionSearch,glob:t.interactionSearch,bash:t.interactionCommand,exec_command:t.interactionCommand},s=new Map;for(const i of e.filter(e=>"tool"===e.role)){const e=i.toolName||"Tool",t=n[e.toLowerCase()]??e;s.set(t,(s.get(t)??0)+1)}return[...s].map(([e,t])=>t>1?`${e} × ${t}`:e).join(" · ")}(n,i)||o;return r.jsx("button",{className:`tool-group-bubble ${e?"match":""} ${t?"expanded":""}`,type:"button",onClick:s,"aria-expanded":t,"aria-label":o?`${a}: ${o}`:a,children:r.jsxs("span",{className:"tool-group-header",children:[r.jsxs("span",{className:"tool-group-title",children:[r.jsx(_,{className:"tool-group-chevron","aria-hidden":"true"}),r.jsx("strong",{children:a})]}),o?r.jsx("span",{className:"tool-group-summary",children:o}):null]})})}const Ui=o.memo(function({message:e,index:t,actions:n,messageRefs:s,baseCwd:i,canRewind:o,activeMatch:a,replying:c,queued:l,sourceOpen:d,toolOpen:u,setOpenSourceKey:h,setOpenToolKey:p,copyText:m,failedSend:f,t:g}){const y=fi(e,t);return r.jsxs("div",{className:`message-frame ${e.role} ${"info"===e.type?"info":""}`,"data-message-index":t,ref:e=>{s.current[t]=e},children:[r.jsx(Bi,{activeMatch:a,baseCwd:i,message:e,replying:c,queued:l,onCopy:m,onRewind:o?()=>n.current.onRewindMessage(e):void 0,onCloseTool:()=>p(null),onOpenRemoteFile:(e,t)=>n.current.onOpenRemoteFile(e,t),onToggleSource:()=>h(e=>e===y?null:y),onToggleTool:()=>p(e=>e===y?null:y),sourceOpen:d,toolOpen:u,t:g}),f?r.jsx(ti,{failedSend:f,onRetry:()=>{n.current.retry()},onDismiss:()=>n.current.onDismissFailedSend?.(),t:g}):null]},y)}),Ki=o.memo(function({items:e,activeQueue:t,actions:n,messageRefs:s,activeMatchedMessageIndex:i,baseCwd:o,canRewind:a,hiddenLaterItemCount:c,replyingMessageIndex:l,openSourceKey:d,openToolKey:u,setOpenSourceKey:h,setOpenToolKey:p,copyText:m,failedSend:f,t:g}){return r.jsx(r.Fragment,{children:e.map(e=>{if("toolGroup"===e.type){const t=e.entries.map(e=>e.message),n=e.entries.some(e=>i===e.index),o=u===e.id;return r.jsx("div",{className:"message-frame tool info",ref:t=>{for(const n of e.entries)s.current[n.index]=t},children:r.jsxs("div",{className:"inline-message-stack",children:[r.jsx(Wi,{t:g,activeMatch:n,expanded:o,messages:t,onToggle:()=>p(t=>t===e.id?null:e.id)}),o?r.jsx($i,{messages:t,showHeader:!1,onClose:()=>p(null),onCopy:m,t:g}):null]})},e.id)}const{index:y,message:v}=e,b=fi(v,y),x=d===b,w=u===b,S=f?.historyKey===v.historyKey?f:null;return r.jsx(Ui,{message:v,queued:!!t?.some(e=>!!e.clientMessageId&&(v.historyKey===`client:${e.clientMessageId}`||v.localClientMessageId===e.clientMessageId)),index:y,actions:n,messageRefs:s,baseCwd:o,canRewind:a,activeMatch:i===y,replying:0===c&&y===l,sourceOpen:x,toolOpen:w,setOpenSourceKey:h,setOpenToolKey:p,copyText:m,failedSend:S,t:g},b)})})}),Qi={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:"Writer lock released · return to the terminal and press R",handoff:"Cancel and return to terminal",unavailable:"Execution status unavailable",waitHint:"No new output yet. You can cancel and return to the terminal."},Vi={cancelTimeout:"尚未确认取消,会话仍由 Vibelet 占用。可重试交还终端。",releaseUnconfirmed:"尚未确认写锁释放,请重试交还终端。",handoffFailed:"尚未交还终端",resuming:"正在恢复会话",submitting:"正在提交消息",waiting:"消息已接收,等待模型",compacting:"正在压缩上下文",responding:"正在接收回复",retrying:"正在重连 Codex…",noProgress:"无进展",latestError:"最近错误:",idle:"当前没有运行中的轮次",error:"本轮执行出错",releasing:"正在取消并释放会话…",released:"写锁已释放,可回终端按 R 继续",handoff:"取消并交还终端",unavailable:"暂时无法取得执行状态",waitHint:"尚无新输出,可取消本轮并交还终端。"},Gi={cancelTimeout:"尚未確認取消,會話仍由 Vibelet 佔用。可重試交還終端。",releaseUnconfirmed:"尚未確認寫鎖釋放,請重試交還終端。",handoffFailed:"尚未交還終端",resuming:"正在恢復會話",submitting:"正在提交訊息",waiting:"訊息已接收,等待模型",compacting:"正在壓縮上下文",responding:"正在接收回覆",retrying:"正在重新連線 Codex…",noProgress:"無進展",latestError:"最近錯誤:",idle:"目前沒有執行中的輪次",error:"本輪執行出錯",releasing:"正在取消並釋放會話…",released:"寫鎖已釋放,可回終端按 R 繼續",handoff:"取消並交還終端",unavailable:"暫時無法取得執行狀態",waitHint:"尚無新輸出,可取消本輪並交還終端。"};function Ji({client:e,sessionId:t,t:n}){const s=(e=>e===u.zh?Vi:e===u["zh-TW"]?Gi:Qi)(n),[i,a]=o.useState(null),[c,l]=o.useState(""),[d,h]=o.useState(!1),[p,m]=o.useState(!1),[f,g]=o.useState(Date.now());o.useEffect(()=>{if(!e)return;let n,s=!1;const i=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)||m(!1))}catch{s||a(null)}s||(n=setTimeout(i,2e3))};i();const r=e.onMessage(e=>{"sessionId"in e&&e.sessionId===t&&["text.delta","session.queue"].includes(e.type)&&m(!1)});return()=>{s=!0,clearTimeout(n),r()}},[e,t]);const y=d?"releasing":p?"released":c?"error":i?.phase;return r.jsxs("div",{className:"notice",role:"status","data-testid":"codex-session-control",style:{flexWrap:"wrap"},children:[r.jsxs("span",{style:{flex:1},children:[c?s.handoffFailed:y?s[y]:s.unavailable,i&&["compacting","waiting","submitting","retrying","responding"].includes(i.phase)&&!d&&!p&&r.jsxs("small",{style:{display:"block"},children:[s.noProgress," ",Math.max(0,Math.floor((f-(i.lastProgressAt??i.since))/1e3)),"s ·"," ",s.waitHint]}),"retrying"===i?.phase&&i.detail&&r.jsxs("small",{style:{display:"block"},children:[s.latestError,i.detail]}),c&&r.jsx("small",{role:"alert",style:{display:"block"},children:c})]}),r.jsx("button",{type:"button",className:"icon-text-button",disabled:!e?.isConnected||d,onClick:()=>{(async()=>{if(e&&!d){h(!0),m(!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);m(!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 Zi({client:e,activeSession:t,busy:n,errorText:s,failedSend:i,failedSendVisibleInConversation:o,onClearInterrupt:a,onDismissError:c,onDismissFailedSend:l,onRetry:d,onRetryFailedSend:u,t:h}){return r.jsxs("div",{className:"chat-notices","aria-live":"polite",children:["codex"===t?.agent&&r.jsx(Ji,{client:e,sessionId:t.sessionId,t:h},t.sessionId),s?r.jsx(Xs,{message:s,retryLabel:h.retry,onRetry:d,closeLabel:h.close,onDismiss:c}):null,i&&!o?r.jsx(ti,{failedSend:i,onRetry:u,onDismiss:l,t:h}):null,t?.interruptReason?r.jsxs("div",{className:"notice error",role:"alert",children:[r.jsx(Ue,{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:h.replyStopped})," ",t.interruptReason.humanText||t.interruptReason.kind]}),r.jsx("button",{className:"icon-text-button",disabled:n,onClick:a,type:"button",children:h.clear})]}):null,t?.stallWarning?r.jsxs("div",{className:"notice warning",children:[r.jsx(U,{"aria-hidden":"true"}),r.jsx("span",{children:t.stallWarning.humanText||h.agentMayBeStalled}),r.jsx("button",{className:"chat-notice-dismiss",type:"button","aria-label":h.close,title:h.close,onClick:a,children:r.jsx(We,{"aria-hidden":"true"})})]}):null]})}function Yi({title:e,draft:t,label:n,disabled:s,onDraftChange:i,onCommit:a}){const[c,l]=o.useState(!1),[d,u]=o.useState(t),h=o.useRef(null),p=o.useRef(null),m=o.useRef(!1),f=o.useRef(!1);o.useLayoutEffect(()=>{c?(h.current?.focus(),h.current?.select()):m.current&&(m.current=!1,p.current?.focus()),c||(f.current=!1)},[c]);const g=()=>{m.current=!0,l(!1)};return c?r.jsx("input",{ref:h,className:"inline-session-title-input","aria-label":n,value:d,onChange:e=>{u(e.target.value),i(e.target.value)},onBlur:()=>{f.current||(d.trim()&&d.trim()!==e&&a(d),l(!1))},onKeyDown:t=>{t.nativeEvent.isComposing||229===t.keyCode||("Enter"===t.key?(t.preventDefault(),f.current=!0,d.trim()&&d.trim()!==e&&a(d),g()):"Escape"===t.key&&(t.preventDefault(),t.stopPropagation(),f.current=!0,g()))}}):r.jsx("button",{ref:p,type:"button",className:"inline-session-title-button",title:e,"aria-label":`${n}: ${e}`,disabled:s,onClick:()=>{u(e),i(e),l(!0)},children:e})}const Xi=o.createContext(null);function er({matchCount:e,activeMatchIndex:t,query:n,onChange:s,onNext:i,onPrevious:o,onClose:a,t:c}){const l="浏览器"===c.browser?"上一个匹配项":"瀏覽器"===c.browser?"上一個匹配項":"Previous match",d="浏览器"===c.browser?"下一个匹配项":"瀏覽器"===c.browser?"下一個匹配項":"Next match";return r.jsxs("div",{className:"message-search-bar",id:"conversation-message-search",children:[r.jsx(Te,{"aria-hidden":"true"}),r.jsx("input",{autoFocus:!0,"aria-label":c.searchThisSession,value:n,onChange:e=>s(e.target.value),onKeyDown:e=>{e.nativeEvent.isComposing||(["Enter","ArrowUp","ArrowDown"].includes(e.key)&&(e.preventDefault(),"ArrowUp"===e.key||"Enter"===e.key&&e.shiftKey?o():i()),"Escape"===e.key&&(e.preventDefault(),a()))},placeholder:c.searchThisSession}),r.jsx("span",{className:"message-search-position","aria-live":"polite",title:c.messageSearchMatches(e),children:n.trim()?`${t} / ${e}`:c.allMessages}),r.jsx("button",{type:"button",className:"icon-button mini-button","aria-label":l,title:l,disabled:!e,onClick:o,children:r.jsx(q,{"aria-hidden":"true"})}),r.jsx("button",{type:"button",className:"icon-button mini-button","aria-label":d,title:d,disabled:!e,onClick:i,children:r.jsx(D,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":c.clearMessageSearch,title:c.clearMessageSearch,className:"icon-button mini-button",onClick:a,type:"button",children:r.jsx(We,{"aria-hidden":"true"})})]})}function tr({activeSession:e,agent:t,cwd:s,t:i,onOpenDetails:c,onScrollToStart:l,renameTitle:u,busy:h,onRename:p,onRenameTitleChange:m,onViewChanges:f,search:g}){const[y,v]=o.useState(!1),b=o.useRef(null),x=o.useRef(!1);o.useEffect(()=>{const e=()=>{v(!0),requestAnimationFrame(()=>{const e=document.querySelector("#conversation-message-search input");e?.focus(),e?.select()})};return window.addEventListener("vibelet.message-search",e),()=>window.removeEventListener("vibelet.message-search",e)},[]),o.useEffect(()=>{g.query&&v(!0)},[g.query]),o.useLayoutEffect(()=>{!y&&x.current&&(x.current=!1,b.current?.focus())},[y]);const w=e?d(e):i.newSession,S=e?.cwd??(s.trim().length>0&&"."!==s?s:""),k=e?.agent??t,I=o.useContext(Xi),C=n().toolbarTarget?.("conversation")??I,j=r.jsxs("div",{className:"chat-header-title-row",onClick:e=>{e.target instanceof Element&&e.target.closest('button,a,input,textarea,[contenteditable="true"],.message-search-bar')||l()},children:[r.jsxs("div",{className:"chat-title-block",children:[r.jsxs("span",{className:"chat-title-line",children:[r.jsx("button",{className:`agent-status-pill chat-session-details-button ${k}`,type:"button",onClick:c,"aria-label":i.details,title:i.details,disabled:!e,children:"codex"===k?"Codex":"Claude"}),r.jsx("h1",{children:e?r.jsx(Yi,{title:w,draft:u,label:i.rename,disabled:h,onDraftChange:m,onCommit:p},e.sessionId):w})]}),S?r.jsx("p",{title:S,children:S}):null,e?.branch||e?.diffStat?r.jsxs("div",{className:"header-metadata",children:[e.branch?r.jsx("span",{children:e.branch}):null,e.runtime.state?r.jsx("span",{children:i.runtimeState(e.runtime.state)}):null,e.terminal?.mode?r.jsx("span",{children:e.terminal.mode}):null]}):null]}),r.jsx("button",{"aria-label":i.scrollToConversationStart,className:"chat-scroll-start-target",onClick:l,title:i.scrollToConversationStart,type:"button"}),e&&!y?r.jsxs("button",{className:"chat-changes-button",type:"button","aria-label":i.viewChanges,title:i.viewChanges,onClick:()=>f(e.sessionId),children:[r.jsx(oe,{"aria-hidden":"true"}),e.diffStat&&(e.diffStat.additions>0||e.diffStat.deletions>0)?r.jsxs("span",{className:"chat-changes-summary","aria-hidden":"true",children:[r.jsxs("span",{className:"diff-add",children:["+",e.diffStat.additions]}),r.jsxs("span",{className:"diff-del",children:["−",e.diffStat.deletions]})]}):null]}):null,y?r.jsx(er,{...g,t:i,onClose:()=>{x.current=!0,g.onChange(""),v(!1)}}):r.jsx("button",{ref:b,className:"icon-button chat-search-toggle",type:"button","aria-label":i.searchThisSession,title:st(i.searchThisSession,"searchMessages"),"aria-expanded":!1,"aria-controls":"conversation-message-search",onClick:()=>v(!0),children:r.jsx(Te,{"aria-hidden":"true"})})]});return r.jsx("header",{className:"chat-header chat-search-header "+(C?"chat-header-in-titlebar":""),children:C?a.createPortal(j,C):j})}const nr={};function sr(e,t){return ir(e,"boolean"!=typeof nr.includeImageAlt||nr.includeImageAlt,"boolean"!=typeof nr.includeHtml||nr.includeHtml)}function ir(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 rr(e.children,t,n)}return Array.isArray(e)?rr(e,t,n):""}function rr(e,t,n){const s=[];let i=-1;for(;++i<e.length;)s[i]=ir(e[i],t,n);return s.join("")}const or=document.createElement("i");function ar(e){const t="&"+e+";";or.innerHTML=t;const n=or.textContent;return(59!==n.charCodeAt(n.length-1)||"semi"===e)&&n!==t&&n}function cr(e,t,n,s){const i=e.length;let r,o=0;if(t=t<0?-t>i?0:i+t:t>i?i:t,n=n>0?n:0,s.length<1e4)r=Array.from(s),r.unshift(t,n),e.splice(...r);else for(n&&e.splice(t,n);o<s.length;)r=s.slice(o,o+1e4),r.unshift(t,0),e.splice(...r),o+=1e4,t+=1e4}function lr(e,t){return e.length>0?(cr(e,e.length,0,t),e):t}const dr={}.hasOwnProperty;function ur(e){const t={};let n=-1;for(;++n<e.length;)hr(t,e[n]);return t}function hr(e,t){let n;for(n in t){const s=(dr.call(e,n)?e[n]:void 0)||(e[n]={}),i=t[n];let r;if(i)for(r in i){dr.call(s,r)||(s[r]=[]);const e=i[r];pr(s[r],Array.isArray(e)?e:e?[e]:[])}}}function pr(e,t){let n=-1;const s=[];for(;++n<t.length;)("after"===t[n].add?e:s).push(t[n]);cr(e,0,0,s)}function mr(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 fr(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const gr=Mr(/[A-Za-z]/),yr=Mr(/[\dA-Za-z]/),vr=Mr(/[#-'*+\--9=?A-Z^-~]/);function br(e){return null!==e&&(e<32||127===e)}const xr=Mr(/\d/),wr=Mr(/[\dA-Fa-f]/),Sr=Mr(/[!-/:-@[-`{-~]/);function kr(e){return null!==e&&e<-2}function Ir(e){return null!==e&&(e<0||32===e)}function Cr(e){return-2===e||-1===e||32===e}const jr=Mr(new RegExp("\\p{P}|\\p{S}","u")),Rr=Mr(/\s/);function Mr(e){return function(t){return null!==t&&t>-1&&e.test(String.fromCharCode(t))}}function Er(e,t,n,s){const i=s?s-1:Number.POSITIVE_INFINITY;let r=0;return function(s){return Cr(s)?(e.enter(n),o(s)):t(s)};function o(s){return Cr(s)&&r++<i?(e.consume(s),o):(e.exit(n),t(s))}}const Tr={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"),Er(e,t,"linePrefix");e.consume(n)},function(t){return e.enter("paragraph"),s(t)});let n;return t;function s(t){const s=e.enter("chunkText",{contentType:"text",previous:n});return n&&(n.next=s),n=s,i(t)}function i(t){return null===t?(e.exit("chunkText"),e.exit("paragraph"),void e.consume(t)):kr(t)?(e.consume(t),e.exit("chunkText"),s):(e.consume(t),i)}}},Nr={tokenize:function(e){const t=this,n=[];let s,i,r,o=0;return a;function a(s){if(o<n.length){const i=n[o];return t.containerState=i[1],e.attempt(i[0].continuation,c,l)(s)}return l(s)}function c(e){if(o++,t.containerState._closeFlow){t.containerState._closeFlow=void 0,s&&v();const n=t.events.length;let i,r=n;for(;r--;)if("exit"===t.events[r][0]&&"chunkFlow"===t.events[r][1].type){i=t.events[r][1].end;break}y(o);let a=n;for(;a<t.events.length;)t.events[a][1].end={...i},a++;return cr(t.events,r+1,0,t.events.slice(n)),t.events.length=a,l(e)}return a(e)}function l(i){if(o===n.length){if(!s)return h(i);if(s.currentConstruct&&s.currentConstruct.concrete)return m(i);t.interrupt=Boolean(s.currentConstruct&&!s._gfmTableDynamicInterruptHack)}return t.containerState={},e.check(Ar,d,u)(i)}function d(e){return s&&v(),y(o),h(e)}function u(e){return t.parser.lazy[t.now().line]=o!==n.length,r=t.now().offset,m(e)}function h(n){return t.containerState={},e.attempt(Ar,p,m)(n)}function p(e){return o++,n.push([t.currentConstruct,t.containerState]),h(e)}function m(n){return null===n?(s&&v(),y(0),void e.consume(n)):(s=s||t.parser.flow(t.now()),e.enter("chunkFlow",{_tokenizer:s,contentType:"flow",previous:i}),f(n))}function f(n){return null===n?(g(e.exit("chunkFlow"),!0),y(0),void e.consume(n)):kr(n)?(e.consume(n),g(e.exit("chunkFlow")),o=0,t.interrupt=void 0,a):(e.consume(n),f)}function g(e,n){const a=t.sliceStream(e);if(n&&a.push(null),e.previous=i,i&&(i.next=e),i=e,s.defineSkip(e.start),s.write(a),t.parser.lazy[e.start.line]){let e=s.events.length;for(;e--;)if(s.events[e][1].start.offset<r&&(!s.events[e][1].end||s.events[e][1].end.offset>r))return;const n=t.events.length;let i,a,c=n;for(;c--;)if("exit"===t.events[c][0]&&"chunkFlow"===t.events[c][1].type){if(i){a=t.events[c][1].end;break}i=!0}for(y(o),e=n;e<t.events.length;)t.events[e][1].end={...a},e++;cr(t.events,c+1,0,t.events.slice(n)),t.events.length=e}}function y(s){let i=n.length;for(;i-- >s;){const s=n[i];t.containerState=s[1],s[0].exit.call(t,e)}n.length=s}function v(){s.write([null]),i=void 0,s=void 0,t.containerState._closeFlow=void 0}}},Ar={tokenize:function(e,t,n){return Er(e,e.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}};function Pr(e){return null===e||Ir(e)||Rr(e)?1:jr(e)?2:void 0}function Dr(e,t,n){const s=[];let i=-1;for(;++i<e.length;){const r=e[i].resolveAll;r&&!s.includes(r)&&(t=r(t,n),s.push(r))}return t}const Fr={name:"attention",resolveAll:function(e,t){let n,s,i,r,o,a,c,l,d=-1;for(;++d<e.length;)if("enter"===e[d][0]&&"attentionSequence"===e[d][1].type&&e[d][1]._close)for(n=d;n--;)if("exit"===e[n][0]&&"attentionSequence"===e[n][1].type&&e[n][1]._open&&t.sliceSerialize(e[n][1]).charCodeAt(0)===t.sliceSerialize(e[d][1]).charCodeAt(0)){if((e[n][1]._close||e[d][1]._open)&&(e[d][1].end.offset-e[d][1].start.offset)%3&&!((e[n][1].end.offset-e[n][1].start.offset+e[d][1].end.offset-e[d][1].start.offset)%3))continue;a=e[n][1].end.offset-e[n][1].start.offset>1&&e[d][1].end.offset-e[d][1].start.offset>1?2:1;const u={...e[n][1].end},h={...e[d][1].start};Lr(u,-a),Lr(h,a),r={type:a>1?"strongSequence":"emphasisSequence",start:u,end:{...e[n][1].end}},o={type:a>1?"strongSequence":"emphasisSequence",start:{...e[d][1].start},end:h},i={type:a>1?"strongText":"emphasisText",start:{...e[n][1].end},end:{...e[d][1].start}},s={type:a>1?"strong":"emphasis",start:{...r.start},end:{...o.end}},e[n][1].end={...r.start},e[d][1].start={...o.end},c=[],e[n][1].end.offset-e[n][1].start.offset&&(c=lr(c,[["enter",e[n][1],t],["exit",e[n][1],t]])),c=lr(c,[["enter",s,t],["enter",r,t],["exit",r,t],["enter",i,t]]),c=lr(c,Dr(t.parser.constructs.insideSpan.null,e.slice(n+1,d),t)),c=lr(c,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",s,t]]),e[d][1].end.offset-e[d][1].start.offset?(l=2,c=lr(c,[["enter",e[d][1],t],["exit",e[d][1],t]])):l=0,cr(e,n-1,d-n+3,c),d=n+c.length-l-2;break}for(d=-1;++d<e.length;)"attentionSequence"===e[d][1].type&&(e[d][1].type="data");return e},tokenize:function(e,t){const n=this.parser.constructs.attentionMarkers.null,s=this.previous,i=Pr(s);let r;return function(t){return r=t,e.enter("attentionSequence"),o(t)};function o(a){if(a===r)return e.consume(a),o;const c=e.exit("attentionSequence"),l=Pr(a),d=!l||2===l&&i||n.includes(a),u=!i||2===i&&l||n.includes(s);return c._open=Boolean(42===r?d:d&&(i||!u)),c._close=Boolean(42===r?u:u&&(l||!d)),t(a)}}};function Lr(e,t){e.column+=t,e.offset+=t,e._bufferIndex+=t}const qr={name:"autolink",tokenize:function(e,t,n){let s=0;return function(t){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(t),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),i};function i(t){return gr(t)?(e.consume(t),r):64===t?n(t):c(t)}function r(e){return 43===e||45===e||46===e||yr(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||yr(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||br(s)?n(s):(e.consume(s),a)}function c(t){return 64===t?(e.consume(t),l):vr(t)?(e.consume(t),c):n(t)}function l(e){return yr(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||yr(t))&&s++<63){const n=45===t?u:d;return e.consume(t),n}return n(t)}}},Or={partial:!0,tokenize:function(e,t,n){return function(t){return Cr(t)?Er(e,s,"linePrefix")(t):s(t)};function s(e){return null===e||kr(e)?t(e):n(e)}}},$r={continuation:{tokenize:function(e,t,n){const s=this;return function(t){return Cr(t)?Er(e,i,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):i(t)};function i(s){return e.attempt($r,t,n)(s)}}},exit:function(e){e.exit("blockQuote")},name:"blockQuote",tokenize:function(e,t,n){const s=this;return function(t){if(62===t){const n=s.containerState;return n.open||(e.enter("blockQuote",{_container:!0}),n.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(t),e.exit("blockQuoteMarker"),i}return n(t)};function i(n){return Cr(n)?(e.enter("blockQuotePrefixWhitespace"),e.consume(n),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),t):(e.exit("blockQuotePrefix"),t(n))}}},zr={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 Sr(s)?(e.enter("characterEscapeValue"),e.consume(s),e.exit("characterEscapeValue"),e.exit("characterEscape"),t):n(s)}}},_r={name:"characterReference",tokenize:function(e,t,n){const s=this;let i,r,o=0;return function(t){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(t),e.exit("characterReferenceMarker"),a};function a(t){return 35===t?(e.enter("characterReferenceMarkerNumeric"),e.consume(t),e.exit("characterReferenceMarkerNumeric"),c):(e.enter("characterReferenceValue"),i=31,r=yr,l(t))}function c(t){return 88===t||120===t?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(t),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),i=6,r=wr,l):(e.enter("characterReferenceValue"),i=7,r=xr,l(t))}function l(a){if(59===a&&o){const i=e.exit("characterReferenceValue");return r!==yr||ar(s.sliceSerialize(i))?(e.enter("characterReferenceMarker"),e.consume(a),e.exit("characterReferenceMarker"),e.exit("characterReference"),t):n(a)}return r(a)&&o++<i?(e.consume(a),l):n(a)}}},Br={partial:!0,tokenize:function(e,t,n){const s=this;return function(t){return null===t?n(t):(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),i)};function i(e){return s.parser.lazy[s.now().line]?n(e):t(e)}}},Hr={concrete:!0,name:"codeFenced",tokenize:function(e,t,n){const s=this,i={partial:!0,tokenize:function(e,t,n){let i=0;return function(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),o};function o(t){return e.enter("codeFencedFence"),Cr(t)?Er(e,c,"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(t):c(t)}function c(t){return t===r?(e.enter("codeFencedFenceSequence"),l(t)):n(t)}function l(t){return t===r?(i++,e.consume(t),l):i>=a?(e.exit("codeFencedFenceSequence"),Cr(t)?Er(e,d,"whitespace")(t):d(t)):n(t)}function d(s){return null===s||kr(s)?(e.exit("codeFencedFence"),t(s)):n(s)}}};let r,o=0,a=0;return function(t){return function(t){const n=s.events[s.events.length-1];return o=n&&"linePrefix"===n[1].type?n[2].sliceSerialize(n[1],!0).length:0,r=t,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),c(t)}(t)};function c(t){return t===r?(a++,e.consume(t),c):a<3?n(t):(e.exit("codeFencedFenceSequence"),Cr(t)?Er(e,l,"whitespace")(t):l(t))}function l(n){return null===n||kr(n)?(e.exit("codeFencedFence"),s.interrupt?t(n):e.check(Br,p,v)(n)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),d(n))}function d(t){return null===t||kr(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),l(t)):Cr(t)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Er(e,u,"whitespace")(t)):96===t&&t===r?n(t):(e.consume(t),d)}function u(t){return null===t||kr(t)?l(t):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),h(t))}function h(t){return null===t||kr(t)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),l(t)):96===t&&t===r?n(t):(e.consume(t),h)}function p(t){return e.attempt(i,v,m)(t)}function m(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),f}function f(t){return o>0&&Cr(t)?Er(e,g,"linePrefix",o+1)(t):g(t)}function g(t){return null===t||kr(t)?e.check(Br,p,v)(t):(e.enter("codeFlowValue"),y(t))}function y(t){return null===t||kr(t)?(e.exit("codeFlowValue"),g(t)):(e.consume(t),y)}function v(n){return e.exit("codeFenced"),t(n)}}},Wr={name:"codeIndented",tokenize:function(e,t,n){const s=this;return function(t){return e.enter("codeIndented"),Er(e,i,"linePrefix",5)(t)};function i(e){const t=s.events[s.events.length-1];return t&&"linePrefix"===t[1].type&&t[2].sliceSerialize(t[1],!0).length>=4?r(e):n(e)}function r(t){return null===t?a(t):kr(t)?e.attempt(Ur,r,a)(t):(e.enter("codeFlowValue"),o(t))}function o(t){return null===t||kr(t)?(e.exit("codeFlowValue"),r(t)):(e.consume(t),o)}function a(n){return e.exit("codeIndented"),t(n)}}},Ur={partial:!0,tokenize:function(e,t,n){const s=this;return i;function i(t){return s.parser.lazy[s.now().line]?n(t):kr(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),i):Er(e,r,"linePrefix",5)(t)}function r(e){const r=s.events[s.events.length-1];return r&&"linePrefix"===r[1].type&&r[2].sliceSerialize(r[1],!0).length>=4?t(e):kr(e)?i(e):n(e)}}},Kr={name:"codeText",previous:function(e){return 96!==e||"characterEscape"===this.events[this.events.length-1][1].type},resolve:function(e){let t,n,s=e.length-4,i=3;if(!("lineEnding"!==e[i][1].type&&"space"!==e[i][1].type||"lineEnding"!==e[s][1].type&&"space"!==e[s][1].type))for(t=i;++t<s;)if("codeTextData"===e[t][1].type){e[i][1].type="codeTextPadding",e[s][1].type="codeTextPadding",i+=2,s-=2;break}for(t=i-1,s++;++t<=s;)void 0===n?t!==s&&"lineEnding"!==e[t][1].type&&(n=t):t!==s&&"lineEnding"!==e[t][1].type||(e[n][1].type="codeTextData",t!==n+2&&(e[n][1].end=e[t-1][1].end,e.splice(n+2,t-n-2),s-=t-n-2,t=n+2),n=void 0);return e},tokenize:function(e,t,n){let s,i,r=0;return function(t){return e.enter("codeText"),e.enter("codeTextSequence"),o(t)};function o(t){return 96===t?(e.consume(t),r++,o):(e.exit("codeTextSequence"),a(t))}function a(t){return null===t?n(t):32===t?(e.enter("space"),e.consume(t),e.exit("space"),a):96===t?(i=e.enter("codeTextSequence"),s=0,l(t)):kr(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||kr(t)?(e.exit("codeTextData"),a(t)):(e.consume(t),c)}function l(n){return 96===n?(e.consume(n),s++,l):s===r?(e.exit("codeTextSequence"),e.exit("codeText"),t(n)):(i.type="codeTextData",c(n))}}};class Qr{constructor(e){this.left=e?[...e]:[],this.right=[]}get(e){if(e<0||e>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return e<this.left.length?this.left[e]:this.right[this.right.length-e+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(e,t){const n=t??Number.POSITIVE_INFINITY;return n<this.left.length?this.left.slice(e,n):e>this.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){const s=t||0;this.setCursor(Math.trunc(e));const i=this.right.splice(this.right.length-s,Number.POSITIVE_INFINITY);return n&&Vr(this.left,n),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(e){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(e)}pushMany(e){this.setCursor(Number.POSITIVE_INFINITY),Vr(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),Vr(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);Vr(this.right,t.reverse())}else{const t=this.right.splice(this.left.length+this.right.length-e,Number.POSITIVE_INFINITY);Vr(this.left,t.reverse())}}}function Vr(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 Gr(e){const t={};let n,s,i,r,o,a,c,l=-1;const d=new Qr(e);for(;++l<d.length;){for(;l in t;)l=t[l];if(n=d.get(l),l&&"chunkFlow"===n[1].type&&"listItemPrefix"===d.get(l-1)[1].type&&(a=n[1]._tokenizer.events,i=0,i<a.length&&"lineEndingBlank"===a[i][1].type&&(i+=2),i<a.length&&"content"===a[i][1].type))for(;++i<a.length&&"content"!==a[i][1].type;)"chunkText"===a[i][1].type&&(a[i][1]._isInFirstContentOfListItem=!0,i++);if("enter"===n[0])n[1].contentType&&(Object.assign(t,Jr(d,l)),l=t[l],c=!0);else if(n[1]._container){for(i=l,s=void 0;i--;)if(r=d.get(i),"lineEnding"===r[1].type||"lineEndingBlank"===r[1].type)"enter"===r[0]&&(s&&(d.get(s)[1].type="lineEndingBlank"),r[1].type="lineEnding",s=i);else if("linePrefix"!==r[1].type&&"listItemIndent"!==r[1].type)break;s&&(n[1].end={...d.get(s)[1].start},o=d.slice(s,l),o.unshift(n),d.splice(s,l-s+1,o))}}return cr(e,0,Number.POSITIVE_INFINITY,d.slice(0)),!c}function Jr(e,t){const n=e.get(t)[1],s=e.get(t)[2];let i=t-1;const r=[];let o=n._tokenizer;o||(o=s.parser[n.contentType](n.start),n._contentTypeTextTrailing&&(o._contentTypeTextTrailing=!0));const a=o.events,c=[],l={};let d,u,h=-1,p=n,m=0,f=0;const g=[f];for(;p;){for(;e.get(++i)[1]!==p;);r.push(i),p._tokenizer||(d=s.sliceStream(p),p.next||d.push(null),u&&o.defineSkip(p.start),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=!0),o.write(d),p._isInFirstContentOfListItem&&(o._gfmTasklistFirstContentOfListItem=void 0)),u=p,p=p.next}for(p=n;++h<a.length;)"exit"===a[h][0]&&"enter"===a[h-1][0]&&a[h][1].type===a[h-1][1].type&&a[h][1].start.line!==a[h][1].end.line&&(f=h+1,g.push(f),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(o.events=[],p?(p._tokenizer=void 0,p.previous=void 0):g.pop(),h=g.length;h--;){const t=a.slice(g[h],g[h+1]),n=r.pop();c.push([n,n+t.length-1]),e.splice(n,2,t)}for(c.reverse(),h=-1;++h<c.length;)l[m+c[h][0]]=m+c[h][1],m+=c[h][1]-c[h][0]-1;return l}const Zr={resolve:function(e){return Gr(e),e},tokenize:function(e,t){let n;return function(t){return e.enter("content"),n=e.enter("chunkContent",{contentType:"content"}),s(t)};function s(t){return null===t?i(t):kr(t)?e.check(Yr,r,i)(t):(e.consume(t),s)}function i(n){return e.exit("chunkContent"),e.exit("content"),t(n)}function r(t){return e.consume(t),e.exit("chunkContent"),n.next=e.enter("chunkContent",{contentType:"content",previous:n}),n=n.next,s}}},Yr={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"),Er(e,i,"linePrefix")};function i(i){if(null===i||kr(i))return n(i);const r=s.events[s.events.length-1];return!s.parser.constructs.disable.null.includes("codeIndented")&&r&&"linePrefix"===r[1].type&&r[2].sliceSerialize(r[1],!0).length>=4?t(i):e.interrupt(s.parser.constructs.flow,n,t)(i)}}};function Xr(e,t,n,s,i,r,o,a,c){const l=c||Number.POSITIVE_INFINITY;let d=0;return function(t){return 60===t?(e.enter(s),e.enter(i),e.enter(r),e.consume(t),e.exit(r),u):null===t||32===t||41===t||br(t)?n(t):(e.enter(s),e.enter(o),e.enter(a),e.enter("chunkString",{contentType:"string"}),m(t))};function u(n){return 62===n?(e.enter(r),e.consume(n),e.exit(r),e.exit(i),e.exit(s),t):(e.enter(a),e.enter("chunkString",{contentType:"string"}),h(n))}function h(t){return 62===t?(e.exit("chunkString"),e.exit(a),u(t)):null===t||60===t||kr(t)?n(t):(e.consume(t),92===t?p:h)}function p(t){return 60===t||62===t||92===t?(e.consume(t),h):h(t)}function m(i){return d||null!==i&&41!==i&&!Ir(i)?d<l&&40===i?(e.consume(i),d++,m):41===i?(e.consume(i),d--,m):null===i||32===i||40===i||br(i)?n(i):(e.consume(i),92===i?f:m):(e.exit("chunkString"),e.exit(a),e.exit(o),e.exit(s),t(i))}function f(t){return 40===t||41===t||92===t?(e.consume(t),m):m(t)}}function eo(e,t,n,s,i,r){const o=this;let a,c=0;return function(t){return e.enter(s),e.enter(i),e.consume(t),e.exit(i),e.enter(r),l};function l(u){return c>999||null===u||91===u||93===u&&!a||94===u&&!c&&"_hiddenFootnoteSupport"in o.parser.constructs?n(u):93===u?(e.exit(r),e.enter(i),e.consume(u),e.exit(i),e.exit(s),t):kr(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||kr(t)||c++>999?(e.exit("chunkString"),l(t)):(e.consume(t),a||(a=!Cr(t)),92===t?u:d)}function u(t){return 91===t||92===t||93===t?(e.consume(t),c++,d):d(t)}}function to(e,t,n,s,i,r){let o;return function(t){return 34===t||39===t||40===t?(e.enter(s),e.enter(i),e.consume(t),e.exit(i),o=40===t?41:t,a):n(t)};function a(n){return n===o?(e.enter(i),e.consume(n),e.exit(i),e.exit(s),t):(e.enter(r),c(n))}function c(t){return t===o?(e.exit(r),a(o)):null===t?n(t):kr(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),Er(e,c,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),l(t))}function l(t){return t===o||null===t||kr(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 no(e,t){let n;return function s(i){return kr(i)?(e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),n=!0,s):Cr(i)?Er(e,s,n?"linePrefix":"lineSuffix")(i):t(i)}}const so={name:"definition",tokenize:function(e,t,n){const s=this;let i;return function(t){return e.enter("definition"),function(t){return eo.call(s,e,r,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(t)}(t)};function r(t){return i=fr(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 Ir(t)?no(e,a)(t):a(t)}function a(t){return Xr(e,c,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(t)}function c(t){return e.attempt(io,l,l)(t)}function l(t){return Cr(t)?Er(e,d,"whitespace")(t):d(t)}function d(r){return null===r||kr(r)?(e.exit("definition"),s.parser.defined.push(i),t(r)):n(r)}}},io={partial:!0,tokenize:function(e,t,n){return function(t){return Ir(t)?no(e,s)(t):n(t)};function s(t){return to(e,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(t)}function i(t){return Cr(t)?Er(e,r,"whitespace")(t):r(t)}function r(e){return null===e||kr(e)?t(e):n(e)}}},ro={name:"hardBreakEscape",tokenize:function(e,t,n){return function(t){return e.enter("hardBreakEscape"),e.consume(t),s};function s(s){return kr(s)?(e.exit("hardBreakEscape"),t(s)):n(s)}}},oo={name:"headingAtx",resolve:function(e,t){let n,s,i=e.length-2,r=3;return"whitespace"===e[r][1].type&&(r+=2),i-2>r&&"whitespace"===e[i][1].type&&(i-=2),"atxHeadingSequence"===e[i][1].type&&(r===i-1||i-4>r&&"whitespace"===e[i-2][1].type)&&(i-=r+1===i?2:4),i>r&&(n={type:"atxHeadingText",start:e[r][1].start,end:e[i][1].end},s={type:"chunkText",start:e[r][1].start,end:e[i][1].end,contentType:"text"},cr(e,r,i-r+1,[["enter",n,t],["enter",s,t],["exit",s,t],["exit",n,t]])),e},tokenize:function(e,t,n){let s=0;return function(t){return e.enter("atxHeading"),function(t){return e.enter("atxHeadingSequence"),i(t)}(t)};function i(t){return 35===t&&s++<6?(e.consume(t),i):null===t||Ir(t)?(e.exit("atxHeadingSequence"),r(t)):n(t)}function r(n){return 35===n?(e.enter("atxHeadingSequence"),o(n)):null===n||kr(n)?(e.exit("atxHeading"),t(n)):Cr(n)?Er(e,r,"whitespace")(n):(e.enter("atxHeadingText"),a(n))}function o(t){return 35===t?(e.consume(t),o):(e.exit("atxHeadingSequence"),r(t))}function a(t){return null===t||35===t||Ir(t)?(e.exit("atxHeadingText"),r(t)):(e.consume(t),a)}}},ao=["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"],co=["pre","script","style","textarea"],lo={concrete:!0,name:"htmlFlow",resolveTo:function(e){let t=e.length;for(;t--&&("enter"!==e[t][0]||"htmlFlow"!==e[t][1].type););return t>1&&"linePrefix"===e[t-2][1].type&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e},tokenize:function(e,t,n){const s=this;let i,r,o,a,c;return function(t){return function(t){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(t),l}(t)};function l(a){return 33===a?(e.consume(a),d):47===a?(e.consume(a),r=!0,p):63===a?(e.consume(a),i=3,s.interrupt?t:D):gr(a)?(e.consume(a),o=String.fromCharCode(a),m):n(a)}function d(r){return 45===r?(e.consume(r),i=2,u):91===r?(e.consume(r),i=5,a=0,h):gr(r)?(e.consume(r),i=4,s.interrupt?t:D):n(r)}function u(i){return 45===i?(e.consume(i),s.interrupt?t:D):n(i)}function h(i){return i==="CDATA[".charCodeAt(a++)?(e.consume(i),6===a?s.interrupt?t:j:h):n(i)}function p(t){return gr(t)?(e.consume(t),o=String.fromCharCode(t),m):n(t)}function m(a){if(null===a||47===a||62===a||Ir(a)){const c=47===a,l=o.toLowerCase();return c||r||!co.includes(l)?ao.includes(o.toLowerCase())?(i=6,c?(e.consume(a),f):s.interrupt?t(a):j(a)):(i=7,s.interrupt&&!s.parser.lazy[s.now().line]?n(a):r?g(a):y(a)):(i=1,s.interrupt?t(a):j(a))}return 45===a||yr(a)?(e.consume(a),o+=String.fromCharCode(a),m):n(a)}function f(i){return 62===i?(e.consume(i),s.interrupt?t:j):n(i)}function g(t){return Cr(t)?(e.consume(t),g):I(t)}function y(t){return 47===t?(e.consume(t),I):58===t||95===t||gr(t)?(e.consume(t),v):Cr(t)?(e.consume(t),y):I(t)}function v(t){return 45===t||46===t||58===t||95===t||yr(t)?(e.consume(t),v):b(t)}function b(t){return 61===t?(e.consume(t),x):Cr(t)?(e.consume(t),b):y(t)}function x(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),c=t,w):Cr(t)?(e.consume(t),x):S(t)}function w(t){return t===c?(e.consume(t),c=null,k):null===t||kr(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||Ir(t)?b(t):(e.consume(t),S)}function k(e){return 47===e||62===e||Cr(e)?y(e):n(e)}function I(t){return 62===t?(e.consume(t),C):n(t)}function C(t){return null===t||kr(t)?j(t):Cr(t)?(e.consume(t),C):n(t)}function j(t){return 45===t&&2===i?(e.consume(t),T):60===t&&1===i?(e.consume(t),N):62===t&&4===i?(e.consume(t),F):63===t&&3===i?(e.consume(t),D):93===t&&5===i?(e.consume(t),P):!kr(t)||6!==i&&7!==i?null===t||kr(t)?(e.exit("htmlFlowData"),R(t)):(e.consume(t),j):(e.exit("htmlFlowData"),e.check(uo,L,R)(t))}function R(t){return e.check(ho,M,L)(t)}function M(t){return e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),E}function E(t){return null===t||kr(t)?R(t):(e.enter("htmlFlowData"),j(t))}function T(t){return 45===t?(e.consume(t),D):j(t)}function N(t){return 47===t?(e.consume(t),o="",A):j(t)}function A(t){if(62===t){const n=o.toLowerCase();return co.includes(n)?(e.consume(t),F):j(t)}return gr(t)&&o.length<8?(e.consume(t),o+=String.fromCharCode(t),A):j(t)}function P(t){return 93===t?(e.consume(t),D):j(t)}function D(t){return 62===t?(e.consume(t),F):45===t&&2===i?(e.consume(t),D):j(t)}function F(t){return null===t||kr(t)?(e.exit("htmlFlowData"),L(t)):(e.consume(t),F)}function L(n){return e.exit("htmlFlow"),t(n)}}},uo={partial:!0,tokenize:function(e,t,n){return function(s){return e.enter("lineEnding"),e.consume(s),e.exit("lineEnding"),e.attempt(Or,t,n)}}},ho={partial:!0,tokenize:function(e,t,n){const s=this;return function(t){return kr(t)?(e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),i):n(t)};function i(e){return s.parser.lazy[s.now().line]?n(e):t(e)}}},po={name:"htmlText",tokenize:function(e,t,n){const s=this;let i,r,o;return function(t){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(t),a};function a(t){return 33===t?(e.consume(t),c):47===t?(e.consume(t),x):63===t?(e.consume(t),v):gr(t)?(e.consume(t),k):n(t)}function c(t){return 45===t?(e.consume(t),l):91===t?(e.consume(t),r=0,p):gr(t)?(e.consume(t),y):n(t)}function l(t){return 45===t?(e.consume(t),h):n(t)}function d(t){return null===t?n(t):45===t?(e.consume(t),u):kr(t)?(o=d,A(t)):(e.consume(t),d)}function u(t){return 45===t?(e.consume(t),h):d(t)}function h(e){return 62===e?N(e):45===e?u(e):d(e)}function p(t){return t==="CDATA[".charCodeAt(r++)?(e.consume(t),6===r?m:p):n(t)}function m(t){return null===t?n(t):93===t?(e.consume(t),f):kr(t)?(o=m,A(t)):(e.consume(t),m)}function f(t){return 93===t?(e.consume(t),g):m(t)}function g(t){return 62===t?N(t):93===t?(e.consume(t),g):m(t)}function y(t){return null===t||62===t?N(t):kr(t)?(o=y,A(t)):(e.consume(t),y)}function v(t){return null===t?n(t):63===t?(e.consume(t),b):kr(t)?(o=v,A(t)):(e.consume(t),v)}function b(e){return 62===e?N(e):v(e)}function x(t){return gr(t)?(e.consume(t),w):n(t)}function w(t){return 45===t||yr(t)?(e.consume(t),w):S(t)}function S(t){return kr(t)?(o=S,A(t)):Cr(t)?(e.consume(t),S):N(t)}function k(t){return 45===t||yr(t)?(e.consume(t),k):47===t||62===t||Ir(t)?I(t):n(t)}function I(t){return 47===t?(e.consume(t),N):58===t||95===t||gr(t)?(e.consume(t),C):kr(t)?(o=I,A(t)):Cr(t)?(e.consume(t),I):N(t)}function C(t){return 45===t||46===t||58===t||95===t||yr(t)?(e.consume(t),C):j(t)}function j(t){return 61===t?(e.consume(t),R):kr(t)?(o=j,A(t)):Cr(t)?(e.consume(t),j):I(t)}function R(t){return null===t||60===t||61===t||62===t||96===t?n(t):34===t||39===t?(e.consume(t),i=t,M):kr(t)?(o=R,A(t)):Cr(t)?(e.consume(t),R):(e.consume(t),E)}function M(t){return t===i?(e.consume(t),i=void 0,T):null===t?n(t):kr(t)?(o=M,A(t)):(e.consume(t),M)}function E(t){return null===t||34===t||39===t||60===t||61===t||96===t?n(t):47===t||62===t||Ir(t)?I(t):(e.consume(t),E)}function T(e){return 47===e||62===e||Ir(e)?I(e):n(e)}function N(s){return 62===s?(e.consume(s),e.exit("htmlTextData"),e.exit("htmlText"),t):n(s)}function A(t){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(t),e.exit("lineEnding"),P}function P(t){return Cr(t)?Er(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)}}},mo={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&&cr(e,0,e.length,n),e},resolveTo:function(e,t){let n,s,i,r,o=e.length,a=0;for(;o--;)if(n=e[o][1],s){if("link"===n.type||"labelLink"===n.type&&n._inactive)break;"enter"===e[o][0]&&"labelLink"===n.type&&(n._inactive=!0)}else if(i){if("enter"===e[o][0]&&("labelImage"===n.type||"labelLink"===n.type)&&!n._balanced&&(s=o,"labelLink"!==n.type)){a=2;break}}else"labelEnd"===n.type&&(i=o);const c={type:"labelLink"===e[s][1].type?"link":"image",start:{...e[s][1].start},end:{...e[e.length-1][1].end}},l={type:"label",start:{...e[s][1].start},end:{...e[i][1].end}},d={type:"labelText",start:{...e[s+a+2][1].end},end:{...e[i-2][1].start}};return r=[["enter",c,t],["enter",l,t]],r=lr(r,e.slice(s+1,s+a+3)),r=lr(r,[["enter",d,t]]),r=lr(r,Dr(t.parser.constructs.insideSpan.null,e.slice(s+a+4,i-3),t)),r=lr(r,[["exit",d,t],e[i-2],e[i-1],["exit",l,t]]),r=lr(r,e.slice(i+1)),r=lr(r,[["exit",c,t]]),cr(e,s,e.length,r),e},tokenize:function(e,t,n){const s=this;let i,r,o=s.events.length;for(;o--;)if(("labelImage"===s.events[o][1].type||"labelLink"===s.events[o][1].type)&&!s.events[o][1]._balanced){i=s.events[o][1];break}return function(t){return i?i._inactive?d(t):(r=s.parser.defined.includes(fr(s.sliceSerialize({start:i.end,end:s.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelEnd"),a):n(t)};function a(t){return 40===t?e.attempt(fo,l,r?l:d)(t):91===t?e.attempt(go,l,r?c:d)(t):r?l(t):d(t)}function c(t){return e.attempt(yo,l,d)(t)}function l(e){return t(e)}function d(e){return i._balanced=!0,n(e)}}},fo={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 Ir(t)?no(e,i)(t):i(t)}function i(t){return 41===t?l(t):Xr(e,r,o,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(t)}function r(t){return Ir(t)?no(e,a)(t):l(t)}function o(e){return n(e)}function a(t){return 34===t||39===t||40===t?to(e,c,n,"resourceTitle","resourceTitleMarker","resourceTitleString")(t):l(t)}function c(t){return Ir(t)?no(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)}}},go={tokenize:function(e,t,n){const s=this;return function(t){return eo.call(s,e,i,r,"reference","referenceMarker","referenceString")(t)};function i(e){return s.parser.defined.includes(fr(s.sliceSerialize(s.events[s.events.length-1][1]).slice(1,-1)))?t(e):n(e)}function r(e){return n(e)}}},yo={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)}}},vo={name:"labelStartImage",resolveAll:mo.resolveAll,tokenize:function(e,t,n){const s=this;return function(t){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(t),e.exit("labelImageMarker"),i};function i(t){return 91===t?(e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelImage"),r):n(t)}function r(e){return 94===e&&"_hiddenFootnoteSupport"in s.parser.constructs?n(e):t(e)}}},bo={name:"labelStartLink",resolveAll:mo.resolveAll,tokenize:function(e,t,n){const s=this;return function(t){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(t),e.exit("labelMarker"),e.exit("labelLink"),i};function i(e){return 94===e&&"_hiddenFootnoteSupport"in s.parser.constructs?n(e):t(e)}}},xo={name:"lineEnding",tokenize:function(e,t){return function(n){return e.enter("lineEnding"),e.consume(n),e.exit("lineEnding"),Er(e,t,"linePrefix")}}},wo={name:"thematicBreak",tokenize:function(e,t,n){let s,i=0;return function(t){return e.enter("thematicBreak"),function(e){return s=e,r(e)}(t)};function r(r){return r===s?(e.enter("thematicBreakSequence"),o(r)):i>=3&&(null===r||kr(r))?(e.exit("thematicBreak"),t(r)):n(r)}function o(t){return t===s?(e.consume(t),i++,o):(e.exit("thematicBreakSequence"),Cr(t)?Er(e,r,"whitespace")(t):r(t))}}},So={continuation:{tokenize:function(e,t,n){const s=this;return s.containerState._closeFlow=void 0,e.check(Or,function(n){return s.containerState.furtherBlankLines=s.containerState.furtherBlankLines||s.containerState.initialBlankLine,Er(e,t,"listItemIndent",s.containerState.size+1)(n)},function(n){return s.containerState.furtherBlankLines||!Cr(n)?(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,i(n)):(s.containerState.furtherBlankLines=void 0,s.containerState.initialBlankLine=void 0,e.attempt(Io,t,i)(n))});function i(i){return s.containerState._closeFlow=!0,s.interrupt=void 0,Er(e,e.attempt(So,t,n),"linePrefix",s.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(i)}}},exit:function(e){e.exit(this.containerState.type)},name:"list",tokenize:function(e,t,n){const s=this,i=s.events[s.events.length-1];let r=i&&"linePrefix"===i[1].type?i[2].sliceSerialize(i[1],!0).length:0,o=0;return function(t){const i=s.containerState.type||(42===t||43===t||45===t?"listUnordered":"listOrdered");if("listUnordered"===i?!s.containerState.marker||t===s.containerState.marker:xr(t)){if(s.containerState.type||(s.containerState.type=i,e.enter(i,{_container:!0})),"listUnordered"===i)return e.enter("listItemPrefix"),42===t||45===t?e.check(wo,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 xr(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(Or,s.interrupt?n:l,e.attempt(ko,u,d))}function l(e){return s.containerState.initialBlankLine=!0,r++,u(e)}function d(t){return Cr(t)?(e.enter("listItemPrefixWhitespace"),e.consume(t),e.exit("listItemPrefixWhitespace"),u):n(t)}function u(n){return s.containerState.size=r+s.sliceSerialize(e.exit("listItemPrefix"),!0).length,t(n)}}},ko={partial:!0,tokenize:function(e,t,n){const s=this;return Er(e,function(e){const i=s.events[s.events.length-1];return!Cr(e)&&i&&"listItemPrefixWhitespace"===i[1].type?t(e):n(e)},"listItemPrefixWhitespace",s.parser.constructs.disable.null.includes("codeIndented")?void 0:5)}},Io={partial:!0,tokenize:function(e,t,n){const s=this;return Er(e,function(e){const i=s.events[s.events.length-1];return i&&"listItemIndent"===i[1].type&&i[2].sliceSerialize(i[1],!0).length===s.containerState.size?t(e):n(e)},"listItemIndent",s.containerState.size+1)}},Co={name:"setextUnderline",resolveTo:function(e,t){let n,s,i,r=e.length;for(;r--;)if("enter"===e[r][0]){if("content"===e[r][1].type){n=r;break}"paragraph"===e[r][1].type&&(s=r)}else"content"===e[r][1].type&&e.splice(r,1),i||"definition"!==e[r][1].type||(i=r);const o={type:"setextHeading",start:{...e[n][1].start},end:{...e[e.length-1][1].end}};return e[s][1].type="setextHeadingText",i?(e.splice(s,0,["enter",o,t]),e.splice(i+1,0,["exit",e[n][1],t]),e[n][1].end={...e[i][1].end}):e[n][1]=o,e.push(["exit",o,t]),e},tokenize:function(e,t,n){const s=this;let i;return function(t){let o,a=s.events.length;for(;a--;)if("lineEnding"!==s.events[a][1].type&&"linePrefix"!==s.events[a][1].type&&"content"!==s.events[a][1].type){o="paragraph"===s.events[a][1].type;break}return s.parser.lazy[s.now().line]||!s.interrupt&&!o?n(t):(e.enter("setextHeadingLine"),i=t,function(t){return e.enter("setextHeadingLineSequence"),r(t)}(t))};function r(t){return t===i?(e.consume(t),r):(e.exit("setextHeadingLineSequence"),Cr(t)?Er(e,o,"lineSuffix")(t):o(t))}function o(s){return null===s||kr(s)?(e.exit("setextHeadingLine"),t(s)):n(s)}}},jo={tokenize:function(e){const t=this,n=e.attempt(Or,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,Er(e,e.attempt(this.parser.constructs.flow,s,e.attempt(Zr,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)}}},Ro={resolveAll:No()},Mo=To("string"),Eo=To("text");function To(e){return{resolveAll:No("text"===e?Ao:void 0),tokenize:function(t){const n=this,s=this.parser.constructs[e],i=t.attempt(s,r,o);return r;function r(e){return c(e)?i(e):o(e)}function o(e){if(null!==e)return t.enter("data"),t.consume(e),a;t.consume(e)}function a(e){return c(e)?(t.exit("data"),i(e)):(t.consume(e),a)}function c(e){if(null===e)return!0;const t=s[e];let i=-1;if(t)for(;++i<t.length;){const e=t[i];if(!e.previous||e.previous.call(n,n.previous))return!0}return!1}}}}function No(e){return function(t,n){let s,i=-1;for(;++i<=t.length;)void 0===s?t[i]&&"data"===t[i][1].type&&(s=i,i++):t[i]&&"data"===t[i][1].type||(i!==s+2&&(t[s][1].end=t[i-1][1].end,t.splice(s+2,i-s-2),i=s+2),s=void 0);return e?e(t,n):t}}function Ao(e,t){let n=0;for(;++n<=e.length;)if((n===e.length||"lineEnding"===e[n][1].type)&&"data"===e[n-1][1].type){const s=e[n-1][1],i=t.sliceStream(s);let r,o=i.length,a=-1,c=0;for(;o--;){const e=i[o];if("string"==typeof e){for(a=e.length;32===e.charCodeAt(a-1);)c++,a--;if(a)break;a=-1}else if(-2===e)r=!0,c++;else if(-1!==e){o++;break}}if(t._contentTypeTextTrailing&&n===e.length&&(c=0),c){const i={type:n===e.length||r||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?a:s.start._bufferIndex+a,_index:s.start._index+o,line:s.end.line,column:s.end.column-c,offset:s.end.offset-c},end:{...s.end}};s.end={...i.start},s.start.offset===s.end.offset?Object.assign(s,i):(e.splice(n,0,["enter",i,t],["exit",i,t]),n+=2)}n++}return e}const Po={42:So,43:So,45:So,48:So,49:So,50:So,51:So,52:So,53:So,54:So,55:So,56:So,57:So,62:$r},Do={91:so},Fo={[-2]:Wr,[-1]:Wr,32:Wr},Lo={35:oo,42:wo,45:[Co,wo],60:lo,61:Co,95:wo,96:Hr,126:Hr},qo={38:_r,92:zr},Oo={[-5]:xo,[-4]:xo,[-3]:xo,33:vo,38:_r,42:Fr,60:[qr,po],91:bo,92:[ro,zr],93:mo,95:Fr,96:Kr},$o={null:[Fr,Ro]},zo=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:{null:[42,95]},contentInitial:Do,disable:{null:[]},document:Po,flow:Lo,flowInitial:Fo,insideSpan:$o,string:qo,text:Oo},Symbol.toStringTag,{value:"Module"})),_o=/[\0\t\n\r]/g,Bo=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function Ho(e){return e.replace(Bo,Wo)}function Wo(e,t,n){if(t)return t;if(35===n.charCodeAt(0)){const e=n.charCodeAt(1),t=120===e||88===e;return mr(n.slice(t?2:1),t?16:10)}return ar(n)||e}function Uo(e){return e&&"object"==typeof e?"position"in e||"type"in e?Qo(e.position):"start"in e||"end"in e?Qo(e):"line"in e||"column"in e?Ko(e):"":""}function Ko(e){return Vo(e&&e.line)+":"+Vo(e&&e.column)}function Qo(e){return Ko(e&&e.start)+"-"+Ko(e&&e.end)}function Vo(e){return e&&"number"==typeof e?e:1}const Go={}.hasOwnProperty;function Jo(e,t,n){return t&&"object"==typeof t&&(n=t,t=void 0),function(e){const t={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:i(v),autolinkProtocol:d,autolinkEmail:d,atxHeading:i(f),blockQuote:i(function(){return{type:"blockquote",children:[]}}),characterEscape:d,characterReference:d,codeFenced:i(m),codeFencedFenceInfo:r,codeFencedFenceMeta:r,codeIndented:i(m,r),codeText:i(function(){return{type:"inlineCode",value:""}},r),codeTextData:d,data:d,codeFlowValue:d,definition:i(function(){return{type:"definition",identifier:"",label:null,title:null,url:""}}),definitionDestinationString:r,definitionLabelString:r,definitionTitleString:r,emphasis:i(function(){return{type:"emphasis",children:[]}}),hardBreakEscape:i(g),hardBreakTrailing:i(g),htmlFlow:i(y,r),htmlFlowData:d,htmlText:i(y,r),htmlTextData:d,image:i(function(){return{type:"image",title:null,url:"",alt:null}}),label:r,link:i(v),listItem:i(function(e){return{type:"listItem",spread:e._spread,checked:null,children:[]}}),listItemValue:function(e){this.data.expectingFirstListItemValue&&(this.stack[this.stack.length-2].start=Number.parseInt(this.sliceSerialize(e),10),this.data.expectingFirstListItemValue=void 0)},listOrdered:i(b,function(){this.data.expectingFirstListItemValue=!0}),listUnordered:i(b),paragraph:i(function(){return{type:"paragraph",children:[]}}),reference:function(){this.data.referenceType="collapsed"},referenceString:r,resourceDestinationString:r,resourceTitleString:r,setextHeading:i(f),strong:i(function(){return{type:"strong",children:[]}}),thematicBreak:i(function(){return{type:"thematicBreak"}})},exit:{atxHeading:a(),atxHeadingSequence:function(e){const t=this.stack[this.stack.length-1];if(!t.depth){const n=this.sliceSerialize(e).length;t.depth=n}},autolink:a(),autolinkEmail:function(e){u.call(this,e),this.stack[this.stack.length-1].url="mailto:"+this.sliceSerialize(e)},autolinkProtocol:function(e){u.call(this,e),this.stack[this.stack.length-1].url=this.sliceSerialize(e)},blockQuote:a(),characterEscapeValue:u,characterReferenceMarkerHexadecimal:p,characterReferenceMarkerNumeric:p,characterReferenceValue:function(e){const t=this.sliceSerialize(e),n=this.data.characterReferenceType;let s;n?(s=mr(t,"characterReferenceMarkerNumeric"===n?10:16),this.data.characterReferenceType=void 0):s=ar(t),this.stack[this.stack.length-1].value+=s},characterReference:function(e){this.stack.pop().position.end=Zo(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=fr(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=Ho(t),n.identifier=fr(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=Zo(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=fr(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()}};Yo(t,(e||{}).mdastExtensions||[]);const n={};return function(e){let i={type:"root",children:[]};const a={stack:[i],tokenStack:[],config:t,enter:o,exit:c,buffer:r,resume:l,data:n},d=[];let u=-1;for(;++u<e.length;)"listOrdered"!==e[u][1].type&&"listUnordered"!==e[u][1].type||("enter"===e[u][0]?d.push(u):u=s(e,d.pop(),u));for(u=-1;++u<e.length;){const n=t[e[u][0]];Go.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]||ea).call(a,void 0,e[0])}for(i.position={start:Zo(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:Zo(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},u=-1;++u<t.transforms.length;)i=t.transforms[u](i)||i;return i};function s(e,t,n){let s,i,r,o,a=t-1,c=-1,l=!1;for(;++a<=n;){const t=e[a];switch(t[1].type){case"listUnordered":case"listOrdered":case"blockQuote":"enter"===t[0]?c++:c--,o=void 0;break;case"lineEndingBlank":"enter"===t[0]&&(!s||o||c||r||(r=a),o=void 0);break;case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:o=void 0}if(!c&&"enter"===t[0]&&"listItemPrefix"===t[1].type||-1===c&&"exit"===t[0]&&("listUnordered"===t[1].type||"listOrdered"===t[1].type)){if(s){let o=a;for(i=void 0;o--;){const t=e[o];if("lineEnding"===t[1].type||"lineEndingBlank"===t[1].type){if("exit"===t[0])continue;i&&(e[i][1].type="lineEndingBlank",l=!0),t[1].type="lineEnding",i=o}else if("linePrefix"!==t[1].type&&"blockQuotePrefix"!==t[1].type&&"blockQuotePrefixWhitespace"!==t[1].type&&"blockQuoteMarker"!==t[1].type&&"listItemIndent"!==t[1].type)break}r&&(!i||r<i)&&(s._spread=!0),s.end=Object.assign({},i?e[i][1].start:t[1].end),e.splice(i||a,0,["exit",s,t[2]]),a++,n++}if("listItemPrefix"===t[1].type){const i={type:"listItem",_spread:!1,start:Object.assign({},t[1].start),end:void 0};s=i,e.splice(a,0,["enter",i,t[2]]),a++,n++,r=void 0,o=!0}}}return e[t][1]._spread=l,n}function i(e,t){return function(n){o.call(this,e(n),n),t&&t.call(this,n)}}function r(){this.stack.push({type:"fragment",children:[]})}function o(e,t,n){this.stack[this.stack.length-1].children.push(e),this.stack.push(e),this.tokenStack.push([t,n||void 0]),e.position={start:Zo(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+"` ("+Uo({start:e.start,end:e.end})+"): it’s not open");s[0].type!==e.type&&(t?t.call(this,e,s[0]):(s[1]||ea).call(this,e,s[0])),n.position.end=Zo(e.end)}function l(){return sr(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:Zo(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=Zo(e.end)}function h(){this.data.atHardBreak=!0}function p(e){this.data.characterReferenceType=e.type}function m(){return{type:"code",lang:null,meta:null,value:""}}function f(){return{type:"heading",depth:0,children:[]}}function g(){return{type:"break"}}function y(){return{type:"html",value:""}}function v(){return{type:"link",title:null,url:"",children:[]}}function b(e){return{type:"list",ordered:"listOrdered"===e.type,start:null,spread:e._spread,children:[]}}}(n)(function(e){for(;!Gr(e););return e}(function(e){const t={constructs:ur([zo,...(e||{}).extensions||[]]),content:n(Tr),defined:[],document:n(Nr),flow:n(jo),lazy:{},string:n(Mo),text:n(Eo)};return t;function n(e){return function(n){return function(e,t,n){let s={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0};const i={},r=[];let o=[],a=[];const c={attempt:f(function(e,t){g(e,t.from)}),check:f(m),consume:function(e){kr(e)?(s.line++,s.column=1,s.offset+=-3===e?2:1,y()):-1!==e&&(s.column++,s.offset++),s._bufferIndex<0?s._index++:(s._bufferIndex++,s._bufferIndex===o[s._index].length&&(s._bufferIndex=-1,s._index++)),l.previous=e},enter:function(e,t){const n=t||{};return n.type=e,n.start=h(),l.events.push(["enter",n,l]),a.push(n),n},exit:function(e){const t=a.pop();return t.end=h(),l.events.push(["exit",t,l]),t},interrupt:f(m,{interrupt:!0})},l={code:null,containerState:{},defineSkip:function(e){i[e.line]=e.column,y()},events:[],now:h,parser:e,previous:null,sliceSerialize:function(e,t){return function(e,t){let n=-1;const s=[];let i;for(;++n<e.length;){const r=e[n];let o;if("string"==typeof r)o=r;else switch(r){case-5:o="\r";break;case-4:o="\n";break;case-3:o="\r\n";break;case-2:o=t?" ":"\t";break;case-1:if(!t&&i)continue;o=" ";break;default:o=String.fromCharCode(r)}i=-2===r,s.push(o)}return s.join("")}(u(e),t)},sliceStream:u,write:function(e){return o=lr(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=Dr(r,l.events,l),l.events)}};let d=t.tokenize.call(l,c);return t.resolveAll&&r.push(t),l;function u(e){return function(e,t){const n=t.start._index,s=t.start._bufferIndex,i=t.end._index,r=t.end._bufferIndex;let o;if(n===i)o=[e[n].slice(s,r)];else{if(o=e.slice(n,i),s>-1){const e=o[0];"string"==typeof e?o[0]=e.slice(s):o.shift()}r>0&&o.push(e[i].slice(0,r))}return o}(o,e)}function h(){const{_bufferIndex:e,_index:t,line:n,column:i,offset:r}=s;return{_bufferIndex:e,_index:t,line:n,column:i,offset:r}}function p(e){d=d(e)}function m(e,t){t.restore()}function f(e,t){return function(n,i,r){let o,d,u,p;return Array.isArray(n)?m(n):"tokenize"in n?m([n]):function(e){return function(t){const n=null!==t&&e[t],s=null!==t&&e.null;return m([...Array.isArray(n)?n:n?[n]:[],...Array.isArray(s)?s:s?[s]:[]])(t)}}(n);function m(e){return o=e,d=0,0===e.length?r:f(e[d])}function f(e){return function(n){return p=function(){const e=h(),t=l.previous,n=l.currentConstruct,i=l.events.length,r=Array.from(a);return{from:i,restore:function(){s=e,l.previous=t,l.currentConstruct=n,l.events.length=i,a=r,y()}}}(),u=e,e.partial||(l.currentConstruct=e),e.name&&l.parser.constructs.disable.null.includes(e.name)?v():e.tokenize.call(t?Object.assign(Object.create(l),t):l,c,g,v)(n)}}function g(t){return e(u,p),i}function v(e){return p.restore(),++d<o.length?f(o[d]):r}}}function g(e,t){e.resolveAll&&!r.includes(e)&&r.push(e),e.resolve&&cr(l.events,t,l.events.length-t,e.resolve(l.events.slice(t),l)),e.resolveTo&&(l.events=e.resolveTo(l.events,l))}function y(){s.line in i&&s.column<2&&(s.column=i[s.line],s.offset+=i[s.line]-1)}}(t,e,n)}}}(n).document().write(function(){let e,t=1,n="",s=!0;return function(i,r,o){const a=[];let c,l,d,u,h;for(i=n+("string"==typeof i?i.toString():new TextDecoder(r||void 0).decode(i)),d=0,n="",s&&(65279===i.charCodeAt(0)&&d++,s=void 0);d<i.length;){if(_o.lastIndex=d,c=_o.exec(i),u=c&&void 0!==c.index?c.index:i.length,h=i.charCodeAt(u),!c){n=i.slice(d);break}if(10===h&&d===u&&e)a.push(-3),e=void 0;else switch(e&&(a.push(-5),e=void 0),d<u&&(a.push(i.slice(d,u)),t+=u-d),h){case 0:a.push(65533),t++;break;case 9:for(l=4*Math.ceil(t/4),a.push(-2);t++<l;)a.push(-1);break;case 10:a.push(-4),t=1;break;default:e=!0,t=1}d=u+1}return o&&(e&&a.push(-5),n&&a.push(n),a.push(null)),a}}()(e,t,!0))))}function Zo(e){return{line:e.line,column:e.column,offset:e.offset}}function Yo(e,t){let n=-1;for(;++n<t.length;){const s=t[n];Array.isArray(s)?Yo(e,s):Xo(e,s)}}function Xo(e,t){let n;for(n in t)if(Go.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 ea(e,t){throw e?new Error("Cannot close `"+e.type+"` ("+Uo({start:e.start,end:e.end})+"): a different token (`"+t.type+"`, "+Uo({start:t.start,end:t.end})+") is open"):new Error("Cannot close document, a token (`"+t.type+"`, "+Uo({start:t.start,end:t.end})+") is still open")}const ta=new WeakMap;function na(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(Jo(e))}function sa(e,t){const n=t.trim().toLowerCase();return n?e.flatMap((e,t)=>{if(pi(e))return[];let s=ta.get(e);s?.content!==e.content&&(s={content:e.content,text:na(e.content).toLowerCase()},ta.set(e,s));const i=s.text,r=[];for(let o=i.indexOf(n);o>=0;o=i.indexOf(n,o+n.length))r.push({index:t,message:e,occurrence:r.length});return r}):[]}function ia(e,t){const n=t.trim().toLowerCase();if(!n)return[];const s=document.createTreeWalker(e,NodeFilter.SHOW_TEXT),i=[];let r="";for(;s.nextNode();){const e=s.currentNode;e.parentElement?.closest('button, [hidden], [aria-hidden="true"]')||(i.push({node:e,start:r.length,end:r.length+e.length}),r+=e.data)}const o=[],a=r.toLowerCase();for(let c=a.indexOf(n);c>=0;c=a.indexOf(n,c+n.length)){const e=c+n.length,t=i.find(e=>e.end>c),s=i.find(t=>t.end>=e);if(!t||!s)continue;const r=document.createRange();r.setStart(t.node,c-t.start),r.setEnd(s.node,e-s.start),o.push(r)}return o}const ra=160;function oa(e){return Math.max(0,e-ra)}const aa=()=>null,ca=()=>()=>{};function la({activeSession:e,activeUsage:t,messages:n,renameTitle:s,busy:i,t:a,onBrowseFiles:c,onClose:l,onExport:u,onJumpToMessage:h,onRename:p,onRenameTitleChange:m,onToggleArchived:y,onTogglePinned:v,onViewChanges:b}){const[x,w]=o.useState(""),{copyText:S,feedback:k}=Zs(a.commandCopied,a.copyResumeFailed),I=o.useRef(null),C=f(l,I),j=o.useMemo(()=>Ht(e),[e]),R=o.useMemo(()=>{const e=x.trim().toLowerCase();return e?n.map((e,t)=>({message:e,index:t})).filter(({message:t})=>("user"===t.role||"assistant"===t.role)&&t.content.toLowerCase().includes(e)).slice(0,20):[]},[n,x]);return r.jsxs("div",{"aria-labelledby":"session-detail-title","aria-modal":"true",className:"session-detail-drawer",ref:C,role:"dialog",tabIndex:-1,children:[r.jsx("div",{className:"drawer-backdrop",onClick:l,"aria-hidden":"true"}),r.jsxs("aside",{className:"session-detail-panel",children:[r.jsxs("header",{className:"drawer-header",children:[r.jsxs("div",{children:[r.jsx("span",{className:"eyebrow",children:e.agent}),r.jsx("strong",{id:"session-detail-title",title:d(e),children:r.jsx(Yi,{title:d(e),draft:s,label:a.rename,disabled:i,onDraftChange:m,onCommit:p},e.sessionId)})]}),r.jsx("button",{"aria-label":a.closeSessionDetails,title:a.closeSessionDetails,className:"icon-button",onClick:l,ref:I,type:"button",children:r.jsx(We,{"aria-hidden":"true"})})]}),r.jsxs("div",{className:"detail-info-grid",children:[r.jsxs("div",{children:[r.jsx(te,{"aria-hidden":"true"}),r.jsx("span",{children:a.workingDirectory}),r.jsx("strong",{title:e.cwd,children:e.cwd})]}),r.jsxs("div",{children:[r.jsx(ye,{"aria-hidden":"true"}),r.jsx("span",{children:a.messages}),r.jsx("strong",{children:n.filter(e=>"user"===e.role||"assistant"===e.role).length})]}),r.jsxs("div",{children:[r.jsx(le,{"aria-hidden":"true"}),r.jsx("span",{children:a.session}),r.jsx("strong",{title:e.sessionId,children:e.sessionId})]}),r.jsxs("div",{children:[r.jsx(ze,{"aria-hidden":"true"}),r.jsx("span",{children:a.runtime}),r.jsx("strong",{children:a.runtimeState(e.runtime.state)})]})]}),e.branch||e.diffStat?r.jsxs("button",{className:"detail-command-card detail-changes-card",type:"button",onClick:b,children:[r.jsx(oe,{"aria-hidden":"true"}),r.jsx("span",{className:"detail-change-label",children:e.branch??a.changes}),r.jsx("span",{className:"detail-change-stats",role:"group","aria-label":a.changes,children:e.diffStat?r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"diff-add",children:["+",e.diffStat.additions]}),r.jsxs("span",{className:"diff-del",children:["-",e.diffStat.deletions]})]}):null})]}):null,r.jsxs("label",{className:"detail-search",children:[r.jsx(Te,{"aria-hidden":"true"}),r.jsx("input",{value:x,onChange:e=>w(e.target.value),placeholder:a.searchMessages}),x.trim()?r.jsx("small",{children:a.searchResultCount(R.length)}):null]}),x.trim()&&R.length?r.jsx("div",{className:"detail-search-results",children:R.map(({message:e,index:t})=>r.jsxs("button",{type:"button",onClick:()=>{h(t,x),l()},children:[r.jsx("span",{children:cn(e,a)}),r.jsx("strong",{children:e.content})]},`${e.historyKey??e.timestamp??t}:${t}`))}):null,x.trim()?null:r.jsxs(r.Fragment,{children:[r.jsxs("button",{className:"detail-command-card",type:"button",onClick:c,children:[r.jsx(te,{"aria-hidden":"true"}),r.jsx("span",{children:a.browseFiles})]}),j&&r.jsxs("button",{className:"detail-command-card",type:"button",onClick:()=>{S(j)},children:[r.jsx(W,{"aria-hidden":"true"}),r.jsx("span",{title:j,children:j})]}),r.jsx(Ys,{feedback:k}),r.jsxs("div",{className:"detail-action-grid",children:[r.jsxs("button",{className:"icon-text-button",disabled:i,type:"button",onClick:v,children:[r.jsx(Ie,{"aria-hidden":"true"}),e.pinned?a.unpin:a.pin]}),r.jsxs("button",{className:"icon-text-button",disabled:i,type:"button",onClick:y,children:[r.jsx(P,{"aria-hidden":"true"}),e.archived?a.unarchive:a.archive]}),r.jsxs("button",{className:"icon-text-button",type:"button",onClick:u,children:[r.jsx(g,{"aria-hidden":"true"}),a.exportSession]})]}),t?r.jsxs("p",{className:"detail-usage",children:[a.usage,": ",t.limits?.fiveHour?.usedPercent??"-","% 5h ·"," ",t.limits?.weekly?.usedPercent??"-","% weekly"]}):null,r.jsxs("p",{className:"detail-usage",children:[a.created," ",an(e.createdAt,Date.now(),a)]})]})]})]})}function da({client:e,activeSession:t,activeSessionId:n,activeModelOptions:s,activeQueue:i,queueControls:a,activeUsage:c,agent:l,approvalMode:d,attachments:u,busy:h,cwd:p,draft:m,effort:f,errorText:g,failedSend:y,onDismissFailedSend:v,fastMode:b,historyLoading:x,hasOlderHistory:w,olderHistoryLoading:S,onLoadOlderHistory:k,messages:I,messagesSessionId:C,model:j,phase:R,quickReplies:M,onQuickRepliesChange:E,quickRepliesOpen:T,onQuickRepliesOpenChange:N,onSendQuickReply:A,renameTitle:P,respondingSessionIds:D,sendShortcut:F,skills:L,uploadBusy:q,detailsOpen:O,t:$,onApprovalModeChange:z,onBrowseFiles:_,onCancelQueuedTurn:B,onClearInterrupt:H,onDraftChange:W,onDetailsOpenChange:U,onEffortChange:K,onExportActiveSession:Q,onRewindMessage:V,onFastModeChange:G,onRetryFailedSend:J,onModelChange:Z,onOpenRemoteFile:Y,onInterrupt:X,onRetry:ee,onDismissError:te,onRefreshSkills:ne,onRenameSession:se,onRenameTitleChange:ie,onRemoveAttachment:re,onSubmit:oe,onToggleArchived:ae,onTogglePinned:ce,onUploadFiles:le,onViewChanges:de}){const ue=ut(e,l,p,n,j,s,$),he=function(e,t,n,s){const i=o.useSyncExternalStore(e.submission?.subscribe??ca,e.submission?.getSnapshot??aa,aa),r=o.useRef(new Set),a=async e=>{if(!r.current.has(s)){r.current.add(s);try{await e()}finally{r.current.delete(s)}}};return{sending:!!i?.some(e=>e.sessionId===s),submit:t=>{if(t?.preventDefault(),n)return a(()=>e())},retry:()=>a(t)}}(oe,J,"connected"===R&&!h&&!!m.trim(),n),pe=o.useRef({onRewindMessage:V,onOpenRemoteFile:Y,onDismissFailedSend:v,retry:he.retry});o.useLayoutEffect(()=>{pe.current={onRewindMessage:V,onOpenRemoteFile:Y,onDismissFailedSend:v,retry:he.retry}});const[me,fe]=o.useState(null),[ge,ye]=o.useState(null),[ve,be]=o.useState(!1),xe=function(e,t,n){let s;for(let o=t.length-1;o>=0;o--)if("assistant"===t[o].role&&"info"!==t[o].type){s=t[o];break}const i=s?`${s.historyKey??s.timestamp}:${s.content.length}`:"",r=o.useRef({sessionId:e,revision:i}),[a,c]=o.useState(!1);return o.useEffect(()=>{r.current.sessionId===e&&n?i&&i!==r.current.revision&&c(!0):c(!1),r.current={sessionId:e,revision:i}},[e,i,n]),n&&r.current.sessionId===e&&a}(n,C===n?I:[],ve),we=o.useRef(null),Se=o.useRef([]),ke=o.useRef(null),Ie=o.useRef(null),Ce=o.useRef(!1),je=o.useRef(!1),Re=o.useRef(!0),Me=o.useRef(0),Ee=o.useRef(0),Te=o.useMemo(()=>function(e){const t=[];for(let n=0;n<e.length;n+=1){const s=e[n];if(!pi(s)){t.push({type:"message",index:n,message:s});continue}const i=[];let r=n;for(;r<e.length&&pi(e[r]);)i.push({index:r,message:e[r]}),r+=1;t.push({type:"toolGroup",entries:i,id:`tool-group:${i.map(({index:e,message:t})=>fi(t,e)).join("|")}`}),n=r-1}return t}(I),[I]),Ne=Boolean(n&&D.has(n)),Ae=Ne&&C===n&&!x,Pe=Ae&&"assistant"===I.at(-1)?.role&&"info"!==I.at(-1)?.type?I.length-1:-1,[De,Fe]=o.useState(!1),{ensureMessageVisible:Le,hiddenItemCount:qe,hiddenLaterItemCount:Oe,revealAll:$e,revealEarlier:ze,revealLatest:_e,revealStart:Be,visibleItems:He}=function(e,t,n=!1){const s=t.length,[i,r]=o.useState(()=>({sessionId:e,start:oa(s),total:s})),a=i.sessionId!==e?oa(s):n?0:-1===i.start?-1:s>i.total&&i.start+ra>=i.total?oa(s):Math.min(i.start,oa(s));o.useLayoutEffect(()=>{i.sessionId===e&&i.start===a&&i.total===s||r({sessionId:e,start:a,total:s})},[e,a,i,s]);const c=o.useCallback(()=>{r(t=>({sessionId:e,start:Math.max(0,(t.sessionId===e?t.start:oa(s))-120),total:s}))},[e,s]),l=o.useCallback(n=>{const i=t.findIndex(e=>function(e,t){return"message"===e.type?e.index===t:e.entries.some(e=>e.index===t)}(e,n));if(-1===a||i<0||i>=a&&i<a+ra)return!1;const o=Math.min(oa(s),Math.max(0,i-40));return r({sessionId:e,start:o,total:s}),!0},[t,e,a,s]),d=o.useCallback(()=>{r({sessionId:e,start:oa(s),total:s})},[e,s]),u=o.useCallback(()=>{r({sessionId:e,start:0,total:s})},[e,s]),h=Math.max(0,a),p=-1===a?s:Math.min(s,a+ra);return{ensureMessageVisible:l,hiddenItemCount:h,hiddenLaterItemCount:Math.max(0,s-p),revealEarlier:c,revealLatest:d,revealStart:u,revealAll:()=>r({sessionId:e,start:-1,total:s}),visibleItems:o.useMemo(()=>t.slice(h,p),[t,h,p])}}(n,Te,De),We=o.useRef(!1),Ue=o.useRef(null),Ke=o.useMemo(()=>Boolean(y&&He.some(e=>"message"===e.type&&e.message.historyKey===y.historyKey)),[y,He]),Qe=o.useRef(null),{copyText:Ve,feedback:Ge}=Zs($.messageCopied,$.copyFailed),Je=function(e,t,n,s){const[i,r]=o.useState(""),[a,c]=o.useState(0),l=o.useMemo(()=>sa(e,i),[e,i]),d=l.length?a%l.length:0,u=l[d],h=o.useRef(s);return h.current=s,o.useEffect(()=>{r(""),c(0)},[t]),o.useEffect(()=>{u&&h.current(u.index)},[i,d,u?.index]),o.useEffect(()=>{const e=n.current;if(!i.trim()||!e||"undefined"==typeof CSS||!CSS.highlights||"undefined"==typeof Highlight)return;let t=0,s=!1;const r=()=>{const t=[],n=[];for(const s of e.querySelectorAll(".message-frame[data-message-index]")){const e=s.querySelector(".message-markdown, .message-markdown-source, .message > pre");if(!e)continue;const r=ia(e,i);t.push(...r),Number(s.getAttribute("data-message-index"))===u?.index&&r[u.occurrence]&&n.push(r[u.occurrence])}if(CSS.highlights.set("conversation-matches",new Highlight(...t)),CSS.highlights.set("conversation-current",new Highlight(...n)),n[0]&&!s){s=!0;const t=n[0].getBoundingClientRect(),i=e.getBoundingClientRect();(t.top<i.top||t.bottom>i.bottom)&&(e.scrollTop+=t.top-i.top-i.height/2)}},o=()=>{cancelAnimationFrame(t),t=requestAnimationFrame(()=>{t=requestAnimationFrame(r)})},a=new MutationObserver(o);return a.observe(e,{childList:!0,characterData:!0,subtree:!0}),o(),()=>{a.disconnect(),cancelAnimationFrame(t),CSS.highlights.delete("conversation-matches"),CSS.highlights.delete("conversation-current")}},[i,d,u?.index,u?.occurrence,n]),{query:i,matchCount:l.length,activeMatchIndex:l.length?d+1:0,activeMessageIndex:u?.index,onChange:e=>{r(e),c(0)},onJump:(t,n)=>{r(n),c(Math.max(0,sa(e,n).findIndex(e=>e.index===t)))},onNext:()=>c(e=>l.length?(e+1)%l.length:0),onPrevious:()=>c(e=>l.length?(e+l.length-1)%l.length:0)}}(I,n,we,e=>((e,t="smooth")=>{Re.current=!1,Me.current=0;const n=Le(e),s=()=>Se.current[e]?.scrollIntoView({behavior:t,block:"center"});n?requestAnimationFrame(()=>requestAnimationFrame(s)):s()})(e,"instant")),Ze=o.useCallback(()=>{const e=we.current;e&&(Re.current=!0,Me.current=0,e.scrollTop=e.scrollHeight,be(!1))},[]),Ye=o.useCallback(e=>{Re.current=!0,Me.current=0,je.current=!0,Ce.current=!1,Qe.current=null;const t=we.current,n=t?t.scrollHeight-t.scrollTop-t.clientHeight:0,s=e??(0===Oe&&t&&n<=t.clientHeight?"smooth":"auto"),i=()=>{const e=we.current;e&&je.current&&(e.scrollTo({top:e.scrollHeight,behavior:s}),be(!1),requestAnimationFrame(()=>{je.current=!1}))};Oe>0?(_e(),requestAnimationFrame(()=>requestAnimationFrame(i))):i()},[Oe,_e]),Xe=()=>{const e=we.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,He))},et=async()=>{if(!n||!w||!k||x||S||Ue.current)return;const e=n;Ue.current=e,We.current=!0,Re.current=!1,Ce.current=!0,Xe(),Fe(!0);try{await k()}finally{Ue.current===e&&(Ue.current=null,Fe(!1))}},tt=()=>{const e=we.current;if(!e)return;Me.current>0&&e.scrollTop<160&&C===n&&!Ce.current&&!je.current&&(qe>0?(Ce.current=!0,Xe(),ze()):et());const t=e.scrollTop>Ee.current;Ee.current=e.scrollTop;const s=e.scrollHeight-e.scrollTop-e.clientHeight;Me.current>0&&!je.current&&!Ce.current&&(Re.current=t&&s<=2&&0===Oe),be(s>180||Oe>0)};o.useLayoutEffect(()=>{Oe>0&&be(!0)},[Oe]);const nt=function(e,t,n,s,i,r,o,a=0){const c=()=>{const o=t.current||s.current;n.current=null,s.current=!1,t.current=!1,i.current=performance.now();const a=e.current;r.current=a?.scrollTop??0,o&&a?.scrollTo({top:a.scrollTop,behavior:"auto"})};return{toStart:()=>{const c=e.current;c&&(n.current=null,s.current=!1,t.current=!1,i.current=performance.now(),r.current=0,c.scrollTo({top:c.scrollTop,behavior:"auto"}),a>0&&o?.(),requestAnimationFrame(()=>requestAnimationFrame(()=>e.current?.scrollTo({top:0,behavior:a>0?"auto":"smooth"}))))},onWheel:t=>{if(!t.deltaY)return;const n=e.current;(t.deltaY<0||n&&n.scrollHeight-n.scrollTop-n.clientHeight>2)&&c()},onPointerDown:e=>{const t=e.currentTarget.getBoundingClientRect();(1===e.button||e.clientX>=t.right-16)&&c()},onTouchStart:c,onKeyDown:e=>{e.target instanceof Element&&e.target.closest('input,textarea,[contenteditable="true"]')||["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(e.key)&&c()}}}(we,Re,Ie,je,Me,Ee,Be,qe),st=function(e){const t=e.at(-1);return t?`${e.length}:${t.historyKey??""}:${t.timestamp??""}:${t.content.length}`:"0"}(I);o.useLayoutEffect(()=>{ke.current!==n&&(Qe.current=null,Ce.current=!1,We.current=!1,Ue.current=null,Fe(!1));const e=Qe.current,t=we.current;if(e&&t){if(De)return;return qe>0&&We.current?void Be():(function(e,t,n,s){const i=t.message,r=i?n.findIndex(e=>e===i||(i.historyKey?e.historyKey===i.historyKey:e.role===i.role&&e.timestamp===i.timestamp&&e.content===i.content)):-1,o=r>=0?s[r]:t.element;e.scrollTop+=o?.isConnected?o.getBoundingClientRect().top-e.getBoundingClientRect().top-t.top:e.scrollHeight-t.height}(t,e,I,Se.current),Qe.current=null,Ce.current=!1,void(We.current=!1))}if(ke.current!==n&&(ke.current=n,Ie.current=n,fe(null),ye(null)),!we.current)return;const s=C===n;if(null!==n&&Ie.current===n&&s&&(!x||I.length>0)){Ze();let e=0,t=-1,s=0;const i=performance.now(),r=()=>{if(Ie.current!==n)return;Ze();const o=we.current?.scrollHeight??0;s=o===t?s+1:0,t=o;const a=performance.now()-i>=1400;!x&&s>=4||!x&&a?Ie.current=null:a||(e=requestAnimationFrame(r))};return e=requestAnimationFrame(r),be(!1),()=>cancelAnimationFrame(e)}Re.current&&0===Oe&&Ze()},[n,qe,Oe,x,st,De,Be,I.length,C,R,Ae,Ze]),o.useLayoutEffect(()=>{const e=we.current;if(!e)return;const t=new ResizeObserver(()=>{Re.current&&0===Oe&&Ze()});t.observe(e);for(const n of e.children)t.observe(n);return()=>t.disconnect()},[n,st,qe,Oe,Ae,Ze]);const it=Je.activeMessageIndex;return function(e,t,n){const s=o.useRef(n);s.current=n;const i=o.useRef(!1),[r,a]=o.useState(0);o.useLayoutEffect(()=>{i.current=!1;const t=t=>{"focusin"===t.type&&t.target instanceof Element&&t.target.contains(e.current)||(i.current=t.target instanceof Element&&Boolean(e.current?.contains(t.target))&&!t.target.closest("input,textarea,select")&&!t.target.isContentEditable)},n=[["pointerdown",t],["focusin",t],["keydown",e=>{i.current&&!e.isComposing&&(!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey||"a"!==e.key.toLowerCase()||(e.preventDefault(),s.current(),a(e=>e+1)))}]];return n.forEach(([e,t])=>document.addEventListener(e,t,!0)),()=>n.forEach(([e,t])=>document.removeEventListener(e,t,!0))},[e,t]),o.useLayoutEffect(()=>{if(!i.current)return;const t=e.current?.querySelectorAll(".message-frame"),n=t?.[t.length-1];n&&window.getSelection()?.setBaseAndExtent(t[0],0,n,n.childNodes.length)},[r,e,t])}(we,n,()=>{Xe(),$e()}),r.jsxs("section",{className:"chat-pane","aria-label":$.chat,children:[r.jsx(tr,{activeSession:t,agent:l,cwd:p,t:$,onOpenDetails:()=>t&&U(!0),onScrollToStart:nt.toStart,renameTitle:P,busy:h,onRename:se,onRenameTitleChange:ie,onViewChanges:de,search:Je}),r.jsxs("div",{className:"message-scroll","data-session-id":C===n?n??void 0:void 0,"aria-busy":x,"data-history-loading":x?"true":"false","data-rendered-items":He.length,"data-hidden-items":qe,"data-hidden-later-items":Oe,"data-total-messages":I.length,ref:we,onScroll:tt,...nt,onWheel:e=>{nt.onWheel(e),e.deltaY<0&&tt()},children:[x&&0===I.length?r.jsx(ei,{label:$.loadingHistory}):null,x||0!==I.length||Ae?null:r.jsx(dt,{title:t?$.noVisibleMessages:$.startDaemonSession,hint:$.emptyChatHint}),w&&0===qe?r.jsx("div",{className:"conversation-window-gate",children:r.jsx("button",{type:"button",disabled:S,onClick:()=>{et()},children:S?$.loadingHistory:$.loadEarlierMessages})}):null,qe>0?r.jsx("div",{className:"conversation-window-gate",children:r.jsx("button",{type:"button",onClick:()=>{Ce.current=!0,Xe(),ze()},children:$.showEarlierMessages(qe)})}):null,r.jsx(Ki,{items:He,activeQueue:C===n?i:void 0,actions:pe,messageRefs:Se,activeMatchedMessageIndex:it,baseCwd:t?.cwd,canRewind:!h&&!Ne,hiddenLaterItemCount:Oe,replyingMessageIndex:Pe,openSourceKey:me,openToolKey:ge,setOpenSourceKey:fe,setOpenToolKey:ye,copyText:Ve,failedSend:y,t:$}),Ae&&0===Oe&&Pe<0?r.jsx("div",{className:"message-frame assistant","data-replying-placeholder":"true",children:r.jsx("div",{className:"message assistant replying-placeholder",children:r.jsx(_i,{label:$.replyingMessage})})}):null,Oe>0?r.jsx("div",{className:"conversation-window-gate",children:r.jsx("button",{type:"button",onClick:()=>Ye("auto"),children:$.showLatestMessages(Oe)})}):null,r.jsx("div",{"aria-hidden":"true",className:"message-latest-anchor"})]}),ve?r.jsx(ni,{label:xe?$.interactionNewReply:$.interactionLatest,onClick:()=>Ye()}):null,r.jsx(Ys,{feedback:Ge}),r.jsx(Gs,{terminals:t?.runtime.backgroundTerminals,t:$},`terminals:${n}`),r.jsx(Zi,{client:e,activeSession:t,busy:h,errorText:g,failedSend:y,failedSendVisibleInConversation:Ke,onClearInterrupt:H,onDismissError:te,onDismissFailedSend:v,onRetry:ee,onRetryFailedSend:()=>{he.retry()},t:$}),r.jsx(Vs,{activeModelOptions:ue,activeQueue:i,queueControls:{...a,onAction:(e,t)=>(Ye("auto"),a.onAction(e,t))},agent:l,approvalMode:d,attachments:u,busy:h,sending:he.sending,responding:Ne,onStop:X,draft:m,effort:f,fastMode:b,model:j,phase:R,quickReplies:M,onQuickRepliesChange:E,quickRepliesOpen:T,onQuickRepliesOpenChange:N,onSendQuickReply:A,sendShortcut:F,skills:L,uploadBusy:q,onApprovalModeChange:z,onCancelQueuedTurn:B,onDraftChange:W,onEffortChange:K,onFastModeChange:G,onModelChange:Z,onRemoveAttachment:re,onOpenRemoteFile:Y,onRefreshSkills:ne,onSubmit:e=>(Ye("auto"),he.submit(e)),onUploadFiles:le,t:$},n),O&&t?r.jsx(la,{activeSession:t,activeUsage:c,busy:h,messages:I,renameTitle:P,t:$,onBrowseFiles:()=>{U(!1),_()},onClose:()=>U(!1),onExport:Q,onJumpToMessage:(e,t)=>{Je.onJump(e,t)},onRename:se,onRenameTitleChange:ie,onToggleArchived:ae,onTogglePinned:ce,onViewChanges:()=>{U(!1),de(t.sessionId)}}):null]})}const ua=["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"],ha=["authorization","proxy-authorization"],pa=["cookie","set-cookie"],ma=[...ha,...pa],fa=(e,t)=>t.length-e.length,ga=[...ua].sort(fa).join("|"),ya=ua.filter(e=>!ma.includes(e)).sort(fa).join("|"),va=[...ha].sort(fa).join("|"),ba=[...pa].sort(fa).join("|"),xa=new RegExp(`(?:${ga}|credential|private[-_ ]?key|session[-_ ]?id|e-?mail|phone|mobile|address)`,"i"),wa=new RegExp(`(["']?(?:${va})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|(?:Basic|Bearer)\\s+[^\\s,;}]+|AWS4-HMAC-SHA256[^\\r\\n]*(?=\\r?$)|[^\\s,;}]+)`,"gim"),Sa=new RegExp(`(["']?(?:${ba})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\r\\n]+)`,"gi"),ka=new RegExp(`(["']?(?:${ya})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\s,;}&]+)`,"gi"),Ia=new RegExp(`([?&](?:${ga})=)[^&\\s]+`,"gi");function Ca(e){return function(e){return e.replace(/(^|[\s("'=])(?:file:\/\/)?\/(?:Users|home|Volumes|private|var|tmp|storage\/emulated\/\d+|data\/user\/\d+|sdcard)[^\r\n"'<>]*?\.[A-Za-z0-9]{1,12}\b/gim,"$1[LOCAL_PATH]").replace(/(^|[\s("'=])(?:file:\/\/)?\/(?:Users|home|Volumes|private|var|tmp|storage\/emulated\/\d+|data\/user\/\d+|sdcard)(?:\/[^\s"'<>]*)?/gim,"$1[LOCAL_PATH]").replace(/\b[A-Z]:\\(?:Users\\)?[^\r\n"'<>]*?\.[A-Za-z0-9]{1,12}\b/gi,"[LOCAL_PATH]").replace(/\b[A-Z]:\\(?:Users\\)?[^\s"'<>]+/gi,"[LOCAL_PATH]").replace(/\\\\[^\s\\"'<>]+\\[^\r\n"'<>]+/g,"[LOCAL_PATH]").replace(/\bcontent:\/\/[^\s"'<>]+/gi,"[LOCAL_PATH]").replace(/\b(?:[\w.-]+\/)+(?:[\w.-]+\.(?:md|txt|json|ya?ml|pdf|docx?|xlsx?|csv|log|db|sqlite|png|jpe?g|webp|gif))\b/gi,"[RELATIVE_PATH]")}(function(e,t="[REDACTED]"){const n=(e,n,s)=>{const i='"'===s[0]||"'"===s[0]?s[0]:"";if(!i)return`${n}${t}`;const r=s.slice(1,-1).trim(),o=/^(Basic|Bearer)\b/i.exec(r)?.[1];return`${n}${i}${o?`${o} `:""}${t}${i}`};return e.replace(/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gi,t).replace(wa,n).replace(Sa,n).replace(ka,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(Ia,`$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 ja(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 Ra(e,t={}){const n=new AbortController,s=Number.isFinite(t.timeoutMs)&&(t.timeoutMs??0)>0?t.timeoutMs:15e3;let i;try{const r=(t.transport??ja)({url:t.endpoint??"https://service.lifeos.vip/feedback",method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:n.signal}),o=new Promise((e,t)=>{i=setTimeout(()=>{n.abort(),t(new Error("Feedback request timed out"))},s)}),a=await Promise.race([r,o]),c=function(e){try{const t=JSON.parse(e);return t&&"object"==typeof t?t:{}}catch{return{}}}(a.body);if(a.status<200||a.status>=300||0!==c.code)throw new Error(c.message||a.statusText||"Feedback request failed");if("string"!=typeof c.data?.id||!c.data.id||"string"!=typeof c.data.createdAt)throw new Error("Feedback response is invalid");return{id:c.data.id,createdAt:c.data.createdAt,issueFingerprint:"string"==typeof c.data?.issueFingerprint?c.data.issueFingerprint:void 0,issueOccurrence:"number"==typeof c.data?.issueOccurrence?c.data.issueOccurrence:void 0}}finally{i&&clearTimeout(i)}}const Ma=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 Ea(e){const t={contextSchemaVersion:1};if(e)for(const[n,s]of Object.entries(e))Ma.has(n)&&void 0!==s&&(t[n]=s);return function(e,t={}){if(!e)return{};const n=Math.max(0,t.characterBudget??6e4),s=Math.max(0,t.maxArrayEntries??50),i=Math.max(0,t.maxDepth??8),r=Math.max(0,t.maxObjectEntries??80),o=Math.max(0,t.maxStringLength??4e3),a={remaining:n},c=new WeakSet,l=(e,t)=>{if(a.remaining<=0)return"[TRUNCATED]";if(null===e||"boolean"==typeof e||"number"==typeof e)return e;if("bigint"==typeof e)return e.toString();if("string"==typeof e){const t=Ca(e).slice(0,Math.min(o,a.remaining));return a.remaining-=t.length,t}if(t>=i)return"[MAX_DEPTH]";if("object"!=typeof e)return Ca(String(e)).slice(0,Math.min(200,a.remaining));if(c.has(e))return"[Circular]";if(c.add(e),Array.isArray(e))return e.slice(0,s).map(e=>l(e,t+1));const n={};for(const[s,i]of Object.entries(e).slice(0,r)){if(a.remaining<=0)break;const e=Ca(s).slice(0,Math.min(120,a.remaining));a.remaining-=e.length,n[e]=xa.test(s)?"[REDACTED]":l(i,t+1)}return n};return l(e,0)}(t)}const Ta={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"},Na={title:"意见反馈",subtitle:"报告问题,或告诉我们希望改进的地方。",bug:"问题",feature:"建议",description:"详细说明",descriptionPlaceholder:"发生了什么,或者你希望我们怎样改进?",email:"邮箱(选填)",emailPlaceholder:"便于我们回复你",includeDiagnostics:"附带经过隐私处理的诊断信息",privacyNotice:"仅在需要时附带诊断信息;发送前会移除已识别的凭据、个人标识和本地路径。",submit:"发送反馈",sending:"正在发送…",success:"感谢反馈,已经发送成功。",error:"发送失败,请稍后重试。",close:"关闭"},Aa={title:"意見回饋",subtitle:"回報問題,或告訴我們希望改善的地方。",bug:"問題",feature:"建議",description:"詳細說明",descriptionPlaceholder:"發生了什麼,或你希望我們如何改善?",email:"電子郵件(選填)",emailPlaceholder:"方便我們回覆你",includeDiagnostics:"附上經過隱私處理的診斷資訊",privacyNotice:"僅在需要時附上診斷資訊;傳送前會移除已識別的憑證、個人識別資訊和本機路徑。",submit:"傳送回饋",sending:"正在傳送…",success:"感謝回饋,已成功傳送。",error:"傳送失敗,請稍後再試。",close:"關閉"};function Pa(e){const t=e?.trim().toLowerCase().replace(/_/g,"-")??"";return/^zh(?:-(?:tw|hk|mo|hant))(?:-|$)/u.test(t)?Aa:t.startsWith("zh")?Na:Ta}const Da=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function Fa(e){if(!e?.length)return;if(e.length>4)throw new Error("Feedback supports at most 4 images");const t=e.map(e=>{if(!Da.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:Ca(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 La({language:e,entry:t="web-settings"}){const i=s(e),a=o.useMemo(()=>Pa(i),[i]),[c,l]=o.useState("bug"),[d,u]=o.useState(""),[h,p]=o.useState(""),[m,f]=o.useState("idle");return r.jsxs("section",{className:"control-section compact-section",children:[r.jsx("h2",{children:a.title}),r.jsx("p",{className:"empty-copy",children:a.subtitle}),r.jsxs("div",{className:"feedback-type-grid",children:[r.jsx("button",{className:"bug"===c?"primary-button":"",type:"button","aria-pressed":"bug"===c,onClick:()=>l("bug"),children:a.bug}),r.jsx("button",{className:"feature"===c?"primary-button":"",type:"button","aria-pressed":"feature"===c,onClick:()=>l("feature"),children:a.feature})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:a.description}),r.jsx("textarea",{rows:5,maxLength:8e3,value:d,placeholder:a.descriptionPlaceholder,onChange:e=>u(e.target.value)})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:a.email}),r.jsx("input",{type:"email",maxLength:320,value:h,placeholder:a.emailPlaceholder,onChange:e=>p(e.target.value)})]}),r.jsx("button",{className:"primary-button",type:"button",disabled:!d.trim()||"sending"===m,onClick:()=>{(async()=>{if(d.trim()&&"sending"!==m){f("sending");try{await Ra(function(e){const t=function(e){return Ca(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=Ca(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:Ea(e.metadata),images:Fa(e.images)}}({product:"vibelet",source:"desktop"===n().kind?"desktop":"web",type:c,description:d,email:h,appVersion:n().appVersion||"web",locale:i,platform:navigator.platform||"web",metadata:{app:"desktop"===n().kind?"vibelet-desktop":"vibelet-web",entry:t,screen:"connection-guide"===t?"connection-guide":"settings/language",module:"feedback",action:"manual-submit",userAgent:navigator.userAgent}})),u(""),f("success")}catch{f("error")}}})()},children:"sending"===m?a.sending:a.submit}),"success"===m?r.jsx("p",{className:"empty-copy success-copy",children:a.success}):null,"error"===m?r.jsx("p",{className:"empty-copy error-copy",children:a.error}):null]})}const qa={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 Oa(){const e=qa[s(i().language)],[t,n]=o.useState(""),[a,c]=o.useState("");return r.jsxs("form",{className:"web-pairing-form",onSubmit:n=>{n.preventDefault();try{const e=new URL(function(e){const t=function(e){if(e.length>16384)throw new Error("Pairing link is too long");const t=new URL(e),n="vibelet:"===t.protocol&&"pair"===t.hostname?t.searchParams.get("link"):null,s=n?new URL(n):t,i=s.searchParams.get("data");return i&&!s.hash&&"vibelet:"===s.protocol&&"pair"===s.hostname&&(s.hash=new URLSearchParams({pair:i}).toString(),s.searchParams.delete("data")),s}(e.trim()),n=Mn(t.hash);if(!["http:","https:"].includes(t.protocol)||t.username||t.password||!n)throw new Error("invalid");if(n.expiresAt&&(!Number.isFinite(Date.parse(n.expiresAt))||Date.parse(n.expiresAt)<=Date.now()))throw new Error("expired");return t.pathname="/web/",t.search="",t.href}(t)),n=e.origin===window.location.origin&&e.pathname===window.location.pathname&&e.search===window.location.search;window.location.assign(e.href),n&&window.location.reload()}catch(s){c(s instanceof Error&&"expired"===s.message?e.expired:e.invalid)}},children:[r.jsx("label",{htmlFor:"web-pairing-link",children:e.label}),r.jsx("p",{children:e.hint}),r.jsx("input",{id:"web-pairing-link",value:t,onChange:e=>{n(e.target.value),c("")},autoComplete:"off",spellCheck:!1,required:!0}),r.jsx("button",{className:"primary-button",type:"submit",children:e.connect}),a&&r.jsx("p",{role:"alert",className:"connection-guide-error",children:a})]})}const $a="vibelet --access=quick";function za({errorText:e,t}){const[n,s]=o.useState("idle"),[a,c]=o.useState(!1),l=i().language,d=Pa(l);return r.jsx("main",{className:"connection-guide",id:"vibelet-main-content",tabIndex:-1,children:r.jsxs("section",{className:"connection-guide-content","aria-labelledby":"connection-guide-title",children:[r.jsx("span",{className:"connection-guide-mark","aria-hidden":"true",children:r.jsx(qe,{})}),r.jsx("span",{className:"connection-guide-eyebrow",children:"Vibelet"}),r.jsx("h1",{id:"connection-guide-title",children:t.openDaemonWebLink}),r.jsx("p",{children:t.openDaemonWebLinkHint}),r.jsx(Oa,{}),r.jsxs("div",{className:"connection-command",children:[r.jsx("code",{children:$a}),r.jsxs("button",{className:"primary-button",onClick:()=>{(async()=>{try{await Js($a),s("success")}catch{s("error")}window.setTimeout(()=>s("idle"),1800)})()},type:"button",children:["success"===n?r.jsx($,{"aria-hidden":"true"}):r.jsx(Q,{"aria-hidden":"true"}),r.jsx("span",{children:"success"===n?t.commandCopied:"error"===n?t.copyFailed:t.copyStartCommand})]})]}),r.jsx("p",{className:"connection-guide-footnote",children:t.connectionGuideFootnote}),e?r.jsx("p",{className:"connection-guide-error",children:e}):null,r.jsxs("button",{className:"connection-feedback-toggle",type:"button","aria-expanded":a,onClick:()=>c(e=>!e),children:[r.jsx(ye,{"aria-hidden":"true"}),d.title]}),a?r.jsx("div",{className:"connection-feedback-panel",children:r.jsx(La,{language:l,entry:"connection-guide"})}):null]})})}const _a=o.lazy(()=>m(()=>import("./ImageViewer-BKLAZsx-.js"),__vite__mapDeps([8,1,2,9,10])));function Ba(){const[e,t]=o.useState(null);return o.useEffect(()=>{const e=e=>t(e.detail);return window.addEventListener(cs,e),()=>window.removeEventListener(cs,e)},[]),e?r.jsx(o.Suspense,{fallback:null,children:r.jsx(_a,{request:e,onClose:()=>t(null)},e.images[e.index].src)}):null}const Ha=o.createContext(null);function Wa({children:e,scopeKey:t}){const n=function(e="default"){const t=o.useRef(null),n=o.useRef(null),s=o.useRef({browser:0,terminal:0}),[i,r]=o.useState(0),[a,c]=o.useState([]),l=a.filter(t=>(t.scopeKey??"default")===e),[d,u]=vi(`${i}:${e}`,null),[h,p]=vi(`${i}:${e}`,()=>({})),[m,f]=o.useState({}),g=o.useCallback((t,n,i,r,o,a)=>{const l=crypto.randomUUID(),d="diff"===t?"center":"right",h=n;return"diff"!==t&&(n=`${n} ${++s.current[t]}`),c(s=>[...s,{id:l,kind:t,title:n,defaultTitle:h,cwd:i,session:r,scope:o,path:a,location:d,scopeKey:e}]),"center"===d?u(l):p(e=>({...e,[t]:l})),l},[e,u,p]),y=o.useRef(new Set),v=o.useCallback((n,s)=>{const i=l.filter(e=>"browser"===e.kind&&"right"===e.location&&!e.url&&!e.currentUrl&&!y.current.has(e.id)),r=i.find(e=>e.id===h.browser)??i[0],o=r?.id??crypto.randomUUID();r&&y.current.add(o),c(t=>r?t.map(e=>e.id===o?{...e,title:s,url:n,emptyPlaceholder:!1}:e):[...t,{id:o,kind:"browser",location:"right",title:s,defaultTitle:s,url:n,scopeKey:e}]),p(e=>({...e,browser:o})),t.current?.("browser",!0)},[l,h.browser,e,p]),b=o.useCallback((e,t)=>{c(n=>n.map(n=>n.id===e&&n.currentUrl!==t?{...n,currentUrl:t,emptyPlaceholder:!t&&n.emptyPlaceholder}:n))},[]),x=o.useCallback((e,n)=>{const s=l.find(t=>t.id===e);s&&(c(t=>t.map(t=>t.id===e?{...t,location:n}:t)),"center"===n?(u(e),p(t=>({...t,[s.kind]:l.find(t=>t.id!==e&&t.kind===s.kind&&"right"===t.location)?.id}))):(p(t=>({...t,[s.kind]:e})),t.current?.(s.kind),d===e&&u(null)))},[l,d,u,p]),w=o.useCallback(t=>{y.current.delete(t);const s=l.find(e=>e.id===t);if(!s)return;const i=l.find(e=>e.id!==t&&e.kind===s.kind&&e.location===s.location),r=i||"diff"===s.kind||"right"!==s.location&&l.some(e=>e.id!==t&&e.kind===s.kind)?void 0:{id:crypto.randomUUID(),kind:s.kind,location:"right",title:s.defaultTitle??s.title,defaultTitle:s.defaultTitle,cwd:s.cwd,scopeKey:e,autoOpenTerminal:!0,emptyPlaceholder:!0};c(e=>[...e.filter(e=>e.id!==t),...r?[r]:[]]),i||"right"!==s.location||"diff"===s.kind||n.current?.(s.kind),d===t&&u(null),(r||h[s.kind]===t)&&p(e=>({...e,[s.kind]:r?.id??i?.id}))},[l,d,h,e,u,p]),S=o.useCallback(e=>{c(t=>t.map(t=>t.id===e&&t.emptyPlaceholder?{...t,emptyPlaceholder:!1}:t))},[]),k=o.useCallback((e,t)=>c(n=>n.map(n=>n.id===e&&n.title!==t?{...n,title:t}:n)),[]),I=o.useCallback((e,t)=>f(n=>{if(n[e]===t||!n[e]&&!t)return n;const s={...n};return t?s[e]=t:delete s[e],s}),[]),C=o.useCallback(()=>{y.current.clear(),c([]),u(null),p({}),r(e=>e+1)},[u,p]);return o.useMemo(()=>({scopeKey:e,allItems:a,openRight:t,closeRight:n,openBrowser:v,updateBrowserUrl:b,activate:S,epoch:i,items:l,center:d,right:h,hosts:m,add:g,move:x,close:w,rename:k,register:I,reset:C,setCenter:u,setRight:p}),[e,a,v,b,S,i,l,d,h,m,g,x,w,k,I,C])}(t);return r.jsx(Ha.Provider,{value:n,children:e})}function Ua(){const e=o.useContext(Ha);if(!e)throw new Error("Dock workspace provider missing");return e}function Ka(){return o.useContext(Ha)}const Qa="application/x-vibelet-workspace-tab",Va=o.createContext(null),Ga={browser:ce,terminal:qe,diff:oe};function Ja(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 Za({location:e,kind:t,t:n,cwd:s}){const i=Ua(),c=Ja(n),l=o.useRef(null),d=o.useRef(null),u=i.items.filter(n=>n.location===e&&(!t||n.kind===t)),h=function(e,t,n,s=""){const i=o.useContext(Va),r=i?.element;t=t&&i?.kind===n;const[a,c]=o.useState(!1);return o.useLayoutEffect(()=>{const n=e.current,s=r?.querySelector(".control-tabs");if(!(t&&r&&n&&s))return;const i=()=>{const t=(e.current??n).cloneNode(!0);t.setAttribute("aria-hidden","true"),t.inert=!0,Object.assign(t.style,{position:"fixed",visibility:"hidden",width:"max-content",maxWidth:"none",left:"-10000px",font:getComputedStyle(n).font}),document.body.append(t);const i=t.getBoundingClientRect().width;t.remove();const o=r.clientWidth-s.getBoundingClientRect().width-8;c(e=>i>0?i<=o:e)},o=new ResizeObserver(i);return o.observe(r),o.observe(s),i(),()=>o.disconnect()},[t,r,e,s]),t&&a?r:null}(d,"right"===e&&u.length>1,t,u.map(e=>`${e.id}:${e.title}`).join("|"));if(o.useEffect(()=>{"right"===e&&t&&!i.items.some(e=>e.kind===t)&&i.add(t,n["browser"===t?"browser":"terminal"],s)},[e,t,i.epoch,i.scopeKey]),o.useEffect(()=>{if("right"!==e||!l.current)return;const t=l.current.querySelector('.dock-tab[data-active="true"]');t&&(l.current.scrollLeft=Math.max(0,t.offsetLeft-l.current.offsetLeft))},[e,t,i.right,u.map(e=>e.title).join("|")]),"right"===e&&t&&1===u.length)return null;const p=r.jsxs("div",{className:"dock-tabs",ref:d,role:"right"===e?"tablist":"group","aria-label":t?n["browser"===t?"browser":"terminal"]:void 0,children:["right"===e&&t&&i.right[t]&&r.jsx("button",{type:"button",className:"dock-move dock-move-first","aria-label":c.center,title:c.center,onClick:()=>i.move(i.right[t],"center"),children:r.jsx(F,{})}),r.jsx("div",{className:"dock-tab-items",ref:l,children:u.map(t=>{const s="center"===e?i.center===t.id:i.right[t.kind]===t.id,o=Ga[t.kind];return r.jsxs("div",{className:"document-tab dock-tab","data-active":s,"data-dock-id":t.id,draggable:!0,onDragStart:e=>{e.dataTransfer.setData(Qa,t.id),e.dataTransfer.effectAllowed="move"},children:[r.jsxs("button",{type:"button",role:"tab","aria-selected":s,title:t.title,onClick:()=>"center"===e?i.setCenter(t.id):i.setRight(e=>({...e,[t.kind]:t.id})),children:[r.jsx(o,{}),r.jsx("span",{children:t.title})]}),s&&"center"===e&&r.jsx("button",{type:"button",className:"dock-move","aria-label":c.right,title:c.right,onClick:()=>i.move(t.id,"right"),children:r.jsx(L,{})}),r.jsx("button",{type:"button",className:"document-tab-close","aria-label":`${n.close} ${t.title}`,title:n.close,onClick:()=>i.close(t.id),children:r.jsx(We,{})})]},t.id)})}),"right"===e&&t&&r.jsx("button",{type:"button",className:"dock-new","aria-label":c.create,title:st(c.create,"newTab"),onClick:()=>i.add(t,n["browser"===t?"browser":"terminal"],s),children:r.jsx(je,{})})]});return h?a.createPortal(p,h):p}function Ya({item:e,t}){const n=Ua(),s=Ja(t);return r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button","aria-label":s.center,title:s.center,draggable:!0,onDragStart:t=>{t.dataTransfer.setData(Qa,e.id),t.dataTransfer.effectAllowed="move"},onClick:()=>n.move(e.id,"center"),children:r.jsx(F,{})}),r.jsx("button",{type:"button","aria-label":s.create,title:st(s.create,"newTab"),onClick:()=>n.add(e.kind,t["browser"===e.kind?"browser":"terminal"],e.cwd),children:r.jsx(je,{})})]})}function Xa({location:e,kind:t}){const n=Ua(),s="center"===e?"center":`right-${t}`,i=o.useCallback(e=>n.register(s,e),[n.register,s]);return r.jsx("div",{ref:i,className:"dock-slot","data-dock-location":e,"data-dock-kind":t})}function ec(e,t){const n=Ka();return n?{onDragOver:e=>{e.dataTransfer.types.includes(Qa)&&(e.preventDefault(),e.dataTransfer.dropEffect="move",e.currentTarget.classList.add("dock-drop-target"))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||e.currentTarget.classList.remove("dock-drop-target")},onDrop:s=>{s.currentTarget.classList.remove("dock-drop-target");const i=s.dataTransfer.getData(Qa),r=n.items.find(e=>e.id===i);r&&(s.preventDefault(),s.stopPropagation(),document.body.classList.remove("dock-dragging"),n.move(i,e),t?.(r.kind))}}:{}}const tc=o.lazy(()=>m(()=>import("./BrowserControlPanel-7SS9C-wJ.js"),__vite__mapDeps([11,1,2,9]))),nc=o.lazy(()=>m(()=>import("./TerminalControlPanel-_G2RVzCv.js"),__vite__mapDeps([12,1,2]))),sc=o.lazy(()=>m(()=>Promise.resolve().then(()=>mc),void 0).then(e=>({default:e.DiffDrawer})));function ic({item:e,...t}){const n=Ua(),s=ec(e.location),[i]=o.useState(()=>document.createElement("div")),c="right"===e.location,l=c&&1===n.items.filter(t=>"right"===t.location&&t.kind===e.kind).length,d=l?r.jsx(Ya,{item:e,t:t.t}):void 0,u=(e.scopeKey??"default")===n.scopeKey&&(c?"diff"===e.kind?n.right.diff===e.id:t.rightVisible&&t.controlTab===e.kind&&n.right[e.kind]===e.id:n.center===e.id),h=n.hosts[c?`right-${e.kind}`:"center"]??n.hosts.parking,p=n.hosts.parking;o.useLayoutEffect(()=>{p&&i.parentElement!==p&&p.appendChild(i)},[i,p]),o.useLayoutEffect(()=>{i.className="dock-surface",i.dataset.dockId=e.id,i.dataset.location=e.location,i.dataset.kind=e.kind,i.hidden=!u;const t=c&&"diff"===e.kind,n=()=>{const e=h?.getBoundingClientRect();Object.assign(i.style,t?{left:"0px",top:"0px",width:"100vw",height:"100vh"}:{left:`${e?.left??0}px`,top:`${e?.top??0}px`,width:`${e?.width??0}px`,height:`${e?.height??0}px`})};n();const s=new ResizeObserver(n);return h&&s.observe(h),window.addEventListener("resize",n),document.addEventListener("transitionend",n,!0),window.addEventListener("scroll",n,!0),()=>{s.disconnect(),window.removeEventListener("resize",n),document.removeEventListener("transitionend",n,!0),window.removeEventListener("scroll",n,!0)}},[i,h,u,e.id,e.location,e.kind,c]),o.useLayoutEffect(()=>()=>i.remove(),[i]);const m=o.useCallback(t=>n.updateBrowserUrl(e.id,t),[n.updateBrowserUrl,e.id]);return a.createPortal(r.jsx("div",{className:"dock-surface-content",...s,children:r.jsx(o.Suspense,{fallback:r.jsx("p",{className:"control-panel-loading",children:t.t.loading}),children:"browser"===e.kind?r.jsx(tc,{initialUrl:e.url,visible:u,onUrlChange:m,t:t.t,dockActions:d,onClose:l?()=>n.close(e.id):void 0,onTitleChange:t=>n.rename(e.id,t)}):"terminal"===e.kind?r.jsx(nc,{client:t.client,cwd:e.cwd??"",deviceName:t.deviceName,visible:u,autoOpen:!1!==e.autoOpenTerminal,onOpen:()=>n.activate(e.id),onCloseTab:()=>n.close(e.id),t:t.t,dockActions:d}):e.session&&t.client?r.jsx(sc,{client:t.client,sessionId:e.session.sessionId,cwd:e.session.cwd,sessionTitle:e.title,t:t.t,onClose:()=>n.close(e.id),onDock:()=>n.move(e.id,c?"center":"right"),dockLabel:Ja(t.t).center,presentation:c?"drawer":"workspace",initialScope:e.scope,initialPath:e.path}):null})}),i)}function rc(e){const t=Ua();t.openRight.current=(t,n)=>{"browser"===t&&n&&e.onOpenBrowserLink?.(),"browser"!==t&&"terminal"!==t||e.onOpenRight?.(t)},t.closeRight.current=t=>{e.controlTab===t&&e.onCloseRight?.()},o.useEffect(()=>n().subscribeCommand?.(n=>{if(!n.startsWith("open-link:"))return;const s=n.slice(10);/^https?:\/\//i.test(s)&&t.openBrowser(s,e.t.browser)}),[t.openBrowser,e.t.browser]);const s=o.useCallback(e=>t.register("parking",e),[t.register]);return o.useEffect(()=>{t.reset()},[e.daemonId]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"dock-parking",ref:s}),r.jsx("div",{className:"dock-overlay-slot",children:r.jsx(Xa,{location:"right",kind:"diff"})}),t.allItems.map(t=>r.jsx(ic,{item:t,...e},t.id))]})}function oc({patch:e,truncated:t,truncatedLabel:n,loadingLabel:s}){const i=o.useMemo(()=>function(e){let t=0,n=0;return e.split("\n").map(e=>{const s=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(e);return s?(t=Number(s[1]),n=Number(s[2]),{text:e,kind:"hunk",oldLine:"",newLine:"",sign:""}):e.startsWith("diff ")||e.startsWith("index ")||e.startsWith("---")||e.startsWith("+++")||!t&&!n?{text:e,kind:"header",oldLine:"",newLine:"",sign:""}:e.startsWith("+")?{text:e.slice(1),kind:"add",oldLine:"",newLine:String(n++),sign:"+"}:e.startsWith("-")?{text:e.slice(1),kind:"del",oldLine:String(t++),newLine:"",sign:"−"}:e.startsWith(" ")?{text:e.slice(1),kind:"ctx",oldLine:String(t++),newLine:String(n++),sign:""}:{text:e,kind:"header",oldLine:"",newLine:"",sign:""}})}(e),[e]),[a,c]=o.useState(400),l=o.useRef(null);return o.useEffect(()=>{c(400)},[e]),o.useEffect(()=>{const e=l.current;if(!e)return;const t=new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&c(e=>e+400)},{root:e.closest(".diff-patch"),rootMargin:"200px"});return t.observe(e),()=>t.disconnect()},[a,i.length]),r.jsxs("div",{className:"diff-patch-view",children:[i.slice(0,a).map((e,t)=>r.jsxs("div",{className:`diff-line ${e.kind}`,children:[r.jsx("span",{className:"diff-line-number","aria-hidden":"true",children:e.oldLine}),r.jsx("span",{className:"diff-line-number","aria-hidden":"true",children:e.newLine}),r.jsx("span",{className:"diff-line-sign","aria-hidden":"true",children:e.sign}),r.jsx("span",{className:"diff-line-text",children:e.text||" "})]},t)),a<i.length&&r.jsx("div",{ref:l,className:"diff-more",role:"status",children:s}),t&&r.jsx("p",{className:"diff-empty",children:n})]})}const ac=new WeakMap;function cc(e,t,n){let s=ac.get(e);s||ac.set(e,s=new Map);const i=JSON.stringify([t.sessionId,t.cwd,n]);let r=s.get(i);return r||(s.size>=12&&s.delete(s.keys().next().value),s.set(i,r={updated:0,patches:new Map})),r}function lc(e,t,n){return cc(e,t,n)}function dc(e,t,n){const s=cc(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 uc(e,t,n,s){const i=cc(e,t,n),r=i.patches.get(s);if(r?.pending)return r.pending;if(r?.data&&Date.now()-i.updated<5e3)return Promise.resolve(r.data);i.patches.size>=12&&i.patches.delete(i.patches.keys().next().value);const o={};return i.patches.set(s,o),o.pending=e.request({action:"session.gitDiff.file",id:e.makeId("gitDiffFile"),...t,scope:n,path:s}).then(e=>(o.data=e,e)).finally(()=>{o.pending=void 0}),o.pending}const hc={loading:!1,files:null,error:null};function pc({client:e,sessionId:t,cwd:n,sessionTitle:s,t:i,onClose:a,onDock:c,dockLabel:l,presentation:d="drawer",initialScope:u="unstaged",initialPath:h}){const p=o.useId(),m=o.useRef(null),[g,y]=o.useState(!1),v=o.useRef(void 0),b=o.useCallback(()=>{void 0===v.current&&("workspace"===d||window.matchMedia("(prefers-reduced-motion: reduce)").matches?a():(y(!0),v.current=window.setTimeout(a,180)))},[a,d]);o.useEffect(()=>()=>window.clearTimeout(v.current),[]);const x=f(b,m,"drawer"===d),w=lc(e,{sessionId:t,cwd:n},u),[S,k]=o.useState(u),[I,C]=o.useState({unstaged:hc,staged:hc,[u]:{...hc,files:w.data?.files??null}}),[j,R]=o.useState(h??w.data?.files[0]?.path??null),[M,E]=o.useState(w.patches.get(h??w.data?.files[0]?.path??"")?.data??null),[T,N]=o.useState(!1),[A,P]=o.useState(null),D=function(e){const t=o.useRef(void 0);return o.useEffect(()=>()=>t.current?.(),[]),{"data-dock-draggable":!!e,onPointerDown:n=>{if(!e||0!==n.button||n.target.closest("button"))return;t.current?.();const s=n.currentTarget,i=n.clientX,r=n.clientY,o=document.querySelector(".workspace-documents");if(!o)return;let a=!1;const c=(e,t)=>{const n=o.getBoundingClientRect();return e>=n.left&&e<=n.right&&t>=n.top&&t<=n.bottom},l=e=>{Math.hypot(e.clientX-i,e.clientY-r)<6&&!a||(a=!0,document.body.classList.add("dock-dragging"),o.classList.toggle("dock-drop-target",c(e.clientX,e.clientY)))},d=()=>{document.body.classList.remove("dock-dragging"),o.classList.remove("dock-drop-target"),window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",u),window.removeEventListener("pointercancel",d),s.hasPointerCapture(n.pointerId)&&s.releasePointerCapture(n.pointerId),t.current=void 0},u=t=>{const n=a&&c(t.clientX,t.clientY);d(),n&&e()};t.current=d,s.setPointerCapture(n.pointerId),window.addEventListener("pointermove",l),window.addEventListener("pointerup",u),window.addEventListener("pointercancel",d),n.preventDefault()}}}("drawer"===d&&c?()=>c({scope:S,path:j}):void 0),L=I[S],q=o.useCallback(async s=>{C(e=>({...e,[s]:{loading:!0,files:e[s].files,error:null}}));try{const i=await dc(e,{sessionId:t,cwd:n},s);C(e=>({...e,[s]:{loading:!1,files:i.files,error:null}}))}catch(i){C(e=>({...e,[s]:{loading:!1,files:null,error:i instanceof Error?i.message:String(i)}}))}},[e,t,n]);o.useEffect(()=>{q(S)},[S,q]),o.useEffect(()=>{const e=L.files;e&&(e.length?R(t=>e.some(e=>e.path===t)?t:e[0].path):R(null))},[L.files]),o.useEffect(()=>{if(!j)return E(null),void P(null);let s=!1;const i=lc(e,{sessionId:t,cwd:n},S).patches.get(j)?.data;return E(e=>i??(e?.path===j?e:null)),N(!i&&M?.path!==j),P(null),uc(e,{sessionId:t,cwd:n},S,j).then(e=>{s||(E(e),N(!1))}).catch(e=>{s||(P(e instanceof Error?e.message:String(e)),N(!1))}),()=>{s=!0}},[e,t,n,S,j,L.files]);const O=o.useMemo(()=>{const e=e=>e?e.reduce((e,t)=>({adds:e.adds+t.additions,dels:e.dels+t.deletions,count:e.count+1}),{adds:0,dels:0,count:0}):{adds:0,dels:0,count:0};return{unstaged:e(I.unstaged.files),staged:e(I.staged.files)}},[I]);return r.jsxs("div",{"aria-labelledby":p,"aria-modal":"drawer"===d||void 0,className:`diff-drawer ${"workspace"===d?"diff-workspace":""} ${g?"closing":""}`,ref:x,role:"drawer"===d?"dialog":"region",tabIndex:-1,children:["drawer"===d&&r.jsx("div",{className:"diff-drawer-backdrop",onClick:b,"aria-hidden":"true"}),r.jsxs("div",{className:"diff-drawer-panel",children:[r.jsxs("header",{className:"diff-drawer-header",...D,children:[c&&"drawer"===d&&r.jsx("button",{type:"button",className:"icon-button","aria-label":l,title:l,onClick:()=>c({scope:S,path:j}),children:r.jsx(F,{})}),r.jsxs("div",{children:[r.jsx("strong",{id:p,children:i.changes}),r.jsx("span",{children:s})]}),r.jsx("button",{"aria-label":i.closeChanges,className:"icon-button",onClick:b,ref:m,type:"button",title:i.closeChanges,children:r.jsx(We,{"aria-hidden":"true"})})]}),r.jsx("div",{className:"diff-tabs",role:"tablist",children:["unstaged","staged"].map(e=>{const t=O[e],n=S===e;return r.jsxs("button",{type:"button",role:"tab","aria-selected":n,className:"diff-tab "+(n?"active":""),onClick:()=>{e!==S&&(R(null),E(null),P(null),k(e))},children:[r.jsx("span",{className:"diff-tab-label",children:"unstaged"===e?i.workingChanges:i.stagedChanges}),t.count>0?r.jsxs("span",{className:"diff-tab-meta",children:[r.jsxs("span",{className:"diff-add",children:["+",t.adds]}),r.jsxs("span",{className:"diff-del",children:["-",t.dels]})]}):null]},e)})}),r.jsxs("div",{className:"diff-body",children:[r.jsxs("aside",{className:"diff-files","aria-label":i.changedFiles,children:[L.loading&&!L.files?r.jsx("p",{className:"diff-empty",children:i.loading}):null,L.error?r.jsx("p",{className:"diff-empty diff-error",children:L.error}):null,L.files&&0===L.files.length?r.jsx("p",{className:"diff-empty",children:i.noChanges}):null,L.files?.map(e=>r.jsxs("button",{type:"button",className:`diff-file diff-file-${e.status} ${j===e.path?"active":""}`,onClick:()=>R(e.path),children:[r.jsx("span",{className:`diff-status diff-status-${e.status}`,children:e.status}),r.jsx("span",{className:"diff-file-path",title:e.path,children:e.path}),r.jsxs("span",{className:"diff-file-stats",children:[e.binary?r.jsx("span",{className:"diff-binary",children:"bin"}):null,!e.binary&&e.additions>0?r.jsxs("span",{className:"diff-add",children:["+",e.additions]}):null,!e.binary&&e.deletions>0?r.jsxs("span",{className:"diff-del",children:["-",e.deletions]}):null]})]},e.path))]}),r.jsx("section",{className:"diff-patch","aria-label":i.fileDiff,children:j?T?r.jsx("p",{className:"diff-empty",children:i.loadingPatch}):A?r.jsx("p",{className:"diff-empty diff-error",children:A}):M?.binary?r.jsx("p",{className:"diff-empty",children:i.binaryDiffUnavailable}):M?r.jsx(oc,{patch:M.patch,truncated:M.truncated,truncatedLabel:i.patchTruncated,loadingLabel:i.loadingPatch},`${S}:${j}`):null:r.jsxs("div",{className:"diff-empty",children:[r.jsx(ee,{"aria-hidden":"true"}),r.jsx("p",{children:i.selectFileForDiff})]})})]})]})]})}const mc=Object.freeze(Object.defineProperty({__proto__:null,DiffDrawer:pc},Symbol.toStringTag,{value:"Module"})),fc=o.lazy(async()=>m(()=>import("./FilesControlPanel-c4WfDaKU.js"),__vite__mapDeps([13,1,2,14,15])).then(e=>({default:e.FilesControlPanel}))),gc=o.lazy(async()=>m(()=>import("./LanguageSettingsPanel-CaykSwtb.js"),__vite__mapDeps([16,1,2,17])).then(e=>({default:e.LanguageSettingsPanel}))),yc=o.lazy(async()=>m(()=>import("./ThemeSettingsPanel-BgkL7mH7.js"),__vite__mapDeps([18,1,2,17])).then(e=>({default:e.ThemeSettingsPanel}))),vc=o.lazy(async()=>m(()=>import("./NotificationSettingsPanel-BBUZhjoO.js"),__vite__mapDeps([19,1,2])).then(e=>({default:e.NotificationSettingsPanel})));function bc({t:e}){return r.jsxs("div",{className:"control-panel-loading","aria-live":"polite","aria-busy":"true",children:[r.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),r.jsx("span",{children:e.loadingControls})]})}function xc({client:e,id:t,activeSession:n,sessions:s,t:i,close:a}){const c=Ka(),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 dc(e,t,"unstaged");n.files[0]&&await uc(e,t,"unstaged",n.files[0].path)}(e,{sessionId:l,cwd:u}).catch(()=>{})},350);return()=>window.clearTimeout(t)},[e,l,u,h]);const p=s.find(e=>e.sessionId===t);return p&&e?r.jsx(pc,{client:e,sessionId:p.sessionId,cwd:p.cwd,sessionTitle:d(p),t:i,onClose:a,dockLabel:Ja(i).center,onDock:c?({scope:e,path:t})=>{c.add("diff",d(p),p.cwd,p,e,t),a()}:void 0},p.sessionId):null}function wc(e,t,n){return e.replace(/tailcat/gi,t).replace(/(?:https?:\/\/|wss?:\/\/)?\b127\.0\.0\.1\b(?::\d+)?/gi,n)}const Sc="vibelet.web.hideDeviceAddresses";function kc({activeDaemonId:e,busy:s,fallbackName:i,phase:a,statusText:c,t:l,targets:d,onConnect:u,onRename:h,onEditConnection:p}){const{hidden:m,toggle:f}=function(){const[e,n]=o.useState(()=>{try{return"true"===t().getItem(Sc)}catch{return!1}});return{hidden:e,toggle:()=>{const s=!e;n(s);try{t().setItem(Sc,String(s))}catch{}}}}(),g=e=>m?function(e){return e.replace(/([^\s]+):(\d+)(?=\s|$)/g,(e,t,n)=>{const s=t.split(".");if(4===s.length&&s.every(e=>/^\d{1,3}$/.test(e)))return`${s[0]}.***.${s[3]}:${n}`;const i=Math.min(3,Math.floor((t.length-1)/2));return`${i>0?`${t.slice(0,i)}***${t.slice(-i)}`:"***"}:${n}`})}(e):e,y=m?l.showDeviceAddresses:l.hideDeviceAddresses,[v,b]=o.useState(!1),[x,w]=o.useState(null),[S,k]=o.useState(""),I=o.useRef(null),C=o.useRef(null),j=n().isLocalDaemon??(()=>!1),R=function(e,t,n){const s=e.find(e=>e.daemonId===t&&n(e.daemonId))??e.find(e=>n(e.daemonId));return e.filter(e=>!n(e.daemonId)||e===s)}(d,e,j),M=d.find(t=>t.daemonId===e),E=g(M?.label||i||e?.slice(0,10)||"Vibelet");return o.useEffect(()=>{v||w(null),x&&C.current?.select()},[v,x]),o.useEffect(()=>{if(!v)return;const e=e=>{e.target instanceof Node&&!I.current?.contains(e.target)&&b(!1)},t=e=>{"Escape"===e.key&&b(!1)};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[v]),r.jsxs("div",{className:"device-switcher",ref:I,children:[r.jsxs("button",{"aria-expanded":v,"aria-haspopup":"menu",className:"device-switcher-trigger",onClick:()=>b(e=>!e),title:E,type:"button",children:[r.jsx("strong",{children:E}),r.jsx(z,{"aria-hidden":"true"})]}),r.jsxs("span",{className:`brand-connection ${a}`,children:[r.jsx("i",{"aria-hidden":"true"}),"connected"===a?l.connected:c]}),v?r.jsxs("div",{"aria-label":l.savedDevices,className:"device-switcher-menu",role:"menu",children:[r.jsxs("div",{className:"device-switcher-menu-header",children:[r.jsx("span",{children:l.savedDevices}),r.jsx("button",{type:"button",className:"device-rename-button","aria-label":y,title:y,onClick:f,children:m?r.jsx(Z,{"aria-hidden":"true"}):r.jsx(Y,{"aria-hidden":"true"})})]}),R.map(t=>{const i=t.daemonId===e,o=(e=>{const t=n();if(!j(e.daemonId))return"desktop"===t.kind?t.connectionEndpoint?.(e.daemonId):e.webSocketUrl?function(e){try{const t=new URL(e);if(!["http:","https:","ws:","wss:"].includes(t.protocol))return;const n=t.port||(["https:","wss:"].includes(t.protocol)?"443":"80");return`${t.hostname}:${n}`}catch{return}}(e.webSocketUrl):void 0})(t),a=g(t.label);return r.jsx("div",{className:"device-switcher-row"+(i?" is-active":""),children:x===t.daemonId?r.jsxs("form",{className:"device-rename-form",onSubmit:e=>{e.preventDefault(),x&&S.trim()&&(h(x,S),w(null))},children:[r.jsx("input",{ref:C,"aria-label":l.rename,autoFocus:!0,onChange:e=>k(e.target.value),onKeyDown:e=>{"Escape"===e.key&&(e.stopPropagation(),w(null))},value:S}),r.jsx("button",{"aria-label":l.rename,title:l.rename,disabled:!S.trim(),type:"submit",children:r.jsx($,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":l.cancel,title:l.cancel,type:"button",onClick:()=>w(null),children:r.jsx(We,{"aria-hidden":"true"})})]}):r.jsxs(r.Fragment,{children:[r.jsxs("button",{className:"device-connect-button",disabled:s||i,onClick:()=>{u(t),b(!1)},role:"menuitem","aria-current":i?"true":void 0,type:"button",children:[i?r.jsx($,{"aria-hidden":"true"}):r.jsx(Ce,{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsxs("strong",{className:"device-target-heading",children:[r.jsx("span",{children:a}),i?r.jsx("em",{className:"device-active-label",children:l.active}):null]}),t.displayName&&t.displayName!==t.label?r.jsx("small",{children:g(t.displayName)}):null,j(t.daemonId)||!t.displayName?r.jsx("small",{children:j(t.daemonId)?l.currentDevice:g(t.daemonId)}):null,o?r.jsx("small",{className:"device-connection-endpoint",children:g(o)}):null]})]}),r.jsx("button",{"aria-label":`${l.rename} ${a}`,title:`${l.rename} ${a}`,className:"device-rename-button",onClick:()=>(e=>{w(e.daemonId),k(e.label)})(t),type:"button",children:r.jsx(ke,{"aria-hidden":"true"})}),p&&n().canEditConnection?.(t.daemonId)&&r.jsx("button",{"aria-label":`${l.editConnection} ${a}`,title:`${l.editConnection} ${a}`,className:"device-rename-button",onClick:()=>{p(t),b(!1)},type:"button",children:r.jsx(Ae,{"aria-hidden":"true"})})]})},t.daemonId)}),0===d.length?r.jsx("p",{className:"empty-copy",children:l.noSavedDevices}):null]}):null]})}function Ic({label:e,value:t,options:n,onChange:s}){const i=o.useId();return r.jsxs("div",{className:"filter-section",children:[r.jsx("span",{className:"filter-section-label",id:i,children:e}),r.jsx("div",{className:"filter-choice-list",role:"radiogroup","aria-labelledby":i,children:n.map(e=>r.jsxs("label",{className:"filter-menu-row",children:[r.jsx("input",{type:"radio",name:i,value:e.value,checked:t===e.value,onChange:()=>s(e.value)}),r.jsx("span",{children:e.label}),r.jsx($,{className:"filter-menu-check","aria-hidden":"true","data-checked":t===e.value})]},e.value))})]})}function Cc({folder:e,initialValue:t,t:n,onClose:s,onSave:i}){const[c,l]=o.useState(t),d=o.useRef(null),u=f(s,d);return a.createPortal(r.jsxs("div",{"aria-labelledby":"folder-tag-dialog-title","aria-modal":"true",className:"folder-tag-dialog-layer",ref:u,role:"dialog",tabIndex:-1,children:[r.jsx("div",{"aria-hidden":"true",className:"folder-tag-dialog-backdrop",onClick:s}),r.jsxs("form",{className:"folder-tag-dialog",onSubmit:e=>{e.preventDefault(),i(c)},children:[r.jsxs("header",{children:[r.jsx("span",{className:"folder-tag-dialog-icon","aria-hidden":"true",children:r.jsx($e,{})}),r.jsxs("div",{children:[r.jsx("strong",{id:"folder-tag-dialog-title",children:n.editDirectoryTags}),r.jsx("span",{title:e,children:e})]}),r.jsx("button",{"aria-label":n.cancel,title:n.cancel,className:"mini-button",onClick:s,type:"button",children:r.jsx(We,{"aria-hidden":"true"})})]}),r.jsxs("label",{className:"folder-tag-dialog-field",children:[r.jsx("span",{children:n.directoryTags}),r.jsx("textarea",{"aria-describedby":"folder-tag-dialog-help",placeholder:n.directoryTagsPlaceholder,ref:d,rows:3,value:c,onChange:e=>l(e.target.value)})]}),r.jsx("p",{id:"folder-tag-dialog-help",children:n.directoryTagsDescription}),r.jsxs("footer",{children:[r.jsx("button",{className:"icon-text-button",onClick:s,type:"button",children:n.cancel}),r.jsx("button",{className:"primary-button",type:"submit",children:n.saveDirectoryTags})]})]})]}),document.body)}function jc({folderToggle:e,search:t,connected:n,filtersOpen:s,filtersActive:i,t:a,onSearchChange:c,onSearchCommit:l,onToggleFilters:d,onCreate:u}){const[h,p]=o.useState(Boolean(t)),m=h||t.length>0,f=o.useRef(null),g=o.useRef(null),y=o.useRef(!1),v=()=>{y.current=!0,l(),c(""),p(!1),g.current?.focus(),y.current=!1};return o.useEffect(()=>{const e=()=>{p(!0),requestAnimationFrame(()=>f.current?.focus())};return window.addEventListener("vibelet.session-search",e),()=>window.removeEventListener("vibelet.session-search",e)},[]),r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"rail-list-heading",children:[r.jsx("div",{className:"rail-heading-folders",children:e}),r.jsxs("div",{className:"rail-heading-actions",children:[r.jsx("button",{ref:g,"aria-label":a.searchSessions,"aria-expanded":m,className:"rail-create-button",title:st(a.searchSessions,"searchSessions"),type:"button",onClick:()=>{p(!0),requestAnimationFrame(()=>f.current?.focus())},children:r.jsx(Te,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":a.newSession,className:"rail-create-button",disabled:!n,onClick:u,title:a.newSession,type:"button",children:r.jsx(je,{"aria-hidden":"true"})}),r.jsx("button",{"aria-expanded":s,"aria-label":a.sessionFilters,className:"filter-toggle "+(s||i?"selected":""),onClick:d,title:a.sessionFilters,type:"button",children:r.jsx(ie,{"aria-hidden":"true"})})]})]}),m&&r.jsxs("div",{className:"search-box rail-search-overlay",onBlur:e=>{y.current||e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||(l(),p(Boolean(t)))},children:[r.jsx(Te,{"aria-hidden":"true"}),r.jsx("input",{ref:f,"aria-label":a.searchSessions,value:t,onChange:e=>c(e.target.value),placeholder:a.searchSessions,onKeyDown:e=>{"Enter"===e.key&&l(),"Escape"===e.key&&v()}}),r.jsx("button",{className:"search-close","aria-label":a.cancel,title:a.cancel,type:"button",onClick:v,children:r.jsx(We,{"aria-hidden":"true"})})]})]})}function Rc({menu:e,pending:t,t:n,onOpen:s,onDetails:i,onRename:o,onCopyResumeCommand:a,onResumeInTerminal:c,terminalBusy:l,onTogglePinned:d,onToggleArchived:u,onDelete:h}){return r.jsxs("div",{className:"session-context-menu",role:"menu",style:{left:e.x,top:e.y},onPointerDown:e=>e.stopPropagation(),children:[r.jsxs("button",{type:"button",role:"menuitem",onClick:s,children:[r.jsx(y,{"aria-hidden":"true"}),n.open]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:o,children:[r.jsx(ke,{"aria-hidden":"true"}),n.rename]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:i,children:[r.jsx(ue,{"aria-hidden":"true"}),n.details]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:a,children:[r.jsx(Q,{"aria-hidden":"true"}),n.copyResumeCommand]}),c&&r.jsxs("button",{type:"button",role:"menuitem",disabled:t||l,title:l?n.resumeTerminalBusy:n.resumeInTerminal,onClick:c,children:[r.jsx(ze,{"aria-hidden":"true"}),n.resumeInTerminal]}),r.jsx("span",{className:"context-menu-separator"}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:d,children:[r.jsx(Ie,{"aria-hidden":"true"}),e.session.pinned?n.unpin:n.pin]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:u,children:[r.jsx(P,{"aria-hidden":"true"}),e.session.archived?n.unarchive:n.archive]}),r.jsxs("button",{className:"danger",type:"button",role:"menuitem",onClick:h,children:[r.jsx(_e,{"aria-hidden":"true"}),n.delete]})]})}function Mc({title:e,t,onClose:n,onSave:s}){const[i,a]=o.useState(e),[c,l]=o.useState(!1),[d,u]=o.useState(!1),h=o.useRef(null),p=o.useRef(!1),m=o.useRef(!1),f=()=>{const e=h.current?.closest(".session-item")?.querySelector(".session-row");n(),m.current&&window.requestAnimationFrame(()=>e?.isConnected&&e.focus())};o.useLayoutEffect(()=>{h.current?.focus(),h.current?.select()},[]);const g=async()=>{if(p.current)return;const t=i.trim();if(t&&t!==e){p.current=!0,u(!0),l(!1);try{if(await s(t))return void f()}catch{}p.current=!1,u(!1),l(!0),h.current?.focus()}else f()};return r.jsxs("form",{className:"session-rename-inline",onSubmit:e=>{e.preventDefault(),g()},children:[r.jsx("input",{ref:h,"aria-label":t.rename,value:i,readOnly:d,onChange:e=>a(e.target.value),onBlur:()=>{g()},onKeyDown:e=>{e.stopPropagation(),e.nativeEvent.isComposing||229===e.keyCode||("Enter"===e.key&&(m.current=!0),"Escape"!==e.key||d||(e.preventDefault(),p.current=!0,m.current=!0,f()))}}),c&&r.jsx("small",{role:"alert",children:t.renameFailed})]})}function Ec({session:e,renamingRowId:t,onRename:n,onCloseRename:s,active:i,selected:c=!1,responding:l,pending:u=!1,attentionReason:h,tagLabels:p,showFolder:m=!0,t:f,onSelect:g,onContextMenu:y,onToggleArchived:v,onTogglePinned:b}){const x=o.useId(),w=t===x,S=d(e),k=an(e.lastActivityAt,Date.now(),f),I=e.cwd?.split(/[\\/]/).filter(Boolean).at(-1)||e.cwd||".",C=e.branchUrl||(e.branch&&e.pullRequest?.url.match(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/)?e.pullRequest.url.replace(/\/pull\/\d+$/,`/tree/${encodeURIComponent(e.branch)}`):void 0),[j,R]=o.useState(!1),M=o.useRef(null),E=o.useRef(null),T=o.useRef({x:0,y:0}),N=o.useRef(null),A=()=>{const e=E.current;if(!e)return;const{x:t,y:n}=T.current,s=e.getBoundingClientRect(),i=n+18+s.height<=window.innerHeight-8?n+18:n-s.height-12;e.style.left=`${Math.max(8,Math.min(t+14,window.innerWidth-s.width-8))}px`,e.style.top=`${Math.max(8,Math.min(i,window.innerHeight-s.height-8))}px`,e.style.visibility="visible"};o.useLayoutEffect(()=>{j&&A()},[j,S]);const D=()=>{null!==M.current&&window.clearTimeout(M.current),M.current=null,null!==N.current&&window.cancelAnimationFrame(N.current),N.current=null,R(!1)};return o.useEffect(()=>()=>{null!==M.current&&window.clearTimeout(M.current),null!==N.current&&window.cancelAnimationFrame(N.current)},[e.sessionId]),o.useEffect(()=>{if(!j)return;const e=()=>R(!1);return document.addEventListener("scroll",e,!0),()=>document.removeEventListener("scroll",e,!0)},[j]),r.jsxs("div",{className:"session-item","data-renaming":w||void 0,"data-active":i||void 0,"data-multi-selected":c||void 0,"data-statuses":Number(Boolean(e.pinned))+Number(Boolean(e.archived)),onMouseEnter:e=>{T.current={x:e.clientX,y:e.clientY},w||(e=>{null!==M.current&&window.clearTimeout(M.current),M.current=window.setTimeout(()=>{M.current=null,e.isConnected&&e.matches(":hover")&&R(!0)},2e3)})(e.currentTarget)},onMouseMove:e=>{T.current={x:e.clientX,y:e.clientY},j&&null===N.current&&(N.current=window.requestAnimationFrame(()=>{N.current=null,A()}))},onMouseLeave:D,onFocusCapture:e=>{if(!w&&e.target instanceof HTMLElement&&e.target.matches(":focus-visible")){null!==M.current&&window.clearTimeout(M.current),M.current=null;const t=e.currentTarget.getBoundingClientRect();T.current={x:t.left+t.width/2,y:t.bottom},R(!0)}},onBlurCapture:e=>{e.relatedTarget instanceof Node&&e.currentTarget.contains(e.relatedTarget)||D()},children:[r.jsxs("button",{className:`session-row ${i?"active":""} ${e.archived?"archived":""} ${l?"responding":""}`,"data-session-id":e.sessionId,"data-row-id":x,disabled:w,"aria-current":i?"true":void 0,"aria-pressed":c,onContextMenu:y,onClick:g,onMouseDown:e=>{e.shiftKey&&e.preventDefault()},type:"button",children:[r.jsxs("span",{className:"session-row-head",children:[r.jsx("strong",{children:S}),r.jsx("span",{className:"session-row-metadata",children:r.jsx("span",{className:"session-row-time",title:k,children:k})}),l?r.jsx("span",{className:"session-running-indicator",role:"img","aria-label":f.agentResponding,title:f.agentResponding}):r.jsx("span",{className:"session-running-placeholder","aria-hidden":"true"})]}),h&&r.jsx("span",{className:"session-attention-reason",children:h}),e.runtime.backgroundTerminals?.length?r.jsx("span",{className:"session-terminal-count",children:f.backgroundTerminalsRunning(e.runtime.backgroundTerminals.length)}):null,p?.length?r.jsx("span",{className:"directory-tag-row",title:f.directoryTags,children:p.map(e=>r.jsx("em",{children:e},e))}):null,r.jsx("span",{className:"session-row-footer","aria-hidden":"true"})]}),w&&n&&s&&r.jsx(Mc,{title:S,t:f,onClose:s,onSave:t=>n(e,t)}),r.jsxs("div",{className:"session-quick-actions",children:[r.jsx("button",{"aria-label":e.pinned?f.unpin:f.pin,className:e.pinned?"is-pinned":void 0,disabled:u,onClick:b,title:e.pinned?f.unpin:f.pin,type:"button",children:r.jsx(Ie,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":e.archived?f.unarchive:f.archive,className:e.archived?"is-archived":void 0,disabled:u,onClick:v,title:e.archived?f.unarchive:f.archive,type:"button",children:r.jsx(P,{"aria-hidden":"true"})})]}),r.jsxs("div",{className:"session-git-links",children:[m&&r.jsx("span",{className:"session-git-folder",title:e.cwd,children:I}),e.branch&&(C&&i?r.jsx("a",{className:"session-branch-link",href:C,target:"_blank",rel:"noopener noreferrer",title:e.branch,children:e.branch}):r.jsx("span",{className:"session-branch-link",title:e.branch,children:e.branch})),e.pullRequest&&(i?r.jsxs("a",{className:"session-pr-link",href:e.pullRequest.url,target:"_blank",rel:"noopener noreferrer",title:e.pullRequest.title,children:["PR #",e.pullRequest.number]}):r.jsxs("span",{className:"session-pr-link",title:e.pullRequest.title,children:["PR #",e.pullRequest.number]})),e.pinned?r.jsx("span",{className:"session-row-status",children:f.pinned}):null,e.archived?r.jsx("span",{className:"session-row-status",children:f.archived}):null,r.jsx("span",{className:"session-row-agent",children:"codex"===e.agent?"Codex":"Claude"})]}),j&&a.createPortal(r.jsx("div",{"aria-hidden":"true",className:"session-title-tooltip",ref:E,style:{left:0,top:0,visibility:"hidden"},children:S}),document.body)]})}function Tc(e){const t=o.useRef(e);o.useLayoutEffect(()=>{t.current=e});const n=o.useMemo(()=>({onRenameSession:(e,n)=>t.current.onRenameSession?.(e,n)??Promise.resolve(!1),onCloseRename:()=>t.current.onCloseRename?.(),onEditFolderTags:e=>t.current.onEditFolderTags(e),onOpenCreateMenu:(e,n)=>t.current.onOpenCreateMenu(e,n),onOpenSessionMenu:(e,n)=>t.current.onOpenSessionMenu(e,n),onSelectSession:e=>t.current.onSelectSession(e),onToggleSessionArchived:e=>t.current.onToggleSessionArchived(e),onToggleSessionPinned:e=>t.current.onToggleSessionPinned(e),onToggleFolder:e=>t.current.onToggleFolder(e)}),[]);return r.jsx(Nc,{...e,...n})}const Nc=o.memo(function({activeSessionId:e,renamingRowId:t,onRenameSession:n,onCloseRename:s,collapsedFolders:i,folderCounts:a,getFolderTags:c,groupFolders:l,groupedSessions:d,phase:u,attentionReasons:h,pendingSessionIds:p,respondingSessionIds:m,t:f,visibleSessions:g,onEditFolderTags:y,onOpenCreateMenu:v,onOpenSessionMenu:b,onSelectSession:x,onToggleSessionArchived:w,onToggleSessionPinned:S,onToggleFolder:k}){const I=o.useId(),[C,j]=o.useState(()=>new Set),R=o.useRef(null),M=o.useMemo(()=>{const e=l?d.flatMap(e=>i[e.folder]?[]:e.sessions):g;return[...new Set(e.map(e=>e.sessionId))]},[i,l,d,g]);o.useEffect(()=>{const e=new Set(M);j(t=>[...t].every(t=>e.has(t))?t:new Set([...t].filter(t=>e.has(t)))),R.current&&!e.has(R.current)&&(R.current=null)},[M]),o.useEffect(()=>{0===C.size&&(R.current=e)},[e,C]);const E=(t,n)=>{if(n.shiftKey){const s=R.current??e??t,i=M.indexOf(s),r=M.indexOf(t),o=M.slice(Math.min(i<0?r:i,r),Math.max(i,r)+1);return j(e=>{const t=n.metaKey||n.ctrlKey?new Set(e):new Set;for(const n of o)t.add(n);return t}),void(R.current=s)}R.current=t,n.metaKey||n.ctrlKey?j(n=>{const s=n.size?new Set(n):new Set(e?[e]:[]);return s.has(t)?s.delete(t):s.add(t),s}):(j(new Set),x(t))};return l?r.jsxs(r.Fragment,{children:[d.map(o=>{const l=!!i[o.folder],d=`${I}-${encodeURIComponent(o.folder)}`,g="folder"===o.kind?a[o.folder]??o.sessions.length:o.sessions.length,x="attention"===o.kind?f.needsAttentionSessionsGroup:"running"===o.kind?f.runningSessionsGroup:"pinned"===o.kind?f.pinnedSessionsGroup:o.folder;return r.jsxs("div",{className:"folder-group "+("folder"!==o.kind?"virtual-session-group":""),"data-group-kind":o.kind,"data-contains-active":o.sessions.some(t=>t.sessionId===e)||void 0,children:[r.jsxs("div",{className:"folder-heading",children:[r.jsxs("div",{className:"folder-header",children:[r.jsxs("button",{"aria-expanded":!l,"aria-controls":d,title:x,onClick:()=>k(o.folder),type:"button",children:[r.jsx(_,{className:"folder-disclosure","aria-hidden":"true"}),"attention"===o.kind?r.jsx(ue,{"aria-hidden":"true"}):"running"===o.kind?r.jsx(N,{"aria-hidden":"true"}):"pinned"===o.kind?r.jsx(Ie,{"aria-hidden":"true"}):l?r.jsx(se,{"aria-hidden":"true"}):r.jsx(te,{"aria-hidden":"true"}),r.jsx("span",{children:"folder"===o.kind?o.folder.split(/[\\/]/).filter(Boolean).at(-1)||o.folder:x})]}),"folder"===o.kind?r.jsxs(r.Fragment,{children:[r.jsx("button",{"aria-label":c(o.folder).length?f.editDirectoryTags:f.addDirectoryTags,className:"mini-button folder-hover-action",onClick:()=>y(o.folder),title:c(o.folder).length?f.editDirectoryTags:f.addDirectoryTags,type:"button",children:r.jsx($e,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":f.newSession,className:"mini-button folder-hover-action",disabled:"connected"!==u,onClick:e=>v(e,o.folder),title:f.newSession,type:"button",children:r.jsx(je,{"aria-hidden":"true"})})]}):null,r.jsx("small",{className:"folder-session-count",title:`${g} ${f.sessions}`,children:g})]}),"folder"===o.kind&&c(o.folder).length?r.jsx("div",{className:"folder-tag-row",children:c(o.folder).map(e=>r.jsx("span",{children:e},e))}):null]}),r.jsx("div",{className:"folder-session-list",id:d,hidden:l,children:l?null:o.sessions.map(i=>r.jsx(Ec,{renamingRowId:t,onRename:n,onCloseRename:s,active:i.sessionId===e,selected:C.has(i.sessionId),responding:m.has(i.sessionId),attentionReason:h?.[i.sessionId],pending:p?.has(i.sessionId),session:i,showFolder:"folder"!==o.kind,tagLabels:c(i.cwd),t:f,onContextMenu:e=>b(e,i),onSelect:e=>E(i.sessionId,e),onToggleArchived:()=>w(i),onTogglePinned:()=>S(i)},i.sessionId))})]},o.folder)}),0===g.length?r.jsx("div",{className:"session-empty-state",children:r.jsx("p",{children:f.noSessionsMatch})}):null]}):r.jsxs(r.Fragment,{children:[g.map(i=>r.jsx(Ec,{renamingRowId:t,onRename:n,onCloseRename:s,active:i.sessionId===e,selected:C.has(i.sessionId),responding:m.has(i.sessionId),attentionReason:h?.[i.sessionId],pending:p?.has(i.sessionId),session:i,tagLabels:c(i.cwd),t:f,onContextMenu:e=>b(e,i),onSelect:e=>E(i.sessionId,e),onToggleArchived:()=>w(i),onTogglePinned:()=>S(i)},i.sessionId)),0===g.length?r.jsx("div",{className:"session-empty-state",children:r.jsx("p",{children:f.noSessionsMatch})}):null]})});function Ac({agentFilter:e,t,onAgentFilterChange:n}){return r.jsx(Ic,{label:t.agentFilterLabel,value:e,options:[{value:"all",label:t.agentFilterAll},{value:"claude",label:t.agentFilterClaude},{value:"codex",label:t.agentFilterCodex}],onChange:n})}function Pc({groupFolders:e,hideArchived:t,separatePinnedGroup:n,showNeedsAttentionGroup:s,showRunningGroup:i,t:o,onToggleGroupFolders:a,onToggleHideArchived:c,onToggleNeedsAttentionGroup:l,onToggleRunningGroup:d,onToggleSeparatePinnedGroup:u}){const h=[[o.showNeedsAttentionGroup,s,l],[o.showRunningGroup,i,d],[o.separatePinnedGroup,n,u]];return r.jsxs("div",{className:"filter-section",children:[r.jsx("span",{className:"filter-section-label",children:o.filterViewOptions}),r.jsxs("div",{className:"filter-view-list",children:[r.jsxs("button",{"aria-pressed":e,className:"filter-menu-row",onClick:a,type:"button",children:[r.jsx("span",{children:o.groupByFolder}),r.jsx($,{className:"filter-menu-check","aria-hidden":"true","data-checked":e})]}),h.map(([t,n,s])=>r.jsxs("button",{"aria-pressed":e&&n,className:"filter-menu-row nested-filter-option",disabled:!e,onClick:s,type:"button",children:[r.jsx("span",{children:t}),r.jsx($,{className:"filter-menu-check","aria-hidden":"true","data-checked":e&&n})]},t)),r.jsxs("button",{"aria-pressed":t,className:"filter-menu-row",onClick:c,type:"button",children:[r.jsx("span",{children:o.hideArchived}),r.jsx($,{className:"filter-menu-check","aria-hidden":"true","data-checked":t})]})]})]})}function Dc({connectionIndicators:e,activeSessionId:t,busy:s,collapsedFolders:i,allFoldersCollapsed:c,currentCwd:l,activeDaemonId:d,displayName:u,savedTargets:h,directoryTags:p,folderCounts:m,groupFolders:f,sessionSort:g,onSessionSortChange:y,groupedSessions:v,hideArchived:b,separatePinnedGroup:x,showNeedsAttentionGroup:w,showRunningGroup:S,inventoryVersion:k,nextCursor:I,phase:C,attentionReasons:j,pendingSessionIds:R,respondingSessionIds:M,search:E,sessionAgentFilter:T,sessionsCount:N,sinceFilter:A,statusText:P,t:D,visibleSessions:F,onLoadMore:L,onCopyResumeCommand:q,onResumeInTerminal:O,onConnectTarget:$,onRequestNewSession:z,onDeleteSession:_,onRenameSession:B,onEditFolderTags:H,onOpenSessionDetails:W,onResetFilters:U,onRenameTarget:K,onEditConnection:Q,onSearchChange:V,onSearchCommit:G,onSelectSession:J,onToggleSessionArchived:Z,onToggleSessionPinned:Y,onSessionAgentFilterChange:X,onSinceFilterChange:ee,onToggleFolder:te,onToggleAllFolders:ne,onToggleGroupFolders:se,onToggleHideArchived:ie,onToggleNeedsAttentionGroup:re,onToggleRunningGroup:oe,onToggleSeparatePinnedGroup:ae}){const ce=function({activeSessionId:e,activeDaemonId:t,groupFolders:s,groupedSessions:i,collapsedFolders:r,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=i.filter(t=>t.sessions.some(t=>t.sessionId===e)),n=t.find(e=>!r[e.folder])??t[0];if(n&&r[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,r,s,i,a]),c}({activeSessionId:t,activeDaemonId:d,groupFolders:f,groupedSessions:v,collapsedFolders:i,onToggleFolder:te}),[le,de]=o.useState(null),[ue,he]=o.useState(!1),[pe,me]=o.useState(null);o.useEffect(()=>{if(!pe)return;const e=window.setTimeout(()=>me(null),2400);return()=>window.clearTimeout(e)},[pe]);const[ye,ve]=o.useState(null),[xe,we]=o.useState(null),Se=o.useRef(null),ke=o.useRef(null),[Ie,Ce]=o.useState(null),je="updated"!==g||"all"!==T||"30d"!==A||!f||f&&(w||S||x)||b,Re=function(e,t,n=!1){const s=o.useMemo(()=>e,[e?.lastActivityAt,e?.sessionId]),i=o.useRef(null),r=o.useRef(null),a=o.useRef(t),[c,l]=o.useState(null),d=Boolean(e?.lastActivityAt&&e.sessionId),u=d?`${e?.lastActivityAt}:${e?.sessionId}`:null;return o.useEffect(()=>{a.current=t},[t]),o.useEffect(()=>{const e=i.current;if(!e||!s||!u)return r.current=null,void l(null);const t=e.closest(".session-list");if(!(t instanceof HTMLElement))return;let o,c=!0;l(null);const d=()=>{r.current!==u&&(r.current=u,l(u),a.current(s).catch(()=>{c&&(o=window.setTimeout(()=>{c&&(r.current=null,n?d():(h?.unobserve(e),h?.observe(e)))},1500))}).finally(()=>{c&&l(e=>e===u?null:e)}))},h=n?null:new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&d()},{root:t,rootMargin:"0px 0px 240px 0px",threshold:.01});return n?d():h?.observe(e),()=>{c=!1,r.current=null,void 0!==o&&window.clearTimeout(o),h?.disconnect()}},[u,s,n]),{canLoadMore:d,loading:d&&c===u,sentinelRef:i}}(I,L,"updated"!==g||!b),Me=!!xe&&Boolean(R?.has(xe.session.sessionId)),Ee=o.useCallback(e=>p[function(e){return"string"==typeof e&&e.trim().length>0?e:void 0}(e)??"/"]??[],[p]),Te=`${P} · ${"connected"===C?`${F.length}/${N} sessions · v${k??"-"}`:D.sameOriginAccess}`,Ne=n().toolbarTarget?.("left");o.useLayoutEffect(()=>{if(!ue)return;const e=()=>{const e=Se.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&&!xe)return;const e=e=>{const t=e.target;t instanceof Node&&(Se.current?.contains(t)||ke.current?.contains(t))||(he(!1),we(null))},t=e=>{"Escape"===e.key&&(he(!1),we(null))};return document.addEventListener("pointerdown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("pointerdown",e),document.removeEventListener("keydown",t)}},[xe,ue]);const Ae=(e,t)=>{we(null),he(!1),z(t)},De=()=>we(null),Fe=e=>{if(!xe)return;const{session:t}=xe;De(),e(t)},Le=r.jsxs("div",{className:"brand-block",title:Te,children:[r.jsx("div",{className:"brand-mark","aria-hidden":"true",children:r.jsx("img",{alt:"",className:"brand-logo",height:"40",src:"/web/assets/logo-CVsV06Wq.webp",width:"40"})}),r.jsx(kc,{activeDaemonId:d,busy:s,fallbackName:u,phase:C,statusText:P,t:D,targets:h,onConnect:$,onRename:K,onEditConnection:Q})]});return r.jsxs("aside",{className:"session-rail","aria-label":D.sessions,children:[Ne?a.createPortal(Le,Ne):Le,r.jsxs("div",{className:"search-filter-wrap",ref:Se,children:[r.jsx(jc,{folderToggle:f&&v.length>0&&r.jsx("button",{"aria-label":c?D.expandAllSessions:D.collapseAllSessions,"aria-pressed":c,className:"session-folders-toggle",onClick:ne,title:c?D.expandAllSessions:D.collapseAllSessions,type:"button",children:c?r.jsx(ge,{"aria-hidden":"true"}):r.jsx(be,{"aria-hidden":"true"})}),search:E,connected:"connected"===C,filtersOpen:ue,filtersActive:je,t:D,onSearchChange:V,onSearchCommit:G,onToggleFilters:()=>he(e=>!e),onCreate:Ae}),ue&&Ie?a.createPortal(r.jsxs("div",{className:"filter-popover session-filter-popover",role:"dialog","aria-label":D.sessionFilters,ref:ke,style:{top:Ie.top,left:Ie.left},children:[r.jsx(Ic,{label:D.sessionSortLabel,value:g,options:[{value:"updated",label:D.sessionSortUpdated},{value:"created",label:D.sessionSortCreated},{value:"title",label:D.sessionSortTitle},{value:"folder",label:D.sessionSortFolder}],onChange:y}),r.jsx(Ac,{agentFilter:T,t:D,onAgentFilterChange:X}),r.jsx(Ic,{label:D.searchTimeRangeLabel,value:A,options:[{value:"all",label:D.searchTimeRangeAllTime},{value:"7d",label:D.searchTimeRangeLast7Days},{value:"30d",label:D.searchTimeRangeLast30Days},{value:"90d",label:D.searchTimeRangeLast90Days}],onChange:ee}),r.jsx(Pc,{groupFolders:f,hideArchived:b,separatePinnedGroup:x,showNeedsAttentionGroup:w,showRunningGroup:S,t:D,onToggleGroupFolders:se,onToggleHideArchived:ie,onToggleNeedsAttentionGroup:re,onToggleRunningGroup:oe,onToggleSeparatePinnedGroup:ae}),je?r.jsx("button",{className:"filter-reset-button",onClick:U,type:"button",children:D.resetFilters}):null]}),document.body):null]}),r.jsxs("div",{className:"session-list",ref:ce,children:[r.jsx(Tc,{activeSessionId:t,renamingRowId:le,onRenameSession:B,onCloseRename:()=>de(null),collapsedFolders:i,folderCounts:m,getFolderTags:Ee,groupFolders:f,groupedSessions:v,phase:C,attentionReasons:j,pendingSessionIds:R,respondingSessionIds:M,t:D,visibleSessions:F,onEditFolderTags:e=>{he(!1),we(null),ve({folder:e,value:Ee(e).join(", ")})},onOpenCreateMenu:Ae,onOpenSessionMenu:(e,t)=>{e.preventDefault(),we({session:t,rowId:e.currentTarget.dataset.rowId??"",x:Math.min(e.clientX,window.innerWidth-224-10),y:Math.min(e.clientY,window.innerHeight-342-10)})},onSelectSession:J,onToggleSessionArchived:Z,onToggleSessionPinned:Y,onToggleFolder:te},d??"unconnected"),Re.canLoadMore?r.jsx("div",{"aria-live":"polite",className:"session-load-sentinel "+(Re.loading?"loading":""),ref:Re.sentinelRef,role:"status",children:Re.loading?r.jsxs(r.Fragment,{children:[r.jsx(fe,{className:"spin","aria-hidden":"true"}),r.jsx("span",{children:D.loadingMore})]}):null}):null]}),r.jsxs("div",{className:"session-rail-footer",children:[r.jsx("div",{className:"rail-footer-indicators",children:e}),n().openSettings&&r.jsxs("button",{"aria-label":D.settings,className:"icon-button rail-settings-button",onClick:()=>n().openSettings?.(),title:D.settings,type:"button",children:[r.jsx(Pe,{"aria-hidden":"true"}),n().settingsBadge]})]}),ye?r.jsx(Cc,{folder:ye.folder,initialValue:ye.value,t:D,onClose:()=>ve(null),onSave:e=>{ye&&(H(ye.folder,e),ve(null))}}):null,xe?r.jsx(Rc,{menu:xe,pending:Me,t:D,onOpen:()=>Fe(e=>J(e.sessionId)),onRename:()=>{de(xe.rowId),De()},onDetails:()=>Fe(W),onCopyResumeCommand:()=>Fe(e=>{Promise.resolve(q(e)).then(()=>me({message:D.commandCopied,tone:"success"})).catch(()=>me({message:D.copyResumeFailed,tone:"error"}))}),onResumeInTerminal:O&&d&&n().resumeInTerminal&&n().isLocalDaemon?.(d)?()=>Fe(O):void 0,terminalBusy:M.has(xe.session.sessionId),onTogglePinned:()=>Fe(Y),onToggleArchived:()=>Fe(Z),onDelete:()=>Fe(_)}):null,r.jsx(Ys,{feedback:pe})]})}function Fc({collapsed:e,children:t,onExpand:s,onResize:i,t:o}){const c=n().toolbarTarget?.("left"),l=r.jsx("button",{"aria-label":e?o.expandSessionSidebar:o.collapseSessionSidebar,className:"sidebar-titlebar-toggle",onClick:s,title:st(e?o.expandSessionSidebar:o.collapseSessionSidebar,"leftSidebar"),type:"button",children:r.jsx(xe,{"aria-hidden":"true"})});return r.jsxs(r.Fragment,{children:[c?a.createPortal(l,c):l,r.jsx("div",{className:"session-sidebar-motion",inert:e,"aria-hidden":e,children:t}),r.jsx("button",{"aria-label":o.resizeSessionSidebar,"aria-hidden":e,className:"resize-handle",disabled:e,onPointerDown:i,title:o.resizeSessionSidebar,type:"button",children:r.jsx("span",{})})]})}const Lc={version:"",latestVersion:"",loading:!1,error:null};function qc(e){const t=e.match(/^\d+/);return t?Number(t[0]):0}function Oc(e,t){return function(e,t){const n=e.split(/[+-]/,1)[0].split(".").map(qc),s=t.split(/[+-]/,1)[0].split(".").map(qc),i=Math.max(n.length,s.length);for(let r=0;r<i;r+=1){const e=n[r]??0,t=s[r]??0;if(e<t)return-1;if(e>t)return 1}return 0}(e,t)<0}function $c({busy:e,connected:t,dismissed:n,feedback:s,synced:i,t:o,onPull:a,onPushMerge:c,onPushReplace:l,onSkip:d}){const u=!t||null!==e;return r.jsxs("section",{className:"control-section compact-section archive-sync-panel",children:[r.jsx("h2",{children:o.archiveSyncTitle}),r.jsx("p",{className:"empty-copy",children:i?o.archiveSyncSynced:n?o.archiveSyncSkippedState:o.archiveSyncBody}),r.jsxs("div",{className:"action-grid archive-sync-actions",children:[r.jsxs("button",{className:"icon-text-button",disabled:u,onClick:c,type:"button",children:[r.jsx(ae,{"aria-hidden":"true"}),"pushMerge"===e?o.archiveSyncSyncing:o.archiveSyncPushMerge]}),r.jsxs("button",{className:"icon-text-button",disabled:u,onClick:a,type:"button",children:[r.jsx(g,{"aria-hidden":"true"}),"pull"===e?o.archiveSyncSyncing:o.archiveSyncPull]}),r.jsxs("button",{className:"icon-text-button",disabled:u,onClick:l,type:"button",children:[r.jsx(Be,{"aria-hidden":"true"}),"pushReplace"===e?o.archiveSyncSyncing:o.archiveSyncPushReplace]}),r.jsxs("button",{className:"icon-text-button",disabled:u,onClick:d,type:"button",children:[r.jsx(A,{"aria-hidden":"true"}),o.archiveSyncSkip]})]}),s?r.jsx("p",{className:"empty-copy "+("error"===s.tone?"error-copy":"success-copy"),children:s.message}):null]})}function zc({pairing:e,label:t,phase:n,t:s,onForgetPairing:i}){const o="connected"===n?"connected":e?n:s.notPaired;return r.jsxs("section",{className:"control-section compact-section",children:[r.jsx("h2",{children:s.currentDevice}),r.jsxs("dl",{children:[r.jsxs("div",{children:[r.jsx("dt",{children:s.daemon}),r.jsxs("dd",{className:"connection-device-name",children:[r.jsx("strong",{children:t||e?.displayName||e?.daemonId||s.notPaired}),t&&e?.displayName&&t!==e.displayName?r.jsx("small",{children:e.displayName}):null]})]}),r.jsxs("div",{children:[r.jsx("dt",{children:s.status}),r.jsx("dd",{children:o})]})]}),r.jsx("div",{className:"action-grid",children:r.jsxs("button",{className:"danger-button",disabled:!e,onClick:i,type:"button",children:[r.jsx(he,{"aria-hidden":"true"}),s.forget]})})]})}function _c({connected:e,metadata:t,showUpdate:n,updateBusy:s,restartBusy:i,t:o,updateStatus:a,onUpdate:c,onRestart:l}){const d=t.version&&t.latestVersion&&n?`${t.version} -> ${t.latestVersion}`:t.version||o.unknown;return r.jsxs("section",{className:"control-section compact-section",children:[r.jsx("h2",{children:o.desktopConnector}),r.jsx("dl",{children:r.jsxs("div",{children:[r.jsx("dt",{children:o.version}),r.jsx("dd",{children:t.loading?o.checking:d})]})}),r.jsxs("div",{className:"action-grid",children:[n?r.jsxs("button",{className:"primary-button",disabled:!e||s||i,onClick:c,type:"button",children:[r.jsx(g,{"aria-hidden":"true"}),s?o.updating:o.update]}):null,r.jsxs("button",{className:"danger-button",disabled:!e||i,onClick:l,type:"button",children:[r.jsx(Re,{"aria-hidden":"true"}),i?o.restarting:o.restart]})]}),t.error?r.jsx("p",{className:"empty-copy",children:t.error}):null,a?r.jsx("p",{className:"empty-copy",children:a}):null]})}function Bc({activeDaemonId:e,busy:t,t:n,targets:s,onConnect:i,onForget:o}){return r.jsxs("section",{className:"control-section compact-section",children:[r.jsx("h2",{children:n.savedDevices}),r.jsxs("div",{className:"stack-list",children:[s.map(s=>r.jsxs("div",{className:"data-row target-row",children:[r.jsxs("div",{children:[r.jsxs("strong",{children:[s.label,s.daemonId===e?` · ${n.active}`:""]}),r.jsxs("span",{children:[s.displayName??s.daemonId," ·"," ",s.lastConnectedAt?an(s.lastConnectedAt,Date.now(),n):n.notConnectedRecently]})]}),r.jsxs("div",{className:"row-actions",children:[r.jsx("button",{"aria-label":`Connect to ${s.label}`,title:`Connect to ${s.label}`,className:"icon-button",disabled:t,onClick:()=>i(s),type:"button",children:r.jsx(Ce,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":`Forget ${s.label}`,title:`Forget ${s.label}`,className:"icon-button danger-icon",disabled:t,onClick:()=>o(s.daemonId),type:"button",children:r.jsx(_e,{"aria-hidden":"true"})})]})]},s.daemonId)),0===s.length?r.jsx("p",{className:"empty-copy",children:n.noSavedDevices}):null]})]})}function Hc({workspace:e,portalOnly:t=!1}){const[s,i]=o.useState(()=>n().settingsTarget?.()??null);o.useEffect(()=>{const e=()=>i(n().settingsTarget?.()??null);return window.addEventListener("vibelet.settings.target.changed",e),e(),()=>window.removeEventListener("vibelet.settings.target.changed",e)},[]);const c=e,l=r.jsxs(r.Fragment,{children:[!t&&r.jsxs(r.Fragment,{children:[r.jsx(zc,{pairing:c.pairing,label:c.savedTargets.find(e=>e.daemonId===c.pairing?.daemonId)?.label,phase:c.phase,t:c.t,onForgetPairing:c.clearPairing}),r.jsx(Bc,{activeDaemonId:c.pairing?.daemonId,busy:c.busy,t:c.t,targets:c.savedTargets,onConnect:c.connectSavedTarget,onForget:c.forgetSavedTarget})]}),r.jsx($c,{busy:c.archiveSyncBusy,connected:"connected"===c.phase,dismissed:c.archiveSyncDismissed,feedback:c.archiveSyncStatus,synced:c.archiveSynced,t:c.t,onPull:()=>{c.runArchiveSync("pull")},onPushMerge:()=>{c.runArchiveSync("pushMerge")},onPushReplace:()=>{c.runArchiveSync("pushReplace")},onSkip:c.skipArchiveSync}),r.jsx(_c,{connected:"connected"===c.phase,metadata:c.daemonMetadata,restartBusy:c.admin.loading&&"restart"===c.admin.action,showUpdate:Boolean(c.daemonMetadata.version&&c.daemonMetadata.latestVersion&&Oc(c.daemonMetadata.version,c.daemonMetadata.latestVersion)),t:c.t,updateBusy:c.admin.loading&&"update"===c.admin.action,updateStatus:c.admin.statusText,onRestart:()=>{c.runAdminAction("restart")},onUpdate:()=>{c.runAdminAction("update")}})]}),d=r.jsx("div",{className:"remote-workspace-settings",children:l});return t?s?a.createPortal(d,s):null:d}function Wc(){const e=n().polishSettings,t="en"!==s(i().language),[a,c]=o.useState(),[l,d]=o.useState({...v}),[u,h]=o.useState(""),[p,m]=o.useState(!1),[f,g]=o.useState(""),[y,b]=o.useState(!1);if(o.useEffect(()=>{let n=!0;return e?.status().then(e=>{n&&(c(e),d(e.settings))}).catch(()=>{n&&(b(!0),g(t?"无法读取润色设置。":"Could not load polishing settings."))}),()=>{n=!1}},[e]),!e)return null;const x=async n=>{m(!0),g(""),b(!1);try{const s=await e.save(l,n);c(s),d(s.settings),h(""),g(t?"已保存":"Saved"),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch{b(!0),g(t?"保存失败,请检查 HTTPS API 地址、模型和提示词。":"Save failed. Check the HTTPS API URL, model and prompts.")}finally{m(!1)}};return r.jsxs("section",{className:"control-section compact-section speech-polish-settings",children:[r.jsx("h2",{children:t?"语音润色":"Voice polishing"}),r.jsxs("label",{className:"speech-enabled",children:[r.jsx("input",{type:"checkbox",role:"switch","aria-checked":l.enabled,className:"settings-switch",checked:l.enabled,disabled:!a||p,onChange:async n=>{const s={...l,enabled:n.target.checked};d(s),m(!0),g(""),b(!1);try{const t=await e.save({...a.settings,enabled:s.enabled});c(t),d(s),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch{d(l),b(!0),g(t?"无法保存开关设置":"Could not save setting")}finally{m(!1)}}}),t?"启用语音润色":"Enable voice polishing"]}),l.enabled&&r.jsxs("fieldset",{disabled:!a||p,className:"speech-polish-fields",children:[r.jsx("p",{className:"empty-copy",children:t?"识别后轻度整理口误、重复和标点,保留原意。转写文字会发送到你配置的模型;失败时保留原始文字,仅填入草稿。":"Lightly correct slips, repetition and punctuation while preserving meaning. Transcripts are sent to your configured model. Failures keep the original text; nothing is sent from your draft."}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"API 地址":"API URL"}),r.jsx("input",{type:"url",value:l.baseUrl,onChange:e=>d({...l,baseUrl:e.target.value}),autoComplete:"off"})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"模型":"Model"}),r.jsx("input",{value:l.model,onChange:e=>d({...l,model:e.target.value}),autoComplete:"off"})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"润色 API Key":"Polishing API Key"}),r.jsx("input",{type:"password",autoComplete:"off",value:u,onChange:e=>h(e.target.value),placeholder:a?.configured?t?"已保存 · 留空保留":"Saved · leave blank to keep":"API Key"})]}),r.jsx("p",{className:"empty-copy",children:"encrypted"===a?.persistence?t?"密钥加密保存在这台 Mac。支持 OpenAI 兼容接口。":"Key encrypted on this Mac. Supports OpenAI-compatible APIs.":t?"密钥仅保留在当前页面,刷新后需重新填写。Web API 需允许跨域访问。":"Key kept only in this page; enter it again after reload. The API must allow cross-origin requests."}),l.enabled&&!a?.configured&&!u.trim()&&r.jsx("p",{className:"empty-copy",children:t?"请填写 API Key 并保存,润色才能生效。":"Enter and save an API key to use polishing."}),r.jsxs("details",{className:"speech-polish-advanced",children:[r.jsx("summary",{children:t?"自定义提示词":"Custom prompts"}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"中文提示词":"Chinese prompt"}),r.jsx("textarea",{rows:5,value:l.promptZh,onChange:e=>d({...l,promptZh:e.target.value})})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"英文提示词":"English prompt"}),r.jsx("textarea",{rows:5,value:l.promptEn,onChange:e=>d({...l,promptEn:e.target.value})})]}),r.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>d({...l,promptZh:v.promptZh,promptEn:v.promptEn}),children:t?"恢复默认提示词":"Reset prompts"})]}),r.jsxs("div",{className:"attention-actions",children:[r.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{x(u.trim()||void 0)},children:t?"保存润色设置":"Save polishing settings"}),a?.configured&&r.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{x("")},children:t?"移除润色密钥":"Remove polishing key"})]})]}),f&&r.jsx("p",{role:y?"alert":"status",className:y?"error-copy":"empty-copy",children:f})]})}const Uc={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 Kc(){const e=n().speechSettings,a=Uc[s(i().language)],[c,l]=o.useState(),[d,u]=o.useState(""),[h,p]=o.useState(!1),[m,f]=o.useState(""),[g,y]=o.useState("true"===t().getItem("vibelet.web.voice.enabled")),v=Boolean(globalThis.isSecureContext&&"function"==typeof globalThis.navigator?.mediaDevices?.getUserMedia&&globalThis.MediaRecorder?.isTypeSupported("audio/webm"));o.useEffect(()=>{let t=!0;return e?.status().then(e=>{t&&l(e)}).catch(()=>{t&&f("Unable to load speech settings.")}),()=>{t=!1}},[e]);const b=e=>{y(e),t().setItem("vibelet.web.voice.enabled",String(e)),window.dispatchEvent(new Event("vibelet.speech.changed"))},x=async t=>{if(e&&!h){p(!0),f("");try{l(await e.saveKey(t)),u(""),t||b(!1),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch(n){f(n instanceof Error?n.message:String(n))}finally{p(!1)}}};if(!e)return null;const w="volcengine"===c?.engine,S=[...c?.systemAvailable?[{value:"system",label:"macOS · Apple"}]:[],{value:"deepgram",label:"Deepgram · Nova-3"},{value:"volcengine",label:"en"===s(i().language)?"Volcengine · ASR Flash":"火山引擎 · 录音识别"}];return r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:"control-section compact-section speech-input-settings",children:[r.jsx("h2",{children:a.title}),r.jsxs("label",{className:"speech-enabled",children:[r.jsx("input",{type:"checkbox",role:"switch","aria-checked":g,className:"settings-switch",checked:g,disabled:!v,onChange:e=>b(e.target.checked)}),a.enabled]}),g&&r.jsxs(r.Fragment,{children:[e.setEngine&&r.jsxs("div",{className:"field speech-engine-field",children:[r.jsx("span",{children:"en"===s(i().language)?"Recognition engine":"识别引擎"}),r.jsx(Ps,{icon:ve,menuLabel:"Speech engine",label:S.find(e=>e.value===c?.engine)?.label??"Deepgram · Nova-3",options:S,value:c?.engine??"deepgram",disabled:h,onSelect:async t=>{p(!0),f(""),u("");try{l(await e.setEngine(t)),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch(n){f(n instanceof Error?n.message:String(n))}finally{p(!1)}}})]}),r.jsx("p",{className:"empty-copy",children:"system"===c?.engine?"en"===s(i().language)?"No API key needed. macOS 26+ uses on-device recognition and may download a language model on first use. Earlier versions may send audio to Apple. Text is added to your draft without sending.":"无需 API Key。macOS 26 及以上在本机识别,首次可能下载语言模型;较旧系统可能将音频发送给 Apple。文字只填入草稿,不会自动发送。":w?"en"===s(i().language)?"Audio is sent to Volcengine ASR Flash (volc.bigasr.auc_turbo), billed to your account. Enable this voice resource and use its API Key. Text only enters your draft.":"音频会上传至火山引擎录音识别极速版(volc.bigasr.auc_turbo),按你的账户计费。请开通此语音资源并填写语音 API Key,文字只追加到草稿。":a.disclosure}),"system"!==c?.engine&&r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"empty-copy",children:"encrypted"===c?.persistence?a.secure:a.session}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:w?"火山引擎 API Key":"Deepgram API Key"}),r.jsx("input",{type:"password",autoComplete:"off",value:d,onChange:e=>u(e.target.value),placeholder:c?.configured?a.saved:"API Key"})]}),r.jsxs("div",{className:"attention-actions",children:[r.jsx("button",{type:"button",className:"icon-text-button",disabled:h||!d.trim(),onClick:()=>{x(d)},children:a.save}),c?.configured&&r.jsx("button",{type:"button",className:"icon-text-button",disabled:h,onClick:()=>{x("")},children:a.remove})]})]})]}),!v&&r.jsx("p",{className:"empty-copy",children:a.unsupported}),m&&r.jsx("p",{role:"alert",className:"error-copy",children:m})]}),g&&r.jsx(Wc,{})]})}async function Qc(e,t,n){for(let i=0;i<2&&n();i++)try{return await e.request(t(),{timeoutMs:135e3})}catch(s){if(!(s instanceof Error&&/timeout|timed out/i.test(s.message)))return}}function Vc(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 Gc(e){return e?"success":"warning"}function Jc(e,t){return e&&null!==t?t<150?"success":t<500?"warning":"danger":"warning"}function Zc({connected:e,latencyMs:t,limits:n,t:s,failed:i={},loading:a=!1,onRetry:c}){const l=function(e){const t=[],n=Vc(e.codex),s=Vc(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,m=h?`${h.label} ${h.availablePercent}%`:"",f=!!h&&i[h.agent],g=f?s.quotaUpdateFailed:h?"":a?s.loading:s.quotaUnavailable,y=`${s.remainingQuota}: ${m||g}${f?` · ${g}`:""} · ${p?s.quotaResetsAt.replace("{time}",p):s.quotaResetUnavailable}${e?"":` · ${s.latencyDisconnected}`}`,v=e?null===t?s.latencyMeasuring:`${t} ms`:s.latencyDisconnected;return r.jsxs("div",{className:"connection-indicators",children:[(h||c)&&r.jsxs("button",{type:"button",className:"connection-quota",disabled:!e||a||!c,onClick:c,title:`${y}${c?` · ${s.retry}`:""}`,"aria-label":`${y}${c?` · ${s.retry}`:""}`,"aria-busy":a,children:[r.jsx("span",{className:"connection-quota-dot",style:{background:`var(--${f||!h?"warning":Gc(e)})`}}),r.jsxs("span",{className:"connection-quota-text",children:[m||g,f?" ↻":""]})]}),r.jsxs("span",{role:"img",className:"connection-latency",style:{color:`var(--${Jc(e,t)})`},"aria-label":`${s.connectionLatency}: ${v}`,children:[r.jsx(N,{size:11,"aria-hidden":"true"}),r.jsx("span",{className:"connection-latency-text",children:v})]})]})}function Yc({workspace:e}){const{phase:t,clientRef:n,pairing:s,t:i}=e,[a,c]=o.useState(null),[l,d]=o.useState({}),[u,h]=o.useState({}),[p,m]=o.useState(!1),f=o.useRef(()=>{});return o.useEffect(()=>{h({}),d({})},[s?.daemonId]),o.useEffect(()=>{const e=n.current;if(c(null),m(!1),"connected"!==t||!e)return;let s=!0;const i=e.onLatency(c),r=new Set,o=new Map,a={codex:0,claude:0},l=()=>s&&n.current===e&&e.isConnected,u=(t,n=!1)=>{l()&&!r.has(t)&&(clearTimeout(o.get(t)),r.add(t),m(!0),Qc(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(()=>{r.delete(t),s&&m(r.size>0)}))},p=()=>{u("codex"),u("claude")};return f.current=()=>{u("codex",!0),u("claude",!0)},p(),window.addEventListener("online",p),window.addEventListener("focus",p),()=>{s=!1,f.current=()=>{},i();for(const e of o.values())clearTimeout(e);window.removeEventListener("online",p),window.removeEventListener("focus",p)}},[t,n,s?.daemonId]),r.jsx(Zc,{connected:"connected"===t,latencyMs:a,limits:l,failed:u,loading:p,onRetry:()=>f.current(),t:i})}function Xc({value:e,t,showSession:n=!0,onChange:s}){const i=[...n?[{tab:"session",label:t.session,Icon:Fe}]:[],{tab:"files",label:t.files,Icon:te},{tab:"terminal",label:t.terminal,Icon:qe},{tab:"browser",label:t.browser,Icon:ce}];return r.jsx("div",{className:"control-tabs",children:i.map(({tab:t,label:n,Icon:i})=>r.jsxs("button",{"aria-label":n,"aria-pressed":e===t,className:e===t?"selected":"",onClick:()=>s(t),title:n,type:"button",children:[r.jsx(i,{"aria-hidden":"true"}),r.jsx("span",{children:n})]},t))})}function el(){const[e,t]=o.useState(null);return o.useEffect(()=>{let e=null,n=null;const s=()=>{e&&null!==n&&e.setAttribute("title",n),e=null,n=null,t(null)},i=e=>{if(!(e instanceof Element))return null;const t=e.closest("button, a");return t?.closest(".control-pane, .control-tabs, .header-actions, .right-resize-handle")?t.textContent?.trim()?null:t:null},r=i=>{if(i===e)return;if(s(),!i)return;const r=i.getAttribute("title")||i.getAttribute("aria-label");if(!r)return;e=i,n=i.getAttribute("title"),null!==n&&i.removeAttribute("title");const o=i.getBoundingClientRect(),a=o.bottom+42>window.innerHeight,c=o.right>window.innerWidth-140?"end":o.left<140?"start":"center";t({label:r,left:"end"===c?o.right:"start"===c?o.left:o.left+o.width/2,top:a?o.top-7:o.bottom+7,above:a,align:c})},o=e=>r(i(e.target)),a=t=>{e&&t.relatedTarget instanceof Node&&e.contains(t.relatedTarget)||i(t.target)===e&&s()},c=e=>r(i(e.target)),l=t=>{i(t.target)===e&&s()};return document.addEventListener("pointerover",o),document.addEventListener("pointerout",a),document.addEventListener("focusin",c),document.addEventListener("focusout",l),()=>{document.removeEventListener("pointerover",o),document.removeEventListener("pointerout",a),document.removeEventListener("focusin",c),document.removeEventListener("focusout",l),s()}},[]),e?a.createPortal(r.jsx("div",{className:"right-sidebar-icon-hint",role:"tooltip",style:{left:e.left,top:e.top,transform:`translate(${"end"===e.align?"-100%":"start"===e.align?"0":"-50%"}, ${e.above?"-100%":"0"})`},children:e.label}),document.body):null}function tl({chinese:e}){const[s,i]=o.useState(tt),[a,c]=o.useState(null),[l,d]=o.useState(""),u=e=>{!function(e){t().setItem(et,JSON.stringify(e)),window.dispatchEvent(new Event(Ke))}(e),i(e),d("")};return r.jsxs("section",{className:"control-section compact-section workspace-shortcut-settings",children:[r.jsx("h2",{children:e?"应用内快捷键":"In-app shortcuts"}),r.jsx("p",{className:"empty-copy",children:e?"点击组合键后直接按键录制。Esc 取消,退格键清除。新建标签会沿用当前终端或浏览器;其他页面默认新建浏览器标签。":"Click a shortcut to record it. Escape cancels; Backspace clears. New tab follows the current terminal or browser; elsewhere it opens a browser tab."}),Ve.map(t=>r.jsxs("div",{className:"workspace-shortcut-row",children:[r.jsx("span",{children:e?t.zh:t.en}),r.jsx("button",{type:"button","data-shortcut-recording":a===t.id?"true":void 0,"aria-label":`${e?"设置快捷键:":"Set shortcut: "}${e?t.zh:t.en}`,onClick:()=>{c(t.id),d("")},onBlur:()=>c(null),onKeyDown:i=>{if(a!==t.id)return;if(i.preventDefault(),i.stopPropagation(),"Escape"===i.key)return c(null),void d("");if("Backspace"===i.key||"Delete"===i.key)return u({...s,[t.id]:""}),void c(null);const r=Ze(i.nativeEvent);if(!r)return;const o=function(e,t,s){return"browser"===n().kind?"mod+w"===t?"reserved":Xe(e,t,{closeTab:"mod+alt+w",...s}):Xe(e,t,s)}(t.id,r,s);if(o){const t=Ve.find(e=>e.id===o);return void d("reserved"===o?e?"此组合键用于系统菜单或编辑操作,请换一个组合。":"Reserved for a system menu or editing action. Choose another combination.":`${e?"已用于:":"Already assigned to: "}${e?t?.zh:t?.en}`)}u({...s,[t.id]:r}),c(null)},children:a===t.id?e?"按下快捷键…":"Press shortcut…":Ye(nt(t.id,s))||(e?"未设置":"Not set")})]},t.id)),l&&r.jsx("p",{role:"alert",children:l}),r.jsx("div",{className:"attention-actions",children:r.jsx("button",{type:"button",onClick:()=>{u({}),c(null)},children:e?"恢复默认快捷键":"Restore defaults"})}),r.jsx("p",{className:"empty-copy",children:e?"⌘N 新建会话,⌘, 打开设置;⌘W 保留为关闭窗口。关闭标签默认使用 ⌘⌥W。":"⌘N creates a session; ⌘, opens settings; ⌘W closes the window. Close tab defaults to ⌘⌥W."})]})}function nl({children:e,t,onClose:n}){const s=o.useRef(null);return o.useEffect(()=>{const e=document.getElementById("vibelet-workspace");return e&&(e.inert=!0),s.current?.focus(),()=>{e&&(e.inert=!1)}},[]),a.createPortal(r.jsxs("section",{className:"browser-settings-page","aria-label":t.settings,onKeyDown:e=>{if("Escape"!==e.key||e.defaultPrevented||(e.preventDefault(),n()),"Tab"!==e.key)return;const t=[...e.currentTarget.querySelectorAll("button:not(:disabled),input:not(:disabled),a[href]")].filter(e=>e.getBoundingClientRect().width>0),s=t[0],i=t.at(-1);e.shiftKey&&document.activeElement===s&&(e.preventDefault(),i?.focus()),e.shiftKey||document.activeElement!==i||(e.preventDefault(),s?.focus())},children:[r.jsxs("button",{ref:s,type:"button",className:"icon-text-button",onClick:n,children:["← ",t.chat]}),r.jsx("h1",{children:t.settings}),r.jsxs("div",{className:"browser-settings-body",children:[r.jsx(at,{}),e,r.jsx(tl,{chinese:"Browser"!==t.browser})]})]}),document.body)}function sl({children:e,collapsed:t,t:s,value:i,showSession:c,onChange:l,onResize:d}){const u=ec("right",e=>{"terminal"!==e&&"browser"!==e||l(e)}),h=n().toolbarTarget?.("controls"),[p,m]=o.useState(null),f=r.jsx("div",{className:"right-dock-toolbar",ref:m,children:r.jsx(Xc,{value:i,t:s,showSession:c,onChange:l})});return"admin"===i&&"browser"===n().kind?r.jsx(nl,{t:s,onClose:()=>l("files"),children:e}):r.jsxs(Va.Provider,{value:{element:p,kind:i},children:[r.jsx(el,{}),h&&!t?a.createPortal(f,h):null,r.jsx("button",{"aria-label":s.resizeControlsSidebar,"aria-hidden":t,className:"resize-handle right-resize-handle",disabled:t,onPointerDown:d,title:s.resizeControlsSidebar,type:"button",children:r.jsx("span",{})}),r.jsx("div",{className:"workspace-control-sidebar-motion",inert:t,"aria-hidden":t,children:r.jsxs("aside",{tabIndex:-1,"aria-label":s.controls,className:"control-pane",...u,children:[!h&&r.jsx("div",{className:"control-pane-toolbar",children:f}),e]})})]})}function il({path:e,label:t,zh:n}){const{copyText:s,feedback:i}=Zs(n?"已复制路径":"Path copied",n?"复制失败,请重试":"Copy failed. Please try again."),o=i?.message??t;return r.jsx("button",{type:"button",title:o,"aria-label":o,onClick:()=>{s(e)},children:i?"success"===i.tone?r.jsx($,{}):r.jsx(We,{}):r.jsx(Q,{})})}function rl(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 ol(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 al(){const e=s(i().language);return"en"===e?{read:"Read",live:"Edit",edit:"Visual",source:"Source",properties:"Properties",loading:"Loading…",unavailable:"Reference unavailable",editorError:"Unable to load the editor. Switch to source mode."}:"zh-TW"===e?{read:"瀏覽",live:"編輯",edit:"視覺化",source:"原始碼",properties:"屬性",loading:"正在載入…",unavailable:"無法讀取引用",editorError:"無法載入編輯器,請切換到原始碼模式。"}:{read:"浏览",live:"编辑",edit:"可视化",source:"源码",properties:"属性",loading:"正在加载…",unavailable:"无法读取引用",editorError:"无法加载编辑器,请切换到源码模式。"}}function cl({file:e}){const[t,c]=o.useState(!1),l=f(()=>c(!1),void 0,t),d=yi(),u=s(i().language),h="en"===u?"Close":"zh-TW"===u?"關閉":"关闭",p=n().pdfPreviewUrl?.(e.path,e.cwd)??e.objectUrl;return r.jsxs(r.Fragment,{children:[r.jsxs("button",{className:"icon-text-button",type:"button",onClick:()=>c(!0),children:[r.jsx(ee,{"aria-hidden":"true"}),d.pdfPreview]}),t&&a.createPortal(r.jsx("div",{className:"remote-document-layer",onPointerDown:e=>{e.target===e.currentTarget&&c(!1)},children:r.jsxs("div",{ref:l,className:"remote-document-dialog","aria-label":d.pdfPreview,role:"dialog","aria-modal":"true",tabIndex:-1,children:[r.jsxs("header",{children:[r.jsx("span",{children:e.path.split("/").pop()}),r.jsx("button",{className:"icon-button",type:"button","aria-label":h,title:h,onClick:()=>c(!1),children:r.jsx(We,{"aria-hidden":"true"})})]}),r.jsx("iframe",{title:d.pdfPreview,src:`${p}#toolbar=1&navpanes=0&view=Fit`})]})}),document.body)]})}function ll({file:e}){const[t,s]=o.useState(),i=e.objectUrl??e.path,a=()=>s(i),c=yi(),l=rl(e.path,e.contentType,"text"===e.kind);if(t===i)return r.jsx("p",{className:"empty-copy",role:"status",children:c.mediaError});if("html"===l){const t=e.dirty?void 0:n().htmlPreviewUrl?.(e.path,e.cwd);return r.jsx("iframe",{className:"remote-document-preview",sandbox:"allow-scripts",title:c.htmlPreview,src:t,srcDoc:t?void 0:ol(e.text)})}return e.objectUrl?"image"===l?r.jsx("div",{className:"remote-media-viewer remote-image-viewer",children:r.jsx("img",{className:"remote-image",src:e.objectUrl,alt:e.path,onError:a})}):"audio"===l?r.jsx("audio",{"aria-label":c.audioPreview,controls:!0,preload:"metadata",src:e.objectUrl,onError:a}):"video"===l?r.jsx("div",{className:"remote-media-viewer remote-video-viewer",children:r.jsx("video",{"aria-label":c.videoPreview,controls:!0,playsInline:!0,preload:"metadata",src:e.objectUrl,onError:a},e.objectUrl)}):"pdf"===l?r.jsx(cl,{file:e}):r.jsx("p",{className:"empty-copy",children:c.mediaError}):null}function dl(e){const t=e.split("#")[0];return/\.[^/\\.]+$/.test(t)?t:`${t}.md`}function ul(e,t){return ss(ki(e,t))??t??"."}function hl(e,t,n){if(!e)return{path:ki(t,n),cwd:n??ul(t,n)};const s=e.includes("/")&&!/^\.\.?\//.test(e)?n??ul(t,n):ul(t,n);return{path:dl(e||t),cwd:s}}function pl(e,t){if(!t)return;let n=t.replace(/^#/,"");try{n=decodeURIComponent(n)}catch{}const s=e.querySelectorAll(n.startsWith("^")?"p,li":"h1,h2,h3,h4,h5,h6"),i=Array.from(s).find(e=>n.startsWith("^")?e.textContent?.trim().endsWith(n):e.textContent?.trim()===n||e.id===n);i?.scrollIntoView({block:"start"})}const ml=new Map;function fl(e,t,n){for(const[s,i]of ml)Date.now()-i.time>1e4&&ml.delete(s);n&&ml.set(ki(e,t),{hash:n,time:Date.now()})}function gl(e,t){const n=ki(e,t),s=ml.get(n);return ml.delete(n),s&&Date.now()-s.time<1e4?s.hash:""}const yl=o.lazy(()=>m(()=>import("./MarkdownModePanel-MUsXqLwF.js"),__vite__mapDeps([20,1,2,21])).then(e=>({default:e.MarkdownModePanel}))),vl=o.lazy(()=>m(()=>import("./file-editor-FileCodeEditor-DMbYLQga.js"),__vite__mapDeps([22,1,2,23,24])).then(e=>({default:e.FileCodeEditor}))),bl=o.lazy(()=>m(()=>import("./file-editor-ObsidianCodeEditor-TJxlWj2j.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}))),xl=o.lazy(()=>m(()=>import("./file-editor-ObsidianFileEditor-cHj5bINn.js"),__vite__mapDeps([37,1,2,32,3,23,33,38,27,5,39,40,41,42])).then(e=>({default:e.ObsidianFileEditor})));function wl({file:e,client:t,onOpenRemoteFile:n,onTextChange:a}){const c=function(e,t){return o.useMemo(()=>{let n;return async(s,i)=>{const r=hl(s,i,t),o={path:ki(r.path,r.cwd),cwd:t??r.cwd};if(!e?.isConnected||!t||!s||/^([/.]|[a-z]:)/i.test(s))return o;n??=e.request({action:"vault.listMarkdown",id:`editor-vault-${crypto.randomUUID()}`,cwd:t});try{const{entries:e}=await n,i=s.replace(/\.(?:md|markdown)$/i,"").toLowerCase(),a=e.filter(e=>e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase()===i||e.basename.toLowerCase()===i||e.aliases?.includes(i)),c=ki(dl(s),r.cwd),l=a.find(e=>ki(e.relPath,t)===c)??a.find(e=>e.relPath.replace(/\.(?:md|markdown)$/i,"").toLowerCase()===i)??a.sort((e,t)=>e.relPath.localeCompare(t.relPath))[0];return l?{path:ki(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"===rl(e.path,e.contentType,!0),p="en"!==s(i().language);return r.jsxs(r.Fragment,{children:[h&&r.jsxs("div",{className:"segmented editor-mode-tabs",children:[r.jsx("button",{type:"button",className:"edit"===d?"selected":"",onClick:()=>u("edit"),children:p?"编辑":"Edit"}),r.jsx("button",{type:"button",className:"preview"===d?"selected":"",onClick:()=>u("preview"),children:p?"预览":"Preview"})]}),l?r.jsx(o.Suspense,{fallback:r.jsx("pre",{className:"remote-editor",children:e.text}),children:r.jsx(yl,{text:e.text,modes:["edit","source"],initialMode:"edit",labels:al(),renderVisual:s=>r.jsx(xl,{client:t,resolveFile:c,path:e.path,cwd:e.cwd,text:e.text,readOnly:s,onChange:a,onOpenFile:n}),renderCode:s=>r.jsx(bl,{client:t,cwd:e.cwd,path:e.path,resolveFile:c,onOpenFile:n,text:e.text,onChange:a,preview:s})})}):h&&"preview"===d?r.jsx(ll,{file:e}):r.jsx(o.Suspense,{fallback:r.jsx("pre",{className:"remote-editor",children:e.text}),children:r.jsx(vl,{path:e.path,text:e.text,onChange:a})})]})}function Sl({workspace:e,children:t}){const a=Ua(),c=bi(e.pairing?.daemonId,e.activeSessionId),l=ec("center"),[d,u]=vi(c,()=>({})),[h,p]=vi(c,null),[m,f]=o.useState(null),y=o.useRef({files:d,remoteFile:e.remoteFile,daemonId:e.pairing?.daemonId});y.current={files:d,remoteFile:e.remoteFile,daemonId:e.pairing?.daemonId};const v=o.useRef(new Map),w="en"!==s(i().language);o.useEffect(()=>{y.current.files={},u({}),p(null),v.current.set(c,null)},[e.pairing?.daemonId]),o.useEffect(()=>{if(!e.remoteFile)return void v.current.set(c,null);const t=e.remoteFile,n=y.current.files[t.path];if(n?.dirty&&!t.dirty&&n.cwd===t.cwd&&n.text!==t.text)return e.setRemoteFile(n),p(n.path),void a.setCenter(null);u(e=>({...e,[t.path]:t})),v.current.get(c)!==t.path&&(p(t.path),a.setCenter(null)),v.current.set(c,t.path)},[e.remoteFile,c]);const S=t=>{a.setCenter(null),e.setRemoteFile(d[t]),p(t)},k=async t=>{const n=d[t],s=e.pairing?.daemonId;if(!n)return;const i=b();n.dirty&&!(await x({title:i.discard,message:t,confirmLabel:i.discardAction,danger:!0}))||y.current.daemonId===s&&y.current.files[t]?.text===n.text&&(u(e=>{const n={...e};return delete n[t],n}),t===h&&(p(null),v.current.set(c,null),e.setRemoteFile(null)))};!function(e){const t=o.useRef(e);t.current=e,o.useEffect(()=>{const e=e=>{const{detail:n}=e,s=t.current;s.daemonId===n.daemonId&&"copy"!==n.action&&"restore"!==n.action&&[...Object.values(s.files),s.remoteFile].filter(Boolean).some(e=>e.dirty&&Ii(e.path,n.path,n.cwd))&&e.preventDefault()},n=e=>{const{detail:n}=e,s=t.current;if(s.daemonId!==n.daemonId||"copy"===n.action||"restore"===n.action)return;const i=n.source??n.path,r=e=>{if(!Ii(e.path,i,n.cwd))return e;if("delete"===n.action)return null;const t=`${n.target}${ki(e.path,n.cwd).slice(ki(i,n.cwd).length)}`;return{...e,path:t}};s.setFiles(e=>Object.fromEntries(Object.values(e).flatMap(e=>{const t=r(e);return t?[[t.path,t]]:[]}))),s.active&&s.files[s.active]&&s.setActive(r(s.files[s.active])?.path??null),s.setRemoteFile(e=>e?r(e):e);const o=new URL(window.location.href),a=o.searchParams.get("file");a&&Ii(a,i,n.cwd)&&("delete"===n.action?o.searchParams.delete("file"):o.searchParams.set("file",`${n.target}${ki(a,n.cwd).slice(ki(i,n.cwd).length)}`),window.history.replaceState(null,"",o.href))};return window.addEventListener(wi,e),window.addEventListener(Si,n),()=>{window.removeEventListener(wi,e),window.removeEventListener(Si,n)}},[])}({daemonId:e.pairing?.daemonId,files:d,active:h,remoteFile:e.remoteFile,setFiles:u,setActive:p,setRemoteFile:e.setRemoteFile}),o.useEffect(()=>{const e=e=>{const t=e.detail;if("closeTab"===t)return void(a.center?a.close(a.center):h&&k(h));const n=[null,...Object.keys(d),...a.items.filter(e=>"center"===e.location).map(e=>e.id)],s=n.indexOf(a.center||h),i=n[(Math.max(s,0)+("nextTab"===t?1:n.length-1))%n.length];i?d[i]?S(i):a.setCenter(i):(p(null),a.setCenter(null))};return window.addEventListener(Qe,e),()=>window.removeEventListener(Qe,e)},[d,h,a]);const I=h?d[h]:null,C=n().toolbarTarget?.("conversation"),j=I&&!a.center&&r.jsxs("header",{className:"document-file-header",role:"toolbar","aria-label":w?"文件操作":"File actions",children:[r.jsx("button",{type:"button",title:e.t.download,"aria-label":e.t.download,onClick:()=>{e.downloadRemoteFile()},children:r.jsx(g,{})}),r.jsx(il,{path:I.path,label:e.t.copyPath,zh:w},I.path),"text"===I.kind&&r.jsx("button",{type:"button",title:e.t.saveFile,"aria-label":e.t.saveFile,disabled:!I.dirty||e.busy,onClick:()=>{e.saveRemoteFile()},children:r.jsx(Ee,{})})]});return r.jsx(Xi.Provider,{value:m,children:r.jsxs("div",{className:"workspace-documents",...l,children:[!C&&r.jsx("div",{className:"chat-header document-conversation-header",ref:f}),(Object.keys(d).length>0||a.items.some(e=>"center"===e.location))&&r.jsxs("div",{className:"document-tabs",children:[r.jsxs("div",{className:"document-tab-items",role:"tablist","aria-label":w?"工作区标签页":"Workspace tabs",children:[r.jsx("button",{role:"tab","aria-selected":!h&&!a.center,onClick:()=>{p(null),a.setCenter(null),v.current.set(c,null)},type:"button",children:e.t.chat}),Object.values(d).map(t=>r.jsxs("div",{className:"document-tab","data-active":!a.center&&h===t.path,children:[r.jsxs("button",{type:"button",role:"tab","aria-selected":!a.center&&h===t.path,title:t.path,onClick:()=>S(t.path),children:[r.jsx(ee,{}),r.jsxs("span",{className:"document-tab-label",children:[Kn(t.path),t.dirty?" ·":""]})]}),r.jsx("button",{type:"button",className:"document-tab-close",title:e.t.close,"aria-label":`${e.t.close} ${Kn(t.path)}`,onClick:()=>k(t.path),children:r.jsx(We,{})})]},t.path)),r.jsx(Za,{location:"center",t:e.t})]}),j]}),r.jsx("div",{hidden:!!h||!!a.center,className:"document-chat",children:t}),r.jsx("div",{hidden:!a.center,className:"dock-center-content",children:r.jsx(Xa,{location:"center"})}),I&&!a.center&&r.jsxs("section",{className:"document-file",role:"tabpanel","aria-label":Kn(I.path),children:["text"===I.kind?r.jsx(wl,{client:e.clientRef?.current,file:I,onOpenRemoteFile:(t,n)=>{e.openRemoteFile(t,n,{updateRoute:!0})},onTextChange:t=>e.setRemoteFile(e=>e?{...e,text:t,dirty:!0}:e)},I.path):r.jsx(ll,{file:I},I.path),e.remoteFileConflict&&r.jsxs("div",{role:"alert",className:"inline-notice warning",children:[r.jsx("span",{children:e.t.remoteFileConflict(I.path)}),r.jsx("button",{type:"button",onClick:()=>{(async()=>{const t=e.remoteFile;t&&await x({message:e.t.confirmOverwrite(Kn(t.path)),danger:!0})&&y.current.remoteFile===t&&await e.saveRemoteFile({force:!0})})()},children:e.t.forceSave})]})]})]})})}const kl="vibelet.web.savedTargets";function Il(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 Cl(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const s of e){const e=Il(s);if(e&&!t.has(e.daemonId)&&(t.add(e.daemonId),n.push(e),n.length>=12))break}return n}function jl(e=t()){const n=e.getItem(kl);if(!n)return[];try{return Cl(JSON.parse(n))}catch{return[]}}function Rl(e,n=t()){n.setItem(kl,JSON.stringify(Cl(e)))}const Ml="vibelet.web.sessionListCache";function El(e){return e instanceof Error&&"auth_failed"===e.message}const Tl="vibelet.web.composerDrafts",Nl={draftsBySessionId:{},newSessionDraft:""};function Al(e){return Boolean(e)&&"object"==typeof e&&!Array.isArray(e)}function Pl(e){return Al(e)?{draftsBySessionId:Al(e.draftsBySessionId)?Object.fromEntries(Object.entries(e.draftsBySessionId).filter(e=>"string"==typeof e[1])):{},newSessionDraft:"string"==typeof e.newSessionDraft?e.newSessionDraft:""}:Nl}function Dl(e=t()){const n=e.getItem(Tl);if(!n)return Nl;try{return Pl(JSON.parse(n))}catch{return Nl}}function Fl(e,n=t()){n.setItem(Tl,JSON.stringify(Pl(e)))}function Ll(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 ql(e,t){return t?e.draftsBySessionId[t]??"":e.newSessionDraft}function Ol(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 $l(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 zl=13e4;function _l(e,t){return Boolean(t)&&Object.hasOwn(e,t)}function Bl(e,t,n){return t&&0!==n.length?{...e,[t]:Xt(e[t]??[],n)}:e}function Hl(e,t){const n=new Map,s=Xt(e,t,(e,t)=>{t.localClientMessageId&&n.set(e,t)}),i=t.map(e=>{const t=n.get(e);return t?{...e,localClientMessageId:t.localClientMessageId,localDelivery:t.localDelivery}:{...e}}),r=new Set(i.map(e=>e.localClientMessageId));return function(e,t,n){const s=e.map(e=>{if(e.liveReply){const t=n.slice().reverse().find(t=>t.liveReply&&t.content.length>0&&(e.content.startsWith(t.content)||t.content.startsWith(e.content)));if(t?.timestamp)return{...e,timestamp:t.timestamp}}return e});for(const i of t){const e=Date.parse(i.timestamp??""),t=Number.isFinite(e)?s.findIndex(t=>{const s=Date.parse(t.timestamp??"");if(s!==e)return s>e;if("assistant"!==t.role)return!1;const r=n.findIndex(e=>t.historyKey&&e.historyKey===t.historyKey||t.liveReply&&e.liveReply&&e.timestamp===t.timestamp);return r<0||n.indexOf(i)<r}):-1;s.splice(t<0?s.length:t,0,i)}return s}(i,s.filter(e=>e.localClientMessageId&&e.historyKey?.startsWith("client:")&&!r.has(e.localClientMessageId)),e)}function Wl(e,t,n){const s=new Set(e);return n?s.add(t):s.delete(t),s}async function Ul(e){return{[e]:"desktop-free"}}function Kl(){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 Ql(e,t,n){const s=ql(e.composerDraftsRef.current,e.activeSessionId),i=s===t?s:[s,t].filter(Boolean).join("\n\n"),r=Ll(e.composerDraftsRef.current,e.activeSessionId,i);e.composerDraftsRef.current=r,e.setComposerDrafts(r),e.activeSessionIdRef.current===e.activeSessionId&&e.setDraft(i);try{Fl(r)}catch{}e.setAttachments(e=>[...e,...n.filter(t=>!e.some(e=>e.path===t.path))])}const Vl="Session send timed out.";function Gl(e){return"string"==typeof e&&e.trim().length>0?e:void 0}const Jl="vibelet.web.sessionSettings";function Zl(e){return"string"==typeof e&&e.trim().length>0?e:void 0}function Yl(e=window.location.search){const t=new URLSearchParams(e),n=Zl(t.get("folder")),s=Zl(t.get("file")),i=Zl(t.get("cwd"));return{...n?{folder:n}:{},...s?{file:s}:{},...i?{cwd:i}:{}}}function Xl(e,t={}){const n=t.history??window.history,s=t.location??window.location,i=[];e.folder&&i.push("file","cwd"),e.file&&i.push("folder");const r=function(e,t,n=[]){const s=new URLSearchParams(e);for(const r of n)s.delete(r);for(const[r,o]of Object.entries(t))o?s.set(r,o):s.delete(r);const i=s.toString();return i?`?${i}`:""}(s.search,e,i),o=`${s.pathname}${r}${s.hash}`;t.replace?n.replaceState(null,"",o):n.pushState(null,"",o)}function ed(e,t){o.useEffect(()=>{e.current=t},[e,t])}class td{constructor(e,t,n){this.storage=e,this.key=t,this.isReading=n;try{const n=JSON.parse(e?.getItem(t)??"null");if(n&&"object"==typeof n){const e=n,t=e=>Array.isArray(e)?e.filter(e=>"string"==typeof e):[];if(this.observed=new Set(t(e.observed)),this.unseen=new Set(t(e.unseen)),Array.isArray(e.failed))for(const n of e.failed)Array.isArray(n)&&2===n.length&&n.every(e=>"string"==typeof e)&&this.failed.set(n[0],n[1])}}catch{}this.recovered=new Set(this.observed),this.snapshot=new Set([...this.unseen,...this.failed.values()])}observed=new Set;failed=new Map;unseen=new Set;recovered=new Set;suppressed=new Set;runtime=new Map;listeners=new Set;snapshot=new Set;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});getSnapshot=()=>this.snapshot;save(){try{this.storage?.setItem(this.key,JSON.stringify({observed:[...this.observed].slice(-256),unseen:[...this.unseen].slice(-256),failed:[...this.failed].slice(-256)}))}catch{}const e=new Set([...this.unseen,...this.failed.values()]);this.snapshot.size===e.size&&[...e].every(e=>this.snapshot.has(e))||(this.snapshot=e,this.listeners.forEach(e=>e()))}deliveryChanged=(e,t,n)=>{"failed"===n?this.failed.set(t,e):this.failed.delete(t),this.save()};observe=e=>{this.suppressed.delete(e),this.observed.has(e)||(this.observed.add(e),this.save())};complete=e=>{this.observed.delete(e)&&(this.suppressed.add(e),this.recovered.delete(e),this.isReading(e)?this.unseen.delete(e):this.unseen.add(e),this.save())};reconcile=(e,t)=>{const n=this.runtime.get(e);this.runtime.set(e,t),t?this.suppressed.has(e)||!0===n||this.observe(e):((!0===n||this.recovered.has(e))&&this.observed.has(e)&&this.complete(e),this.suppressed.delete(e))};acknowledgeVisible=()=>{let e=!1;for(const t of this.unseen)this.isReading(t)&&(this.unseen.delete(t),e=!0);e&&this.save()};remap=(e,t)=>{for(const n of[this.observed,this.unseen,this.suppressed,this.recovered])n.delete(e)&&n.add(t);this.runtime.has(e)&&(this.runtime.set(t,this.runtime.get(e)),this.runtime.delete(e));for(const[n,s]of this.failed)s===e&&this.failed.set(n,t);this.save()}}function nd(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 sd(e,t,n,s){const i=await fetch(`/upload?name=${encodeURIComponent(e.name)}`,{method:"POST",signal:n,headers:{authorization:`Bearer ${t}`,"content-type":e.type||"application/octet-stream"},body:e});if(!i.ok)throw new Error(await i.text().catch(()=>s.uploadFailed)||s.uploadFailed);const r=function(e){const t=e;return"string"==typeof t.path?t.path:null}(await i.json());if(!r)throw new Error(s.uploadPathMissing);return{path:r,name:e.name,type:e.type||"application/octet-stream",size:e.size}}function id(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 rd="vibelet.web.historyDiskCache.v1";function od(){try{const e=JSON.parse(t().getItem(rd)||"[]");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 ad(e,n){try{const s=od().filter(t=>t.daemonId!==e||!Object.hasOwn(n,t.sessionId));for(const[t,r]of Object.entries(n)){if(!r)continue;const n={daemonId:e,sessionId:t,messages:r.slice(-1e3)};for(;n.messages.length&&(new TextEncoder).encode(JSON.stringify(n)).length>524288;)n.messages.shift();(n.messages.length||0===r.length)&&s.unshift(n)}const i=s.slice(0,40);for(;i.length&&(new TextEncoder).encode(JSON.stringify(i)).length>2097152;)i.pop();t().setItem(rd,JSON.stringify(i))}catch{}}const cd=new Set(["attachmentCount","domNodes","durationMs","errorKind","failureKind","longTaskCount","maxLongTaskMs","online","phase","visibilityState"]);function ld(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 dd(e,t){return t.has(e.sessionId)||!0===e.runtime?.isResponding||"daemonActive"===e.runtime?.state||"externalRunning"===e.runtime?.state}class ud{cleared=new Map;live(e,t,n){const s=new Set(n.map(e=>e.clientMessageId)),i=this.cleared.get(t)??new Set;for(const r of e[t]??[])r.clientMessageId&&!s.has(r.clientMessageId)&&i.add(r.clientMessageId);for(const r of s)r&&i.delete(r);return this.cleared.set(t,i),{...e,[t]:n}}snapshot(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,t.filter(t=>!t.clientMessageId||!this.cleared.get(e)?.has(t.clientMessageId))]))}remap(e,t){const n=this.cleared.get(e);n&&(this.cleared.set(t,new Set([...this.cleared.get(t)??[],...n])),this.cleared.delete(e))}}const hd=o.lazy(()=>m(()=>import("./NewSessionDialog-6g3uTjpL.js"),__vite__mapDeps([43,1,2,14,44]))),pd=o.lazy(()=>m(()=>import("./GlobalPendingDialog-BRjrQWQb.js"),__vite__mapDeps([45,1,2])));function md({workspace:e}){const t=function(e){const[t,n]=o.useState(0),[s,i]=o.useState(0);return o.useLayoutEffect(()=>{if(!s)return;const e=requestAnimationFrame(()=>{document.querySelector('[role="dialog"]')||document.querySelector(".document-chat:not([hidden]) .composer textarea")?.focus({preventScroll:!0})});return()=>cancelAnimationFrame(e)},[s]),{selectSession:t=>{i(e=>e+1),e.activeSessionIdRef.current=t,e.setActiveSessionId(t);const s=e.displaySessions.find(e=>e.sessionId===t);if(!e.pendingApprovals[t]&&!e.pendingQuestions[t]&&!s?.runtime.needsAttention)return;n(e=>e+1);const r=e.clientRef.current;e.requestReconnectSnapshot().catch(n=>{e.clientRef.current===r&&e.activeSessionIdRef.current===t&&e.setErrorText(n instanceof Error?n.message:String(n))})},revealKey:t}}(e),[s,i]=o.useState(!0),[a,c]=o.useState(!1),[l,d]=o.useState(!1);!function(e){const t=Ua(),[s,i]=o.useState(tt),r=o.useRef({workspace:e,dock:t,shortcuts:s});r.current={workspace:e,dock:t,shortcuts:s},o.useEffect(()=>{const e=()=>i(tt()),t=e=>e instanceof Element&&!!e.closest('.workspace-control-sidebar-motion, .dock-surface[data-location="right"], #desktop-toolbar-controls');let s=!1;const o=e=>{s=t(e.target)},a=(e,n,i=e.target)=>{if(e.defaultPrevented||e.isComposing||e.repeat||document.querySelector('[data-shortcut-recording="true"], [role="dialog"], .desktop-workspace-container[hidden], .browser-settings-page'))return;const o=Ze(e);if(!o&&!n)return;const{workspace:a,dock:c,shortcuts:l}=r.current,d=n??Ve.find(e=>nt(e.id,l)===o)?.id;if(!d)return;if("searchMessages"===d&&(t(i)||!document.querySelector(".document-chat:not([hidden]) .chat-pane")))return;e.preventDefault(),e.stopPropagation();const u="terminal"===a.controlTab?"terminal":"browser",h=c.items.find(e=>e.id===c.center),p=!a.rightSidebarCollapsed&&(t(i)||i===document.body&&s),m=!p&&h?h:c.items.find(e=>e.id===c.right[u]);switch(d){case"searchMessages":window.dispatchEvent(new Event("vibelet.message-search"));break;case"leftSidebar":a.setLeftSidebarCollapsed(e=>!e);break;case"rightSidebar":a.setRightSidebarCollapsed(e=>!e);break;case"files":case"terminal":case"browser":a.setControlTabAndOpen(d);break;case"searchSessions":a.setLeftSidebarCollapsed(!1),window.dispatchEvent(new Event("vibelet.session-search"));break;case"newTab":{const e="terminal"===m?.kind||"browser"===m?.kind?m.kind:u;c.add(e,a.t[e],a.cwd),a.setControlTabAndOpen(e);break}case"moveTab":m&&c.move(m.id,"center"===m.location?"right":"center");break;case"diff":a.activeSession&&a.setDiffSessionId(a.activeSession.sessionId);break;case"closeTab":case"nextTab":case"previousTab":if(p)if("closeTab"===d)!m||m.emptyPlaceholder?a.setRightSidebarCollapsed(!0):(document.querySelector(".control-pane")?.focus(),c.close(m.id));else{const e=c.items.filter(e=>"right"===e.location&&e.kind===u);e.length&&c.setRight(t=>({...t,[u]:e[(Math.max(0,e.findIndex(e=>e.id===m?.id))+("nextTab"===d?1:e.length-1))%e.length].id}))}else window.dispatchEvent(new CustomEvent(Qe,{detail:d}))}},c=e=>a(e),l=n().subscribeCommand?.(e=>{"close-tab"===e&&a(new KeyboardEvent("keydown"),"closeTab",document.activeElement)});return window.addEventListener(Ke,e),window.addEventListener("focusin",o,!0),window.addEventListener("pointerdown",o,!0),window.addEventListener("keydown",c,!0),()=>{l?.(),window.removeEventListener(Ke,e),window.removeEventListener("focusin",o,!0),window.removeEventListener("pointerdown",o,!0),window.removeEventListener("keydown",c,!0)}},[])}(e);const[u,h]=function(e){const[t,s]=o.useState(null);return o.useEffect(()=>{const t=()=>s(t=>t??{cwd:e}),i=n().subscribeCommand?.(e=>{"new-session"===e&&t()}),r=e=>{"browser"!==n().kind||!e.metaKey&&!e.ctrlKey||e.altKey||e.shiftKey||"n"!==e.key.toLowerCase()||(e.preventDefault(),t())};return window.addEventListener("keydown",r),()=>{i?.(),window.removeEventListener("keydown",r)}},[e]),[t,s]}(e.cwd);o.useEffect(()=>{"browser"===e.controlTab&&i(!0)},[e.controlTab]),o.useEffect(()=>{"terminal"===e.controlTab&&c(!0)},[e.controlTab]),o.useEffect(()=>{("session"===e.controlTab||"desktop"===n().kind&&"admin"===e.controlTab)&&e.setControlTab("files");const t=()=>e.setControlTabAndOpen("admin");return window.addEventListener("vibelet.browser.settings",t),()=>window.removeEventListener("vibelet.browser.settings",t)},[e.controlTab,e.setControlTab,e.setControlTabAndOpen]),o.useEffect(()=>{e.activeQuestion&&e.setQuestionAnswers(Vn(e.activeQuestion))},[e.activeQuestion,e.setQuestionAnswers]);const{clientRef:p,phase:m,statusText:f,errorText:g,pairing:y,sessions:v,nextCursor:b,folderCounts:x,inventoryVersion:w,activeSessionId:S,diffSessionId:k,setDiffSessionId:I,respondingSessions:C,questionAnswers:j,agent:R,cwd:M,approvalMode:E,model:T,setModel:N,effort:A,setEffort:P,fastMode:D,setFastMode:F,renameTitle:L,setRenameTitle:q,draft:O,webPreferences:$,sessionSort:z,setSessionSort:_,search:B,setSearch:H,sinceFilter:W,setSinceFilter:U,hideArchived:K,setHideArchived:Q,groupFolders:V,setGroupFolders:G,showNeedsAttentionGroup:J,setShowNeedsAttentionGroup:Z,showRunningGroup:Y,setShowRunningGroup:X,separatePinnedGroup:ee,setSeparatePinnedGroup:te,collapsedFolders:ne,setCollapsedFolders:se,sessionAgentFilter:ie,setSessionAgentFilter:re,directoryTags:oe,composerPreferences:ae,savedTargets:ce,leftSidebarCollapsed:le,setLeftSidebarCollapsed:de,rightSidebarCollapsed:ue,setRightSidebarCollapsed:he,workspaceClassName:pe,wideMainClassName:me,workspaceStyle:fe,beginPaneResize:ge,commitSearch:ye,saveTargets:ve,setLanguagePreference:be,setThemePreference:xe,updateComposerPreferences:we,t:Se,busy:ke,rewindMessage:Ie,controlTab:Ce,setControlTab:je,detailsOpen:Re,setDetailsOpen:Me,setControlTabAndOpen:Ee,skills:Te,admin:Ne,daemonMetadata:Ae,notificationSettings:Pe,notificationPermission:De,archiveSyncBusy:Fe,archiveSyncStatus:Le,attachments:qe,setAttachments:Oe,uploadBusy:$e,directory:ze,newDirName:_e,setNewDirName:Be,remoteFile:He,uploadFiles:We,openRemoteFile:Ue,listDirectory:Ge,listSessionDirectories:Je,listFileTreeDirectory:Ye,createDirectory:Xe,createSessionDirectory:et,pendingActionsCount:st,activeQueue:it,activeModelOptions:rt,activeUsage:ot,activeApproval:at,activeQuestion:ct,activeSession:dt,displaySessions:ut,groupedSessions:ht,pendingSessionIds:pt,visibleSessions:mt,historyLoading:ft,hasOlderHistory:gt,olderHistoryLoading:yt,requestHistory:vt,messages:bt,messagesSessionIdRef:xt,updateDraft:wt,requestReconnectSnapshot:St,requestSessions:kt,fetchAgentResources:It,failedSend:Ct,dismissFailedSend:jt,retryFailedSend:Rt,stagePendingSession:Mt,listSessionModels:Et,loadDirectoryGitMetadata:Tt,sendDraft:Nt,sendQuickReply:At,respondApproval:Pt,respondQuestion:Dt,cancelQuestion:Ft,setQuestionChoice:Lt,requestActiveAction:qt,interruptActiveSession:Ot,retrySessions:$t,updateApprovalMode:zt,cancelQueuedTurn:_t,setSessionPinned:Bt,setSessionArchived:Ht,deleteSession:Wt,updatePinned:Ut,updateArchived:Kt,renameSession:Qt,runArchiveSync:Vt,skipArchiveSync:Gt,runAdminAction:Jt,exportActiveSession:Zt,clearPairing:Yt,setNotificationsEnabled:Xt,connectSavedTarget:en,forgetSavedTarget:tn,openSessionDetails:nn,editFolderTags:sn,copyResumeCommand:rn,resumeInTerminal:on,notificationsBlocked:an,hasDaemonUpdate:cn,archiveSynced:ln,archiveSyncDismissed:dn}=e,un=o.useMemo(()=>function(e,t,n){const s={};for(const i of Object.values(e))s[i.sessionId]=`${n.interactionWaitingApproval} · ${i.description||i.toolName}`;for(const i of Object.values(t))s[i.sessionId]=`${n.interactionWaitingAnswer} · ${i.questions[0]?.question??""}`;return s}(e.pendingApprovals,e.pendingQuestions,Se),[e.pendingApprovals,e.pendingQuestions,Se]),hn=o.useMemo(()=>l?Object.fromEntries(ht.map(e=>[e.folder,!1!==ne[e.folder]])):ne,[l,ne,ht]),pn=ht.length>0&&ht.every(e=>hn[e.folder]);return"missing-pair"===m?r.jsxs(r.Fragment,{children:[r.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:Se.skipToConversation}),r.jsx(za,{errorText:g,t:Se})]}):r.jsxs("main",{className:pe,id:"vibelet-workspace",style:fe,children:[u&&r.jsx(o.Suspense,{fallback:null,children:r.jsx(hd,{client:"connected"===m?p.current:null,onOpenRemoteFile:Ue,pairing:y,onLoadGitMetadata:Tt,cwd:u.cwd,agent:R,device:y?.daemonId??"disconnected",connected:"connected"===m,approvalMode:E,model:T,fastMode:D,t:Se,onClose:()=>h(null),onCreate:Mt,onListModels:Et,onListDirectories:Je,onCreateDirectory:et},y?.daemonId??"disconnected")}),r.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:Se.skipToConversation}),r.jsx(Fc,{collapsed:le,onExpand:()=>de(e=>!e),onResize:ge("left"),t:Se,children:r.jsx(Dc,{connectionIndicators:r.jsx(Yc,{workspace:e}),activeDaemonId:y?.daemonId,activeSessionId:S,busy:ke,collapsedFolders:hn,allFoldersCollapsed:pn,currentCwd:M,directoryTags:oe,displayName:y?.displayName,savedTargets:ce,folderCounts:x,groupFolders:V,sessionSort:z,onSessionSortChange:_,groupedSessions:ht,hideArchived:K,separatePinnedGroup:ee,showNeedsAttentionGroup:J,showRunningGroup:Y,inventoryVersion:w,nextCursor:b,phase:m,respondingSessionIds:C,search:B,sessionAgentFilter:ie,sessionsCount:ut.length,sinceFilter:W,statusText:f,t:Se,visibleSessions:mt,onLoadMore:e=>kt({append:!0,cursor:e}),onCopyResumeCommand:rn,onResumeInTerminal:on,onConnectTarget:en,attentionReasons:un,pendingSessionIds:pt,onRequestNewSession:e=>h({cwd:e??M}),onRenameSession:Qt,onDeleteSession:e=>{Wt(e)},onEditFolderTags:sn,onOpenSessionDetails:nn,onResetFilters:()=>{_("updated"),re("all"),U("30d"),Q(!1),G(!0),Z(!1),X(!1),te(!1)},onRenameTarget:(e,t)=>ve(function(e,t,n){const s=n.trim();return s?e.map(e=>e.daemonId===t?{...e,label:s}:e):e}(ce,e,t)),onEditConnection:n().settingsTarget?e=>window.dispatchEvent(new CustomEvent("vibelet.desktop.edit-connection",{detail:e.pairToken})):void 0,onSearchChange:H,onSearchCommit:ye,onSelectSession:t.selectSession,onToggleSessionArchived:e=>{Ht(e,!e.archived)},onToggleSessionPinned:e=>{Bt(e,!e.pinned)},onSessionAgentFilterChange:re,onSinceFilterChange:U,onToggleFolder:e=>se(t=>({...t,[e]:l?!1===t[e]:!t[e]})),onToggleAllFolders:()=>{d(!pn),se({})},onToggleGroupFolders:()=>G(e=>!e),onToggleHideArchived:()=>Q(e=>!e),onToggleNeedsAttentionGroup:()=>{e.toggleSessionViewGroup("needsAttention")},onToggleRunningGroup:()=>{e.toggleSessionViewGroup("running")},onToggleSeparatePinnedGroup:()=>{e.toggleSessionViewGroup("pinned")},onToggleCollapse:()=>de(!0)})}),r.jsxs("section",{className:me,"aria-label":Se.vibeletWorkspace,id:"vibelet-main-content",tabIndex:-1,children:[r.jsx(Sl,{workspace:e,children:r.jsx(da,{client:"connected"===m?p.current:null,activeSession:dt,activeSessionId:S,activeModelOptions:rt,activeQueue:it,activeUsage:ot,agent:R,approvalMode:E,attachments:qe,busy:ke,cwd:M,draft:O,effort:A,errorText:g,failedSend:Ct,onDismissFailedSend:jt,fastMode:D,historyLoading:ft,hasOlderHistory:gt,olderHistoryLoading:yt,onLoadOlderHistory:()=>dt?vt(dt,{older:!0}):Promise.resolve(),messages:bt,messagesSessionId:xt.current,model:T,phase:m,quickReplies:ae.quickReplies,onQuickRepliesChange:e=>we(t=>({...t,quickReplies:e})),quickRepliesOpen:ae.quickRepliesOpen,onQuickRepliesOpenChange:e=>we(t=>({...t,quickRepliesOpen:e})),renameTitle:L,respondingSessionIds:C,sendShortcut:ae.sendShortcut,skills:Te,uploadBusy:$e,detailsOpen:Re,t:Se,onApprovalModeChange:e=>{zt(e)},onBrowseFiles:()=>{const e=dt?.cwd||M||zn;Ee("files"),Ge(e,{updateRoute:!0})},queueControls:e.queueControls,onCancelQueuedTurn:e=>{_t(e)},onClearInterrupt:()=>{qt("session.clearInterrupt")},onDraftChange:wt,onDetailsOpenChange:Me,onEffortChange:P,onExportActiveSession:()=>{Zt()},onRewindMessage:e=>{Ie(e)},onFastModeChange:F,onRetryFailedSend:Rt,onModelChange:N,onOpenRemoteFile:(e,t)=>{Ue(e,t,{updateRoute:!0})},onInterrupt:Ot,onDismissError:()=>e.setErrorText(null),onRetry:()=>{$t(),It(dt?.agent??R,M)},onRenameSession:e=>{Qt(void 0,e)},onRenameTitleChange:q,onRemoveAttachment:e=>Oe(t=>t.filter(t=>t.path!==e)),onRefreshSkills:()=>{It(dt?.agent??R,M)},onSubmit:Nt,onSendQuickReply:At,onToggleArchived:()=>{Kt()},onTogglePinned:()=>{Ut()},onUploadFiles:We,onViewChanges:I})}),r.jsxs(sl,{collapsed:ue,t:Se,value:Ce,showSession:!1,onChange:je,onResize:ge("right"),children:[r.jsx("div",{hidden:"files"!==Ce,style:{display:"files"===Ce?"contents":"none"},children:r.jsx(o.Suspense,{fallback:r.jsx(bc,{t:Se}),children:r.jsx(fc,{busy:ke,cwd:M,directory:ze,onLoadChildren:Ye,newDirName:_e,remoteFile:He,t:Se,onCreateDirectory:()=>{Xe()},onListDirectory:e=>{Ge(e,{updateRoute:!0})},onNewDirNameChange:Be,onOpenRemoteFile:(e,t)=>{Ue(e,t,{updateRoute:!0})}},y?.daemonId)})}),a?r.jsxs("div",{hidden:"terminal"!==Ce,className:"terminal-tab-content",children:[r.jsx(Za,{location:"right",kind:"terminal",t:Se,cwd:M===zn?ze.path:M}),r.jsx(Xa,{location:"right",kind:"terminal"})]}):null,s?r.jsxs("div",{hidden:"browser"!==Ce,className:"browser-tab-content",children:[r.jsx(Za,{location:"right",kind:"browser",t:Se}),r.jsx(Xa,{location:"right",kind:"browser"})]}):null,"admin"===Ce?r.jsxs(o.Suspense,{fallback:r.jsx(bc,{t:Se}),children:[r.jsx(gc,{language:$.language,t:Se,onLanguageChange:be}),!n().settingsTarget&&r.jsx(Kc,{}),r.jsx(yc,{t:Se,theme:$.theme,onThemeChange:xe}),r.jsx(vc,{notificationsBlocked:an,permission:De,settings:Pe,t:Se,onToggleEnabled:Xt}),!n().settingsTarget&&r.jsx(Hc,{workspace:e})]}):null]})]}),n().settingsTarget&&r.jsx(Hc,{workspace:e,portalOnly:!0}),r.jsx("div",{className:"workspace-header-actions",children:r.jsx(lt,{client:"connected"===m?p.current:null,activeSession:dt,busy:ke,controlsOpen:!ue,pendingCount:st,t:Se,onOpenControls:()=>{ue&&0===st&&"session"===Ce&&je("files"),he(e=>!e)},onRefreshSessions:()=>{kt({force:!0})},onRestoreSnapshot:()=>{St()},onToggleArchived:()=>{Kt()},onTogglePinned:()=>{Ut()},onViewChanges:I})}),r.jsx(o.Suspense,{fallback:null,children:r.jsx(pd,{activeApproval:at,activeQuestion:ct,pendingCount:st,requestKey:Hi(e.pendingApprovals,e.pendingQuestions),sessions:v,busy:ke,errorText:g,questionAnswers:j,t:Se,onCancelQuestion:()=>{Ft()},onQuestionChoice:Lt,onRespondApproval:e=>{Pt(e)},onRespondQuestion:()=>{Dt()},onDismissRequest:(t,n,s)=>{"approval"===t?e.setPendingApprovals(e=>{if(e[n]?.requestId!==s)return e;const t={...e};return delete t[n],t}):e.setPendingQuestions(e=>{if(e[n]?.requestId!==s)return e;const t={...e};return delete t[n],t})},onClearRequests:()=>{e.setPendingApprovals({}),e.setPendingQuestions({})}},t.revealKey)}),r.jsx(Ba,{}),r.jsx(rc,{onOpenBrowserLink:e.applyBrowserDefaultWidth,onOpenRight:Ee,onCloseRight:()=>he(!0),client:"connected"===m?p.current:null,daemonId:y?.daemonId,deviceName:y?.displayName??"",controlTab:Ce,rightVisible:!ue,t:Se}),r.jsx(xc,{activeSession:dt,client:p.current,close:()=>I(null),id:k,sessions:v,t:Se})]})}const fd=Object.freeze(Object.defineProperty({__proto__:null,App:function(){const e=function(){const e=function(){const e=function(){const e=o.useRef(null),t=o.useRef(async()=>{}),n=o.useRef(null),[r]=o.useState(()=>({permission:Qt(),notifications:Kt(),preferences:i(),drafts:Dl(),targets:jl()})),a=o.useRef(r.permission),c=o.useRef(r.notifications),l=o.useRef(r.preferences),d=o.useRef(r.drafts),h=o.useRef(r.targets),m=o.useRef(a.current),f=o.useRef(c.current),g=o.useRef(d.current),y=o.useRef(null),v=o.useRef(null),b=o.useRef(new Set),x=o.useRef(null),w=o.useRef(new Set),S=o.useRef(null),k=o.useRef(0),I=o.useRef(new Set),C=o.useRef({}),M=o.useRef(!1),[E,T]=o.useState("connecting"),[N,A]=o.useState(()=>u[s(l.current.language)].preparingVibeletWeb),[P,D]=o.useState(null),[F,L]=o.useState(null),[q,O]=o.useState([]),[$,z]=o.useState({}),[_,B]=o.useState({}),[H,W]=o.useState(),[U,K]=o.useState({}),[Q,V]=o.useState(),[G,J]=o.useState(null),Z=bi(F?.daemonId,G),[Y,X]=o.useState(null),[ee,te]=o.useState(()=>new Set),[ne,se]=o.useState({}),[ie,re]=o.useState({}),[oe,ae]=o.useState({}),{pendingQueues:ce,setPendingQueues:le,setLivePendingQueue:de,remapPendingQueue:ue}=function(){const e=o.useRef(new ud),[t,n]=o.useState({});return{pendingQueues:t,setPendingQueues:o.useCallback(t=>{n(n=>e.current.snapshot("function"==typeof t?t(n):t))},[]),setLivePendingQueue:o.useCallback((t,s)=>{n(n=>e.current.live(n,t,s))},[]),remapPendingQueue:o.useCallback((t,n)=>{e.current.remap(t,n)},[])}}(),[he,pe]=o.useState("claude"),[me,fe]=o.useState(zn),[ge,ye]=o.useState(_n),[ve]=o.useState(!1),[be,xe]=o.useState(""),[we,Se]=o.useState(""),[ke,Ie]=o.useState(!1),[Ce,je]=o.useState(""),[Re,Me]=o.useState(d.current),[Ee,Te]=o.useState(()=>ql(d.current,null)),{webPreferences:Ne,sessionSort:Ae,setSessionSort:Pe,setRightSidebarCollapsed:De,search:Fe,setSearch:Le,sinceFilter:qe,setSinceFilter:Oe,hideArchived:$e,setHideArchived:ze,groupFolders:_e,setGroupFolders:Be,showNeedsAttentionGroup:He,setShowNeedsAttentionGroup:We,showRunningGroup:Ue,setShowRunningGroup:Ke,separatePinnedGroup:Qe,setSeparatePinnedGroup:Ve,collapsedFolders:Ge,setCollapsedFolders:Je,sessionAgentFilter:Ze,setSessionAgentFilter:Ye,directoryTags:Xe,archiveSyncedDaemonIds:et,archiveSyncCardDismissedDaemonIds:tt,composerPreferences:nt,savedTargets:st,setSavedTargets:it,leftSidebarCollapsed:rt,setLeftSidebarCollapsed:ot,rightSidebarCollapsed:at,workspaceClassName:ct,wideMainClassName:lt,workspaceStyle:dt,beginPaneResize:ut,applyBrowserDefaultWidth:ht,commitSearch:pt,saveTargets:mt,setLanguagePreference:ft,setThemePreference:gt,updateSessionListPreferences:yt,updateComposerPreferences:vt}=function(e,t,n="default"){const[s,r]=o.useState(e);o.useEffect(()=>{const e=()=>{const e=i();r(t=>({...t,theme:e.theme,language:e.language,composer:e.composer}))};return window.addEventListener("vibelet.preferences.changed",e),()=>window.removeEventListener("vibelet.preferences.changed",e)},[]);const[a,c]=o.useState(e.sessionList.sortOrder),[l,d]=o.useState(""),[u,h]=o.useState(e.sessionList.searchHistory),[m,f]=o.useState(e.sessionList.sinceFilter),[g,y]=o.useState(e.sessionList.hideArchived),[v,b]=o.useState(e.sessionList.groupFolders),[x,w]=o.useState(e.sessionList.showNeedsAttentionGroup),[S,k]=o.useState(e.sessionList.showRunningGroup),[I,C]=o.useState(e.sessionList.separatePinnedGroup),[R,M]=o.useState(e.sessionList.collapsedFolders),[E,T]=o.useState(e.sessionList.agentFilter),[N,A]=o.useState(t),[P,D]=o.useState(e.layout.leftSidebarCollapsed),[F,L]=o.useState(e.layout.rightSidebarCollapsed),{leftPaneWidth:q,rightPaneWidth:O,beginPaneResize:$,applyBrowserDefaultWidth:z}=function(e,t,n="default"){const[s,i]=o.useState(288),[r,a]=vi(n,"third"),[c,l]=o.useState(()=>window.innerWidth),[d,u]=o.useState(null);o.useEffect(()=>{const e=document.querySelector(".workspace .wide-main");if(!e||"undefined"==typeof ResizeObserver)return;const t=()=>u(e.getBoundingClientRect().width);t();const n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[n]);const h=d??c-(e?0:s+10),p="number"==typeof r?r:Math.round(h/("half"===r?2:3)),m=o.useCallback(()=>{a(e=>"number"==typeof e?e:"half")},[a]),f=o.useRef(null);o.useEffect(()=>()=>f.current?.(),[e,t,n]),o.useEffect(()=>{const e=()=>l(window.innerWidth);return window.addEventListener("resize",e),()=>window.removeEventListener("resize",e)},[]);const g=function(e,t){const n=e.leftCollapsed?0:e.leftPaneWidth,s=e.rightCollapsed?0:e.rightPaneWidth,i=n+s,r=i>t?Math.max(0,t)/i:1;return{leftPaneWidth:e.leftCollapsed?e.leftPaneWidth:Math.floor(n*r),rightPaneWidth:e.rightCollapsed?e.rightPaneWidth:Math.floor(s*r)}}({leftCollapsed:e,rightCollapsed:t,leftPaneWidth:s,rightPaneWidth:p},c-96-64),y=o.useCallback(e=>t=>{if(0!==t.button||!1===t.isPrimary)return;t.preventDefault(),f.current?.();const n=t.currentTarget,s=t.pointerId;let r=!0;const o=document.createElement("div");o.dataset.paneResizeShield="",o.setAttribute("aria-hidden","true"),Object.assign(o.style,{position:"fixed",inset:"0",zIndex:"2147483647",cursor:"col-resize",touchAction:"none"}),document.body.append(o);const c=t.clientX,l="left"===e?g.leftPaneWidth:g.rightPaneWidth,d=t.currentTarget.closest(".workspace")?.querySelector(".chat-pane"),u=l+Math.max(0,(d?.getBoundingClientRect().width??0)-96),h=t=>{if(t.pointerId!==s)return;if(!(1&t.buttons))return void p();const n=(t.clientX-c)*("left"===e?1:-1),r=function(e,t,n=1/0){return Math.min(Math.max(Math.round(e),t),n)}(l+n,"left"===e?252:234,u);"left"===e?i(r):a(r)},p=()=>{if(r){r=!1,o.remove(),document.body.classList.remove("pane-resizing"),window.removeEventListener("pointermove",h,!0),window.removeEventListener("pointerup",m,!0),window.removeEventListener("pointercancel",m,!0),window.removeEventListener("blur",p),window.removeEventListener("keydown",y,!0),document.removeEventListener("visibilitychange",v),n.removeEventListener("lostpointercapture",m);try{n.hasPointerCapture?.(s)&&n.releasePointerCapture(s)}catch{}f.current===p&&(f.current=null)}},m=e=>{e.pointerId===s&&p()},y=e=>{"Escape"===e.key&&(e.preventDefault(),p())},v=()=>{"hidden"===document.visibilityState&&p()};f.current=p,document.body.classList.add("pane-resizing"),window.addEventListener("pointermove",h,!0),window.addEventListener("pointerup",m,!0),window.addEventListener("pointercancel",m,!0),window.addEventListener("blur",p),window.addEventListener("keydown",y,!0),document.addEventListener("visibilitychange",v),n.addEventListener("lostpointercapture",m);try{n.setPointerCapture?.(s)}catch{}},[g.leftPaneWidth,g.rightPaneWidth,a]);return{...g,beginPaneResize:y,applyBrowserDefaultWidth:m}}(P,F,n),_=s.sessionList.directoryTags,B=s.sessionList.archiveSyncedDaemonIds,H=s.sessionList.archiveSyncCardDismissedDaemonIds,W=s.composer,U=function(e){return{workspaceClassName:["workspace",e.leftCollapsed&&"left-sidebar-collapsed"].filter(Boolean).join(" "),wideMainClassName:["wide-main",e.rightCollapsed&&"right-sidebar-collapsed"].filter(Boolean).join(" "),style:{"--left-pane-width":`${e.leftPaneWidth}px`,"--right-pane-width":`${e.rightPaneWidth}px`}}}({leftCollapsed:P,rightCollapsed:F,leftPaneWidth:q,rightPaneWidth:O});o.useEffect(()=>{r(e=>{const t={...e,sessionList:{...e.sessionList,searchHistory:u,sortOrder:a,sinceFilter:m,hideArchived:g,groupFolders:v,showNeedsAttentionGroup:x,showRunningGroup:S,separatePinnedGroup:I,collapsedFolders:R,agentFilter:E},layout:{...e.layout,leftSidebarCollapsed:P,rightSidebarCollapsed:F}};return p(t),t})},[R,v,g,P,F,u,I,E,x,S,m,a]);const K=o.useCallback(()=>{h(e=>j(e,l))},[l]),Q=o.useCallback(e=>{A(e),Rl(e)},[]),V=o.useCallback(e=>{r(t=>{const n={...t,language:e};return p(n),n})},[]),G=o.useCallback(e=>{r(t=>{const n={...t,theme:e};return p(n),n})},[]),J=o.useCallback(e=>{r(t=>{const n={...t,sessionList:e(t.sessionList)};return p(n),n})},[]),Z=o.useCallback(e=>{r(t=>{const n={...t,composer:e(t.composer)};return p(n),n})},[]);return{webPreferences:s,sessionSort:a,setSessionSort:c,search:l,setSearch:d,sinceFilter:m,setSinceFilter:f,hideArchived:g,setHideArchived:y,groupFolders:v,setGroupFolders:b,showNeedsAttentionGroup:x,setShowNeedsAttentionGroup:w,showRunningGroup:S,setShowRunningGroup:k,separatePinnedGroup:I,setSeparatePinnedGroup:C,collapsedFolders:R,setCollapsedFolders:M,sessionAgentFilter:E,setSessionAgentFilter:T,directoryTags:_,archiveSyncedDaemonIds:B,archiveSyncCardDismissedDaemonIds:H,composerPreferences:W,savedTargets:N,setSavedTargets:A,leftSidebarCollapsed:P,setLeftSidebarCollapsed:D,rightSidebarCollapsed:F,setRightSidebarCollapsed:L,workspaceClassName:U.workspaceClassName,wideMainClassName:U.wideMainClassName,workspaceStyle:U.style,beginPaneResize:$,applyBrowserDefaultWidth:z,commitSearch:K,saveTargets:Q,setLanguagePreference:V,setThemePreference:G,updateSessionListPreferences:J,updateComposerPreferences:Z}}(l.current,h.current,Z),bt=s(Ne.language),xt=u[bt],[wt,St]=vi(Z,!1),[kt,It]=vi(Z,"files"),[Ct,jt]=o.useState(!1);!function(e){o.useEffect(()=>{const t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>R(e,document.documentElement,t.matches);if(n(),"system"===e)return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[e])}(Ne.theme);const Rt=o.useCallback(e=>{It(e),De(!1)},[It,De]),[Mt,Et]=o.useState({}),[Tt,Nt]=o.useState({}),[At,Pt]=o.useState([]),[Dt,Ft]=o.useState({statusText:"",loading:!1,action:null}),[Lt,qt]=o.useState(Lc),[Ot,$t]=o.useState(c.current),[zt,_t]=o.useState(a.current),[Bt,Ht]=o.useState(null),[Wt,Ut]=o.useState(null);return{clientRef:e,connectWithPairingRef:t,activeSessionIdRef:n,initialNotificationPermissionRef:a,initialNotificationSettingsRef:c,initialPreferencesRef:l,initialComposerDraftsRef:d,initialSavedTargetsRef:h,notificationPermissionRef:m,notificationSettingsRef:f,composerDraftsRef:g,lastHistorySessionIdRef:y,historyCacheDaemonIdRef:v,historyPrefetchingSessionIdsRef:b,pairingRef:x,notifiedEventsRef:w,reconnectTimerRef:S,connectionAttemptIdRef:k,respondingSessionsRef:I,turnNotificationCountsRef:C,intentionalDisconnectRef:M,phase:E,setPhase:T,statusText:N,setStatusText:A,errorText:P?wc(P,xt.remoteDirectConnection,xt.localConnection):null,setErrorText:D,pairing:F,setPairing:L,sessions:q,setSessions:O,pendingSessions:$,setPendingSessions:z,optimisticSessions:_,setOptimisticSessions:B,nextCursor:H,setNextCursor:W,folderCounts:U,setFolderCounts:K,inventoryVersion:Q,setInventoryVersion:V,activeSessionId:G,setActiveSessionId:J,diffSessionId:Y,setDiffSessionId:X,respondingSessions:ee,setRespondingSessions:te,pendingApprovals:ne,setPendingApprovals:se,pendingQuestions:ie,setPendingQuestions:re,questionAnswers:oe,setQuestionAnswers:ae,pendingQueues:ce,setPendingQueues:le,setLivePendingQueue:de,remapPendingQueue:ue,agent:he,setAgent:pe,cwd:me,setCwd:fe,approvalMode:ge,setApprovalMode:ye,continueSession:ve,model:be,setModel:xe,effort:we,setEffort:Se,fastMode:ke,setFastMode:Ie,renameTitle:Ce,setRenameTitle:je,composerDrafts:Re,setComposerDrafts:Me,draft:Ee,setDraft:Te,webPreferences:Ne,sessionSort:Ae,setSessionSort:Pe,search:Fe,setSearch:Le,sinceFilter:qe,setSinceFilter:Oe,hideArchived:$e,setHideArchived:ze,groupFolders:_e,setGroupFolders:Be,showNeedsAttentionGroup:He,setShowNeedsAttentionGroup:We,showRunningGroup:Ue,setShowRunningGroup:Ke,separatePinnedGroup:Qe,setSeparatePinnedGroup:Ve,collapsedFolders:Ge,setCollapsedFolders:Je,sessionAgentFilter:Ze,setSessionAgentFilter:Ye,directoryTags:Xe,archiveSyncedDaemonIds:et,archiveSyncCardDismissedDaemonIds:tt,composerPreferences:nt,savedTargets:st,setSavedTargets:it,leftSidebarCollapsed:rt,setLeftSidebarCollapsed:ot,rightSidebarCollapsed:at,setRightSidebarCollapsed:De,workspaceClassName:ct,wideMainClassName:lt,workspaceStyle:dt,beginPaneResize:ut,applyBrowserDefaultWidth:ht,commitSearch:pt,saveTargets:mt,setLanguagePreference:ft,setThemePreference:gt,updateSessionListPreferences:yt,updateComposerPreferences:vt,language:bt,t:xt,busy:wt,setBusy:St,controlTab:kt,setControlTab:It,detailsOpen:Ct,setDetailsOpen:jt,setControlTabAndOpen:Rt,modelOptions:Mt,setModelOptions:Et,usageLimits:Tt,setUsageLimits:Nt,skills:At,setSkills:Pt,admin:Dt,setAdmin:Ft,daemonMetadata:Lt,setDaemonMetadata:qt,notificationSettings:Ot,setNotificationSettings:$t,notificationPermission:zt,setNotificationPermission:_t,archiveSyncBusy:Bt,setArchiveSyncBusy:Ht,archiveSyncStatus:Wt,setArchiveSyncStatus:Ut}}(),n=function(e){return{showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup,separatePinnedGroup:e.separatePinnedGroup,toggleSessionViewGroup:async t=>{("needsAttention"===t?e.setShowNeedsAttentionGroup:"running"===t?e.setShowRunningGroup:e.setSeparatePinnedGroup)(e=>!e)}}}(e),{clientRef:r,activeSessionIdRef:a,notificationPermissionRef:c,notificationSettingsRef:l,composerDraftsRef:h,lastHistorySessionIdRef:m,historyPrefetchingSessionIdsRef:f,pairingRef:g,reconnectTimerRef:y,respondingSessionsRef:v,phase:b,setStatusText:x,setErrorText:S,pairing:k,setSessions:I,setOptimisticSessions:N,setNextCursor:A,setFolderCounts:P,setInventoryVersion:D,activeSessionId:F,setActiveSessionId:L,respondingSessions:q,setRespondingSessions:O,pendingApprovals:$,setPendingApprovals:z,pendingQuestions:_,setPendingQuestions:B,setQuestionAnswers:H,pendingQueues:W,setPendingQueues:U,agent:K,setAgent:Q,cwd:V,setCwd:G,setApprovalMode:J,composerDrafts:Z,setComposerDrafts:Y,search:X,sinceFilter:ee,hideArchived:te,sessionAgentFilter:ne,setRightSidebarCollapsed:se,t:ie,controlTab:re,setControlTab:oe,setControlTabAndOpen:ae,modelOptions:ce,setModelOptions:le,usageLimits:de,setUsageLimits:ue,setSkills:he,setDaemonMetadata:pe,notificationSettings:me,setNotificationSettings:fe,notificationPermission:ge,setNotificationPermission:ye,sessions:ve,pendingSessions:be,optimisticSessions:xe,setDraft:we,setBusy:Se}=e,{remoteFile:ke,attachments:Ie,setAttachments:Ce,uploadBusy:je,directory:Re,setDirectory:Me,newDirName:Ee,setNewDirName:Te,setRemoteFile:Ne,remoteFileConflict:Ae,uploadFiles:Pe,openRemoteFile:De,saveRemoteFile:Fe,downloadRemoteFile:Le,listDirectory:qe,listSessionDirectories:Oe,listFileTreeDirectory:$e,createDirectory:ze,createSessionDirectory:_e}=function(e){const{clientRef:t,pairing:n,cwd:s,phase:i,controlTab:r,setControlTab:a,setBusy:c,setErrorText:l,t:d,scopeKey:u="default"}=e,h=o.useRef(!1),p=o.useRef(null),m=p.current&&xi(p.current.key,u)?p.current:null,[f,g]=vi(u,()=>[]),[y,v]=o.useState(!1),b=o.useRef(new Set),[x,w]=vi(u,()=>({path:m?.directory.path||!h.current&&(Yl().folder||Yl().cwd)||s||zn,entries:[],loading:!1,loaded:!1})),[S,k]=vi(u,""),[I,C]=vi(u,()=>m?.file??null),[j,R]=vi(u,()=>new Set);p.current={key:u,file:I,directory:x};const M=e=>JSON.stringify([e.cwd,e.path,e.etag]),E=!!I&&j.has(M(I)),T=o.useRef(null),N=o.useRef(null),A=o.useRef(0),P=o.useRef(x.path);o.useEffect(()=>()=>{p.current&&xi(u,p.current.key)&&!p.current.file&&Yl().file&&(h.current=!1),A.current++,w(e=>e.loading?{...e,loading:!1}:e),N.current?.abort(),T.current&&c(!1),T.current?.abort(),T.current=null;for(const e of b.current)e.abort();b.current.clear(),v(!1)},[u]),o.useEffect(()=>{P.current!==x.path&&(A.current++,P.current=x.path)},[x.path]),o.useEffect(()=>(A.current++,w({path:!h.current&&(Yl().folder||Yl().cwd)||s||zn,entries:[],loading:!1,loaded:!1}),g([]),v(!1),C(null),R(new Set),()=>{A.current++;for(const e of b.current)e.abort();b.current.clear(),N.current?.abort(),T.current&&(T.current.abort(),T.current=null,c(!1))}),[n?.pairToken]),o.useEffect(()=>{x.path!==zn||Yl().folder||(A.current++,w(e=>({...e,entries:[],loaded:!1,loading:!1})))},[s]);const D=o.useRef(new Set);o.useEffect(()=>{I?.objectUrl&&D.current.add(I.objectUrl)},[I?.objectUrl]),o.useEffect(()=>()=>{for(const e of D.current)URL.revokeObjectURL(e);D.current.clear()},[n?.pairToken]);const F=o.useCallback(async e=>{if(!e?.length||!n)return;const t=new AbortController;b.current.add(t),v(!0),l(null);const s=Array.from(e).map(e=>({file:e,path:URL.createObjectURL(e)}));g(e=>[...e,...s.map(({file:e,path:t})=>({path:t,name:e.name,type:e.type,size:e.size,uploading:!0}))]);try{for(const{file:e,path:i}of s){const s=await sd(e,n.pairToken,t.signal,d);if(t.signal.aborted)return;g(e=>e.map(e=>e.path===i?s:e))}}catch(i){t.signal.aborted||l(i instanceof Error?i.message:String(i))}finally{const e=new Set(s.map(e=>e.path));g(t=>t.filter(t=>!e.has(t.path)));for(const t of e)URL.revokeObjectURL(t);b.current.delete(t)&&v(b.current.size>0)}},[n,l,d.uploadFailed,d.uploadPathMissing,u]),L=o.useCallback(async(e,t,s)=>{if(!n)return;N.current?.abort();const i=new AbortController;N.current=i,l(null);try{const r=/^(?:https?:\/\/|data:image\/|blob:)/i.test(e),o=await fetch(r?e:rs(e,t),{headers:r?{}:{authorization:`Bearer ${n.pairToken}`},signal:i.signal});if(!o.ok)throw new Error(await o.text().catch(()=>d.fileOpenFailed)||d.fileOpenFailed);const a=o.headers.get("content-type")??"application/octet-stream";if(r&&!a.startsWith("image/"))throw new Error(d.fileOpenFailed);const c=rl(e,a,!1),l=await o.blob(),u="html"===c||"unsupported"===c&&function(e,t){return!!t.startsWith("text/")||!!(t.includes("json")||t.includes("xml")||t.includes("javascript"))||/\.(md|txt|json|ya?ml|toml|csv|log|ts|tsx|js|jsx|css|html|xml|py|rb|go|rs|java|kt|swift|sh|zsh|bash)$/i.test(e)}(e,a)?await l.text():"unsupported"===c?function(e){const t=new Uint8Array(e);if(!t.some(e=>e<32&&![9,10,12,13].includes(e)||127===e))try{return new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(t)}catch{return}}(await l.arrayBuffer()):void 0;if(i.signal.aborted)return;if(void 0!==u)C({path:e,cwd:t,kind:"text",contentType:a,text:u,etag:os(o.headers,"etag"),lastModified:os(o.headers,"last-modified"),size:Number(o.headers.get("content-length"))||void 0,dirty:!1});else{const n="pdf"===rl(e,a,!1)?new Blob([l],{type:"application/pdf"}):l;C({path:e,cwd:t,kind:is(e,a)?"image":"binary",contentType:a,text:"",objectUrl:URL.createObjectURL(n),etag:os(o.headers,"etag"),lastModified:os(o.headers,"last-modified"),size:l.size,dirty:!1})}s?.updateRoute&&Xl({file:e,...t?{cwd:t}:{}},{replace:s.replaceRoute})}catch(r){if(i.signal.aborted)return;l(r instanceof Error?r.message:String(r))}},[n,l,u]),q=o.useCallback(async e=>{if(!n||!I||"text"!==I.kind||T.current)return;const t=new AbortController;T.current=t,c(!0),l(null);try{const s=await fetch(rs(I.path,I.cwd),{method:"PUT",signal:t.signal,headers:{authorization:`Bearer ${n.pairToken}`,"content-type":"text/markdown; charset=utf-8",...I.etag&&!e?.force?{"if-match":I.etag}:{}},body:I.text});if(t.signal.aborted)return;if(!s.ok){if(409===s.status)throw R(e=>new Set(e).add(M(I))),new Error(d.remoteFileConflict(I.path));throw new Error(await s.text().catch(()=>d.fileSaveFailed)||d.fileSaveFailed)}const i=await s.json().catch(()=>({}));if(t.signal.aborted)return;R(e=>{const t=new Set(e);return t.delete(M(I)),t}),C(e=>function(e,t,n){return e&&e.path===t.path&&e.cwd===t.cwd?{...e,dirty:e.text!==t.text,etag:"string"==typeof n.etag?n.etag:e.etag,lastModified:"string"==typeof n.lastModified?n.lastModified:e.lastModified,size:"number"==typeof n.size?n.size:e.size}:e}(e,I,i))}catch(s){t.signal.aborted||l(s instanceof Error?s.message:String(s))}finally{T.current===t&&(T.current=null,c(!1))}},[n,I,c,l,u]),O=o.useCallback(async()=>{if(n&&I)try{const e=/^(?:https?:\/\/|data:image\/|blob:)/i.test(I.path),t=await fetch(e?I.path:rs(I.path,I.cwd),{headers:e?{}:{authorization:`Bearer ${n.pairToken}`}});if(!t.ok)throw new Error(d.downloadFailed);const s=URL.createObjectURL(await t.blob()),i=document.createElement("a");i.href=s,i.download=Kn(I.path),i.click(),URL.revokeObjectURL(s)}catch(e){l(e instanceof Error?e.message:String(e))}},[n,I,l,u]),$=o.useCallback(async(e=x.path,n)=>{const i=t.current;if(!i?.isConnected)return;P.current=e;const r=++A.current;w(t=>({...t,path:e,entries:e===t.path?t.entries:[],loading:!0,loaded:!1,error:void 0}));try{const t=await i.request({action:"dirs.list",id:i.makeId("dirs"),path:e,cwd:s||void 0});if(r!==A.current)return;w({path:e,entries:t.entries??[],loading:!1,loaded:!0}),n?.updateRoute&&Xl({folder:e},{replace:n.replaceRoute})}catch(o){if(r!==A.current)return;w(e=>({...e,loading:!1,loaded:!0,error:o instanceof Error?o.message:String(o)}))}},[t,s,x.path,u]),z=o.useCallback(async e=>{const n=t.current;if(!n?.isConnected)throw new Error(d.webSocketNotConnected);return(await n.request({action:"dirs.list",id:n.makeId("dirs"),path:e,cwd:s||void 0},{timeoutMs:1e4,timeoutMessage:d.directoryListTimedOut})).entries??[]},[t,s,u]),_=o.useCallback(async e=>(await z(e)).filter(e=>e.isDirectory),[z]);o.useEffect(()=>{!h.current||"files"!==r||"connected"!==i||x.loading||x.loaded||$(x.path||s||zn)},[r,s,x.loaded,x.loading,x.path,$,i]),o.useEffect(()=>{if("connected"!==i||h.current)return;const e=Yl();if(e.folder||e.file){if(h.current=!0,e.folder)return a("files"),void $(e.folder,{updateRoute:!1});e.file&&(e.cwd&&w(t=>({...t,path:e.cwd,loaded:!1})),L(e.file,e.cwd,{updateRoute:!1}))}else h.current=!0},[$,L,i,a]);const B=o.useCallback(async()=>{const e=t.current;if(e?.isConnected&&0!==S.trim().length){c(!0),l(null);try{await e.request({action:"dirs.create",id:e.makeId("mkdir"),path:ns(x.path,S),cwd:s||void 0}),k(""),await $(x.path)}catch(n){l(n instanceof Error?n.message:String(n))}finally{c(!1)}}},[t,s,x.path,$,S,c,l,u]),H=o.useCallback(async e=>{const n=t.current;if(!n?.isConnected)throw new Error(d.webSocketNotConnected);await n.request({action:"dirs.create",id:n.makeId("mkdir"),path:e,cwd:s||void 0},{timeoutMs:1e4,timeoutMessage:d.directoryCreationTimedOut})},[t,s,u]);return{attachments:f,setAttachments:g,uploadBusy:y,directory:x,setDirectory:w,newDirName:S,setNewDirName:k,remoteFile:I,setRemoteFile:C,remoteFileConflict:E,uploadFiles:F,openRemoteFile:L,saveRemoteFile:q,downloadRemoteFile:O,listDirectory:$,listSessionDirectories:_,listFileTreeDirectory:z,createDirectory:B,createSessionDirectory:H}}({scopeKey:bi(k?.daemonId,F),clientRef:r,pairing:k,cwd:V,phase:b,controlTab:re,setControlTab:ae,setBusy:Se,setErrorText:S,t:ie}),Be=Object.keys($).length+Object.keys(_).length,He=function(e,t,n){return"codex"===n&&/^pending_(?:local_)?\d+(?:_\d+)?$/.test(t??"")?e.map(e=>void 0===e.waitingForStartup?{...e,waitingForStartup:!0}:e):e}(F?W[F]??[]:[],F,K),We=ce[K]??[],Ue=de[K],{completionAttention:Ke,reviewSessionIds:Qe}=function(e,t,n){const s=o.useMemo(()=>{let t;try{t=window.localStorage}catch{}return new td(t,`vibelet:completion-attention:${e??"disconnected"}`,nd)},[e]),i=o.useSyncExternalStore(s.subscribe,s.getSnapshot),r=o.useRef(new Set);return o.useEffect(()=>{r.current=new Set},[s]),o.useEffect(()=>{for(const e of t)s.reconcile(e.sessionId,Boolean(e.runtime.isResponding))},[s,t]),o.useEffect(()=>{for(const e of n)r.current.has(e)||s.observe(e);r.current=n},[s,n]),o.useEffect(()=>{if(!i.size)return;const e=window.setInterval(s.acknowledgeVisible,250);return window.addEventListener("focus",s.acknowledgeVisible),document.addEventListener("visibilitychange",s.acknowledgeVisible),()=>{window.clearInterval(e),window.removeEventListener("focus",s.acknowledgeVisible),document.removeEventListener("visibilitychange",s.acknowledgeVisible)}},[s,i]),{completionAttention:s,reviewSessionIds:i}}(k?.daemonId,ve,q),{historyCacheRef:Ve,historyPageStartRef:Ge,hydrateVisibleHistory:Je,messagesSessionIdRef:Ze,remapCachedHistory:Ye,appendCachedDelta:Xe,appendCachedHistory:et,appendInfoMessage:tt,clearHistoryLoading:nt,ensureCachedHistoryEntry:st,setCachedMessageDelivery:it,removeCachedMessage:rt,resolveCachedMessageSession:ot,historyLoading:at,hasOlderHistory:ct,olderHistoryLoading:lt,messages:dt,mergeCachedHistoryPage:ut,removeCachedHistory:ht,renderCachedHistory:pt,replaceCachedHistory:mt,requestHistory:ft,setMessages:gt}=function(e){const t=o.useRef({}),n=function(e,t){const n=o.useRef(new Map),s=o.useRef(new Set),i=o.useRef(null),r=e=>JSON.stringify([t?.current,e]),a=o.useCallback(()=>{i.current&&clearTimeout(i.current),i.current=null;for(const[e,t]of n.current)ad(e,t);n.current.clear()},[]);return o.useEffect(()=>(window.addEventListener("pagehide",a),window.addEventListener("beforeunload",a),()=>{a(),window.removeEventListener("pagehide",a),window.removeEventListener("beforeunload",a)}),[a]),{changed:s=>{const r=t?.current;r&&(n.current.set(r,{...n.current.get(r),[s]:e.current[s]}),i.current||(i.current=setTimeout(a,500)))},fresh:e=>s.current.delete(r(e)),isStale:e=>s.current.has(r(e)),restore:n=>{if(!t?.current||Object.hasOwn(e.current,n))return;const i=function(e,t){return od().find(n=>n.daemonId===e&&n.sessionId===t)?.messages}(t.current,n);return i?(e.current={...e.current,[n]:i},s.current.add(r(n)),!0):void 0}}}(t,e.historyCacheDaemonIdRef),s=o.useRef(n);s.current=n;const i=o.useRef(null),r=o.useRef({}),a=o.useRef({}),c=o.useRef(new Map),[l,d]=o.useState(null),u=o.useRef(null),[h,p]=o.useState(!1),[m,f]=o.useState([]),g=o.useCallback(e=>!(e&&i.current&&i.current!==e||(i.current=null,p(!1),0)),[]),y=o.useCallback(e=>(s.current.restore(e)&&(delete r.current[e],delete a.current[e]),!!_l(t.current,e)&&(u.current=e,f(t.current[e]??[]),!0)),[]),v=o.useCallback((n,i,r)=>{t.current=function(e,t,n){return t?{...e,[t]:Hl(e[t]??[],n)}:e}(t.current,n,i),s.current.changed(n),s.current.fresh(n);const o=t.current[n]??[];return!1!==r?.renderActive&&n===e.activeSessionIdRef.current&&(u.current=n,f(o)),o},[e.activeSessionIdRef]),b=o.useCallback((e,n,s)=>{const i=_l(t.current,e)?a.current[e]:void 0;if(a.current[e]=s,"byte"===s?.cursorMode){const o=function(e,t,n,s){if(!n||"byte"!==n.cursorMode)return[...t];if(s.start<n.start){const n=new Set(t.map(id).filter(Boolean));return[...t,...e.filter(e=>{const t=id(e);return!t||!n.has(t)})]}const i=t[0],r=i?e.findIndex(e=>i.historyKey&&e.historyKey?i.historyKey===e.historyKey:Boolean(i.timestamp)&&i.timestamp===e.timestamp&&i.role===e.role&&i.type===e.type&&i.content===e.content&&JSON.stringify(i.images)===JSON.stringify(e.images)&&i.toolName===e.toolName&&JSON.stringify(i.toolInput)===JSON.stringify(e.toolInput)):-1;return r>=0?[...e.slice(0,r),...t]:[...t]}(t.current[e]??[],n,i,s);return"byte"===i?.cursorMode&&o.length>n.length&&s.start>=i.start&&(a.current[e]={...s,start:i.start,hasMore:i.hasMore}),r.current[e]=a.current[e]?.start,v(e,o)}if(!s)return r.current[e]=void 0,v(e,n);const o=r.current[e],c=t.current[e]??[],l=s.start+n.length;if(void 0===o||l<o||s.start>o+c.length)return r.current[e]=s.start,v(e,n);r.current[e]=Math.min(o,s.start),a.current[e]={...s,start:Math.min(o,s.start),hasMore:Math.min(o,s.start)>0};const d=c.slice(0,Math.max(0,s.start-o)),u=c.slice(Math.max(0,l-o),Math.max(0,s.total-o));return v(e,[...d,...n,...u])},[v]),x=o.useCallback((e,t)=>{delete a.current[e],r.current[e]=0;const n=v(e,t,{renderActive:!1});u.current=e,f(n)},[v]),w=o.useCallback((n,i)=>{t.current=Bl(t.current,n,i),s.current.changed(n),n===e.activeSessionIdRef.current&&(u.current=n,f(t.current[n]??[]))},[e.activeSessionIdRef]),S=o.useCallback((n,i)=>{t.current=function(e,t,n){return n.historyKey&&e[t]?.some(e=>e.historyKey===n.historyKey)?e:Bl(e,t,[n])}(t.current,n,i),s.current.changed(n),n===e.activeSessionIdRef.current&&(u.current=n,f(t.current[n]??[]))},[e.activeSessionIdRef]),k=o.useCallback((e,n)=>function(e,t,n){const s=e=>e?.some(e=>e.localClientMessageId===n||e.historyKey===`client:${n}`);return s(e[t])?t:Object.entries(e).find(([,e])=>s(e))?.[0]??t}(t.current,e,n),[]),I=o.useCallback((n,i,r,o)=>{if(n=k(n,i),!o&&!t.current[n]?.some(e=>e.localClientMessageId===i||e.historyKey===`client:${i}`))return;const a=function(e,t,n,s){const i=e.findIndex(e=>e.localClientMessageId===t||e.historyKey===`client:${t}`),r=e.slice();if(i<0)s&&r.push({role:"user",...s,timestamp:(new Date).toISOString(),historyKey:`client:${t}`,localClientMessageId:t,localDelivery:n});else{const s=e[i],o="delivered"===s.localDelivery||"accepted"===s.delivery||s.historyKey&&!s.historyKey.startsWith("client:");r[i]={...s,localClientMessageId:t,localDelivery:o&&"failed"===n?"delivered":n}}return r}(t.current[n]??[],i,r,o);t.current={...t.current,[n]:a},s.current.changed(n),n!==e.activeSessionIdRef.current&&n!==u.current||(u.current=n,f(t.current[n]??[]));const c=a.find(e=>e.localClientMessageId===i)?.localDelivery;return c&&e.onDeliveryChanged?.(n,i,c),c},[e.activeSessionIdRef,e.onDeliveryChanged]),C=o.useCallback((n,i)=>{n=k(n,i);const r=t.current[n];if(!r)return;const o=r.filter(e=>"user"!==e.role||e.localClientMessageId!==i&&e.historyKey!==`client:${i}`);o.length!==r.length&&(t.current={...t.current,[n]:o},s.current.changed(n),n!==e.activeSessionIdRef.current&&n!==u.current||f(o))},[e.activeSessionIdRef,k]),j=o.useCallback((n,i)=>{t.current=function(e,t,n){return t&&n?{...e,[t]:en(Wn(e[t]??[],n))}:e}(t.current,n,i),s.current.changed(n),n===e.activeSessionIdRef.current&&(u.current=n,f(t.current[n]??[]))},[e.activeSessionIdRef]),R=o.useCallback((e,t)=>{w(e,[{role:"assistant",type:"info",content:t,timestamp:(new Date).toISOString()}])},[w]),M=o.useCallback(e=>{t.current=function(e,t){if(!_l(e,t))return e;const n={...e};return delete n[t],n}(t.current,e),s.current.changed(e),delete r.current[e],delete a.current[e]},[]),E=o.useCallback((e,n)=>{t.current=function(e,t,n){if(!t||!n||t===n||!_l(e,t))return e;const s={...e};return s[n]=e[t],delete s[t],s}(t.current,e,n),s.current.changed(e),s.current.changed(n),r.current[n]=r.current[e],delete r.current[e],a.current[n]=a.current[e],delete a.current[e]},[]),T=o.useCallback(async(t,{older:n=!1,refresh:o=!1}={})=>{const l=e.clientRef.current;if(!l?.isConnected)return;for(;c.current.get(t.sessionId)?.client===l;){if(!o)return;if(await c.current.get(t.sessionId).settled,e.clientRef.current!==l||!l.isConnected||e.activeSessionIdRef.current!==t.sessionId)return}const u=a.current[t.sessionId];if(n&&(!u?.hasMore||u.start<=0))return;let h;const m={client:l,settled:new Promise(e=>{h=e})};c.current.set(t.sessionId,m),n&&d(t.sessionId);const f=()=>e.clientRef.current===l,v=y(t.sessionId);v?g(t.sessionId):(i.current=t.sessionId,delete r.current[t.sessionId],p(!0),e.setErrorText(null));try{if(!n&&!o&&v&&!s.current.isStale(t.sessionId)){const n=await l.request({action:"reconnect.snapshot",id:l.makeId("snapshot"),activeSessionId:t.sessionId,activeAgent:t.agent,skipActiveSessionHistory:!0,skipGitMetadata:!0});if(!f())return;const s=n.snapshot.activeSession;if(s?.sessionId===t.sessionId){e.setPendingQueues(e=>({...e,[t.sessionId]:s.pendingQueue??[]}));for(const e of s.acceptedClientMessageIds??[])I(t.sessionId,e,"delivered")}return}if(await l.request({action:"session.history",id:l.makeId("history"),sessionId:t.sessionId,agent:t.agent,limit:n?100:20,...n&&"byte"!==u?.cursorMode?{before:u?.start}:{pageMode:"cursor",...n?{beforeCursor:u?.start}:{}}},{timeoutMessage:e.historyTimeoutMessage,timeoutMs:15e3}),!f())return}catch(b){f()&&e.activeSessionIdRef.current===t.sessionId&&e.setErrorText(b instanceof Error?b.message:String(b))}finally{c.current.get(t.sessionId)===m&&c.current.delete(t.sessionId),h(),f()&&(n&&d(e=>e===t.sessionId?null:e),g(t.sessionId))}},[g,e.activeSessionIdRef,e.clientRef,e.historyTimeoutMessage,e.setErrorText,e.setPendingQueues,y,I]);return{hasOlderHistory:Boolean(a.current[e.activeSessionIdRef.current??""]?.hasMore),olderHistoryLoading:l===e.activeSessionIdRef.current&&null!==l,resolveCachedMessageSession:k,setCachedMessageDelivery:I,removeCachedMessage:C,appendCachedDelta:j,appendCachedHistory:w,appendInfoMessage:R,clearHistoryLoading:g,ensureCachedHistoryEntry:S,historyCacheRef:t,historyLoading:h,historyPageStartRef:r,hydrateVisibleHistory:x,messages:m,messagesSessionIdRef:u,mergeCachedHistoryPage:b,remapCachedHistory:E,removeCachedHistory:M,renderCachedHistory:y,replaceCachedHistory:v,requestHistory:T,setMessages:f}}({onDeliveryChanged:Ke.deliveryChanged,historyCacheDaemonIdRef:e.historyCacheDaemonIdRef,activeSessionIdRef:a,clientRef:r,historyTimeoutMessage:ie.historyRequestTimedOut,setPendingQueues:U,setErrorText:S}),yt=o.useMemo(()=>new Set(Object.entries(Ve.current).filter(([,e])=>e?.some(e=>"failed"===e.localDelivery)).map(([e])=>e)),[Ve.current]),{activeSession:vt,activeApproval:bt,activeQuestion:xt,displaySessions:wt,groupedSessions:St,pendingSessionIds:kt,visibleSessions:It}=function(e){const t=o.useRef({protectedSessionIds:[]}),n=o.useMemo(()=>Zn(Zn(e.sessions,Object.values(e.optimisticSessions)),Object.values(e.pendingSessions)),[e.optimisticSessions,e.pendingSessions,e.sessions]),s=o.useMemo(()=>new Set(Object.keys(e.pendingSessions)),[e.pendingSessions]),i=o.useMemo(()=>n.find(t=>t.sessionId===e.activeSessionId)??null,[e.activeSessionId,n]),r=(e.activeSessionId?e.pendingApprovals[e.activeSessionId]:null)??Object.values(e.pendingApprovals)[0]??null,a=(e.activeSessionId?e.pendingQuestions[e.activeSessionId]:null)??Object.values(e.pendingQuestions)[0]??null,c=o.useMemo(()=>w(function(e,t){return e.filter(e=>(!t.hideArchived||!e.archived)&&("all"===t.agentFilter||e.agent===t.agentFilter)&&function(e,t){const n=t.trim().toLowerCase();return!n||[d(e),e.cwd,e.agent,e.branch??"",...e.titleAliases??[]].some(e=>e.toLowerCase().includes(n))}(e,t.search))}(n,{search:e.search,hideArchived:e.hideArchived,agentFilter:e.sessionAgentFilter}),e.sessionSort??"updated",!1),[n,e.hideArchived,e.search,e.sessionAgentFilter,e.sessionSort]),l=o.useMemo(()=>new Set([...Object.keys(e.pendingApprovals),...Object.keys(e.pendingQuestions),...e.reviewSessionIds??[],...e.failedSessionIds??[]]),[e.pendingApprovals,e.pendingQuestions,e.reviewSessionIds,e.failedSessionIds]),u=o.useMemo(()=>{if(e.search.trim()||"updated"!==(e.sessionSort??"updated"))return c;const n=function(e,t,n){if(0===e.length)return 0===n.protectedSessionIds.length?{sessions:e,state:n}:{sessions:e,state:{protectedSessionIds:[]}};const s=new Map,i=[];for(const l of e)s.set(l.sessionId,l),(t[l.sessionId]||l.runtime.isResponding)&&i.push(l.sessionId);if(0===i.length)return 0===n.protectedSessionIds.length?{sessions:e,state:n}:{sessions:e,state:{protectedSessionIds:[]}};const r=new Set(i),o=n.protectedSessionIds.filter(e=>s.has(e)&&r.has(e)),a=new Set(o);let c=o.length!==n.protectedSessionIds.length;for(const l of i)a.has(l)||(a.add(l),o.push(l),c=!0);return{sessions:on(e,o,s),state:c?{protectedSessionIds:o}:n}}(c,Object.fromEntries([...e.respondingSessionIds].map(e=>[e,!0])),t.current);return t.current=n.state,n.sessions},[c,e.respondingSessionIds,e.search,e.sessionSort]),h=o.useMemo(()=>Object.fromEntries(u.map((e,t)=>[e.sessionId,t])),[u]),p=o.useMemo(()=>[...w(u.filter(e=>e.pinned&&!e.archived),"updated"),...u.filter(e=>!e.pinned||e.archived)],[u]),m=o.useMemo(()=>C(function(e,t={}){const n=e=>Object.fromEntries(Array.from(e??[],e=>[e,!0])),s=function(e,t,n,s={}){const i=new Map,r=[],o=[],a=[];for(const l of e){const e=l.cwd||"/",n=!0!==l.archived;if(Boolean(s.showNeedsAttentionGroup&&n&&(s.needsAttentionSessionIds?.[l.sessionId]||l.interruptReason||l.runtime.needsAttention&&!l.stallWarning))?o.push(l):s.showRunningGroup&&n&&(t?.[l.sessionId]||l.runtime.isResponding)&&a.push(l),s.separatePinnedGroup&&nn(l,s.pinnedSessionIds,s.pendingPinnedSessionIds)&&n){r.push(l);continue}const c=i.get(e);c?c.push(l):i.set(e,[l])}const c=[];o.length&&c.push({folder:"@vibelet/needs-attention",kind:"attention",sessions:sn(o,s.regularSessionOrderById)}),a.length&&c.push({folder:"@vibelet/running",kind:"running",sessions:sn(a,s.regularSessionOrderById)}),r.length&&c.push({folder:"@vibelet/pinned",kind:"pinned",sessions:s.orderPinnedByLastActivity?rn(r):sn(r,s.regularSessionOrderById)});for(const[l,d]of i)c.push({folder:l,kind:"folder",sessions:d});return c}(e,n(t.respondingSessionIds),0,{...t,needsAttentionSessionIds:n(t.needsAttentionSessionIds),orderPinnedByLastActivity:!0}),i=new Map(t.runningSessionOrder?.map((e,t)=>[e,t]));if(i.size){const e=s.find(e=>"running"===e.kind);e?.sessions.sort((e,t)=>(i.get(e.sessionId)??1/0)-(i.get(t.sessionId)??1/0))}return s}(p,{needsAttentionSessionIds:l,regularSessionOrderById:h,respondingSessionIds:e.respondingSessionIds,separatePinnedGroup:e.separatePinnedGroup,showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup}),e.sessionSort??"updated"),[l,h,e.respondingSessionIds,e.separatePinnedGroup,e.showNeedsAttentionGroup,e.showRunningGroup,e.sessionSort,p]);return{activeApproval:r,activeQuestion:a,activeSession:i,displaySessions:n,groupedSessions:m,pendingSessionIds:s,visibleSessions:p}}({activeSessionId:F,reviewSessionIds:Qe,failedSessionIds:yt,hideArchived:te,optimisticSessions:xe,pendingApprovals:$,pendingQuestions:_,pendingSessions:be,respondingSessionIds:q,search:X,separatePinnedGroup:n.separatePinnedGroup,sessionAgentFilter:ne,sessionSort:e.sessionSort,sessions:ve,showNeedsAttentionGroup:n.showNeedsAttentionGroup,showRunningGroup:n.showRunningGroup});ed(a,F),ed(g,k),ed(v,q),ed(l,me),ed(c,ge),ed(h,Z);const{updateNewSessionDraft:Ct,updateDraft:jt}=function({activeSessionIdRef:e,composerDraftsRef:t,setComposerDrafts:n,setDraft:s}){const i=o.useRef(null),r=o.useRef(null),a=o.useRef(!1),c=o.useCallback(()=>{if(i.current&&clearTimeout(i.current),r.current&&clearTimeout(r.current),i.current=r.current=null,a.current){a.current=!1;try{Fl(t.current)}catch{}}},[t]),l=o.useCallback(()=>{a.current=!0,i.current&&clearTimeout(i.current),i.current=setTimeout(c,300),r.current||(r.current=setTimeout(c,2e3))},[c]);return o.useEffect(()=>{const e=()=>{"hidden"===document.visibilityState&&c()};return window.addEventListener("pagehide",c),window.addEventListener("beforeunload",c),document.addEventListener("visibilitychange",e),()=>{c(),window.removeEventListener("pagehide",c),window.removeEventListener("beforeunload",c),document.removeEventListener("visibilitychange",e)}},[c]),{updateDraft:o.useCallback(i=>{const r=Ll(t.current,e.current,i);t.current=r,n(r),s(i),l()},[e,t,n,s,l]),updateNewSessionDraft:o.useCallback(i=>{const r=Ll(t.current,null,i);t.current=r,n(r),e.current||s(i),l()},[e,t,n,s,l])}}({activeSessionIdRef:a,composerDraftsRef:h,setComposerDrafts:Y,setDraft:we});o.useEffect(()=>{M();const e=E();e&&(Ct(e),oe("session"),T())},[Ct]),o.useEffect(()=>{const e=()=>{fe(Kt()),ye(Qt())};return window.addEventListener("vibelet.notifications.changed",e),()=>window.removeEventListener("vibelet.notifications.changed",e)},[]),o.useEffect(()=>{"admin"===re&&ye(Qt())},[re]),o.useEffect(()=>()=>{y.current&&window.clearTimeout(y.current)},[]);const Rt=o.useCallback((e,n=!1)=>{I(t=>function(e,t,n=!1){const s=new Set(t.map(e=>e.sessionId));return Zn(n?e:e.filter(e=>s.has(e.sessionId)),t)}(t,e.sessions,n)),N(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}),A(e.nextCursor),D(e.inventoryVersion),e.folderCounts&&P(e.folderCounts),n||function(e,n,s=t(),i=(new Date).toISOString()){if(!e)return;const r={daemonId:e,page:{...n,sessions:n.sessions.slice(0,120)},cachedAt:i};s.setItem(Ml,JSON.stringify(r))}(g.current?.daemonId,e),x(e.inventoryBackfillInFlight?ie.connectedIndexing:ie.connected)},[ie.connected,ie.connectedIndexing]),Mt=function({clientRef:e,sessions:t,setSessions:n,activeSessionIdRef:s}){const i=o.useRef(new Map),r=o.useRef(t);r.current=t,o.useEffect(()=>()=>i.current.clear(),[]);const a=o.useCallback(async t=>{const r=e.current;if(!r?.isConnected)return;const o=t.find(e=>e.sessionId===s?.current),a=o?[o,...t]:t,c=[...new Set(a.map(e=>e.cwd).filter(Boolean))];if(0===c.length)return;const l={};for(const e of c)i.current.set(e,l);try{const t=await r.request({action:"sessions.gitMetadata",id:r.makeId("git"),cwds:c});if(e.current!==r||!r.isConnected)return;n(n=>n.map(n=>{if(e.current!==r||!r.isConnected||i.current.get(n.cwd)!==l)return n;const s=Object.hasOwn(t.branches,n.cwd),o=s?t.branches[n.cwd]??void 0:n.branch,a=s&&o!==n.branch,c=t.gitLinksCwds?.includes(n.cwd)??s;return{...n,pullRequest:c?t.pullRequests?.[n.cwd]:a?void 0:n.pullRequest,branchUrl:t.branchUrls?.[n.cwd]??(c||a?void 0:n.branchUrl),branch:o,diffStat:Object.hasOwn(t.diffStats,n.cwd)?t.diffStats[n.cwd]??void 0:n.diffStat}}))}catch{}},[e,n,s]);return o.useEffect(()=>{let e=!1;const t=()=>{"hidden"===document.visibilityState||e||(e=!0,a(r.current).finally(()=>{e=!1}))},n=window.setInterval(t,15e3);return window.addEventListener("focus",t),document.addEventListener("visibilitychange",t),()=>{window.clearInterval(n),window.removeEventListener("focus",t),document.removeEventListener("visibilitychange",t)}},[a]),a}({clientRef:r,sessions:ve,setSessions:I,activeSessionIdRef:a}),Et=o.useCallback((e,t=v.current)=>{const n=r.current;if(!n?.isConnected||0===e.length)return;const s=function(e,t,n,s,i=6){if(i<=0)return[];const r=[];for(const o of e){if(r.length>=i)break;o.sessionId&&dd(o,n)&&(_l(t,o.sessionId)||s.has(o.sessionId)||r.push(o))}return r}(e,Ve.current,t,f.current);for(const i of s)f.current.add(i.sessionId),n.request({action:"session.history",id:n.makeId("history_prefetch"),pageMode:"cursor",limit:20,sessionId:i.sessionId,agent:i.agent},{timeoutMessage:ie.historyPrefetchTimedOut,timeoutMs:15e3}).catch(()=>{}).finally(()=>{f.current.delete(i.sessionId)})},[ie.historyPrefetchTimedOut]),Tt=o.useCallback(e=>{const t=function(e,t={}){const n=new Set,s={},i={},r={};for(const p of e.sessions)p.runtime.isResponding&&n.add(p.sessionId);for(const p of e.pendingApprovals??[])s[p.sessionId]={type:"approval.request",...p};for(const p of e.pendingQuestions??[])i[p.sessionId]={type:"question.request",...p};let o,a,c,l,d,u,h=null;if(e.activeSession){const p=e.activeSession,m=e.sessions.find(e=>e.sessionId===p.sessionId);if(h=p.sessionId,o=p.agent,a=m?.cwd||t.currentCwd||zn,c=p.approvalMode??m?.approvalMode??_n,l=p.approvalMode??null,d=tn(p.messages??[],p.partialReplyText),(p.isResponding||p.externallyResponding)&&n.add(p.sessionId),p.pendingApproval&&(s[p.sessionId]={type:"approval.request",sessionId:p.sessionId,...p.pendingApproval}),p.pendingQuestion){const e={type:"question.request",sessionId:p.sessionId,...p.pendingQuestion};i[p.sessionId]=e,u=Vn(e)}p.pendingQueue?.length&&(r[p.sessionId]=p.pendingQueue)}else{const n=t.currentActiveSessionId??null;if(n){const t=e.sessionAliases?.[n];t?h=t:e.sessions.some(e=>e.sessionId===n)&&(h=n)}h=h??e.sessions[0]?.sessionId??null;const s=e.sessions.find(e=>e.sessionId===h);s&&(o=s.agent,a=s.cwd||zn,c=s.approvalMode??_n)}return{page:{sessions:e.sessions,nextCursor:$n(e.nextCursor),inventoryVersion:e.inventoryVersion,inventoryBackfillInFlight:e.inventoryBackfillInFlight},activeSessionId:h,activeAgent:o,activeCwd:a,activeApprovalMode:c,activeApprovalOverride:l,messages:d,respondingSessionIds:Array.from(n),pendingApprovals:s,pendingQuestions:i,pendingQueues:r,questionAnswers:u}}(e,{currentActiveSessionId:a.current,currentCwd:V});Rt(t.page,!1),A(t.page.nextCursor),D(t.page.inventoryVersion),void 0!==e.activeSession?.messages&&t.messages&&t.activeSessionId&&Je(t.activeSessionId,t.messages);for(const n of e.activeSession?.acceptedClientMessageIds??[])it(e.activeSession.sessionId,n,"delivered");e.activeSession&&void 0===e.activeSession.messages&&ft(e.activeSession,{refresh:!0}),L(t.activeSessionId),t.activeAgent&&Q(t.activeAgent),t.activeCwd&&G(t.activeCwd),t.activeApprovalMode&&J(t.activeApprovalMode),t.questionAnswers&&H(t.questionAnswers),v.current=new Set(t.respondingSessionIds),O(v.current),z(t.pendingApprovals),B(t.pendingQuestions),U(t.pendingQueues),Mt(e.sessions),Et(e.sessions,new Set(t.respondingSessionIds))},[V,Mt,Je,Et,ft,Rt,it]),Nt=function(e){const{clientRef:t,activeSessionIdRef:n,search:s,sinceFilter:i,hideArchived:r,sessionAgentFilter:a}=e,c=o.useMemo(()=>({}),[s,i,r,a,n.current]),l=o.useRef({scope:c,options:e,request:0});return l.current.scope=c,l.current.options=e,o.useEffect(()=>()=>{l.current.request++},[]),o.useCallback(async()=>{const e=t.current;if(!e?.isConnected)return;const s=++l.current.request,i=()=>t.current===e&&e.isConnected&&l.current.request===s;for(;i();){const t=l.current,s=t.scope,o=t.options,a=n.current,c=()=>l.current.scope===s&&n.current===a;try{const t=await e.request({action:"reconnect.snapshot",id:e.makeId("snapshot"),activeSessionId:a??void 0,activeAgent:o.activeAgent,agent:"all"===o.sessionAgentFilter?void 0:o.sessionAgentFilter,search:o.search.trim()||void 0,sinceMs:Jn(o.sinceFilter),hideArchived:o.hideArchived,skipGitMetadata:!0,skipActiveSessionHistory:!0});if(!i())return;if(!c())continue;return void l.current.options.apply(t.snapshot)}catch(r){if(!i())return;if(c())throw r}}},[t,n])}({clientRef:r,activeSessionIdRef:a,activeAgent:vt?.agent??K,sessionAgentFilter:ne,search:X,sinceFilter:ee,hideArchived:te,apply:Tt}),At=function(e){const{clientRef:t,search:n,sinceFilter:s,hideArchived:i,sessionAgentFilter:r,viewKey:a}=e,c=o.useMemo(()=>({refresh:0}),[n,s,i,r,a]),l=o.useRef({options:e,scope:c});l.current={options:e,scope:c};const d=o.useRef(c);o.useLayoutEffect(()=>{d.current!==c&&(d.current=c,e.setNextCursor(void 0))},[e.setNextCursor,c]);const u=o.useRef(!0);return o.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]),o.useCallback(async e=>{const o=t.current;if(!u.current||!o?.isConnected||l.current.scope!==c)return;const a=e?.append?c.refresh:++c.refresh,d=()=>u.current&&t.current===o&&o.isConnected&&l.current.scope===c&&(e?.append||a===c.refresh);try{const t=await o.request({action:"sessions.list",id:o.makeId(e?.append?"sessions_more":"sessions"),limit:e?.preserveLoaded?Math.max(80,l.current.options.loadedCount):80,cursor:e?.cursor,agent:"all"===r?void 0:r,search:n.trim()||void 0,sinceMs:Jn(s),hideArchived:i,skipGitMetadata:!0,force:e?.force});if(!d())return;const a=Un(t),c=l.current.options;c.setSessionsFromPage(a,e?.append),c.setActiveSessionId(e=>e??a.sessions[0]?.sessionId??null),c.hydrateGitMetadata(a.sessions),c.prefetchActiveHistories(a.sessions)}catch(h){if(d())throw h}},[t,c,n,s,i,r])}({clientRef:r,search:X,sinceFilter:ee,hideArchived:te,sessionAgentFilter:ne,viewKey:[e.sessionSort,e.groupFolders,n.showNeedsAttentionGroup,n.showRunningGroup,n.separatePinnedGroup].join(":"),loadedCount:ve.length,setNextCursor:A,setSessionsFromPage:Rt,setActiveSessionId:L,hydrateGitMetadata:Mt,prefetchActiveHistories:Et}),Pt=function({clientRef:e,setModelOptions:t,setUsageLimits:n,setSkills:s,setErrorText:i,t:r}){const a=o.useRef(0),c=o.useRef(null);return o.useEffect(()=>()=>{a.current++},[]),o.useCallback((o,l)=>{const d=e.current;if(!d?.isConnected)return Promise.resolve();if(c.current?.client===d&&c.current.agent===o&&c.current.cwd===l)return c.current.promise;const u=++a.current,h=()=>a.current===u&&e.current===d&&d.isConnected,p="codex"===o?"Codex":"Claude",m=[],f=Promise.allSettled([d.request({action:"models.list",id:d.makeId("models"),agent:o},{timeoutMs:zl}).then(e=>{h()&&t(t=>({...t,[o]:e.options??[]}))}).catch((e=>t=>{if(!h())return;const n=t instanceof Error?t.message:String(t);m.push(/timeout|timed out/i.test(n)?r.resourceLoadTimedOut(e):r.resourceLoadFailed(e,n)),i(m.join("\n"))})(`${p} · ${r.model}`)),Qc(d,()=>({action:"usage.limits.fetch",id:d.makeId("usage"),agent:o}),h).then(e=>{e&&h()&&n(t=>({...t,[o]:e}))}),Qc(d,()=>({action:"skills.list",id:d.makeId("skills"),cwd:l||void 0}),h).then(e=>{e&&h()&&s(Array.isArray(e.skills)?e.skills:[])})]).then(()=>{a.current===u&&(c.current=null)});return c.current={client:d,agent:o,cwd:l,promise:f},f},[e,t,n,s,i,r])}({t:ie,clientRef:r,setModelOptions:le,setUsageLimits:ue,setSkills:he,setErrorText:S}),Dt=o.useCallback((e,t,n="info")=>{const s=r.current;s?.isConnected&&s.request({action:"log.report",id:s.makeId("log"),entries:[{level:n,event:e,data:t,ts:(new Date).toISOString()}]}).catch(()=>{})},[]);!function(e){o.useEffect(()=>{const t=performance.now(),n=(t,n,s="info")=>e(t,function(e){const t={};for(const[n,s]of Object.entries(e))cd.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:ld(e.error)},"error")},i=e=>{n("web.telemetry.unhandled_rejection",{errorKind:ld(e.reason)},"error")},r=window.setTimeout(()=>{n("web.telemetry.workspace_ready",{durationMs:performance.now()-t,domNodes:document.getElementsByTagName("*").length,online:navigator.onLine,visibilityState:document.visibilityState})},1500);let o=0,a=0,c=null;return"undefined"!=typeof PerformanceObserver&&PerformanceObserver.supportedEntryTypes.includes("longtask")&&(c=new PerformanceObserver(e=>{for(const t of e.getEntries())o+=1,a=Math.max(a,t.duration)}),c.observe({entryTypes:["longtask"]})),window.addEventListener("error",s),window.addEventListener("unhandledrejection",i),()=>{window.clearTimeout(r),window.removeEventListener("error",s),window.removeEventListener("unhandledrejection",i),c?.disconnect(),o>0&&n("web.telemetry.long_tasks",{longTaskCount:o,maxLongTaskMs:a},"warn")}},[e])}(Dt);const Ft=o.useCallback(async(e=g.current)=>{if(e){pe(e=>({...e,loading:!0,error:null}));try{const t=await fetch(function(e,t){const n=e?.webSocketUrl?e.webSocketUrl:t.origin;try{const e=new URL(n);return"ws:"===e.protocol&&(e.protocol="http:"),"wss:"===e.protocol&&(e.protocol="https:"),e.pathname="/health",e.search="",e.hash="",e.toString()}catch{return new URL("/health",t.origin).toString()}}(e,window.location),{cache:"no-store"});if(!t.ok)throw new Error(`HTTP ${t.status}`);const n=function(e){if(!e||"object"!=typeof e)return{version:"",latestVersion:""};const t=e;return{version:"string"==typeof t.version?t.version.trim():"",latestVersion:"string"==typeof t.latestVersion?t.latestVersion.trim():""}}(await t.json().catch(()=>null));pe({...n,loading:!1,error:null})}catch{pe(e=>({...e,loading:!1,error:ie.connectorVersionFailed}))}}else pe(Lc)},[ie.connectorVersionFailed]);o.useEffect(()=>{const e=()=>{fe(Kt()),ye(Qt())};return window.addEventListener("vibelet.notifications.changed",e),()=>window.removeEventListener("vibelet.notifications.changed",e)},[]),o.useEffect(()=>{"admin"===re&&"connected"===b&&Ft()},[re,b,Ft]);const Lt=o.useCallback(e=>{fe(n=>{const s={...n,...e};return l.current=s,function(e,n=t()){n.setItem(Wt,JSON.stringify(e))}(s),s})},[]),qt=o.useCallback((t,n)=>{t&&n&&t!==n&&(L(e=>e===t?n:e),m.current===t&&(m.current=n),Ze.current===t&&(Ze.current=n),Ke.remap(t,n),Ye(t,n),v.current=ts(v.current,t,n),O(e=>ts(e,t,n)),z(e=>es(e,t,n)),B(e=>es(e,t,n)),e.remapPendingQueue(t,n),U(e=>es(e,t,n)),N(e=>{const s=e[t];if(!s)return e;const i={...e};return delete i[t],i[n]={...s,sessionId:n},i}),Y(e=>{const s=function(e,t,n){if(!t||!n||t===n)return e;const s=e.draftsBySessionId[t];if(void 0===s)return e;const i={...e.draftsBySessionId};return delete i[t],s.trim()&&(i[n]=s),{...e,draftsBySessionId:i}}(e,t,n);return s!==e&&(h.current=s,Fl(s)),s}))},[Ke]);return{completionAttention:Ke,...e,...n,attachments:Ie,setAttachments:Ce,uploadBusy:je,directory:Re,setDirectory:Me,newDirName:Ee,setNewDirName:Te,remoteFile:ke,setRemoteFile:Ne,remoteFileConflict:Ae,uploadFiles:Pe,openRemoteFile:De,saveRemoteFile:Fe,downloadRemoteFile:Le,listDirectory:qe,listSessionDirectories:Oe,listFileTreeDirectory:$e,createDirectory:ze,createSessionDirectory:_e,pendingActionsCount:Be,activeQueue:He,activeModelOptions:We,activeUsage:Ue,activeApproval:bt,activeQuestion:xt,activeSession:vt,displaySessions:wt,groupedSessions:St,pendingSessionIds:kt,visibleSessions:It,appendCachedDelta:Xe,appendCachedHistory:et,appendInfoMessage:tt,clearHistoryLoading:nt,ensureCachedHistoryEntry:st,setCachedMessageDelivery:it,removeCachedMessage:rt,resolveCachedMessageSession:ot,historyCacheRef:Ve,historyLoading:at,hasOlderHistory:ct,olderHistoryLoading:lt,historyPageStartRef:Ge,hydrateVisibleHistory:Je,messages:dt,messagesSessionIdRef:Ze,mergeCachedHistoryPage:ut,remapCachedHistory:Ye,removeCachedHistory:ht,renderCachedHistory:pt,replaceCachedHistory:mt,requestHistory:ft,setMessages:gt,updateDraft:jt,updateNewSessionDraft:Ct,setSessionsFromPage:Rt,hydrateGitMetadata:Mt,prefetchActiveHistories:Et,applyReconnectSnapshot:Tt,requestReconnectSnapshot:Nt,requestSessions:At,fetchAgentResources:Pt,reportLog:Dt,refreshDaemonMetadata:Ft,updateNotificationSettings:Lt,remapLocalSessionState:qt}}();!function(e){const t=o.useRef({daemonId:"",pending:!0,initial:!0});o.useLayoutEffect(()=>{const s=e.pairing?.daemonId;if("desktop"!==n().kind||"connected"!==e.phase||!s)return;if(t.current.daemonId!==s&&(t.current={daemonId:s,pending:!0,initial:!t.current.daemonId}),!t.current.pending)return;const i=w(e.visibleSessions,"updated",!1)[0];i&&(t.current.initial&&e.activeSessionId||e.setActiveSessionId(i.sessionId),t.current.pending=!1)},[e.pairing?.daemonId,e.phase,e.activeSessionId,e.visibleSessions])}(e);const r=o.useRef(void 0),a=o.useRef(new Set),c=function(e){const t=o.useRef(!1);return async n=>{const s=e.activeSession,i=e.clientRef.current;if(!s||!i?.isConnected||t.current||e.busy)return;const r=yi(),o=e.historyCacheRef.current[s.sessionId]??[],a=function(e,t){const n=e.indexOf(t);if(n>=0)return n;const s=t.historyKey;if(s)return e.findIndex(e=>e.historyKey===s);const i=t.rewindPoint;if(i)return e.findIndex(e=>JSON.stringify(e.rewindPoint)===JSON.stringify(i));const r=e.flatMap((e,n)=>e.role===t.role&&e.type===t.type&&e.content===t.content&&e.timestamp===t.timestamp&&JSON.stringify(e.images)===JSON.stringify(t.images)?[n]:[]);return 1===r.length?r[0]:-1}(o,n);if(a<0||"user"!==n.role||"info"===n.type)return void e.setErrorText(r.unavailable);if((e.historyPageStartRef.current[s.sessionId]??0)>0)return void e.setErrorText(r.incompleteHistory);t.current=!0;let c=!1;try{c=await x({message:r.confirmRewind})}finally{t.current=!1}if(c&&e.clientRef.current===i&&i.isConnected&&e.activeSessionIdRef.current===s.sessionId){t.current=!0,e.setBusy(!0),e.setErrorText(null);try{const t=await i.request({action:"session.rewind",id:i.makeId("rewind"),sessionId:s.sessionId,agent:s.agent,targetUserMessageIndex:o.slice(0,a+1).filter(e=>"user"===e.role&&"info"!==e.type).length-1,featureEntitlements:await Ul("sessionRewind")},{timeoutMs:15e4,timeoutMessage:r.rewindFailed});if(!t||"string"!=typeof t.sessionId||!t.sessionId||t.sessionId===s.sessionId||t.sourceSessionId!==s.sessionId||!0!==t.archivedSource||!Array.isArray(t.messages)||t.messages.some(e=>!e||"string"!=typeof e.content||!["user","assistant","tool"].includes(e.role)))throw new Error(r.invalidResponse);const c={...s,sessionId:t.sessionId,archived:!1};e.setOptimisticSessions(e=>{const n={...e};return delete n[s.sessionId],n[t.sessionId]=c,n}),e.setSessions(e=>[...e.filter(e=>e.sessionId!==t.sessionId).map(e=>e.sessionId===s.sessionId?{...e,archived:!0,pinned:!1}:e),c]),e.replaceCachedHistory(t.sessionId,t.messages),e.lastHistorySessionIdRef.current=t.sessionId,e.activeSessionIdRef.current=t.sessionId,e.setActiveSessionId(t.sessionId),e.renderCachedHistory(t.sessionId),e.updateDraft(n.content),e.setAttachments((n.images??[]).map(e=>({path:e,name:e.split("/").pop()??e,type:"application/octet-stream",size:0}))),await e.requestSessions({force:!0}).catch(()=>{})}catch(l){e.setErrorText(l instanceof Error?l.message:r.rewindFailed)}finally{t.current=!1,e.setBusy(!1)}}}}(e),{initialSavedTargetsRef:l,composerDraftsRef:h,lastHistorySessionIdRef:m,respondingSessionsRef:f,phase:g,setErrorText:y,pairing:v,setSessions:N,pendingSessions:A,activeSessionId:P,setActiveSessionId:D,setRespondingSessions:F,setPendingApprovals:L,setPendingQuestions:q,setPendingQueues:O,setLivePendingQueue:$,agent:z,setAgent:_,cwd:B,setCwd:H,setApprovalMode:W,setModel:U,setEffort:K,setFastMode:Q,setRenameTitle:V,setDraft:G,archiveSyncedDaemonIds:J,archiveSyncCardDismissedDaemonIds:Z,setControlTabAndOpen:Y,daemonMetadata:X,notificationPermission:ee,setDirectory:te,displaySessions:ne,appendInfoMessage:se,clearHistoryLoading:ie,messagesSessionIdRef:re,renderCachedHistory:oe,replaceCachedHistory:ae,requestHistory:ce,setMessages:le,requestSessions:de,remapLocalSessionState:ue,attachments:he,setAttachments:pe,listDirectory:me,activeApproval:fe,activeQuestion:ge,activeSession:ye,appendCachedDelta:ve,appendCachedHistory:be,ensureCachedHistoryEntry:xe,setCachedMessageDelivery:we,resolveCachedMessageSession:Se,historyCacheRef:ke,messages:Ie,mergeCachedHistoryPage:Ce,removeCachedHistory:je,updateDraft:Re,setSessionsFromPage:Me,requestReconnectSnapshot:Ee,fetchAgentResources:Te,reportLog:Ne,refreshDaemonMetadata:Ae,updateNotificationSettings:Pe,clientRef:De,connectWithPairingRef:Fe,activeSessionIdRef:Le,notificationPermissionRef:qe,notificationSettingsRef:Oe,historyCacheDaemonIdRef:$e,pairingRef:ze,notifiedEventsRef:_e,reconnectTimerRef:Be,connectionAttemptIdRef:He,turnNotificationCountsRef:We,intentionalDisconnectRef:Ue,setPhase:Ke,setStatusText:Qe,setPairing:Ve,setPendingSessions:Ge,setOptimisticSessions:Je,questionAnswers:Ze,setQuestionAnswers:Ye,approvalMode:Xe,continueSession:et,model:tt,effort:nt,fastMode:st,renameTitle:it,setComposerDrafts:rt,draft:ot,search:at,sinceFilter:ct,savedTargets:lt,setSavedTargets:dt,saveTargets:ut,updateSessionListPreferences:ht,t:pt,busy:mt,setBusy:ft,setDetailsOpen:gt,setAdmin:yt,setDaemonMetadata:vt,setNotificationPermission:bt,archiveSyncBusy:St,setArchiveSyncBusy:kt,setArchiveSyncStatus:It}=e,jt=o.useCallback(async(e,t,n)=>{const s="string"==typeof n.sessionId?n.sessionId:e,i="string"==typeof n.oldSessionId?n.oldSessionId:e;i&&s&&i!==s&&ue(i,s),"clear"===t.name?(ae(s,[]),O(e=>{const t={...e};return delete t[s],delete t[i],t}),L(e=>{const t={...e};return delete t[s],delete t[i],t}),q(e=>{const t={...e};return delete t[s],delete t[i],t}),D(s)):"new"===t.name?(D(s),re.current=s,oe(s)):"exit"===t.name?(N(e=>e.map(e=>e.sessionId===s?{...e,archived:!0}:e)),D(null),re.current=null,m.current=null,le([])):"goal"===t.name&&"goal"in n&&se(s,function(e){const t="string"==typeof e?.objective?e.objective.trim():"";return t?`Goal${"string"==typeof e?.status&&e.status?` (${e.status})`:""}: ${t}`:"Goal: none."}(n.goal)),n.turnStarted&&!n.queued&&(f.current=new Set(f.current).add(s),F(e=>new Set(e).add(s))),await de({force:!0})},[se,ue,oe,ae,de]),Rt=function(e){const t=t=>{e.setSessions(e=>{const n=e.findIndex(e=>e.sessionId===t&&e.stallWarning);if(n<0)return e;const s=[...e];return s[n]={...e[n],stallWarning:void 0},s})},s=o.useCallback((t,s,i,r,o)=>{const a=e.notificationSettingsRef.current;a[r]&&!e.notifiedEventsRef.current.has(t)&&function(e,t,s={}){const i=s.notificationFactory??("undefined"==typeof Notification?void 0:Notification);if(!i&&!n().notifications)return!1;if(!function(e,t,n=("undefined"==typeof document?"visible":document.visibilityState)){return!(!e.enabled||"granted"!==t||e.hiddenOnly&&"visible"===n)}(s.settings??{enabled:!0,hiddenOnly:!1},s.permission??Qt(),s.visibilityState??("undefined"==typeof document?"visible":document.visibilityState)))return!1;if(n().notifications)return n().notifications.show(e,t,s.onClick),!0;const r=new i(e,{body:t,tag:s.tag});return s.onClick&&(r.onclick=s.onClick),!0}(s,i,{onClick:()=>{window.focus(),o&&e.setActiveSessionId(o)},permission:e.notificationPermissionRef.current,settings:a,tag:t,visibilityState:document.visibilityState})&&e.notifiedEventsRef.current.add(t)},[e]);return o.useCallback(n=>{switch(n.type){case"response":Bn(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 tn(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(Vn(t))}else delete s[n.sessionId];return s})),e.setRespondingSessions(t=>{const s=Wl(t,n.sessionId,Boolean(n.isResponding||n.externallyResponding));return e.respondingSessionsRef.current=s,s});break;case"session.history.append":e.appendCachedHistory(n.sessionId,n.messages);break;case"text.delta":e.completionAttention?.observe(n.sessionId),t(n.sessionId),e.appendCachedDelta(n.sessionId,n.content),e.respondingSessionsRef.current=Wl(e.respondingSessionsRef.current,n.sessionId,!0),e.setRespondingSessions(e=>Wl(e,n.sessionId,!0));break;case"session.background_terminals":e.setSessions(e=>e.map(e=>e.sessionId===n.sessionId?{...e,runtime:{...e.runtime,backgroundTerminals:n.terminals}}:e));break;case"tool.call":t(n.sessionId),e.appendCachedHistory(n.sessionId,[{role:"tool",type:"info",toolName:n.toolName,toolInput:n.input,content:`${e.t.toolCallLabel}: ${n.toolName}\n\n${Qn(n.input)}`,timestamp:(new Date).toISOString()}]);break;case"tool.result":t(n.sessionId),e.appendCachedHistory(n.sessionId,[{role:"tool",type:"info",content:n.output,timestamp:(new Date).toISOString()}]);break;case"approval.request":e.setPendingApprovals(e=>({...e,[n.sessionId]:n})),s(`approval:${n.sessionId}:${n.requestId}`,e.t.notificationApprovalTitle,n.description||n.toolName,"approvals",n.sessionId);break;case"question.request":e.setPendingQuestions(e=>({...e,[n.sessionId]:n})),s(`question:${n.sessionId}:${n.requestId}`,e.t.notificationQuestionTitle,e.t.notificationQuestionCount(n.questions.length),"questions",n.sessionId);break;case"question.cleared":e.setPendingQuestions(e=>{const t={...e};return t[n.sessionId]?.requestId===n.requestId&&delete t[n.sessionId],t});break;case"session.queue":e.setLivePendingQueue(n.sessionId,n.pending);break;case"session.stall_warning":e.setSessions(e=>e.map(e=>e.sessionId===n.sessionId?{...e,stallWarning:n.warning}:e));break;case"session.interrupted_notice":e.setSessions(e=>e.map(e=>e.sessionId===n.sessionId?{...e,interruptReason:n.reason,stallWarning:void 0}:e));break;case"session.done":if(e.respondingSessionsRef.current.has(n.sessionId)&&e.completionAttention?.observe(n.sessionId),e.completionAttention?.complete(n.sessionId),t(n.sessionId),e.respondingSessionsRef.current.has(n.sessionId)){const t=(e.turnNotificationCountsRef.current[n.sessionId]??0)+1;e.turnNotificationCountsRef.current[n.sessionId]=t,s(`done:${n.sessionId}:${t}`,e.t.notificationReplyTitle,e.t.notificationReplyBody,"replies",n.sessionId)}e.respondingSessionsRef.current=Wl(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(e=>Wl(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=Wl(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(e=>Wl(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=Wl(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(e=>Wl(e,n.sessionId,!1)),t(n.sessionId),e.setPendingApprovals(e=>{const t={...e};return delete t[n.sessionId],t}),e.setPendingQuestions(e=>{const t={...e};return delete t[n.sessionId],t}),e.setSessions(e=>e.map(e=>e.sessionId===n.sessionId?{...e,runtime:{...e.runtime,isResponding:!1},interruptReason:n.reason??{kind:"driver_error",at:(new Date).toISOString(),humanText:n.message}}:e)),n.sessionId||e.setErrorText(n.message)}},[e,s])}({refreshInterruptedHistory:e=>{if(e!==Le.current)return;const t=ne.find(t=>t.sessionId===e);t&&ce(t,{refresh:!0})},completionAttention:e.completionAttention,notificationSettingsRef:Oe,notifiedEventsRef:_e,notificationPermissionRef:qe,activeSessionIdRef:Le,respondingSessionsRef:f,turnNotificationCountsRef:We,t:pt,setActiveSessionId:D,setErrorText:y,setPendingQueues:O,setLivePendingQueue:$,setPendingApprovals:L,setPendingQuestions:q,setQuestionAnswers:Ye,setRespondingSessions:F,setSessions:N,remapLocalSessionState:ue,requestSessions:de,clearHistoryLoading:ie,replaceCachedHistory:ae,setCachedMessageDelivery:we,mergeCachedHistoryPage:Ce,appendCachedHistory:be,appendCachedDelta:ve});(function(e){const s=o.useRef(null),i=()=>{null!==s.current&&window.clearTimeout(s.current),s.current=null},r=o.useRef(null),a=o.useRef(e);a.current=e;const c=o.useCallback(e=>{const t=a.current,n=e??t.pairingRef.current;n&&!t.intentionalDisconnectRef.current&&(t.reconnectTimerRef.current&&window.clearTimeout(t.reconnectTimerRef.current),t.reconnectTimerRef.current=window.setTimeout(()=>{t.reconnectTimerRef.current=null,t.connectWithPairingRef.current(n,!0)},1600))},[]),l=o.useCallback(async(e,r=!1)=>{const o=a.current;i(),o.reconnectTimerRef.current&&(window.clearTimeout(o.reconnectTimerRef.current),o.reconnectTimerRef.current=null),o.intentionalDisconnectRef.current=!1,o.setPhase("connecting"),o.setStatusText(r?o.t.reconnectingToDaemon:o.t.connectingToDaemon),o.setErrorText(null);const l=new On,d=o.connectionAttemptIdRef.current+1;o.connectionAttemptIdRef.current=d;const u=o.clientRef.current;o.clientRef.current=l,u?.disconnect();const h=()=>o.connectionAttemptIdRef.current===d&&o.clientRef.current===l;l.onMessage(e=>{h()&&a.current.handleServerMessage(e)});let p=!1;l.onClose(()=>{h()&&p&&(o.clientRef.current=null,i(),o.intentionalDisconnectRef.current||(o.setPhase("connecting"),o.setStatusText(o.t.reconnectingToDaemon),o.setErrorText(o.t.webSocketClosedRetrying),c(e)))});try{const i=await(n().prepareConnection?.(e))??e;if(!h())return;let c,d=i;try{c=await l.connect(i)}catch(m){if(!h()||!i.webSocketUrl||El(m))throw m;d={...i,webSocketUrl:void 0},o.setStatusText(o.t.reconnectingToDaemon),c=await l.connect(d)}if(!h())return;p=!0;const u={...d,displayName:c.displayName??d.displayName},f=!!o.pairingRef.current&&o.pairingRef.current.daemonId!==u.daemonId;f&&o.resetDeviceWorkspace(),o.historyCacheDaemonIdRef.current&&o.historyCacheDaemonIdRef.current!==u.daemonId&&(o.historyCacheRef.current={},o.messagesSessionIdRef.current=null,o.lastHistorySessionIdRef.current=null,o.setMessages([])),o.historyCacheDaemonIdRef.current=u.daemonId,o.setPairing(u),o.pairingRef.current=u,An(u);const g=function(e,n=t()){if(!e)return null;try{const t=n.getItem(Ml);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=Un(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 Rl(t),t}),o.setPhase("connected"),o.setStatusText(o.t.connectedTo(c.displayName??e.displayName??"Vibelet Daemon")),o.refreshDaemonMetadata(u);let y=null;const v=async()=>{if(h())try{if(await a.current.requestReconnectSnapshot(),h()&&y){const e=y;o.setErrorText(t=>t===e?null:t)}}catch(m){if(!h())return;y=m instanceof Error?m.message:String(m),o.setErrorText(y),s.current=window.setTimeout(()=>{s.current=null,v()},1600)}};v();const b=a.current;b.fetchAgentResources(b.agent,f?zn:b.cwd).catch(e=>{h()&&o.setErrorText(e instanceof Error?e.message:String(e))}),o.reportLog("web.connected",{reconnecting:r})}catch(m){if(!h())return;o.clientRef.current=null,l.disconnect(),El(m)&&Nn()?.pairToken===e.pairToken&&Pn(),o.setPhase("error"),o.setStatusText(o.t.connectionFailed),o.setErrorText(El(m)?o.t.pairingAuthFailed:m instanceof Error?m.message:String(m)),El(m)||c(e)}},[c]);o.useEffect(()=>{a.current.connectWithPairingRef.current=l},[l]),o.useEffect(()=>{const e=a.current;let t=!1;return async function(){const n=Mn(),s=Nn()??e.rememberedTarget;if(!n&&!s)return e.setPhase("missing-pair"),void e.setStatusText(e.t.missingPair);try{e.setPhase("pairing"),n&&r.current?.pairNonce!==n.pairNonce&&(r.current={pairNonce:n.pairNonce,promise:Dn(n,s)});const i=n?await(r.current?.promise):s;if(!i||t)return;n&&(An(i),r.current=null,function(){if(!window.location.hash.includes(`${gn}=`))return;const e=`${window.location.pathname}${window.location.search}`;window.history.replaceState(null,"",e)}()),await e.connectWithPairingRef.current(i)}catch(i){if(t)return;n&&(r.current=null),e.setPhase("error"),e.setStatusText(e.t.pairingFailed),e.setErrorText(function(e,t){return e instanceof bn&&"pair_window_expired"===e.code?t.pairingLinkExpired:e instanceof Error?e.message:String(e)}(i,e.t))}}(),()=>{t=!0,i(),e.intentionalDisconnectRef.current=!0,e.connectionAttemptIdRef.current+=1,e.reconnectTimerRef.current&&window.clearTimeout(e.reconnectTimerRef.current),e.clientRef.current?.disconnect()}},[e.t]),o.useEffect(()=>{const e=a.current;if("connected"!==e.phase)return;const t=window.setTimeout(()=>{e.requestSessions({force:!0}).catch(t=>e.setErrorText(t instanceof Error?t.message:String(t)))},260);return()=>window.clearTimeout(t)},[e.phase,e.requestSessions,e.search,e.sinceFilter]),o.useEffect(()=>{const e=a.current;"connected"===e.phase&&e.fetchAgentResources(e.agent,e.cwd)},[e.agent,e.cwd,e.fetchAgentResources,e.phase])})({clientRef:De,connectWithPairingRef:Fe,pairingRef:ze,reconnectTimerRef:Be,connectionAttemptIdRef:He,intentionalDisconnectRef:Ue,historyCacheRef:ke,historyCacheDaemonIdRef:$e,messagesSessionIdRef:re,lastHistorySessionIdRef:m,rememberedTarget:l.current[0]??null,agent:z,cwd:B,phase:g,search:at,sinceFilter:ct,t:pt,handleServerMessage:Rt,setPhase:Ke,setStatusText:Qe,setErrorText:y,setMessages:le,setPairing:Ve,setSavedTargets:dt,setSessionsFromPage:Me,resetDeviceWorkspace:()=>{Le.current=null,D(null),H(zn),N([]),Ge({}),Je({}),e.setDiffSessionId(null),L({}),q({}),O({}),f.current=new Set,F(new Set),r.current=void 0,a.current.clear(),Xl({folder:void 0,file:void 0,cwd:void 0},{replace:!0})},refreshDaemonMetadata:Ae,requestReconnectSnapshot:Ee,fetchAgentResources:Te,reportLog:Ne,requestSessions:de}),o.useLayoutEffect(()=>{G(ql(h.current,P))},[P,v?.daemonId]),o.useEffect(()=>{const e=ne.find(e=>e.sessionId===P);if(!e)return m.current=null,re.current=null,ie(),void le([]);_(e.agent),H(e.cwd||zn),V(e.customTitle??e.title??"");const t=r.current,n=`${v?.daemonId}:${e.sessionId}`;r.current=n;const s=Yl(),i=!a.current.has(n);if(a.current.add(n),i&&te(i=>function(e,t,n,s,i){if(t===n)return e;const r=!t&&i?i:s||zn;return r===e.path?e:{path:r,entries:[],loading:!1,loaded:!1}}(i,t,n,e.cwd||zn,s.folder||s.cwd)),A[e.sessionId])return m.current=e.sessionId,ie(),void(re.current!==e.sessionId&&(re.current=e.sessionId,le([])));if(oe(e.sessionId)){const t=m.current!==e.sessionId;return m.current=e.sessionId,ie(e.sessionId),void(t&&ce(e,{refresh:!0}))}m.current!==e.sessionId&&(m.current=e.sessionId,re.current!==e.sessionId&&(re.current=e.sessionId,le([])),ce(e,{refresh:!0}))},[P,ie,ne,A,oe,ce]);const Mt=function({daemonId:e,session:n,setModel:s,setEffort:i,setFastMode:r,setApprovalMode:a,setPendingSessions:c}){const l=o.useRef(null);l.current||(l.current=function(){try{const e=JSON.parse(t().getItem(Jl)||"{}");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??_n},h=()=>{try{t().setItem(Jl,JSON.stringify(l.current))}catch{}},p=e=>{const t=l.current[d]?.[e];return void 0===t?u[e]:(u[e]===t&&delete l.current[d][e],t)};o.useLayoutEffect(()=>{n&&(s(p("model")),i(p("effort")),r(p("fastMode")),a(p("approvalMode")),h())},[d,u.model,u.effort,u.fastMode,u.approvalMode]);const m=(e,t)=>{n&&(l.current[d]={...l.current[d],[e]:t},h(),c(s=>{const i=s[n.sessionId];if(!i)return s;const r="model"===e?Gn(t):"effort"===e?t||void 0:t;return{...s,[n.sessionId]:{...i,[e]:r}}})),"model"===e&&s(t),"effort"===e&&i(t),"fastMode"===e&&r(t),"approvalMode"===e&&a(t)};return{setModel:e=>m("model",e),setEffort:e=>m("effort",e),setFastMode:e=>m("fastMode",e),setApprovalMode:e=>m("approvalMode",e)}}({daemonId:v?.daemonId,session:ye,setModel:U,setEffort:K,setFastMode:Q,setApprovalMode:W,setPendingSessions:Ge}),{stagePendingSession:Et,failedSend:Tt,dismissFailedSend:Nt,retryFailedSend:At,sendDraft:Pt,sendQuickReply:Dt}=function(e){const[t]=o.useState(Kl),[n,s]=function(e,t){const[n,s]=o.useState({}),i=n=>t(n.sessionId,n.clientMessageId)===e,r=Object.values(n).find(i)??null;return[r,e=>{s(t=>{const n=r?t[r.clientMessageId]??null:Object.values(t).find(i)??null,s="function"==typeof e?e(n):e,o={...t};return n&&delete o[n.clientMessageId],s&&(o[s.clientMessageId]=s),o})}]}(e.activeSessionId,e.resolveCachedMessageSession),[i,r]=o.useState(null);o.useEffect(()=>{n&&e.messagesSessionIdRef.current===e.resolveCachedMessageSession(n.sessionId,n.clientMessageId)&&e.messages.some(e=>(e.localClientMessageId===n.clientMessageId||e.historyKey===n.historyKey)&&("accepted"===e.delivery||"delivered"===e.localDelivery||Boolean(e.historyKey&&!e.historyKey.startsWith("client:"))))&&s(null)},[n,e]);const a=o.useCallback(t=>{e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current),e.respondingSessionsRef.current.delete(t),e.setRespondingSessions(e=>{const n=new Set(e);return n.delete(t),n})},[e]),c=o.useCallback((t,n,s)=>{const i=Gl(t)??Gl(e.cwd)??zn,o=n??e.agent,a=function(e=Date.now()){return Yn=(Yn+1)%1e4,`pending_local_${e}_${Yn}`}(),c=function(e){const t=e.now??(new Date).toISOString();return{sessionId:e.sessionId,agent:e.agent,cwd:e.cwd||zn,...e.model?{model:e.model}:{},...e.effort?{effort:e.effort}:{},fastMode:e.fastMode??!1,...e.title?{title:e.title}:{},createdAt:t,lastActivityAt:t,sources:["daemon"],runtime:{state:"daemonActive",confidence:"high",resumeMode:"reuseDriver"},managed:!0,approvalMode:e.approvalMode}}({sessionId:a,agent:o,cwd:i,approvalMode:s?.approvalMode??e.approvalMode,model:Gn(s?.model??e.model),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?"":ql(e.composerDraftsRef.current,null));return e.setPendingSessions(e=>({...e,[a]:c})),e.setComposerDrafts(t=>{let n=Ll(t,a,l);return e.activeSessionIdRef.current||(n=Ll(n,null,"")),e.composerDraftsRef.current=n,Fl(n),n}),e.setCwd(i),e.setAgent(o),e.activeSessionIdRef.current=a,e.setActiveSessionId(a),e.lastHistorySessionIdRef.current=a,e.messagesSessionIdRef.current=a,e.clearHistoryLoading(),e.setMessages([]),e.setDraft(l),(s?.draft?.trim()||s?.attachments?.length)&&r({sessionId:a,attachments:s.attachments??[]}),e.setErrorText(null),e.reportLog("web.session.pending_create",{sessionId:a,agent:o,cwd:i}),a},[e]),l=o.useCallback(async(t,n,s)=>{const i=e.clientRef.current;if(!i?.isConnected)return e.setErrorText(e.t.webSocketNotConnected),null;const r=s?e.pendingSessions[s]:void 0,o=Gl(t)??Gl(r?.cwd)??Gl(e.cwd)??zn,a=n??r?.agent??e.agent,c=r?.approvalMode??e.approvalMode,l=r?r.model:Gn(e.model),d=r?.effort??(e.effort||void 0),u=r?.fastMode??e.fastMode;e.setErrorText(null);try{const t=await i.request({action:"session.create",id:i.makeId("create"),agent:a,cwd:o,approvalMode:c,continueSession:e.continueSession,model:l,effort:d,fastMode:u,...s?{clientSessionId:s}:{}}),n=function(e){const t=e;return"string"==typeof t.sessionId?t.sessionId:null}(t);if(!n)throw new Error(e.t.sessionIdMissing);const h=Bn(t)&&"string"==typeof t.oldSessionId?t.oldSessionId:s;return e.activeSessionIdRef.current!==(s??null)&&e.activeSessionIdRef.current!==n||(e.setCwd(o),e.setAgent(a),e.activeSessionIdRef.current=n,e.setActiveSessionId(n),e.lastHistorySessionIdRef.current=n,e.messagesSessionIdRef.current=n,e.clearHistoryLoading()),s&&r?(e.setPendingSessions(e=>{const t={...e};return delete t[s],h&&h!==s&&delete t[h],t}),e.setOptimisticSessions(e=>({...e,[n]:Xn(r,n)})),h&&h!==n&&e.remapLocalSessionState(h,n),s!==n&&e.remapLocalSessionState(s,n)):await e.requestSessions({force:!0}),e.reportLog("web.session.create",{sessionId:n,clientSessionId:s,agent:a,cwd:o}),n}catch(h){return e.setErrorText(h instanceof Error?h.message:String(h)),null}},[e]),d=o.useCallback(async t=>{if(!e.sessions.some(e=>e.sessionId===t&&e.archived))return;const n=e.clientRef.current;if(!n?.isConnected)throw new Error(e.t.webSocketNotConnected);await n.request({action:"session.setArchived",id:n.makeId("unarchive"),sessionId:t,archived:!1}),e.setSessions(e=>e.map(e=>e.sessionId===t?{...e,archived:!1}:e)),e.setOptimisticSessions(e=>e[t]?{...e,[t]:{...e[t],archived:!1}}:e),e.requestSessions({force:!0}).catch(()=>{})},[e]),u=o.useCallback(async(n,i,r)=>{n?.preventDefault();const o=(r??e.draft).trim(),c=i??e.attachments;if(c.some(e=>e.uploading))return;if(!o&&!c.length||e.busy||t.has(e.activeSessionId))return;const u=e.clientRef.current;if(!u?.isConnected)return void e.setErrorText(e.t.webSocketNotConnected);const h=t.start(e.activeSessionId);try{const t=Ct(o)?"agentSkills":0===c.length&&xt(o,e.activeSession?.agent??e.agent)?"agentCommands":void 0;let n;if(t)try{n=await Ul(t)}catch(p){return void e.setErrorText(p instanceof Error?p.message:String(p))}e.setErrorText(null),void 0===r&&e.updateDraft("");const i=c;void 0===r&&e.setAttachments([]);let m=e.activeSessionId,f=e.activeSession?.agent??e.agent;const g=m?e.pendingSessions[m]:void 0,y=g?.fastMode??e.fastMode,v=g?g.model:Gn(e.model);if(m&&e.pendingSessions[m]){const t=await l(e.pendingSessions[m].cwd,e.pendingSessions[m].agent,m);if(!t)return void(void 0===r&&Ql(e,o,i));m=t,f=e.pendingSessions[e.activeSessionId??""]?.agent??f}else m||(m=await l());if(!m)return void(void 0===r&&Ql(e,o,i));h.remap(m);const b=0===i.length?xt(o,f):null;if(b){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"}(b.command),s=t?u.makeId("cmd_msg"):void 0;t&&(e.activeSessionIdRef.current===m&&(e.messagesSessionIdRef.current=m),e.appendCachedHistory(m,[{role:"user",content:t,timestamp:(new Date).toISOString()}]),e.activeSessionIdRef.current===m&&e.renderCachedHistory(m));try{t&&await d(m);const i=await u.request({action:"session.command",id:u.makeId("command"),sessionId:m,agent:f,command:b.command,...s?{clientMessageId:s}:{},featureEntitlements:n});await e.handleSessionCommandResponse(m,b.command,i)}catch(p){const t=p instanceof Error?p.message:String(p);e.appendInfoMessage(m,wt(t)),e.activeSessionIdRef.current===m&&e.setErrorText(wt(t))}return}const x=function(e){return e.startsWith("//")?e.slice(1):e}(o),w=i.map(e=>e.path),S=u.makeId("msg"),k=`client:${S}`;e.activeSessionIdRef.current===m&&(e.messagesSessionIdRef.current=m),e.setCachedMessageDelivery(m,S,"sending",{content:x,...w.length?{images:w}:{}}),e.activeSessionIdRef.current===m&&e.renderCachedHistory(m),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(m),e.setRespondingSessions(e=>new Set(e).add(m));const I=Ct(x)??void 0,C=I?n:void 0;try{await d(m);const t=await u.request({action:"session.send",id:u.makeId("send"),sessionId:m,agent:f,message:x,clientMessageId:S,images:w.length?w:void 0,model:v,effort:e.effort||void 0,fastMode:y,skillInvocation:I,featureEntitlements:C},{timeoutMs:zl,timeoutMessage:Vl});Bn(t)&&"string"==typeof t.oldSessionId&&"string"==typeof t.sessionId&&(h.remap(t.sessionId),e.remapLocalSessionState(t.oldSessionId,t.sessionId)),e.setCachedMessageDelivery(Bn(t)&&"string"==typeof t.sessionId?t.sessionId:m,S,"delivered"),e.reportLog("web.telemetry.send_accepted",{attachmentCount:w.length}),s(e=>e?.historyKey===k?null:e)}catch(p){m=e.resolveCachedMessageSession(m,S);const t=$l(as(p instanceof Error?p.message:String(p),Boolean(I)));if("delivered"===e.setCachedMessageDelivery(m,S,"failed"))return;e.activeSessionIdRef.current===m&&e.setErrorText(null),s({sessionId:m,agent:f,message:x,clientMessageId:S,historyKey:k,kind:t,retrying:!1,...w.length?{images:w}:{},model:v,effort:e.effort||void 0,fastMode:y,skillInvocation:I,featureEntitlements:C}),e.reportLog("web.telemetry.send_failed",{attachmentCount:w.length,failureKind:t},"warn"),a(m)}}finally{h.finish()}},[a,l,e,t,d]),h=o.useCallback(async()=>{if(!n||n.retrying||e.busy||t.has(e.activeSessionId))return;const i=e.clientRef.current;if(!i?.isConnected)return void s(e=>e?{...e,kind:"network"}:null);let r=e.resolveCachedMessageSession(n.sessionId,n.clientMessageId);const o=t.start(r);s(e=>e?{...e,retrying:!0}:null),e.ensureCachedHistoryEntry(r,{role:"user",content:n.message,historyKey:n.historyKey,...n.images?.length?{images:n.images}:{}}),e.setCachedMessageDelivery(r,n.clientMessageId,"sending"),e.setErrorText(null),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(r),e.setRespondingSessions(e=>new Set(e).add(r));try{await d(r);const t=await i.request({action:"session.send",id:i.makeId("retry_send"),sessionId:r,agent:n.agent,message:n.message,clientMessageId:n.clientMessageId,images:n.images,model:n.model,effort:n.effort,fastMode:n.fastMode,skillInvocation:n.skillInvocation??void 0,featureEntitlements:n.skillInvocation?await Ul("agentSkills"):void 0},{timeoutMs:zl,timeoutMessage:Vl});Bn(t)&&"string"==typeof t.oldSessionId&&"string"==typeof t.sessionId&&(o.remap(t.sessionId),e.remapLocalSessionState(t.oldSessionId,t.sessionId)),e.setCachedMessageDelivery(Bn(t)&&"string"==typeof t.sessionId?t.sessionId:r,n.clientMessageId,"delivered"),e.reportLog("web.telemetry.retry_accepted",{attachmentCount:n.images?.length??0}),s(null)}catch(c){r=e.resolveCachedMessageSession(r,n.clientMessageId);const t=$l(as(c instanceof Error?c.message:String(c),Boolean(n.skillInvocation)));if("delivered"===e.setCachedMessageDelivery(r,n.clientMessageId,"failed"))return void s(null);s(e=>e?{...e,sessionId:r,kind:t,retrying:!1}:null),e.reportLog("web.telemetry.retry_failed",{attachmentCount:n.images?.length??0,failureKind:t},"warn"),a(r)}finally{o.finish()}},[a,n,e,t,d]);return o.useEffect(()=>{!i||e.busy||t.has(e.activeSessionId)||(e.activeSessionId===i.sessionId&&e.pendingSessions[i.sessionId]?(r(null),u(void 0,i.attachments)):r(null))},[i,e.activeSessionId,e.busy,e.pendingSessions,u]),{failedSend:n,dismissFailedSend:()=>s(null),retryFailedSend:h,stagePendingSession:c,sendDraft:Object.assign(u,{submission:t}),sendQuickReply:e=>u(void 0,[],e)}}({messages:Ie,sessions:ne,setSessions:N,clientRef:De,activeSessionIdRef:Le,composerDraftsRef:h,lastHistorySessionIdRef:m,messagesSessionIdRef:re,respondingSessionsRef:f,agent:z,cwd:B,approvalMode:Xe,continueSession:et,model:tt,effort:nt,fastMode:st,activeSessionId:P,activeSession:ye,pendingSessions:A,draft:ot,busy:mt,attachments:he,t:pt,setPendingSessions:Ge,setOptimisticSessions:Je,setComposerDrafts:rt,setCwd:H,setAgent:_,setActiveSessionId:D,setMessages:le,setDraft:G,setErrorText:y,setBusy:ft,setAttachments:pe,setRespondingSessions:F,clearHistoryLoading:ie,reportLog:Ne,remapLocalSessionState:ue,requestSessions:de,updateDraft:Re,appendCachedHistory:be,ensureCachedHistoryEntry:xe,setCachedMessageDelivery:we,resolveCachedMessageSession:Se,renderCachedHistory:oe,handleSessionCommandResponse:jt,appendInfoMessage:se}),{respondApproval:Ft,respondQuestion:Lt,cancelQuestion:qt,setQuestionChoice:Ot,requestActiveAction:$t,interruptActiveSession:zt,retrySessions:_t,updateApprovalMode:Bt,cancelQueuedTurn:Ut,setSessionPinned:Vt,setSessionArchived:Gt,deleteSession:Jt,updatePinned:Zt,updateArchived:Yt,renameSession:Xt}=function(e){const t=o.useCallback(async t=>{const n=e.clientRef.current,s=e.activeApproval;if(n?.isConnected&&s){e.setBusy(!0),e.setErrorText(null);try{await n.request({action:"session.approve",id:n.makeId("approve"),sessionId:s.sessionId,requestId:s.requestId,approved:t}),e.setPendingApprovals(e=>{const t={...e};return t[s.sessionId]?.requestId===s.requestId&&delete t[s.sessionId],t})}catch(i){const t=i instanceof Error?i.message:String(i);/session not found|session .* inactive/i.test(t)&&e.setPendingApprovals(e=>{if(e[s.sessionId]?.requestId!==s.requestId)return e;const t={...e};return delete t[s.sessionId],t}),e.setErrorText(t)}finally{e.setBusy(!1)}}},[e]),n=o.useCallback(async()=>{const t=e.clientRef.current;if(t?.isConnected&&e.activeQuestion){e.setBusy(!0),e.setErrorText(null);try{await t.request({action:"session.respondQuestion",id:t.makeId("question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId,answers:e.questionAnswers}),e.setPendingQuestions(t=>{const n={...t};return n[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete n[e.activeQuestion.sessionId],n})}catch(n){e.setErrorText(n instanceof Error?n.message:String(n))}finally{e.setBusy(!1)}}},[e]),s=o.useCallback(async()=>{const t=e.clientRef.current;if(t?.isConnected&&e.activeQuestion){e.setBusy(!0),e.setErrorText(null);try{await t.request({action:"session.cancelQuestion",id:t.makeId("cancel_question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId}),e.setPendingQuestions(t=>{const n={...t};return n[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete n[e.activeQuestion.sessionId],n})}catch(n){e.setErrorText(n instanceof Error?n.message:String(n))}finally{e.setBusy(!1)}}},[e]),i=o.useCallback((t,n,s)=>{e.setQuestionAnswers(e=>function(e,t,n,s=!1){if(!s)return{...e,[t]:[n]};const i=e[t]??[],r=i.includes(n)?i.filter(e=>e!==n):[...i,n];return{...e,[t]:r}}(e,t,n,Boolean(s)))},[e]),r=o.useCallback(async t=>{const n=e.clientRef.current,s=e.activeSession,i=s?.sessionId??("session.interrupt"===t?e.activeSessionIdRef.current:null);if(!n?.isConnected||!i)return!1;if("session.interrupt"!==t&&!s)return!1;if("session.delete"===t&&!(await S(b().deleteSession(d(s)))))return!1;if(e.clientRef.current!==n||!n.isConnected)return!1;e.setBusy(!0),e.setErrorText(null);try{return"session.resume"===t?await n.request({action:t,id:n.makeId("resume"),sessionId:i,agent:s.agent}):await n.request({action:t,id:n.makeId(t.split(".").at(-1)??"session"),sessionId:i}),"session.delete"===t&&(e.removeCachedHistory(s.sessionId),e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([])),"session.interrupt"!==t&&await e.requestSessions({force:!0,preserveLoaded:!0}),!0}catch(r){return e.setErrorText(r instanceof Error?r.message:String(r)),!1}finally{e.setBusy(!1)}},[e]),a=o.useCallback(async t=>{const n=e.clientRef.current;if(e.activeSession){if(n?.isConnected){e.setErrorText(null);try{await n.request({action:"session.setApprovalMode",id:n.makeId("approval_mode"),sessionId:e.activeSession.sessionId,approvalMode:t}),e.activeSessionIdRef.current===e.activeSession.sessionId&&e.setApprovalMode(t),e.setSessions(n=>n.map(n=>n.sessionId===e.activeSession.sessionId?{...n,approvalMode:t}:n))}catch(s){e.setErrorText(s instanceof Error?s.message:String(s))}}}else e.setApprovalMode(t)},[e]),c=function(e){return o.useCallback(async t=>{const n=e.clientRef.current;if(!n?.isConnected||!e.activeSessionId||!t.clientMessageId)return;const s=e.activeSessionId;let i=-1;e.setPendingQueues(e=>{const n=e[s]??[];return i=n.findIndex(e=>e.clientMessageId===t.clientMessageId),{...e,[s]:n.filter(e=>e.clientMessageId!==t.clientMessageId)}}),e.setBusy(!0),e.setErrorText(null);try{if(await n.request({action:"session.queue.cancel",id:n.makeId("queue_cancel"),sessionId:s,clientMessageId:t.clientMessageId},{timeoutMs:zl}),e.clientRef.current!==n)return}catch(o){if(e.clientRef.current!==n)return;return e.setPendingQueues(e=>{const n=e[s]??[];if(n.some(e=>e.clientMessageId===t.clientMessageId))return e;const r=Math.min(Math.max(i,0),n.length);return{...e,[s]:[...n.slice(0,r),t,...n.slice(r)]}}),void(e.activeSessionIdRef.current===s&&e.setErrorText(o instanceof Error?o.message:String(o)))}finally{e.setBusy(!1)}e.removeCachedMessage(s,t.clientMessageId);const r=e=>[e,t.content].filter(Boolean).join("\n\n");if(e.setComposerDrafts(t=>{const n=Ll(t,s,r(ql(t,s)));return e.composerDraftsRef.current=n,Fl(n),n}),e.activeSessionIdRef.current===s&&e.setDraft(r),t.images?.length){const n=[...new Set(t.images)];e.setAttachments(e=>{const t=new Set(e.map(e=>e.path));return[...e,...n.filter(e=>!t.has(e)).map(e=>({path:e,name:Kn(e),type:"image/*",size:0}))]})}},[e])}(e),l=o.useCallback(async(t,n)=>{if(e.pendingSessions[t.sessionId])return;const s=e.clientRef.current;if(s?.isConnected){e.setBusy(!0),e.setErrorText(null);try{const i=n?Date.now():void 0;await s.request({action:"session.setPinned",id:s.makeId("pin"),sessionId:t.sessionId,pinned:n,...i?{pinnedAt:i}:{}}),e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,pinned:n,pinnedAt:i}:e)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(i){e.setErrorText(i instanceof Error?i.message:String(i))}finally{e.setBusy(!1)}}},[e]),u=o.useCallback(async(t,n)=>{if(e.pendingSessions[t.sessionId])return;const s=e.clientRef.current;if(s?.isConnected){e.setBusy(!0),e.setErrorText(null);try{await s.request({action:"session.setArchived",id:s.makeId("archive"),sessionId:t.sessionId,archived:n}),e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,archived:n}:e)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(i){e.setErrorText(i instanceof Error?i.message:String(i))}finally{e.setBusy(!1)}}},[e]),h=o.useCallback(async t=>{if(e.pendingSessions[t.sessionId])return e.removeCachedHistory(t.sessionId),e.setPendingSessions(e=>{const n={...e};return delete n[t.sessionId],n}),e.setComposerDrafts(n=>{const s=Ll(n,t.sessionId,"");return e.composerDraftsRef.current=s,Fl(s),s}),void(e.activeSessionIdRef.current===t.sessionId&&(e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([]),e.setDraft(ql(e.composerDraftsRef.current,null)),e.setDetailsOpen(!1)));const n=e.clientRef.current;if(n?.isConnected&&await S(b().deleteSession(d(t)))&&e.clientRef.current===n&&n.isConnected){e.setBusy(!0),e.setErrorText(null);try{await n.request({action:"session.delete",id:n.makeId("delete"),sessionId:t.sessionId}),e.removeCachedHistory(t.sessionId),e.setOptimisticSessions(e=>{if(!e[t.sessionId])return e;const n={...e};return delete n[t.sessionId],n}),e.activeSessionIdRef.current===t.sessionId&&(e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([]),e.setDetailsOpen(!1)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(s){e.setErrorText(s instanceof Error?s.message:String(s))}finally{e.setBusy(!1)}}},[e]),p=o.useCallback(async()=>{e.activeSession&&await l(e.activeSession,!e.activeSession.pinned)},[e.activeSession,l]),m=o.useCallback(async()=>{e.activeSession&&await u(e.activeSession,!e.activeSession.archived)},[e.activeSession,u]),f=o.useCallback(()=>{const t=e.activeSessionId;t&&r("session.interrupt").then(n=>{n&&(e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current),e.respondingSessionsRef.current.delete(t),e.setRespondingSessions(e=>{const n=new Set(e);return n.delete(t),n}))})},[e,r]),g=o.useCallback(()=>{e.setErrorText(null),"connected"===e.phase?e.requestSessions({force:!0,preserveLoaded:!0}):window.location.reload()},[e]),y=o.useCallback(async(t=e.activeSession,n=e.renameTitle)=>{const s=n.trim();if(t&&e.pendingSessions[t.sessionId])return e.setPendingSessions(e=>{const n=e[t.sessionId];return n?{...e,[t.sessionId]:{...n,title:s||n.title,customTitle:s||void 0}}:e}),!0;const i=e.clientRef.current;if(!i?.isConnected||!t)return!1;e.setBusy(!0),e.setErrorText(null);try{return await i.request({action:"session.rename",id:i.makeId("rename"),sessionId:t.sessionId,title:s||void 0}),e.setSessions(e=>e.map(e=>e.sessionId===t.sessionId?{...e,customTitle:s||void 0}:e)),!0}catch(r){return e.setErrorText(r instanceof Error?r.message:String(r)),!1}finally{e.setBusy(!1)}},[e]);return{respondApproval:t,respondQuestion:n,cancelQuestion:s,setQuestionChoice:i,requestActiveAction:r,interruptActiveSession:f,retrySessions:g,updateApprovalMode:a,cancelQueuedTurn:c,setSessionPinned:l,setSessionArchived:u,deleteSession:h,updatePinned:p,updateArchived:m,renameSession:y}}({clientRef:De,activeSessionIdRef:Le,composerDraftsRef:h,lastHistorySessionIdRef:m,messagesSessionIdRef:re,respondingSessionsRef:f,activeApproval:fe,activeQuestion:ge,activeSession:ye,activeSessionId:P,questionAnswers:Ze,pendingSessions:A,phase:g,renameTitle:it,setBusy:ft,setErrorText:y,setPendingApprovals:L,setPendingQuestions:q,setQuestionAnswers:Ye,setPendingQueues:O,setActiveSessionId:D,setMessages:le,setApprovalMode:W,setSessions:N,setPendingSessions:Ge,setComposerDrafts:rt,setDraft:G,setAttachments:pe,setDetailsOpen:gt,setRespondingSessions:F,setOptimisticSessions:Je,removeCachedHistory:je,requestSessions:de,removeCachedMessage:e.removeCachedMessage}),{runArchiveSync:an,skipArchiveSync:cn,runAdminAction:ln,exportActiveSession:hn,clearPairing:mn,setNotificationsEnabled:yn,connectSavedTarget:vn,forgetSavedTarget:xn,openSessionDetails:wn,editFolderTags:Sn,browseFolder:kn,copyResumeCommand:In,resumeInTerminal:Cn}=function(e){const t=o.useCallback((t,n)=>{e.updateSessionListPreferences(e=>({...e,archiveSyncedDaemonIds:"synced"===n?{...e.archiveSyncedDaemonIds,[t]:!0}:e.archiveSyncedDaemonIds,archiveSyncCardDismissedDaemonIds:{...e.archiveSyncCardDismissedDaemonIds,[t]:!0}}))},[e]),s=o.useCallback((n,s)=>{const i="pull"===n?e.t.archiveSyncSuccessPull:"pushMerge"===n?e.t.archiveSyncSuccessMerge:e.t.archiveSyncSuccessPush;if(e.setArchiveSyncStatus(function(e,t,n){return e.ok?{tone:"success",message:t.replace("{n}",String(e.archivedSessionIds.length))}:"timeout"===e.error?{tone:"error",message:n.timeout}:"not_connected"===e.error?{tone:"error",message:n.disconnected}:{tone:"error",message:n.generic.replace("{error}",e.error)}}(s,i,{timeout:e.t.archiveSyncFailedTimeout,disconnected:e.t.archiveSyncFailedDisconnected,generic:e.t.archiveSyncFailedGeneric})),!s.ok)return;const r=new Set(s.archivedSessionIds);e.setSessions(e=>e.map(e=>({...e,archived:r.has(e.sessionId)}))),e.pairingRef.current?.daemonId&&t(e.pairingRef.current.daemonId,"synced"),e.requestSessions({force:!0})},[t,e]),i=o.useCallback(async t=>{if(e.archiveSyncBusy)return;e.setArchiveSyncBusy(t),e.setArchiveSyncStatus(null);const n=await async function(e,t,n){if(!e?.isConnected)return{ok:!1,error:"not_connected"};try{const s=await e.request({action:"sessions.archiveSync",id:e.makeId("archive_sync"),mode:t,..."pull"===t?{}:{archivedSessionIds:n??[]}});return{ok:!0,archivedSessionIds:Array.isArray(s.archivedSessionIds)?s.archivedSessionIds.filter(e=>"string"==typeof e&&e.length>0):[]}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}(e.clientRef.current,t,function(e){return e.filter(e=>!0===e.archived).map(e=>e.sessionId)}(e.displaySessions));s(t,n),e.setArchiveSyncBusy(null)},[s,e]),r=o.useCallback(()=>{e.pairing?.daemonId&&(t(e.pairing.daemonId,"dismissed"),e.setArchiveSyncStatus({tone:"success",message:e.t.archiveSyncSkipped}))},[t,e]),a=o.useCallback(async t=>{const n=e.clientRef.current;if(n?.isConnected&&("update"!==t||await S(b().update))&&("restart"!==t||await S(b().restart))&&e.clientRef.current===n&&n.isConnected){e.setAdmin(e=>({...e,loading:!0,action:t,statusText:""})),e.setErrorText(null);try{if("update"===t){const t=function(e){const t=e.toLowerCase();return t.includes("alpha")?"alpha":t.includes("beta")?"beta":e.trim()?"latest":void 0}(e.daemonMetadata.version),s=await n.request({action:"daemon.update",id:n.makeId("daemon_update"),...t?{channel:t}:{}});return void e.setAdmin(e=>({...e,loading:!1,action:null,statusText:s.alreadyRunning?"Connector update already running":"Connector update started"}))}await n.request({action:"daemon.restart",id:n.makeId("daemon_restart")}),e.setAdmin(e=>({...e,loading:!1,action:null,statusText:"Connector restart requested"})),e.refreshDaemonMetadata()}catch(s){e.setAdmin(e=>({...e,loading:!1,action:null})),e.setErrorText(s instanceof Error?s.message:String(s))}}},[e]),c=o.useCallback(async()=>{if(!e.activeSession)return;const t=function(e,t){return function(e,t){const n=d(e),{markdown:s}=function({title:e,session:t,messages:n,labels:s,exportedAt:i=new Date}){const r=[];for(const a of n){if("user"!==a.type&&"assistant"!==a.type)continue;const e=fn(a,s);e&&r.push(`## ${"user"===a.type?s.userMessage:s.assistantMessage}\n\n${e}`)}const o=[`# ${un(e)||t.sessionId}`,"",`- ${s.agent}: ${pn(t.agent)}`,`- ${s.sessionId}: \`${t.sessionId}\``,`- ${s.workingDirectory}: \`${t.cwd}\``,`- ${s.createdAt}: ${t.createdAt}`,`- ${s.exportedAt}: ${i.toISOString()}`];return{markdown:r.length>0?`${o.join("\n")}\n\n${r.join("\n\n")}`:o.join("\n"),messageCount:r.length}}({title:n,session:e,messages:t.filter(e=>"info"!==e.type).map(e=>({type:e.role,content:"assistant"===e.role?dn(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,Pn(),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(Lc),e.setPhase("missing-pair"),e.setStatusText(e.t.missingPair))},[e]),h=o.useCallback(t=>{t&&"default"===e.notificationPermission?l():e.updateNotificationSettings({enabled:t})},[e,l]),p=o.useCallback(t=>{e.connectWithPairingRef.current(t,!0)},[e]),m=o.useCallback(t=>e.saveTargets(function(e,t){return e.filter(e=>e.daemonId!==t)}(e.savedTargets,t)),[e]),f=o.useCallback(t=>{e.setActiveSessionId(t.sessionId),e.setRenameTitle(t.customTitle??t.title??""),e.setDetailsOpen(!0)},[e]),g=o.useCallback((t,n)=>{const s=k(n);e.updateSessionListPreferences(e=>({...e,directoryTags:I(e.directoryTags,t,s)}))},[e]),y=o.useCallback(t=>{e.setControlTab("files"),e.listDirectory(t,{updateRoute:!0})},[e]),v=o.useCallback(async t=>{try{const n=Ht(t);if(!n)return;await Js(n),e.setStatusText(e.t.commandCopied)}catch{throw e.setErrorText(e.t.copyResumeFailed),new Error(e.t.copyResumeFailed)}},[e]),x=o.useRef(!1);return{runArchiveSync:i,skipArchiveSync:r,runAdminAction:a,exportActiveSession:c,clearPairing:u,setNotificationsEnabled:h,connectSavedTarget:p,forgetSavedTarget:m,openSessionDetails:f,editFolderTags:g,browseFolder:y,copyResumeCommand:v,resumeInTerminal:o.useCallback(async t=>{if(x.current)return;const s=n(),i=e.pairingRef.current?.daemonId;if(i&&s.resumeInTerminal&&s.isLocalDaemon?.(i)){x.current=!0;try{const n=e.clientRef.current;if(!n)throw new Error("Not connected");await n.request({action:"session.release",id:n.makeId("release"),sessionId:t.sessionId,agent:t.agent}),await s.resumeInTerminal({...t,daemonId:i,approvalMode:t.approvalMode??t.observedApprovalMode})}catch(r){e.setErrorText(String(r).includes("session_busy")?e.t.resumeTerminalBusy:e.t.resumeTerminalFailed)}finally{x.current=!1}}},[e])}}({clientRef:De,pairingRef:ze,connectWithPairingRef:Fe,notificationPermissionRef:qe,intentionalDisconnectRef:Ue,connectionAttemptIdRef:He,historyCacheRef:ke,historyCacheDaemonIdRef:$e,messagesSessionIdRef:re,lastHistorySessionIdRef:m,displaySessions:ne,pairing:v,t:pt,archiveSyncBusy:St,daemonMetadata:X,activeSession:ye,messages:Ie,notificationPermission:ee,savedTargets:lt,setArchiveSyncBusy:kt,setArchiveSyncStatus:It,setSessions:N,setAdmin:yt,setErrorText:y,setNotificationPermission:bt,setStatusText:Qe,setMessages:le,setPairing:Ve,setDaemonMetadata:vt,setPhase:Ke,setActiveSessionId:D,setRenameTitle:V,setDetailsOpen:gt,setControlTab:Y,updateSessionListPreferences:ht,requestSessions:de,refreshDaemonMetadata:Ae,updateNotificationSettings:Pe,saveTargets:ut,listDirectory:me}),jn=o.useCallback(async e=>{const t=De.current;return t?.isConnected?(await t.request({action:"models.list",id:t.makeId("models"),agent:e})).options??[]:[]},[]),Rn=o.useCallback(async e=>{const t=De.current;if(!t?.isConnected)throw new Error(pt.webSocketNotConnected);return t.request({action:"sessions.gitMetadata",id:t.makeId("directoryGit"),cwds:[e]})},[De,pt.webSocketNotConnected]),En="denied"===ee||"unsupported"===ee,Tn=Boolean(X.version&&X.latestVersion&&Oc(X.version,X.latestVersion)),Fn=v?.daemonId,qn=Boolean(Fn&&J[Fn]),Hn=Boolean(Fn&&Z[Fn]),ss=function(e){const[t,n]=o.useState(null),s=e.clientRef.current,i=(t,n,s)=>{const i=n.map(t=>t.content||e.t.failedSendImages(t.images?.length??0)).join(" / ");return function(e,t,n,s){switch(Ol(s)){case"turn-changed":return e.queueGuideTurnChanged;case"no-active-turn":return e.queueGuideNoActiveTurn;case"not-ready":return e.queueSessionNotReady;case"stale-selection":return e.queueSelectionChanged;case"pending-request":return e.queuePendingRequest;case"unsupported":return e.queueGuideUnsupported}const i=s instanceof Error?s.message:String(s);return s instanceof Ln?e.queueRequestRejected(t,n,i):e.queueRequestFailed(t,n,/timeout|timed out/i.test(i)?e.queueRequestTimeout:i)}(e.t,t,i,s)},r=e.activeSessionId,{busy:a,begin:c}=function(e,t){const n=o.useRef(new Set),[s,i]=o.useState([]),r=n=>n.client===e&&n.sessionId===t;return{busy:s.some(r),begin:()=>{if(!e||!t||[...n.current].some(r))return null;const s={client:e,sessionId:t};return n.current.add(s),i([...n.current]),()=>{n.current.delete(s),i([...n.current])}}}}(s,r),l=()=>e.clientRef.current===s,d=async()=>{l()&&await Promise.allSettled([e.requestSessions({force:!0,preserveLoaded:!0}),...e.activeSession?[e.requestHistory(e.activeSession,{refresh:!0})]:[]])},u=n=>t?.sessionId===r&&t.action===n&&t.runtime===e.activeSession?.runtime,h="daemonActive"===e.activeSession?.runtime.state&&!e.activeQueue.some(e=>e.waitingForStartup),p=!r||Boolean(e.pendingApprovals[r]||e.pendingQuestions[r]),m=!p&&!0===s?.supportsSessionSteer&&!!r&&e.respondingSessions.has(r)&&h&&!0===e.activeSession?.runtime.isResponding&&!u("guide"),f=!p&&h&&!u("sendNow")&&!0===s?.supportsQueueSendNow;return{busy:a,canGuide:m,canSendNow:f,onAction:async(t,o)=>{if(!r||!s?.isConnected||!("guide"===o?m:f))return;const a=new Set(t.map(e=>e.clientMessageId).filter(Boolean)),u=e.activeQueue.filter(e=>e.clientMessageId&&a.has(e.clientMessageId));if(!u.length)return;const h=c();if(!h)return;e.setErrorText(null);const p=new Set;for(const n of u)e.setCachedMessageDelivery(r,n.clientMessageId,"sending",n);const g=t=>{p.add(t.clientMessageId),e.setCachedMessageDelivery(r,t.clientMessageId,"delivered")};try{if("sendNow"===o){if(await s.request({action:"session.queue.sendNow",id:s.makeId("queue_now"),sessionId:r,clientMessageIds:u.map(e=>e.clientMessageId)},{timeoutMs:zl}),!l())return;u.forEach(g)}else for(const t of u){if(!l())return;if(await s.request({action:"session.steer",id:s.makeId("queue_guide"),sessionId:r,clientMessageId:t.clientMessageId,message:t.content,images:t.images},{timeoutMs:zl}),!l())return;g(t),e.setPendingQueues(e=>({...e,[r]:(e[r]??[]).filter(e=>e.clientMessageId!==t.clientMessageId)}))}}catch(y){if(!l())return;const t=Ol(y);let s=!1;for(const n of u)p.has(n.clientMessageId)||(s="delivered"!==e.setCachedMessageDelivery(r,n.clientMessageId,"failed")||s);t&&("no-active-turn"===t&&e.setRespondingSessions(e=>{const t=new Set(e);return t.delete(r),t}),e.activeSession&&n({sessionId:r,action:o,runtime:e.activeSession.runtime}),await d()),s&&l()&&e.activeSessionIdRef.current===r&&e.setErrorText(i("guide"===o?e.t.queueGuide:e.t.queueSendNow,u.filter(e=>!p.has(e.clientMessageId)),y))}finally{h()}},onCollect:async t=>{if(!r||!s?.isConnected)return;const n=new Set(t.map(e=>e.clientMessageId).filter(e=>!!e)),o=e.activeQueue.filter(e=>e.clientMessageId&&n.has(e.clientMessageId));if(o.length<2)return;const a=c();if(a){e.setErrorText(null);try{const t=await s.request({action:"session.queue.collect",id:s.makeId("queue_collect"),sessionId:r,clientMessageIds:o.map(e=>e.clientMessageId)},{timeoutMs:zl});if(!l())return;const i=t.entries;if(!Array.isArray(i))throw new Error("Invalid queue collection response");const a=i.map(e=>e.content).filter(e=>e.trim()).join("\n\n"),c=e=>[e,a].filter(e=>e.trim()).join("\n\n");e.setComposerDrafts(t=>{const n=Ll(t,r,c(ql(t,r)));return e.composerDraftsRef.current=n,Fl(n),n}),e.activeSessionIdRef.current===r&&e.setDraft(c);const d=[...new Set(i.flatMap(e=>e.images??[]))];e.setAttachments(e=>{const t=new Set(e.map(e=>e.path));return[...e,...d.filter(e=>!t.has(e)).map(e=>({path:e,name:Kn(e),type:"image/*",size:0}))]}),e.setPendingQueues(e=>({...e,[r]:(e[r]??[]).filter(e=>!e.clientMessageId||!n.has(e.clientMessageId))}))}catch(u){if(!l())return;Ol(u)&&await d(),l()&&e.activeSessionIdRef.current===r&&e.setErrorText(i(e.t.queueCollectAll,o,u))}finally{a()}}}}}(e);return{...e,setModel:Mt.setModel,setEffort:Mt.setEffort,setFastMode:Mt.setFastMode,queueControls:ss,listSessionModels:jn,loadDirectoryGitMetadata:Rn,rewindMessage:c,handleSessionCommandResponse:jt,handleServerMessage:Rt,failedSend:Tt,dismissFailedSend:Nt,retryFailedSend:At,stagePendingSession:Et,sendDraft:Pt,sendQuickReply:Dt,respondApproval:Ft,respondQuestion:Lt,cancelQuestion:qt,setQuestionChoice:Ot,requestActiveAction:$t,interruptActiveSession:zt,retrySessions:_t,updateApprovalMode:async e=>{Mt.setApprovalMode(e),ye&&!A[ye.sessionId]&&await Bt(e)},cancelQueuedTurn:Ut,setSessionPinned:Vt,setSessionArchived:Gt,deleteSession:Jt,updatePinned:Zt,updateArchived:Yt,renameSession:Xt,runArchiveSync:an,skipArchiveSync:cn,runAdminAction:ln,exportActiveSession:hn,clearPairing:mn,setNotificationsEnabled:yn,connectSavedTarget:vn,forgetSavedTarget:xn,openSessionDetails:wn,editFolderTags:Sn,browseFolder:kn,copyResumeCommand:In,resumeInTerminal:Cn,notificationsBlocked:En,hasDaemonUpdate:Tn,activeDaemonId:Fn,archiveSynced:qn,archiveSyncDismissed:Hn}}();return r.jsx(Wa,{scopeKey:bi(e.pairing?.daemonId,e.activeSessionId),children:r.jsx(Mi,{workspace:e,children:r.jsx(md,{workspace:e})})},e.pairing?.daemonId??"unpaired")}},Symbol.toStringTag,{value:"Module"}));export{fr as $,q as A,O as B,$ as C,Ka as D,vi as E,La as F,ce as G,Nn as H,de as I,ki as J,he as K,fe as L,ss as M,Ci as N,z as O,ke as P,_ as Q,Re as R,De as S,_e as T,se as U,ee as V,Ri as W,We as X,Rr as Y,Ue as Z,jr as _,Cs as a,yr as a0,gr as a1,Ir as a2,br as a3,Or as a4,Er as a5,cr as a6,Dr as a7,Pr as a8,kr as a9,Cr as aa,ur as ab,ul as ac,al as ad,Ts as ae,hl as af,rs as ag,pl as ah,fl as ai,gl as aj,sr as ak,Uo as al,je as am,ls as an,Ho as ao,qe as ap,lr as aq,fd as ar,Ss as b,Kn as c,Qn as d,Q as e,Jo as f,Js as g,ht as h,Ei as i,Ps as j,te as k,Ws as l,Ns as m,zs as n,_s as o,sd as p,ut as q,ys as r,st as s,ns as t,Es as u,$s as v,Fi as w,Bs as x,G as y,re as z};
|