vibelet 1.2.224 → 1.2.227
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/README.md +14 -37
- package/dist/index.cjs +1 -1
- package/dist/inventory-scan-worker.cjs +1 -1
- package/dist/{tailcat/vibelet-tailcat-darwin-amd64 → remoteDirect/vibelet-remote-direct-darwin-amd64} +0 -0
- package/dist/{tailcat/vibelet-tailcat-darwin-arm64 → remoteDirect/vibelet-remote-direct-darwin-arm64} +0 -0
- package/dist/{tailcat/vibelet-tailcat-linux-amd64 → remoteDirect/vibelet-remote-direct-linux-amd64} +0 -0
- package/dist/{tailcat/vibelet-tailcat-linux-arm64 → remoteDirect/vibelet-remote-direct-linux-arm64} +0 -0
- package/dist/{tailcat/vibelet-tailcat-win32-amd64.exe → remoteDirect/vibelet-remote-direct-win32-amd64.exe} +0 -0
- package/dist/{tailcat/vibelet-tailcat-win32-arm64.exe → remoteDirect/vibelet-remote-direct-win32-arm64.exe} +0 -0
- package/dist/runtime-version.cjs +1 -1
- package/dist/vibelet.mjs +282 -289
- package/dist/web/assets/App-DfyOZYmt.js +12 -0
- package/dist/web/assets/App-t0H-03RW.css +1 -0
- package/dist/web/assets/BrowserControlPanel-dQOp1WlN.js +1 -0
- package/dist/web/assets/ChipGroup-FQF2g0Fr.js +1 -0
- package/dist/web/assets/DiffDrawer-CHjkoGPE.js +2 -0
- package/dist/web/assets/FileCodeEditor-yqSvo7VZ.css +1 -0
- package/dist/web/assets/FilesControlPanel-A7LFhjRm.js +1 -0
- package/dist/web/assets/FilesControlPanel-DsKJrFYk.css +1 -0
- package/dist/web/assets/GlobalPendingDialog-BeOMI3dc.js +1 -0
- package/dist/web/assets/ImageViewer-BQ9YKQDY.js +1 -0
- package/dist/web/assets/ImageViewer-L8SQkFy1.css +1 -0
- package/dist/web/assets/LanguageSettingsPanel-Benilh-Y.js +1 -0
- package/dist/web/assets/NewSessionDialog-B0YMv6RR.js +1 -0
- package/dist/web/assets/NewSessionDialog-CxPwD87T.css +1 -0
- package/dist/web/assets/NotificationSettingsPanel-B_k_PfhC.js +1 -0
- package/dist/web/assets/TerminalControlPanel-DCmHOa9Y.js +13 -0
- package/dist/web/assets/ThemeSettingsPanel-DNDIWk0L.js +1 -0
- package/dist/web/assets/arrow-right-Boi1uHFr.js +1 -0
- package/dist/web/assets/collectMessageImages-BROUPbis.js +3 -0
- package/dist/web/assets/file-editor-FileCodeEditor-CTEWh6kV.js +13 -0
- package/dist/web/assets/file-editor-MarkdownLivePreview-Blr8OOKh.js +1 -0
- package/dist/web/assets/file-editor-clike-B9uivgTg.js +1 -0
- package/dist/web/assets/file-editor-go-CTD25R5P.js +1 -0
- package/dist/web/assets/file-editor-index-C1T947NK.js +13 -0
- package/dist/web/assets/file-editor-index-Cj9yLeGr.js +1 -0
- package/dist/web/assets/file-editor-index-Ckq0jexT.js +6 -0
- package/dist/web/assets/file-editor-index-CxU5Gq1E.js +1 -0
- package/dist/web/assets/file-editor-index-Dv8iMJMj.js +3 -0
- package/dist/web/assets/file-editor-index-DvdSLdIk.js +1 -0
- package/dist/web/assets/file-editor-index-DvenUGpC.js +1 -0
- package/dist/web/assets/file-editor-index-iFiQtQEr.js +1 -0
- package/dist/web/assets/file-editor-rust-Bh1DdySD.js +1 -0
- package/dist/web/assets/file-editor-shell-CjFT_Tl9.js +1 -0
- package/dist/web/assets/file-editor-sql-B0zzsL_y.js +1 -0
- package/dist/web/assets/file-editor-swift-BzpIVaGY.js +1 -0
- package/dist/web/assets/file-editor-toml-Bm5Em-hy.js +1 -0
- package/dist/web/assets/file-editor-yaml-DsCXHVTH.js +1 -0
- package/dist/web/assets/folder-plus-tHXFtdSw.js +1 -0
- package/dist/web/assets/ghostty-vt-DOMeXDrv.wasm +0 -0
- package/dist/web/assets/highlighted-body-TPN3WLV5-D5c7I9mI.js +1 -0
- package/dist/web/assets/index-CoCv7_xG.css +1 -0
- package/dist/web/assets/index-P4_gSQhN.js +71 -0
- package/dist/web/assets/mermaid-O7DHMXV3-BIyESbw5.js +120 -0
- package/dist/web/assets/mermaid-O7DHMXV3-tkqeC_Xz.css +1 -0
- package/dist/web/ghostty-license.txt +21 -0
- package/dist/web/index.html +2 -2
- package/package.json +3 -3
- package/dist/web/assets/App-CAJ3pB85.js +0 -12
- package/dist/web/assets/ArchiveSyncPanel-_lLATKjA.js +0 -1
- package/dist/web/assets/ConnectionSettingsPanel-4MhvD7ra.js +0 -1
- package/dist/web/assets/DaemonSettingsPanel-zHBCPi0h.js +0 -1
- package/dist/web/assets/DiffDrawer-BGx5Fl6h.js +0 -2
- package/dist/web/assets/FilesControlPanel-D7SPEihe.js +0 -2
- package/dist/web/assets/LanguageSettingsPanel-Bofh0WHQ.js +0 -1
- package/dist/web/assets/NotificationSettingsPanel-BafuO9ww.js +0 -1
- package/dist/web/assets/SavedTargetsPanel-lutvzUOp.js +0 -1
- package/dist/web/assets/ThemeSettingsPanel-ARFGBpot.js +0 -1
- package/dist/web/assets/file-text-CpofUkq8.js +0 -1
- package/dist/web/assets/highlighted-body-TPN3WLV5-CEWZdsEu.js +0 -1
- package/dist/web/assets/index-CFMLtw93.css +0 -1
- package/dist/web/assets/index-D3KotGfi.js +0 -17
- package/dist/web/assets/mermaid-O7DHMXV3-BPtfCfol.css +0 -1
- package/dist/web/assets/mermaid-O7DHMXV3-DuCy9NVb.js +0 -124
- /package/dist/web/assets/{splash-logo-SQcOtj-8.png → logo-SQcOtj-8.png} +0 -0
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid-O7DHMXV3-BIyESbw5.js","assets/index-P4_gSQhN.js","assets/index-CoCv7_xG.css","assets/collectMessageImages-BROUPbis.js","assets/mermaid-O7DHMXV3-tkqeC_Xz.css","assets/ImageViewer-BQ9YKQDY.js","assets/arrow-right-Boi1uHFr.js","assets/ImageViewer-L8SQkFy1.css","assets/BrowserControlPanel-dQOp1WlN.js","assets/TerminalControlPanel-DCmHOa9Y.js","assets/DiffDrawer-CHjkoGPE.js","assets/FilesControlPanel-A7LFhjRm.js","assets/folder-plus-tHXFtdSw.js","assets/FilesControlPanel-DsKJrFYk.css","assets/LanguageSettingsPanel-Benilh-Y.js","assets/ChipGroup-FQF2g0Fr.js","assets/ThemeSettingsPanel-DNDIWk0L.js","assets/NotificationSettingsPanel-B_k_PfhC.js","assets/file-editor-FileCodeEditor-CTEWh6kV.js","assets/FileCodeEditor-yqSvo7VZ.css","assets/NewSessionDialog-B0YMv6RR.js","assets/NewSessionDialog-CxPwD87T.css","assets/GlobalPendingDialog-BeOMI3dc.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as L,e as He,l as Be,j as s,r as o,i as It,m as re,S as qi,k as Ge,n as Wi,u as En,E as Pr,o as ps,_ as tt,D as Kn,p as as,q as rn,t as gs,v as yn,w as Hi,x as Bi,s as hn,y as zi,z as Ui,A as Gi,B as Vi,C as Ki}from"./index-P4_gSQhN.js";const Qi=[["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"}]],Zi=L("activity",Qi);const Ji=[["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"}]],Yi=L("archive-restore",Ji);const Xi=[["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"}]],Ms=L("archive",Xi);const ea=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],ta=L("arrow-down",ea);const na=[["path",{d:"M3 19V5",key:"rwsyhb"}],["path",{d:"m13 6-6 6 6 6",key:"1yhaz7"}],["path",{d:"M7 12h14",key:"uoisry"}]],sa=L("arrow-left-to-line",na);const ra=[["path",{d:"M17 12H3",key:"8awo09"}],["path",{d:"m11 18 6-6-6-6",key:"8c2y43"}],["path",{d:"M21 5v14",key:"nzette"}]],ia=L("arrow-right-to-line",ra);const aa=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],oa=L("arrow-up",aa);const ca=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],Dt=L("check",ca);const la=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],_r=L("chevron-down",la);const da=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Dr=L("chevron-right",da);const ua=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],ha=L("chevron-up",ua);const fa=[["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"}]],Lr=L("circle-alert",fa);const ma=[["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"}]],pa=L("clipboard",ma);const ga=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],ya=L("clock-3",ga);const ba=[["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"}]],va=L("code-xml",ba);const xa=[["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"}]],on=L("copy",xa);const wa=[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M4 20v-7a4 4 0 0 1 4-4h12",key:"1lu4f8"}]],Sa=L("corner-up-right",wa);const ka=[["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"}]],os=L("cpu",ka);const ja=[["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"}]],Ca=L("ellipsis",ja);const Ia=[["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"}]],Na=L("eye",Ia);const Aa=[["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"}]],Ea=L("file-pen-line",Aa);const Ra=[["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"}]],$r=L("file-text",Ra);const Ta=[["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"}]],zn=L("folder-open",Ta);const Ma=[["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"}]],Pa=L("folder",Ma);const _a=[["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"}]],Da=L("funnel",_a);const La=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Ct=L("gauge",La);const $a=[["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"}]],Qn=L("git-compare",$a);const Fa=[["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"}]],Oa=L("git-merge",Fa);const qa=[["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"}]],Fr=L("globe",qa);const Wa=[["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"}]],Ha=L("hash",Wa);const Ba=[["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"}]],za=L("image-off",Ba);const Ua=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],Or=L("info",Ua);const Ga=[["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"}]],Va=L("key-round",Ga);const Ka=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],Rn=L("loader-circle",Ka);const Qa=[["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"}]],qr=L("message-circle",Qa);const Za=[["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"}]],Wr=L("mic",Za);const Ja=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],Ya=L("panel-left",Ja);const Xa=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],eo=L("panel-right",Xa);const to=[["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"}]],Hr=L("paperclip",to);const no=[["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"}]],so=L("pencil",no);const ro=[["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"}]],Zn=L("pin",ro);const io=[["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"}]],Br=L("plug-zap",io);const ao=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Jn=L("plus",ao);const oo=[["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"}]],xn=L("refresh-cw",oo);const co=[["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"}]],zr=L("rotate-ccw",co);const lo=[["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"}]],uo=L("save",lo);const ho=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],wn=L("search",ho);const fo=[["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"}]],mo=L("send",fo);const po=[["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"}]],go=L("settings",po);const yo=[["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"}]],Ps=L("shield-check",yo);const bo=[["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"}]],Ur=L("sliders-horizontal",bo);const vo=[["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"}]],xo=L("sparkles",vo);const wo=[["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"}]],Yn=L("square-terminal",wo);const So=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Gr=L("square",So);const ko=[["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"}]],Vr=L("tag",ko);const jo=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],_s=L("terminal",jo);const Co=[["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"}]],Kr=L("trash-2",Co);const Io=[["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"}]],No=L("upload",Io);const Ao=[["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"}]],Eo=L("wrench",Ao);const Ro=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],De=L("x",Ro);const To=[["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"}]],nn=L("zap",To),Mo="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20width='256'%20height='256'%20viewBox='0%200%2035%2035'%20shape-rendering='crispEdges'%3e%3cpath%20fill='%23ffffff'%20d='M0%200h35v35H0z'/%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",Po="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 Un(){const e=He(Be().language);return e==="en"?{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."}:e==="zh-TW"?{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 Qr(){const e=Un();return s.jsxs("section",{className:"mobile-companion-panel control-section",children:[s.jsx("p",{className:"mobile-companion-free",children:e.free}),s.jsx("h2",{children:e.title}),s.jsx("p",{children:e.description}),s.jsx("div",{className:"mobile-companion-downloads",children:[{label:e.ios,qr:Po,url:"https://apps.apple.com/app/id6761245790"},{label:e.android,qr:Mo,url:"https://www.feishu.cn/file/RUnbb7INMocEFjxj5AWcC7WEn6d"}].map(t=>s.jsxs("div",{children:[s.jsx("img",{src:t.qr,alt:`${t.label} · ${e.download}`,width:"140",height:"140"}),s.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",children:t.label})]},t.url))}),s.jsx("p",{children:e.pairing}),s.jsx("p",{className:"mobile-companion-hint",children:e.pro})]})}function _o({onClose:e}){const t=o.useRef(null);o.useEffect(()=>{const r=document.activeElement,i=document.getElementById("vibelet-workspace"),a=i?.inert;return i&&(i.inert=!0),t.current?.focus(),()=>{i&&(i.inert=!!a),r?.focus()}},[]);const n=Un().title;return It.createPortal(s.jsx("div",{className:"mobile-companion-backdrop",onClick:r=>{r.target===r.currentTarget&&e()},children:s.jsxs("section",{ref:t,className:"mobile-companion-dialog",role:"dialog","aria-modal":"true","aria-label":n,tabIndex:-1,onKeyDown:r=>{if(r.key==="Escape"&&(r.preventDefault(),r.stopPropagation(),e()),r.key!=="Tab")return;const i=Array.from(r.currentTarget.querySelectorAll("button,a[href]")),a=i[0],c=i.at(-1);r.shiftKey&&(document.activeElement===a||document.activeElement===t.current)?(r.preventDefault(),c?.focus()):!r.shiftKey&&document.activeElement===c&&(r.preventDefault(),a?.focus())},children:[s.jsx("button",{type:"button",className:"icon-button mobile-companion-close","aria-label":Un().close,onClick:e,children:s.jsx(De,{"aria-hidden":"true"})}),s.jsx(Qr,{})]})}),document.body)}function Do({activeSession:e,busy:t,controlsOpen:n,t:r,onOpenControls:i,onRefreshSessions:a,onRestoreSnapshot:c,onToggleArchived:l,onTogglePinned:u,onViewChanges:h}){const[d,f]=o.useState(!1),[x,b]=o.useState(!1),S=o.useRef(null);o.useEffect(()=>{if(!x)return;const g=w=>{w.target instanceof Node&&!S.current?.contains(w.target)&&b(!1)},j=w=>{w.key==="Escape"&&b(!1)};return document.addEventListener("pointerdown",g),document.addEventListener("keydown",j),()=>{document.removeEventListener("pointerdown",g),document.removeEventListener("keydown",j)}},[x]);const v=g=>{b(!1),g()},m=re(),p=s.jsxs("div",{className:"header-actions",children:[d&&s.jsx(_o,{onClose:()=>f(!1)}),e?null:s.jsx("button",{"aria-label":r.refreshSessions,className:"icon-button",onClick:a,title:r.refreshSessions,type:"button",children:s.jsx(xn,{"aria-hidden":"true"})}),s.jsx("button",{"aria-expanded":n,"aria-label":n?r.collapseControlsSidebar:r.workspaceTools,title:n?r.collapseControlsSidebar:r.workspaceTools,className:"header-tool-button",onClick:i,type:"button",children:s.jsx(eo,{"aria-hidden":"true"})}),e||m.openSettings?s.jsxs("div",{className:"header-more-wrap",ref:S,children:[s.jsx("button",{"aria-expanded":x,"aria-haspopup":"menu","aria-label":r.moreActions,className:"icon-button",onClick:()=>b(g=>!g),title:r.moreActions,type:"button",children:s.jsx(Ca,{"aria-hidden":"true"})}),x?s.jsxs("div",{className:"header-action-menu",role:"menu",children:[e&&s.jsxs(s.Fragment,{children:[s.jsxs("button",{onClick:()=>v(()=>h(e.sessionId)),role:"menuitem",type:"button",children:[s.jsx(Qn,{"aria-hidden":"true"}),s.jsx("span",{children:r.viewChanges})]}),s.jsxs("button",{disabled:t,onClick:()=>v(u),role:"menuitem",type:"button",children:[s.jsx(Zn,{"aria-hidden":"true"}),s.jsx("span",{children:e.pinned?r.unpin:r.pin})]}),s.jsxs("button",{disabled:t,onClick:()=>v(l),role:"menuitem",type:"button",children:[s.jsx(Ms,{"aria-hidden":"true"}),s.jsx("span",{children:e.archived?r.unarchive:r.archive})]}),s.jsxs("button",{onClick:()=>v(c),role:"menuitem",type:"button",children:[s.jsx(zr,{"aria-hidden":"true"}),s.jsx("span",{children:r.restoreSnapshot})]})]}),s.jsxs("button",{role:"menuitem",type:"button",onClick:()=>v(()=>f(!0)),children:[s.jsx(qi,{"aria-hidden":"true"}),s.jsx("span",{children:Un().title})]}),m.openSettings&&s.jsxs("button",{role:"menuitem",type:"button",onClick:()=>v(m.openSettings),children:[s.jsx(go,{"aria-hidden":"true"}),s.jsx("span",{children:r.settings})]}),s.jsxs("button",{onClick:()=>v(a),role:"menuitem",type:"button",children:[s.jsx(xn,{"aria-hidden":"true"}),s.jsx("span",{children:r.refreshSessions})]})]}):null]}):null]}),y=m.toolbarTarget?.("right");return y?It.createPortal(p,y):p}const Lo=/^[A-Za-z][A-Za-z0-9_-]*$/,$o=[{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 Zr(e){return $o.filter(t=>!e||t.agents.includes(e))}function Ds(e){return e.trim().toLowerCase()}function qn(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&&!Lo.test(n)?null:{start:0,end:e.length,keyword:Ds(n)}}function Fo(e,t,n=8){const r=Ds(t);return(r?e.filter(a=>a.name.includes(r)||a.title.toLowerCase().includes(r)).sort((a,c)=>Ys(a,r)-Ys(c,r)):[...e]).slice(0,n)}function Ys(e,t){return e.name===t?0:e.name.startsWith(t)?1:e.name.includes(t)?2:3}function Oo(e,t,n){return`${e.slice(0,t.start)}${Jr(n,"")}${e.slice(t.end)}`}function qo(e,t,n){return t?Oo(e,t,n):`${Jr(n,e)}${e}`}function Jr(e,t){const n=t.length>0,r=n&&!/^\s/.test(t),i=!!(e.argsHint&&!n);return`/${e.name}${i||r?" ":""}`}function Xs(e,t){const n=e.trim();if(!n.startsWith("/")||n.startsWith("//"))return null;const r=/^\/([A-Za-z][A-Za-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(n);if(!r)return null;const i=Ds(r[1]??""),a=Zr(t).find(l=>l.name===i);if(!a)return null;const c=r[2]?.trim()??"";switch(a.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 l=c.toLowerCase();return!c||l==="status"||l==="show"||l==="usage"||l==="help"?{raw:n,command:{name:"goal",operation:"status"}}:l==="clear"||l==="reset"?{raw:n,command:{name:"goal",operation:"clear"}}:l==="pause"||l==="paused"?{raw:n,command:{name:"goal",operation:"pause"}}:l==="resume"||l==="active"?{raw:n,command:{name:"goal",operation:"resume"}}:{raw:n,command:{name:"goal",operation:"set",objective:c}}}}}function Wo(e){return e.startsWith("//")?e.slice(1):e}function Ho(e){return e.name==="compact"?"/compact":e.name!=="goal"?null:e.operation==="clear"?"/goal clear":e.operation==="pause"?"/goal pause":e.operation==="resume"?"/goal resume":e.operation==="set"&&e.objective?.trim()?`/goal ${e.objective.trim()}`:"/goal"}function Bo(e){const t=typeof e?.objective=="string"?e.objective.trim():"";return t?`Goal${typeof e?.status=="string"&&e.status?` (${e.status})`:""}: ${t}`:"Goal: none."}function er(e){return e==="subscriptionRequired"?"Error: Agent commands require an active Pro subscription.":`Error: ${e||"Command failed."}`}function zo(e,t){return!t||!qn(e)?e:t.draftBeforeInsertion}const Yr="vibelet.web.notificationSettings",qt={enabled:!1,approvals:!0,questions:!0,replies:!0,hiddenOnly:!0};function ys(e=Ge()){try{const t=e.getItem(Yr);if(!t)return{...qt};const n=JSON.parse(t);return vn(n)?{enabled:typeof n.enabled=="boolean"?n.enabled:qt.enabled,approvals:typeof n.approvals=="boolean"?n.approvals:qt.approvals,questions:typeof n.questions=="boolean"?n.questions:qt.questions,replies:typeof n.replies=="boolean"?n.replies:qt.replies,hiddenOnly:typeof n.hiddenOnly=="boolean"?n.hiddenOnly:qt.hiddenOnly}:{...qt}}catch{return{...qt}}}function Uo(e,t=Ge()){t.setItem(Yr,JSON.stringify(e))}function bn(e=typeof Notification>"u"?void 0:Notification){return re().notifications?re().notifications.permission():e?.permission??"unsupported"}function Go(e,t,n=typeof document>"u"?"visible":document.visibilityState){return!(!e.enabled||t!=="granted"||e.hiddenOnly&&n==="visible")}function Vo(e,t,n={}){const r=n.notificationFactory??(typeof Notification>"u"?void 0:Notification);if(!r&&!re().notifications)return!1;const i=n.settings??{enabled:!0,hiddenOnly:!1},a=n.permission??bn(),c=n.visibilityState??(typeof document>"u"?"visible":document.visibilityState);if(!Go(i,a,c))return!1;if(re().notifications)return re().notifications.show(e,t,n.onClick),!0;const l=new r(e,{body:t,tag:n.tag});return n.onClick&&(l.onclick=n.onClick),!0}function Xr(e,t){return e.role===t.role&&(e.type??"message")===(t.type??"message")&&e.content===t.content&&JSON.stringify(e.images??[])===JSON.stringify(t.images??[])&&e.toolName===t.toolName&&JSON.stringify(e.toolInput)===JSON.stringify(t.toolInput)}function Ko(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??"")&&Xr(e,t)}function Qo(e){for(let t=e.length-1;t>=0;t-=1)if(e[t]?.role==="user")return t;return-1}function Zo(e,t){const n=e.slice(),r=new Set;for(const i of t){if((i.historyKey?n.findIndex(l=>l.historyKey===i.historyKey):-1)>=0)continue;const c=n.findIndex((l,u)=>r.has(u)?!1:Ko(l,i)?!0:l.historyKey&&!l.historyKey.startsWith("client:")?!1:l.liveReply&&u===n.length-1&&i.role==="assistant"&&i.type!=="info"?l.content.length>0&&i.content.startsWith(l.content):!!(i.historyKey&&!i.historyKey.startsWith("client:")&&l.historyKey?.startsWith("client:")&&l.role==="user"&&u===Qo(n)&&n.slice(u+1).every(h=>h.role!=="assistant"||h.type==="info"||h.liveReply)&&Xr(l,i)));c<0?n.push({...i}):(r.add(c),n[c]={...n[c],...i},delete n[c].liveReply)}return n}function Ls(e){const t=e.at(-1);return t?.role==="assistant"&&t.type!=="info"?[...e.slice(0,-1),{...t,liveReply:!0}]:e.slice()}const Jo=".",Yo="@vibelet/needs-attention",Xo="@vibelet/running",ec="@vibelet/pinned";function tc(e,t={}){const n=new Map,r=[],i=[],a=[];for(const l of e){const u=l.archived!==!0;if(!!(t.showNeedsAttentionGroup&&u&&(t.needsAttentionSessionIds?.has(l.sessionId)||l.runtime.needsAttention||l.interruptReason||l.stallWarning))?r.push(l):t.showRunningGroup&&u&&t.respondingSessionIds?.has(l.sessionId)&&i.push(l),t.separatePinnedGroup&&u&&l.pinned){a.push(l);continue}const d=l.cwd||Jo;n.set(d,[...n.get(d)??[],l])}const c=[];if(r.length>0&&c.push({folder:Yo,kind:"attention",sessions:r}),i.length>0){const l=new Map(t.runningSessionOrder?.map((u,h)=>[u,h]));c.push({folder:Xo,kind:"running",sessions:l.size?[...i].sort((u,h)=>(l.get(u.sessionId)??Number.MAX_SAFE_INTEGER)-(l.get(h.sessionId)??Number.MAX_SAFE_INTEGER)):i})}return a.length>0&&c.push({folder:ec,kind:"pinned",sessions:[...a].sort((l,u)=>Date.parse(u.lastActivityAt)-Date.parse(l.lastActivityAt))}),[...c,...Array.from(n.entries()).map(([l,u])=>({folder:l,kind:"folder",sessions:u}))]}function Xn(e,t=Date.now(),n=Wi){if(!e)return n.timeUnknown;const r=Date.parse(e);if(!Number.isFinite(r))return n.timeUnknown;const i=t-r,a=60*1e3,c=60*a,l=24*c;return i<a?n.timeNow:i<c?n.timeMinutesAgo(Math.floor(i/a)):i<l?n.timeHoursAgo(Math.floor(i/c)):n.timeDaysAgo(Math.floor(i/l))}function ei(e,t){return e.type==="info"?t.messageInfoRole:{user:t.messageUserRole,assistant:t.messageAssistantRole,tool:t.messageToolRole}[e.role]}function ti(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e;return typeof t.lastActivityAt=="string"&&typeof t.sessionId=="string"?{lastActivityAt:t.lastActivityAt,sessionId:t.sessionId}:void 0}const Qe=".",$s="normal",tr=80,nc=1600,sc="pending_local_";function vn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function rc(e){if(!Number.isFinite(e))return"unknown";const t=e??0;return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function St(e){return e.customTitle||e.title||e.sessionId.slice(0,10)}function Fs(e,t){const n=e[e.length-1];return n?.role==="assistant"&&n.type!=="info"?[...e.slice(0,-1),{...n,content:`${n.content}${t}`}]:[...e,{role:"assistant",content:t,timestamp:new Date().toISOString()}]}function ni(e){const t=e;return{sessions:Array.isArray(t.sessions)?t.sessions:[],nextCursor:ti(t.nextCursor),inventoryVersion:t.inventoryVersion,inventoryBackfillInFlight:t.inventoryBackfillInFlight,folderCounts:t.folderCounts}}function ic(e){const t=e;return typeof t.sessionId=="string"?t.sessionId:null}function ac(e){const t=e;return typeof t.path=="string"?t.path:null}function _t(e){return e.split("/").filter(Boolean).at(-1)??e}function oc(e){return Object.entries(e).length===0?"No structured input.":JSON.stringify(e,null,2)}function Os(e){return Object.fromEntries(e.questions.map(t=>[t.id,t.options[0]?[t.options[0].label]:[]]))}function $n(e){return e.trim()||void 0}function nr(e){if(e==="7d")return Date.now()-7*864e5;if(e==="30d")return Date.now()-30*864e5;if(e==="90d")return Date.now()-90*864e5}function bs(e,t){const n=new Map;for(const r of e)n.set(r.sessionId,r);for(const r of t)n.set(r.sessionId,{...n.get(r.sessionId),...r});return Array.from(n.values()).sort((r,i)=>{const a=r.pinned?r.pinnedAt??0:0,c=i.pinned?i.pinnedAt??0:0;return a!==c?c-a:Date.parse(i.lastActivityAt)-Date.parse(r.lastActivityAt)})}let cs=0;function cc(e=Date.now()){return cs=(cs+1)%1e4,`${sc}${e}_${cs}`}function lc(e){const t=e.now??new Date().toISOString();return{sessionId:e.sessionId,agent:e.agent,cwd:e.cwd||Qe,...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}}function dc(e,t,n=new Date().toISOString()){return{...e,sessionId:t,lastActivityAt:n}}function ls(e,t,n){if(!t||!n||t===n||!Object.hasOwn(e,t))return e;const{[t]:r,...i}=e;return{...i,[n]:r}}function sr(e,t,n){if(!t||!n||t===n||!e.has(t))return e;const r=new Set(e);return r.delete(t),r.add(n),r}function uc(e,t){const n=e.replace(/\\/g,"/").replace(/\/+$/,"");return!n||n==="."?t:`${n}/${t}`}function Qh(e){const t=e.replace(/\\/g,"/").replace(/\/+$/,"");if(!t||t==="/"||t==="~"||t===".")return null;const n=t.lastIndexOf("/");return n<0?".":n===0?"/":t.slice(0,n)}function hc(e,t){return t.startsWith("text/")||t.includes("json")||t.includes("xml")||t.includes("javascript")?!0:/\.(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)}function fc(e,t){return t.startsWith("image/")||/\.(png|jpe?g|gif|webp|heic|heif|svg)$/i.test(e)}function Wn(e,t,n=window.location.origin){const r=new URL("/file",n);return r.searchParams.set("path",e),t&&r.searchParams.set("cwd",t),r.toString()}function Fn(e,t){return e.get(t)||void 0}function mc(e,t){return`${e.replace(/[<>:"/\\|?*\u0000-\u001F]/g," ").replace(/\s+/g," ").trim().slice(0,80)||t.slice(0,12)||"session"}.txt`}function pc(e,t){const n=[`# ${St(e)}`,"",`- Agent: ${e.agent}`,`- Session: \`${e.sessionId}\``,`- Working directory: \`${e.cwd}\``,`- Created: ${e.createdAt}`,`- Exported: ${new Date().toISOString()}`,""];for(const r of t){if(r.role!=="user"&&r.role!=="assistant")continue;const i=r.content.trim(),a=(r.images??[]).map(c=>`- Attachment: \`${c}\``);!i&&a.length===0||(n.push(`## ${r.role==="user"?"User":"Assistant"}`,""),i&&n.push(i,""),a.length&&n.push(...a,""))}return n.join(`
|
|
3
|
+
`).trimEnd()}function si(e){const t=[`cd ${gc(e.cwd||Qe)} &&`],n=e.approvalMode??e.observedApprovalMode;return e.agent==="claude"?(t.push("claude","--resume",e.sessionId),n==="autoApprove"?t.push("--dangerously-skip-permissions"):n==="acceptEdits"&&t.push("--permission-mode","acceptEdits"),t.join(" ")):(t.push("codex","resume",e.sessionId),n==="autoApprove"&&t.push("--dangerously-bypass-approvals-and-sandbox"),t.join(" "))}function gc(e){return/^[a-zA-Z0-9._/~-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function yc(e,t){const n=URL.createObjectURL(new Blob([t],{type:"text/plain;charset=utf-8"})),r=document.createElement("a");r.href=n,r.download=e,r.click(),URL.revokeObjectURL(n)}function bc(e,t={}){const n=new Set,r={},i={},a={};for(const b of e.sessions)(b.runtime.isResponding||b.runtime.state==="daemonActive")&&n.add(b.sessionId);for(const b of e.pendingApprovals??[])r[b.sessionId]={type:"approval.request",...b};for(const b of e.pendingQuestions??[])i[b.sessionId]={type:"question.request",...b};let c=null,l,u,h,d,f,x;if(e.activeSession){const b=e.activeSession,S=e.sessions.find(m=>m.sessionId===b.sessionId);c=b.sessionId,l=b.agent,u=S?.cwd||t.currentCwd||Qe,h=b.approvalMode??S?.approvalMode??$s,d=b.approvalMode??null;const v=b.messages??[];if(f=b.partialReplyText?Ls(Fs(v,b.partialReplyText)):v,(b.isResponding||b.externallyResponding)&&n.add(b.sessionId),b.pendingApproval&&(r[b.sessionId]={type:"approval.request",sessionId:b.sessionId,...b.pendingApproval}),b.pendingQuestion){const m={type:"question.request",sessionId:b.sessionId,...b.pendingQuestion};i[b.sessionId]=m,x=Os(m)}b.pendingQueue?.length&&(a[b.sessionId]=b.pendingQueue)}else{const b=t.currentActiveSessionId??null;if(b){const S=e.sessionAliases?.[b];S?c=S:e.sessions.some(v=>v.sessionId===b)&&(c=b)}c=c??e.sessions[0]?.sessionId??null}return{page:{sessions:e.sessions,nextCursor:ti(e.nextCursor),inventoryVersion:e.inventoryVersion,inventoryBackfillInFlight:e.inventoryBackfillInFlight},activeSessionId:c,activeAgent:l,activeCwd:u,activeApprovalMode:h,activeApprovalOverride:d,messages:f,respondingSessionIds:Array.from(n),pendingApprovals:r,pendingQuestions:i,pendingQueues:a,questionAnswers:x}}function rr(e,t){if(e==="subscriptionRequired"){const n=typeof window>"u"?"en":He(Be().language);return n==="en"?"Computer features are free. Update Vibelet on the paired computer and reconnect.":n==="zh-TW"?"電腦端功能免費。請更新配對電腦上的 Vibelet,再重新連線。":"电脑端功能免费。请更新配对电脑上的 Vibelet,再重新连接。"}return e==="skillNotFound"?"Skill not found on the paired computer.":e==="skillResolveFailed"?"Could not load the skill on the paired computer.":e}const vc=/^[A-Za-z_][A-Za-z0-9._:-]*$/,xc=/(?:^|\s)\$([A-Za-z_][A-Za-z0-9._:-]*|)$/;function Sn(e){return e.trim().toLowerCase()}function ir(e){const t=e.trim(),n=/^\$([A-Za-z_][A-Za-z0-9._:-]*)(?:\s+([\s\S]*))?$/.exec(t);return n?{name:Sn(n[1]??""),...n[2]?.trim()?{args:n[2].trim()}:{}}:null}function Hn(e){const t=xc.exec(e);if(!t||t.index+t[0].length!==e.length)return null;const n=t[1]??"";if(n&&!vc.test(n))return null;const r=t[0].lastIndexOf("$");return{start:t.index+r,end:e.length,keyword:Sn(n)}}function wc(e,t,n){return`${e.slice(0,t.start)}$${Sn(n)} ${e.slice(t.end)}`}function Sc(e,t){if(!t)return e;const n=Hn(e);if(!n||n.start!==t.triggerStart)return e;const r=n.start>t.draftBeforeInsertion.length?" ":"";return e.slice(0,n.start)!==`${t.draftBeforeInsertion}${r}`?e:t.draftBeforeInsertion}function kc(e,t,n=8){const r=Sn(t);return(r?e.filter(a=>Sn(a.name).includes(r)):e).slice(0,n)}function gn({icon:e,label:t,menuLabel:n,options:r,value:i,onSelect:a,align:c="left",disabled:l,selected:u,wide:h}){const[d,f]=o.useState(!1),x=o.useRef(null),b=o.useRef(null),S=r.some(v=>v.icon);return o.useEffect(()=>{if(!d)return;const v=x.current?.querySelectorAll('[role="menuitemradio"]:not(:disabled)');([...v??[]].find(y=>y.getAttribute("aria-checked")==="true")??v?.[0])?.focus();const p=y=>{y.target instanceof Node&&!x.current?.contains(y.target)&&f(!1)};return document.addEventListener("pointerdown",p),()=>document.removeEventListener("pointerdown",p)},[d]),s.jsxs("div",{className:"composer-menu",ref:x,onBlur:v=>{const m=v.relatedTarget;(!m||!v.currentTarget.contains(m))&&f(!1)},onKeyDown:v=>{if(v.key==="Escape"&&(v.preventDefault(),f(!1),b.current?.focus()),!["ArrowDown","ArrowUp","Home","End"].includes(v.key))return;if(v.preventDefault(),!d){f(!0);return}const m=[...v.currentTarget.querySelectorAll('[role="menuitemradio"]:not(:disabled)')];if(!m.length)return;const p=m.indexOf(document.activeElement),y=v.key==="Home"?0:v.key==="End"?m.length-1:(p+(v.key==="ArrowDown"?1:-1)+m.length)%m.length;m[y]?.focus()},children:[s.jsxs("button",{ref:b,"aria-expanded":d,"aria-haspopup":"menu",className:`composer-option-button ${d||u?"selected":""}`,disabled:l,onClick:()=>f(v=>!v),title:n,type:"button",children:[s.jsx(e,{"aria-hidden":"true"}),s.jsx("span",{children:t}),d?s.jsx(ha,{"aria-hidden":"true"}):s.jsx(_r,{"aria-hidden":"true"})]}),d?s.jsx("div",{"aria-label":n,className:`composer-option-popover ${S?"":"without-icons"} ${h?"wide":""} ${c==="right"?"align-right":""}`,role:"menu",children:r.map(v=>{const m=v.icon,p=v.value===i;return s.jsxs("button",{"aria-checked":p,className:p?"selected":"",disabled:v.disabled,onClick:()=>{a(v.value),f(!1),b.current?.focus()},role:"menuitemradio",title:v.description??v.label,type:"button",children:[S&&s.jsx("span",{className:"composer-menu-icon",children:m?s.jsx(m,{"aria-hidden":"true"}):null}),s.jsxs("span",{className:"composer-menu-copy",children:[s.jsx("strong",{children:v.label}),v.description?s.jsx("small",{children:v.description}):null]}),s.jsx("span",{className:"composer-menu-indicator","aria-hidden":"true",children:p?s.jsx(Dt,{className:"composer-menu-check"}):null})]},v.value)})}):null]})}function ri(e,t,n){const r=o.useRef(null);return o.useEffect(()=>{n&&document.getElementById(`${e}-${t}`)?.scrollIntoView({block:"nearest"})},[e,t,n]),r}function jc({visible:e,listId:t,selectedIndex:n,onHighlight:r,skills:i,onClose:a,onSelect:c,t:l}){const u=ri(t,n,e);return e?s.jsxs("div",{className:"skill-suggestion-popover",children:[s.jsxs("header",{children:[s.jsx("strong",{children:l.skills}),s.jsx("button",{type:"button",className:"icon-button",onClick:a,title:l.closeSkills,children:s.jsx(De,{"aria-hidden":"true"})})]}),i.length?s.jsx("div",{className:"skill-suggestion-list",id:t,role:"listbox",ref:u,children:i.map((h,d)=>s.jsxs("button",{id:`${t}-${d}`,role:"option","aria-selected":n===d,onMouseEnter:()=>r(d),onClick:()=>c(h),title:h.description??h.name,type:"button",children:[s.jsxs("span",{children:[s.jsxs("strong",{children:["$",h.name]}),h.description?s.jsx("small",{children:h.description}):null]}),s.jsx("em",{children:h.source})]},`${h.source}:${h.name}`))}):s.jsx("p",{children:l.noSkillsFound})]}):null}function Cc({visible:e,listId:t,selectedIndex:n,onHighlight:r,commands:i,onClose:a,onSelect:c,t:l}){const u=ri(t,n,e);return e?s.jsxs("div",{className:"skill-suggestion-popover command-suggestion-popover",children:[s.jsxs("header",{children:[s.jsx("strong",{children:l.commands}),s.jsx("button",{type:"button",className:"icon-button",onClick:a,title:l.closeCommands,children:s.jsx(De,{"aria-hidden":"true"})})]}),i.length?s.jsx("div",{className:"skill-suggestion-list",id:t,role:"listbox",ref:u,children:i.map((h,d)=>s.jsxs("button",{id:`${t}-${d}`,role:"option","aria-selected":n===d,onMouseEnter:()=>r(d),onClick:()=>c(h),title:h.description,type:"button",children:[s.jsxs("span",{children:[s.jsxs("strong",{children:["/",h.name]}),s.jsx("small",{children:h.argsHint?`${h.title} ${h.argsHint}`:h.title})]}),s.jsx("em",{children:h.source})]},h.name))}):s.jsx("p",{children:l.noCommandsFound})]}):null}function Ic({queue:e,controls:t,busy:n,t:r,onCancel:i}){const[a,c]=o.useState(new Set),l=e.filter(f=>f.clientMessageId),u=l.filter(f=>a.has(f.clientMessageId)),h=n||t.busy,d=u.length?u:l;return e.length?s.jsxs("section",{className:"composer-queue-banner","aria-label":r.queuedTurns(e.length),children:[s.jsxs("header",{className:"composer-queue-heading",children:[s.jsx("strong",{children:r.queuedTurns(e.length)}),s.jsx("button",{type:"button",disabled:h||!l.length,onClick:()=>c(l.length>0&&u.length===l.length?new Set:new Set(l.map(f=>f.clientMessageId))),children:l.length>0&&u.length===l.length?r.queueClearSelection:r.queueSelectAll})]}),s.jsx("div",{className:"composer-queue-list",children:e.map((f,x)=>s.jsxs("div",{className:"composer-queue-item",children:[s.jsx("input",{type:"checkbox","aria-label":r.selectQueuedTurn(x+1),checked:!!f.clientMessageId&&a.has(f.clientMessageId),disabled:h||!f.clientMessageId,onChange:()=>c(b=>{const S=new Set(b),v=f.clientMessageId;return S.has(v)?S.delete(v):S.add(v),S})}),s.jsx("span",{title:f.content,children:f.content||r.queuedTurnFallback}),s.jsxs("div",{className:"queue-row-actions",children:[s.jsx("button",{type:"button",title:r.queueGuide,"aria-label":r.guideQueuedTurn(x+1),disabled:h||!f.clientMessageId||!t.canGuide,onClick:()=>{t.onAction([f],"guide")},children:s.jsx(Sa,{"aria-hidden":"true"})}),s.jsx("button",{type:"button",title:r.queueSendNow,"aria-label":r.sendQueuedTurnNow(x+1),disabled:h||!f.clientMessageId||!t.canSendNow,onClick:()=>{t.onAction([f],"sendNow")},children:s.jsx(mo,{"aria-hidden":"true"})}),s.jsx("button",{type:"button",className:"queue-withdraw-button",title:r.withdraw,"aria-label":r.withdrawQueuedTurn(x+1),disabled:h||!f.clientMessageId,onClick:()=>i(f),children:s.jsx(De,{"aria-hidden":"true"})})]})]},f.clientMessageId||`${f.enqueuedAt}:${x}`))}),s.jsxs("footer",{className:"queue-batch-actions",children:[u.length>0&&s.jsx("span",{children:r.queueSelectedCount(u.length)}),s.jsx("button",{type:"button",disabled:h||!d.length||!t.canGuide,onClick:()=>{t.onAction(d,"guide")},children:u.length?r.queueGuideSelected:r.queueGuideAll}),s.jsx("button",{type:"button",disabled:h||!d.length||!t.canSendNow,onClick:()=>{t.onAction(d,"sendNow")},children:u.length?r.queueSendSelected:r.queueSendAll})]})]}):null}function Nc({connected:e,busy:t,sending:n,responding:r,hasDraft:i,shortcut:a,onStop:c,t:l}){const u=n?"sending":r?"replying":"ready",h=r&&!n&&!i,d=n?l.sendingMessage:h?l.stopGenerating:l.send,f=n?l.sendingMessage:r?l.replyingMessage:l.send,x=n?Rn:h?Gr:oa;return s.jsxs("button",{type:h?"button":"submit",className:"send-button","data-state":u,"data-action":h?"stop":"send",disabled:!e||t||n||!h&&!i,"aria-label":d,"aria-description":f,title:h?`${f} · ${l.stopGenerating}`:n?f:`${r?`${f} · `:""}${l.send} · ${a==="enter"?l.sendShortcutEnter:l.sendShortcutModEnter}`,onClick:h?c:void 0,children:[r&&!n&&s.jsx("span",{className:"composer-send-progress","aria-hidden":"true"}),s.jsx(x,{className:n?"composer-send-spinner":h?"composer-send-stop":void 0,"aria-hidden":"true"}),s.jsx("span",{className:"composer-send-status",role:"status","aria-live":"polite",children:f})]})}function Ac({context:e,count:t,onSelect:n,onClose:r}){const i=o.useId(),[a,c]=o.useState({context:"",index:0}),l=a.context===e?Math.min(a.index,Math.max(0,t-1)):0,u=d=>c({context:e,index:d});return{listId:i,selectedIndex:l,selectIndex:u,handleKeyDown:d=>!e||d.nativeEvent.isComposing||d.nativeEvent.keyCode===229||d.metaKey||d.ctrlKey||d.altKey||d.shiftKey?!1:d.key==="Escape"?(d.preventDefault(),d.stopPropagation(),r(),!0):t?d.key==="ArrowDown"||d.key==="ArrowUp"?(d.preventDefault(),d.stopPropagation(),u((l+(d.key==="ArrowDown"?1:-1)+t)%t),!0):d.key==="Enter"||d.key==="Tab"?(d.preventDefault(),d.stopPropagation(),n(l),!0):!1:!1}}async function Ec(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 r=new Uint8Array(44+n.length*2),i=new DataView(r.buffer),a=(l,u)=>[...u].forEach((h,d)=>i.setUint8(l+d,h.charCodeAt(0)));a(0,"RIFF"),i.setUint32(4,r.length-8,!0),a(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,n.sampleRate*2,!0),i.setUint16(32,2,!0),i.setUint16(34,16,!0),a(36,"data"),i.setUint32(40,r.length-44,!0);const c=Array.from({length:n.numberOfChannels},(l,u)=>n.getChannelData(u));for(let l=0;l<n.length;l++){const u=Math.max(-1,Math.min(1,c.reduce((h,d)=>h+d[l],0)/c.length));i.setInt16(44+l*2,u*(u<0?32768:32767),!0)}return r}finally{await t.close()}}function Rc({onTranscript:e}){const t=re(),[n,r]=o.useState("idle"),[i,a]=o.useState("");o.useEffect(()=>{if(!i||n!=="idle")return;const p=setTimeout(()=>a(""),5e3);return()=>clearTimeout(p)},[i,n]);const[c,l]=o.useState(0),u=o.useRef(!1);o.useEffect(()=>{if(n!=="recording")return;const p=Date.now();l(0);const y=setInterval(()=>l(Math.floor((Date.now()-p)/1e3)),1e3);return()=>clearInterval(y)},[n]);const[h,d]=o.useState(!1);o.useEffect(()=>{let p=!0;const y=()=>{t.speechSettings?.status().then(g=>{p&&d(g.configured)}).catch(()=>{p&&d(!1)})};return y(),window.addEventListener("vibelet.speech.changed",y),()=>{p=!1,window.removeEventListener("vibelet.speech.changed",y)}},[]);const f=o.useRef(null),x=o.useRef(!0),b=o.useRef(e);b.current=e;const S=He(Be().language),v=S!=="en";if(o.useEffect(()=>(x.current=!0,()=>{x.current=!1,f.current?.stream.getTracks().forEach(p=>p.stop()),f.current?.state==="recording"&&f.current.stop()}),[]),!h||!t.transcribeAudio||Ge().getItem("vibelet.web.voice.enabled")!=="true")return null;const m=async()=>{if(!u.current){u.current=!0,a(""),r("starting");try{const p=await navigator.mediaDevices.getUserMedia({audio:!0});if(!x.current){p.getTracks().forEach(k=>k.stop());return}let y;try{y=new MediaRecorder(p,{mimeType:"audio/webm"})}catch(k){throw p.getTracks().forEach(N=>N.stop()),k}f.current=y;const g=[];let j=0;y.ondataavailable=k=>{g.push(k.data),j+=k.data.size,j>9*1024*1024&&y.state==="recording"&&y.stop()};const w=setTimeout(()=>{y.state==="recording"&&y.stop()},6e4);y.onstop=async()=>{if(clearTimeout(w),p.getTracks().forEach(k=>k.stop()),f.current=null,!!x.current){r("transcribing");try{const k=new Blob(g,{type:"audio/webm"}),N=await t.speechSettings?.status(),D=N?.engine==="system"||N?.engine==="volcengine"?await Ec(k):new Uint8Array(await k.arrayBuffer()),I=await t.transcribeAudio(D,S==="zh-TW"?"zh-TW":v?"zh":"en");if(x.current)if(I.trim()){a("");let W=I;const K=await t.polishSettings?.status().catch(()=>{});if(!x.current)return;if(K?.settings.enabled&&t.polishTranscript){r("polishing");try{const _=await t.polishTranscript(I);W=_.text,x.current&&_.status==="fallback"&&a(v?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}catch{x.current&&a(v?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}}x.current&&b.current(W)}else a(v?"没有识别到语音,请靠近麦克风重试。":"No speech detected. Try speaking closer to the microphone.")}catch{x.current&&a(v?"语音识别失败,请检查麦克风权限、语音设置和网络。":"Speech failed. Check microphone access, speech settings and connection.")}finally{u.current=!1,x.current&&r("idle")}}};try{y.start(1e3)}catch(k){throw clearTimeout(w),p.getTracks().forEach(N=>N.stop()),f.current=null,k}r("recording")}catch{u.current=!1,x.current&&(r("idle"),a(v?"无法开启麦克风,请检查系统权限。":"Microphone unavailable. Check system permissions."))}}};return s.jsxs("span",{className:"voice-input-control","data-voice-state":n,children:[s.jsx("button",{className:"icon-button",type:"button",disabled:n!=="idle"&&n!=="recording","aria-label":v?n==="recording"?"停止录音":"语音输入":n==="recording"?"Stop recording":"Voice input",title:n==="recording"?v?"停止录音":"Stop recording":v?"语音输入(最长 60 秒)":"Voice input (up to 60 seconds)",onClick:()=>{n==="recording"?f.current?.state==="recording"&&f.current.stop():m()},children:n==="recording"?s.jsx(Gr,{"aria-hidden":"true"}):n==="idle"?s.jsx(Wr,{"aria-hidden":"true"}):s.jsx(Rn,{className:"voice-input-spinner","aria-hidden":"true"})}),n!=="idle"&&s.jsxs("span",{className:"voice-input-progress",children:[n==="recording"&&s.jsxs("span",{className:"voice-input-wave","aria-hidden":"true",children:[s.jsx("i",{}),s.jsx("i",{}),s.jsx("i",{})]}),s.jsx("span",{role:"status","aria-live":"polite",children:n==="recording"?v?"录音中":"Recording":n==="polishing"?v?"润色中":"Polishing":n==="transcribing"?v?"识别中":"Transcribing":v?"开启麦克风":"Opening microphone"}),n==="recording"&&s.jsxs("span",{className:"voice-input-time","aria-hidden":"true",children:["00:",String(c).padStart(2,"0")]})]}),n==="idle"&&i&&s.jsx("span",{className:"voice-input-error",role:"alert",children:i})]})}function Tc(e){return[{value:"normal",label:e.approvalNormal,description:e.approvalNormalDescription,icon:Ps},{value:"plan",label:e.approvalPlan,description:e.approvalPlanDescription,icon:Ur},{value:"acceptEdits",label:e.approvalEdits,description:e.approvalEditsDescription,icon:Ea},{value:"autoApprove",label:e.approvalAuto,description:e.approvalAutoDescription,icon:nn}]}function Mc(e){return[{value:"",label:e.effort,description:e.useDaemonDefault,icon:Ct},{value:"minimal",label:e.effortMinimal,icon:Ct},{value:"low",label:e.effortLow,icon:Ct},{value:"medium",label:e.effortMedium,icon:Ct},{value:"high",label:e.effortHigh,icon:Ct},{value:"xhigh",label:e.effortXHigh,icon:Ct},{value:"max",label:e.effortMax,icon:Ct},{value:"ultra",label:e.effortUltra,icon:Ct}]}function Pc({activeQueue:e,queueControls:t,agent:n,attachments:r,approvalMode:i,activeModelOptions:a,busy:c,sending:l,responding:u,onStop:h,draft:d,effort:f,fastMode:x,model:b,phase:S,quickReplies:v,sendShortcut:m,skills:p,uploadBusy:y,t:g,onApprovalModeChange:j,onCancelQueuedTurn:w,onDraftChange:k,onEffortChange:N,onFastModeChange:D,onModelChange:I,onRefreshSkills:W,onRemoveAttachment:K,onSubmit:_,onUploadFiles:be}){const Te=o.useRef(null),X=o.useRef(null),[ae,ve]=o.useState(!1),[de,Ne]=o.useState(!1),[A,R]=o.useState(!1),[q,H]=o.useState(!1),[B,G]=o.useState(""),[V,oe]=o.useState(""),$=o.useRef(null),U=o.useRef(null),Q=S==="connected",Ve=o.useMemo(()=>Zr(n),[n]),xe=o.useMemo(()=>qn(d),[d]),Ae=xe?`${xe.start}:${xe.end}:${xe.keyword}`:"",se=!!(q||xe&&V!==Ae),we=o.useMemo(()=>Fo(Ve,xe?.keyword??"",8),[Ve,xe?.keyword]),ue=o.useMemo(()=>Hn(d),[d]),ie=ue?`${ue.start}:${ue.end}:${ue.keyword}`:"",te=!!(!se&&(A||ue&&B!==ie)),me=o.useMemo(()=>kc(p,ue?.keyword??"",8),[ue?.keyword,p]),ze=o.useMemo(()=>Tc(g),[g]),Se=o.useMemo(()=>Mc(g),[g]),Ze=a.find(C=>C.value===b)?.label??(b||g.defaultOption),Je=ze.find(C=>C.value===i)?.label??i,Ye=Se.find(C=>C.value===f)?.label??f,ke=a.map(C=>({value:C.value,label:C.label,description:C.desc,icon:os}));ke.some(C=>C.value==="")||ke.unshift({value:"",label:g.defaultOption,description:g.useDaemonDefaultModel,icon:os}),o.useEffect(()=>{ue||($.current=null,G(""),R(!1))},[ue]),o.useEffect(()=>{xe||(U.current=null,oe(""),H(!1))},[xe]);const Me=async(C,Oe)=>{await be(C),Oe.value=""},Le=async C=>{C.preventDefault(),ve(!1),Q&&await be(C.dataTransfer.files)},Ue=async C=>{!Q||!C.clipboardData.files.length||await be(C.clipboardData.files)},$e=()=>{const C=Sc(d,$.current);$.current=null,C!==d&&k(C),ie&&G(ie),R(!1),X.current?.focus()},J=()=>{const C=zo(d,U.current);U.current=null,C!==d&&k(C),Ae&&oe(Ae),H(!1),X.current?.focus()},Z=()=>{if(se){J();return}oe(""),!qn(d)&&d.length===0&&(U.current={draftBeforeInsertion:d},k("/")),H(!0),X.current?.focus()},z=C=>{const Oe=qn(d),qe=qo(d,Oe,C);k(qe),U.current=null,H(!1),oe(""),X.current?.focus()},he=()=>{if(te){$e();return}if(W(),G(""),!Hn(d)){const C=d.length===0||/\s$/.test(d)?"":" ";$.current={draftBeforeInsertion:d,triggerStart:d.length+C.length},k(`${d}${C}$`)}R(!0),X.current?.focus()},ge=C=>{const Oe=Hn(d),qe=Oe?wc(d,Oe,C.name):d.trim().length?`${d}${/\s$/.test(d)?"":" "}$${C.name} `:`$${C.name} `;k(qe),$.current=null,R(!1),G(""),X.current?.focus()},ne=Ac({context:se?`command:${Ae}:${we.map(C=>C.name).join(",")}`:te?`skill:${ie}:${me.map(C=>`${C.source}:${C.name}`).join(",")}`:"",count:se?we.length:te?me.length:0,onSelect:C=>se?z(we[C]):ge(me[C]),onClose:se?J:$e}),Fe=C=>{ne.handleKeyDown(C)||C.key!=="Enter"||C.nativeEvent.isComposing||C.nativeEvent.keyCode===229||!(m==="enter"?!C.shiftKey:C.metaKey||C.ctrlKey)||(C.preventDefault(),_())};return s.jsxs("form",{className:`composer ${ae?"dragging":""}`,onDragEnter:C=>{C.preventDefault(),ve(!0)},onDragLeave:()=>ve(!1),onDragOver:C=>C.preventDefault(),onDrop:C=>{Le(C)},onSubmit:C=>{_(C)},children:[s.jsx(Ic,{queue:e,controls:t,busy:c,t:g,onCancel:w}),de&&v.length?s.jsx("div",{className:"quick-reply-row",children:v.slice(0,6).map(C=>s.jsx("button",{onClick:()=>k(d?`${d}
|
|
4
|
+
${C}`:C),type:"button",children:C},C))}):null,s.jsx(jc,{visible:te,skills:me,listId:ne.listId,selectedIndex:ne.selectedIndex,onHighlight:ne.selectIndex,onClose:$e,onSelect:ge,t:g}),s.jsx(Cc,{visible:se,commands:we,listId:ne.listId,selectedIndex:ne.selectedIndex,onHighlight:ne.selectIndex,onClose:J,onSelect:z,t:g}),s.jsx("textarea",{ref:X,"aria-controls":se||te?ne.listId:void 0,"aria-activedescendant":se&&we.length||te&&me.length?`${ne.listId}-${ne.selectedIndex}`:void 0,"aria-autocomplete":"list",value:d,onChange:C=>k(C.target.value),onPaste:C=>{Ue(C)},onKeyDown:Fe,placeholder:g.messagePlaceholder,rows:3,disabled:!Q}),s.jsxs("div",{className:"composer-toolbar",children:[s.jsxs("div",{className:"composer-leading-controls",children:[s.jsx(Rc,{onTranscript:C=>k(d?`${d} ${C}`:C)}),s.jsx("button",{type:"button",className:"icon-button",onClick:()=>Te.current?.click(),title:g.uploadFiles,disabled:!Q||y,children:s.jsx(Jn,{"aria-hidden":"true"})}),v.length?s.jsx("button",{className:`icon-button ${de?"selected":""}`,type:"button",title:de?g.hideQuickReplies:g.showQuickReplies,onClick:()=>Ne(C=>!C),children:s.jsx(xo,{"aria-hidden":"true"})}):null,s.jsx("button",{className:`icon-button ${te?"selected":""}`,type:"button",title:g.skills,onClick:he,disabled:!Q||y,children:s.jsx(nn,{"aria-hidden":"true"})}),s.jsx("button",{className:`icon-button ${se?"selected":""}`,type:"button",title:g.commands,onClick:Z,disabled:!Q||y,children:s.jsx(Yn,{"aria-hidden":"true"})})]}),s.jsx("input",{ref:Te,type:"file",multiple:!0,hidden:!0,onChange:C=>{Me(C.currentTarget.files,C.currentTarget)}}),s.jsxs("div",{className:"composer-control-strip",children:[s.jsx(gn,{icon:i==="autoApprove"?nn:Ps,label:Je,menuLabel:g.approvalMode,options:ze,value:i,onSelect:j,wide:!0}),s.jsx(gn,{icon:os,label:Ze,menuLabel:g.model,options:ke,value:b,onSelect:I,align:"right",wide:!0}),s.jsx(gn,{icon:Ct,label:Ye||g.effort,menuLabel:g.effort,options:Se,value:f,onSelect:N,align:"right"}),s.jsx(gn,{icon:nn,label:x?g.fast:g.normal,menuLabel:g.fastMode,options:[{value:"off",label:g.normal,description:g.standardExecution,icon:Ct},{value:"on",label:g.fast,description:g.preferFasterResponses,icon:nn}],value:x?"on":"off",onSelect:C=>D(C==="on"),align:"right",selected:x,wide:!0})]}),s.jsx(Nc,{connected:Q,busy:c,sending:l,responding:u,hasDraft:!!d.trim(),shortcut:m,onStop:h,t:g})]}),r.length||y?s.jsx("div",{className:"attachment-row",children:r.length?s.jsx("div",{className:"attachment-list",children:r.map(C=>s.jsxs("span",{children:[s.jsx(Hr,{"aria-hidden":"true"}),C.name||_t(C.path),s.jsx("small",{children:rc(C.size)}),s.jsx("button",{type:"button",onClick:()=>K(C.path),title:g.removeAttachment,children:s.jsx(De,{"aria-hidden":"true"})})]},C.path))}):s.jsxs("span",{className:"attachment-empty",children:[s.jsx("span",{className:"loading-spinner small","aria-hidden":"true"}),g.uploading]})}):null]})}function _c({cwd:e,paths:t,t:n,onClose:r,onOpenRemoteFile:i}){const a=o.useRef(null),c=En(r,a,t.length>0);return t.length?s.jsxs("div",{"aria-labelledby":"attachment-preview-title","aria-modal":"true",className:"side-drawer",ref:c,role:"dialog",tabIndex:-1,children:[s.jsx("button",{className:"side-drawer-backdrop",onClick:r,type:"button","aria-label":n.closeAttachmentPreview}),s.jsxs("aside",{className:"side-drawer-panel",children:[s.jsxs("header",{className:"side-drawer-header",children:[s.jsxs("div",{children:[s.jsx("strong",{id:"attachment-preview-title",children:n.attachments}),s.jsx("span",{children:n.fileCount(t.length)})]}),s.jsx("button",{"aria-label":n.closeAttachmentPreview,className:"icon-button",onClick:r,ref:a,type:"button",children:s.jsx(De,{"aria-hidden":"true"})})]}),s.jsx("div",{className:"stack-list",children:t.map(l=>s.jsxs("button",{className:"data-row attachment-preview-row",onClick:()=>i(l,e),type:"button",children:[s.jsx(Hr,{"aria-hidden":"true"}),s.jsxs("span",{children:[s.jsx("strong",{children:_t(l)}),s.jsx("small",{children:l})]}),s.jsx(Pr,{"aria-hidden":"true"})]},l))})]})]}):null}function ii({title:e,draft:t,label:n,disabled:r,onDraftChange:i,onCommit:a}){const[c,l]=o.useState(!1),u=o.useRef(null),h=o.useRef(null),d=o.useRef(!1);o.useLayoutEffect(()=>{c?(u.current?.focus(),u.current?.select()):d.current&&(d.current=!1,h.current?.focus())},[c]);const f=()=>{d.current=!0,l(!1)};return c?s.jsx("input",{ref:u,className:"inline-session-title-input","aria-label":n,value:t,onChange:x=>i(x.target.value),onBlur:()=>l(!1),onKeyDown:x=>{x.nativeEvent.isComposing||x.keyCode===229||(x.key==="Enter"?(x.preventDefault(),t.trim()&&t.trim()!==e&&a(),f()):x.key==="Escape"&&(x.preventDefault(),x.stopPropagation(),f()))}}):s.jsx("button",{ref:h,type:"button",className:"inline-session-title-button",title:e,"aria-label":`${n}: ${e}`,disabled:r,onClick:()=>{i(e),l(!0)},children:e})}const ai=o.createContext(null);function Dc({matchCount:e,query:t,onChange:n,onNext:r,onClose:i,t:a}){return s.jsxs("div",{className:"message-search-bar",id:"conversation-message-search",children:[s.jsx(wn,{"aria-hidden":"true"}),s.jsx("input",{autoFocus:!0,"aria-label":a.searchThisSession,value:t,onChange:c=>n(c.target.value),onKeyDown:c=>{c.key==="Enter"&&r(),c.key==="Escape"&&(c.preventDefault(),i())},placeholder:a.searchThisSession}),s.jsx("span",{children:t.trim()?a.messageSearchMatches(e):a.allMessages}),s.jsx("button",{"aria-label":a.clearMessageSearch,className:"icon-button mini-button",onClick:i,type:"button",children:s.jsx(De,{"aria-hidden":"true"})})]})}function Lc({activeSession:e,agent:t,cwd:n,t:r,onOpenDetails:i,renameTitle:a,busy:c,onRename:l,onRenameTitleChange:u,onViewChanges:h,search:d}){const[f,x]=o.useState(!1),b=o.useRef(null);o.useEffect(()=>{d.query&&x(!0)},[d.query]);const S=()=>{d.onChange(""),x(!1),b.current?.focus()},v=e?St(e):r.newSession,m=e?.cwd??(n.trim().length>0&&n!=="."?n:""),p=e?.agent??t,y=o.useContext(ai),g=re().toolbarTarget?.("conversation")??y,j=s.jsxs("div",{className:"chat-header-title-row",children:[s.jsxs("div",{className:"chat-title-block",children:[s.jsxs("span",{className:"chat-title-line",children:[s.jsx("button",{className:`agent-status-pill chat-session-details-button ${p}`,type:"button",onClick:i,"aria-label":r.details,title:r.details,disabled:!e,children:p==="codex"?"Codex":"Claude"}),s.jsx("h1",{children:e?s.jsx(ii,{title:v,draft:a,label:r.rename,disabled:c,onDraftChange:u,onCommit:l},e.sessionId):v})]}),m?s.jsx("p",{title:m,children:m}):null,e?.branch||e?.diffStat?s.jsxs("div",{className:"header-metadata",children:[e.branch?s.jsx("span",{children:e.branch}):null,e.runtime.state?s.jsx("span",{children:e.runtime.state}):null,e.terminal?.mode?s.jsx("span",{children:e.terminal.mode}):null]}):null]}),e?s.jsxs("button",{className:"chat-changes-button",type:"button","aria-label":r.viewChanges,title:r.viewChanges,onClick:()=>h(e.sessionId),children:[s.jsx(Qn,{"aria-hidden":"true"}),e.diffStat&&(e.diffStat.additions>0||e.diffStat.deletions>0)?s.jsxs("span",{className:"chat-changes-summary","aria-hidden":"true",children:[s.jsxs("span",{className:"diff-add",children:["+",e.diffStat.additions]}),s.jsxs("span",{className:"diff-del",children:["−",e.diffStat.deletions]})]}):null]}):null,s.jsx("button",{ref:b,className:"icon-button chat-search-toggle",type:"button","aria-label":r.searchThisSession,title:r.searchThisSession,"aria-expanded":f,"aria-controls":"conversation-message-search",onClick:()=>f?S():x(!0),children:s.jsx(wn,{"aria-hidden":"true"})})]});return s.jsxs("header",{className:`chat-header chat-search-header ${g?"chat-header-in-titlebar":""}`,children:[g?It.createPortal(j,g):j,f&&s.jsx(Dc,{...d,t:r,onClose:S})]})}async function $c(e){const t=re().writeClipboardText;if(t)return t(e);try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(e);return}}catch{}const n=document.activeElement,r=window.getSelection(),i=r?Array.from({length:r.rangeCount},(l,u)=>r.getRangeAt(u).cloneRange()):[],a=n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?[n.selectionStart,n.selectionEnd,n.selectionDirection]:void 0,c=document.createElement("textarea");c.value=e,c.setAttribute("readonly",""),c.style.position="fixed",c.style.opacity="0",document.body.append(c);try{if(c.focus({preventScroll:!0}),c.select(),!document.execCommand("copy"))throw new Error("Clipboard copy was rejected")}finally{if(c.remove(),n instanceof HTMLElement&&n.focus({preventScroll:!0}),a&&(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&a[0]!==null&&a[1]!==null&&n.setSelectionRange(a[0],a[1],a[2]??void 0),r){r.removeAllRanges();for(const l of i)r.addRange(l)}}}function Fc(e,t){const[n,r]=o.useState(null),i=o.useRef(null);return o.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]),{copyText:o.useCallback(async c=>{try{await $c(c),r({message:e,tone:"success"})}catch{r({message:t,tone:"error"})}i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>r(null),2400)},[t,e]),feedback:n}}function Oc({feedback:e}){if(!e)return null;const t=e.tone==="success"?Dt:De;return s.jsxs("div",{className:`copy-feedback ${e.tone}`,role:"status",children:[s.jsx(t,{"aria-hidden":"true"}),e.message]})}function qc({message:e,retryLabel:t,onRetry:n,onDismiss:r,closeLabel:i}){return s.jsxs("div",{className:"notice error chat-error-notice",role:"alert",children:[r?s.jsx("button",{type:"button",className:"chat-notice-dismiss","aria-label":i,title:i,onClick:r,children:s.jsx(De,{"aria-hidden":"true"})}):s.jsx(Lr,{"aria-hidden":"true"}),s.jsx("span",{children:e}),s.jsxs("button",{className:"chat-notice-retry",onClick:n,type:"button",children:[s.jsx(xn,{"aria-hidden":"true"}),t]})]})}function Wc({label:e}){return s.jsxs("div",{className:"history-loading-state","aria-busy":"true","aria-label":e,role:"status",children:[s.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),s.jsxs("div",{className:"history-loading-copy",children:[s.jsx("strong",{children:e}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("span",{"aria-hidden":"true"}),s.jsx("span",{"aria-hidden":"true"})]})]})}function ar({failedSend:e,onRetry:t,t:n}){const r={network:n.sendFailedNetwork,timeout:n.sendFailedTimeout,permission:n.sendFailedPermission,subscription:n.sendFailedSubscription,"missing-resource":n.sendFailedMissingResource,unknown:n.sendFailedUnknown}[e.kind];return s.jsxs("div",{className:"failed-send-notice",role:"alert",children:[s.jsx(Lr,{"aria-hidden":"true"}),s.jsxs("span",{children:[s.jsx("strong",{children:n.sendFailed}),r]}),s.jsxs("button",{disabled:e.retrying,onClick:t,type:"button",children:[s.jsx(xn,{"aria-hidden":"true",className:e.retrying?"spin":void 0}),e.retrying?n.retrying:n.retrySend]})]})}function Hc({label:e,onClick:t}){return s.jsxs("button",{className:"scroll-latest-button",type:"button","aria-label":e,title:e,onClick:t,children:[s.jsx(ta,{"aria-hidden":"true"}),s.jsx("span",{role:"status",children:e})]})}const Bc=/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,zc=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\u00AD\u061C\u180E\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g,Uc=new Set(["","{}","[]","null","undefined",'""']);function On(e){return e.replace(/\s+/g," ").trim()}function Ie(e,t){return typeof e[t]=="string"?e[t]:""}function or(e,t){return typeof e[t]=="number"?e[t]:void 0}function fn(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function ds(e){const t=[],n=Ie(e,"file_path")||Ie(e,"filePath");n&&t.push({label:"Path",value:n,isFilePath:!0});const r=or(e,"offset"),i=or(e,"limit");if(r!==void 0||i!==void 0){const a=[];r!==void 0&&a.push(`line ${r+1}`),i!==void 0&&a.push(`to ${r!==void 0?r+i:i}`),t.push({label:"Range",value:a.join(" ")})}return t}function Gc(e){return typeof e!="string"?"":e.replace(/\r\n?/g,`
|
|
5
|
+
`).replace(Bc,"").replace(zc,"").trim()}function qs(e){const t=Gc(e);return Uc.has(t)?"":t}function Vc(e){return qs(e).length>0}function Ws(e){const t=qs(e);if(!t)return"";try{const n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)){const r=typeof n.query=="string"?On(n.query):"";if(r)return r;const i=typeof n.command=="string"?On(n.command):"";if(i)return i;const a=typeof n.description=="string"?On(n.description):"";if(a)return a}}catch{}return On(t)}function Kc(e,t){if(!t)return[];switch((e??"").toLowerCase()){case"read":return ds(t);case"write":{const r=ds(t),i=Ie(t,"content");return i&&r.push({label:"Content",isDiff:!0,value:"",diffNew:fn(i,500)}),r}case"edit":{const r=ds(t),i=Ie(t,"old_string")||Ie(t,"oldString"),a=Ie(t,"new_string")||Ie(t,"newString");return(i||a)&&r.push({label:"Change",isDiff:!0,value:"",diffOld:fn(i,300),diffNew:fn(a,300)}),r}case"bash":{const r=Ie(t,"command");return r?[{label:"Command",value:r,isCode:!0}]:[]}case"websearch":{const r=Ie(t,"query");return r?[{label:"Query",value:r}]:[]}case"webfetch":{const r=[],i=Ie(t,"url");i&&r.push({label:"URL",value:i});const a=Ie(t,"prompt");return a&&r.push({label:"Prompt",value:fn(a,200)}),r}case"glob":{const r=Ie(t,"pattern");return r?[{label:"Pattern",value:r}]:[]}case"grep":{const r=[],i=Ie(t,"pattern");i&&r.push({label:"Pattern",value:i,isCode:!0});const a=Ie(t,"path");return a&&r.push({label:"In",value:a,isFilePath:!0}),r}default:{const r=[],i=Ie(t,"command");if(i)return[{label:"Command",value:i,isCode:!0}];const a=Ie(t,"file_path")||Ie(t,"filePath");a&&r.push({label:"Path",value:a,isFilePath:!0});const c=Ie(t,"description");c&&r.push({label:"Description",value:fn(c,200)});const l=Ie(t,"query");l&&r.push({label:"Query",value:l});const u=Ie(t,"url");return u&&r.push({label:"URL",value:u}),r}}}function cr(e){return e.role==="tool"?!0:e.type!=="info"?!1:!/^Error:/i.test(e.content.trim())}function oi(e){const t=[];for(const r of e){const i=r.toolName?.trim();i&&!t.includes(i)&&t.push(i)}return t.length?t.join(", "):e.map(r=>Ws(r.content)).find(Boolean)??""}function ci(e,t){return`${e.historyKey??e.timestamp??e.toolName??e.content.slice(0,24)??"message"}:${t}`}function Qc(e){const t=[];for(let n=0;n<e.length;n+=1){const r=e[n];if(!cr(r)){t.push({type:"message",index:n,message:r});continue}const i=[];let a=n;for(;a<e.length&&cr(e[a]);)i.push({index:a,message:e[a]}),a+=1;t.push({type:"toolGroup",entries:i,id:`tool-group:${i.map(({index:c,message:l})=>ci(l,c)).join("|")}`}),n=a-1}return t}function Zc(e,t){return e.type==="message"?e.index===t:e.entries.some(n=>n.index===t)}const Jc={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.",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 kn(){return Jc[He(Be().language)]}const vs="vibelet:image-gallery";function Yc(e){window.dispatchEvent(new CustomEvent(vs,{detail:e}))}const Xc="(?:png|jpg|jpeg|gif|webp|svg|heic|heif)",el="(?:~/|/|\\.{1,2}/|[A-Za-z0-9._-]+/)",tl="[^\\n`<>\"')\\]},。!?;:、]*?",nl="(?::\\d+(?::\\d+)?|#[^\\s`<>\"')\\]},。!?;:、]+)?",sl=`${el}${tl}\\.${Xc}${nl}`,lr=new RegExp(`(${sl})`,"gi"),rl=[".png",".jpg",".jpeg",".gif",".webp",".svg",".heic",".heif"],xs="\\s`<>\"')\\]},。!?;:、",dr="`<>\"')\\]},。!?;:、\\n\\r\\t",il=new RegExp(`(^|[\\s([{>])((?:~\\/|\\/|\\.{1,2}\\/)[^${xs}]+|[A-Za-z0-9._-]+(?:\\/[A-Za-z0-9._-]+)+(?:\\.[A-Za-z0-9._-]+)?\\/?)`,"g"),al=new RegExp(`(^|[\\s([{>])((?=[^${dr}]*\\/)[^${dr}]+?\\.[A-Za-z0-9._-]+(?::\\d+(?::\\d+)?|#[^${xs}]+)?)(?=$|[${xs}])`,"g");function ws(e){let t=e;for(;/[.,!?;:,。!?;:、]+$/.test(t);)t=t.slice(0,-1);return t}function Ss(e,t){return!e||/^[a-z]+:\/\//i.test(e)||e.startsWith("streamdown:")?!1:e==="~"||e.startsWith("~/")||e.startsWith("/")||e.startsWith("./")||e.startsWith("../")||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.includes("/")||e.includes("\\")?!0:!!t?.allowBareFilename&&/^[A-Za-z0-9._-]+\.[A-Za-z0-9._-]+$/.test(e)}function es(e){let t=ws(e.trim());if(!t)return"";const n=t.indexOf("#");if(n>0){const i=t.slice(0,n);Ss(i,{allowBareFilename:!0})&&(t=i)}const r=t.match(/^(.*?)(:\d+(?::\d+)?)$/);if(r){const i=r[1]??"";Ss(i,{allowBareFilename:!0})&&(t=i)}return ws(t)}function ol(e,t){return e.start<t.end&&t.start<e.end}function ks(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)?!0:/\s/.test(n)?!1:/[^\p{ASCII}]/u.test(n)}function cl(e){if(ks(e.rawCandidate))return e;const t=e.rawCandidate.indexOf("/");if(t<=0)return e;const n=e.rawCandidate.slice(0,t);for(let r=n.indexOf(" ");r>=0;r=n.indexOf(" ",r+1)){const i=r+1,a=e.rawCandidate.slice(i);if(ks(a))return{start:e.start+i,end:e.end,rawCandidate:a}}return e}function ll(e){const t=[];for(const n of e.matchAll(il)){const r=n[1]??"",i=n[2]??"",c=(n.index??0)+r.length;t.push({start:c,end:c+i.length,rawCandidate:i})}for(const n of e.matchAll(al)){const r=n[1]??"",i=n[2]??"",c=(n.index??0)+r.length,l=cl({start:c,end:c+i.length,rawCandidate:i}),u=t.filter(h=>ol(h,l));if(u.length===0){t.push(l);continue}if(ks(l.rawCandidate)){for(const h of u){const d=t.indexOf(h);d>=0&&t.splice(d,1)}t.push(l)}}return t.sort((n,r)=>n.start-r.start||n.end-r.end)}function Hs(e,t){const n=es(e);return Ss(n,t)}function Bs(e){const t=es(e).toLowerCase();return Hs(t,{allowBareFilename:!0})&&rl.some(n=>t.endsWith(n))}function dl(e){if(!e)return[];const t=[];let n=0;for(const r of ll(e)){r.start>n&&t.push({type:"text",value:e.slice(n,r.start)});const i=ws(r.rawCandidate),a=es(i),c=r.rawCandidate.slice(i.length);Hs(i)&&!Bs(i)?(t.push({type:"path",value:i,target:a||i}),c&&t.push({type:"text",value:c})):t.push({type:"text",value:r.rawCandidate}),n=r.end}return n<e.length&&t.push({type:"text",value:e.slice(n)}),t.length>0?t:[{type:"text",value:e}]}const ul=/^[a-z][a-z0-9+.-]*:/i,hl=/^[a-z]:[\\/]/i,li=/\.(?:md|markdown)$/i,di="https://vibelet.local",ui="/__vibelet_markdown__",fl=`${di}${ui}`;function ml(e){try{return decodeURIComponent(e)}catch{return e}}function hi(e){const t=e?.trim()??"";if(!t||t.startsWith("#")||t.startsWith("//"))return null;const n=pl(t);if(n)return n;if(ul.test(t)&&!hl.test(t))return null;const r=t.split(/[?#]/,1)[0]??"";return li.test(r)?ml(r):null}function Zh(e){const t=e.split(`
|
|
6
|
+
`);let n=null;return t.map(r=>{const i=r.match(/^ {0,3}(`{3,}|~{3,})/);if(i){const a=i[1][0];return n===a?n=null:n||(n=a),r}return n?r:gl(r)}).join(`
|
|
7
|
+
`)}function pl(e){let t;try{t=new URL(e)}catch{return null}if(t.origin!==di||t.pathname!==ui)return null;const n=t.searchParams.get("path");return!n||!li.test(n)?null:n}function gl(e){let t="",n=0;for(;n<e.length;){if(e[n]==="`"){const r=yl(e,n);t+=e.slice(n,r),n=r;continue}if(e[n]==="["&&e[n-1]!=="!"){const r=bl(e,n);if(r){t+=r.text,n=r.end;continue}}t+=e[n],n+=1}return t}function yl(e,t){let n=0;for(;e[t+n]==="`";)n+=1;const r="`".repeat(n),i=e.indexOf(r,t+n);return i<0?e.length:i+n}function bl(e,t){const n=vl(e,t);if(n<0||e[n+1]!=="(")return null;const r=n+2,i=xl(e,r);if(i<0)return null;const a=e.slice(r,i),c=wl(a);return c?{text:`${e.slice(t,r)}${c})`,end:i+1}:null}function vl(e,t){let n=!1;for(let r=t+1;r<e.length;r+=1){const i=e[r];if(n){n=!1;continue}if(i==="\\"){n=!0;continue}if(i==="]")return r}return-1}function xl(e,t){let n=!1;for(let r=t;r<e.length;r+=1){const i=e[r];if(n){n=!1;continue}if(i==="\\"){n=!0;continue}if(i===")")return r}return-1}function wl(e){const t=e.match(/^\s*/)?.[0]??"",n=e.match(/\s*$/)?.[0]??"",r=e.slice(t.length,e.length-n.length);if(r.startsWith("<")){const c=r.indexOf(">");if(c<0)return null;const l=r.slice(1,c),u=ur(l);return u?`${t}<${u}>${r.slice(c+1)}${n}`:null}const i=r.match(/^(\S+)([\s\S]*)$/);if(!i)return null;const a=ur(i[1]);return a?`${t}${a}${i[2]}${n}`:null}function ur(e){const t=hi(e);return t?`${fl}?path=${encodeURIComponent(t)}`:null}const fi="https://vibelet.local/__vibelet_file__";function jn(e){if(!e)return null;const t=hi(e);if(t)return t;let n=e.trim();if(n.startsWith(fi))try{const r=new URL(n);if(r.origin!=="https://vibelet.local"||r.pathname!=="/__vibelet_file__")return null;n=r.searchParams.get("path")??""}catch{return null}else if(/^file:\/\//i.test(n))try{const r=new URL(n);if(r.hostname&&r.hostname!=="localhost")return null;n=r.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=es(n),Hs(n,{allowBareFilename:!0})?n:null}const js=e=>`${fi}?path=${encodeURIComponent(e)}`;function mi(e){return e.value??e.children?.map(mi).join("")??""}function Sl(e){const t=[],n=new RegExp(`(?:file://(?:localhost)?(?=/))?${lr.source}`,lr.flags);let r=0;const i=a=>{for(const c of dl(a))t.push(c.type==="path"?{type:"link",url:js(c.target??c.value),children:[{type:"text",value:c.value}]}:{type:"text",value:c.value})};for(const a of e.matchAll(n)){const c=jn(a[0]);!c||!Bs(c)||(i(e.slice(r,a.index)),t.push({type:"image",url:js(c),alt:c.split(/[\\/]/).at(-1)}),r=a.index+a[0].length)}return i(e.slice(r)),t}function Jh(){return e=>{const t=n=>{if(n.type==="link"||n.type==="image"){const r=jn(n.url);r&&(n.url=js(r),Bs(r)&&(n.alt=n.alt||mi(n)||r.split(/[\\/]/).at(-1),n.type="image",delete n.children));return}!n.children||["code","inlineCode","html"].includes(n.type)||(n.children=n.children.flatMap(r=>r.type==="text"?Sl(r.value??""):(t(r),[r])))};t(e)}}const pi="pair",Xt="vibelet.web.pairing",hr="vibelet.web.deviceId";class Cn extends Error{constructor(t,n){super(n),this.code=t,this.name="PairingCreateError"}}function zs(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function kl(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return decodeURIComponent(Array.from(atob(n),r=>`%${r.charCodeAt(0).toString(16).padStart(2,"0")}`).join(""))}function jl(e){const[t,n,r,i,a,c]=e;return!n||!Number.isFinite(r)||r<=0?null:{kind:t==="relay"?"relay":"direct",host:n,port:Math.floor(r),source:i,stability:a,...c===!0?{secure:!0}:{}}}function Cl(e){if(!zs(e))return null;const{kind:t,host:n,port:r,source:i,stability:a,secure:c}=e;return t!=="direct"&&t!=="relay"||typeof n!="string"||!n.trim()||typeof r!="number"||!Number.isFinite(r)||r<=0||typeof i!="string"||typeof a!="string"?null:{kind:t,host:n.trim(),port:Math.floor(r),source:i,stability:a,...c===!0?{secure:!0}:{}}}function Il(e){const t=e.trim().split(".");if(t.length!==4)return!1;const n=t.map(a=>/^\d+$/.test(a)?Number(a):Number.NaN);if(n.some(a=>!Number.isInteger(a)||a<0||a>255))return!1;const[r,i]=n;return r===10||r===172&&i>=16&&i<=31||r===192&&i===168}function gi(e){const t=e.trim().replace(/^\[(.*)\]$/,"$1").replace(/\.$/,"").toLowerCase();if(t==="localhost"||t.endsWith(".localhost")||t==="::1"||t==="0:0:0:0:0:0:0:1")return!0;const n=t.split(".");if(n.length!==4||n.some(i=>!/^\d+$/.test(i)))return!1;const r=n.map(Number);return r.every(i=>i>=0&&i<=255)&&r[0]===127}function Nl(e){const t=e.trim();return t.includes(":")&&!t.startsWith("[")?`[${t}]`:t}function Al(e,t){return t.protocol==="https:"&&e.secure!==!0?null:`${e.secure===!0?"wss":"ws"}://${Nl(e.host)}:${e.port}`}function fr(e){return Il(e.host)?0:e.source==="local_network"?1:e.source==="configured_host"?2:3}function El(e,t){const n=t?.port??e.port,r=t?.canonicalHost??e.canonicalHost;if(!r||typeof n!="number"||!Number.isFinite(n))return[];const i=Math.floor(n);return[{kind:"direct",host:r,port:i,source:"fallback",stability:"stable"},...[...t?.fallbackHosts??[],...e.fallbackHosts??[]].map(a=>({kind:"direct",host:a,port:i,source:"fallback",stability:"stable"}))]}function Rl(e,t,n=window.location,r=!0){if(r&&gi(n.hostname))return;const i=[...t?.connections??[],...e.connections??[],...El(e,t)].map(Cl).filter(a=>!!a).filter(a=>a.kind==="direct").sort((a,c)=>fr(a)-fr(c));for(const a of i){const c=Al(a,n);if(c)return c}}function Tl(e){if(!e.d||!e.c)return null;const t=Array.isArray(e.o)?e.o.map(jl).filter(n=>!!n):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(n=>typeof n=="string")}:{},...t?.length?{connections:t}:{},...e.e?{expiresAt:e.e}:{}}}function Ml(e){return!e.daemonId||!e.pairNonce?null:{daemonId:e.daemonId,displayName:e.displayName,canonicalHost:e.canonicalHost,fallbackHosts:e.fallbackHosts,port:e.port,connections:e.connections,pairNonce:e.pairNonce,expiresAt:e.expiresAt}}function Pl(e=window.location.hash){const t=e.startsWith("#")?e.slice(1):e,n=new URLSearchParams(t).get(pi);if(!n)return null;try{const r=JSON.parse(kl(n));if(!zs(r))return null;if(r.t==="vp")return Tl(r);if(r.type==="vibelet-pair")return Ml(r)}catch{return null}return null}function _l(){if(!window.location.hash.includes(`${pi}=`))return;const e=`${window.location.pathname}${window.location.search}`;window.history.replaceState(null,"",e)}function Dl(e=Ge()){const t=e.getItem(hr);if(t)return t;const n=typeof crypto.randomUUID=="function"?crypto.randomUUID():`web_${Date.now().toString(36)}_${Math.random().toString(36).slice(2)}`;return e.setItem(hr,n),n}function mr(e){const t=e.getItem(Xt);if(!t)return null;try{const n=JSON.parse(t);return!n.daemonId||!n.deviceId||!n.pairToken?null:{daemonId:n.daemonId,displayName:n.displayName,deviceId:n.deviceId,pairToken:n.pairToken,pairedAt:n.pairedAt??new Date().toISOString(),webSocketUrl:typeof n.webSocketUrl=="string"?n.webSocketUrl:void 0}}catch{return null}}function Us(e){if(typeof window>"u")return null;try{return e===Ge()?window.sessionStorage:null}catch{return null}}function Gs(e=Ge(),t=Us(e)){const n=mr(e);if(n)return n;const r=t?mr(t):null;return r?(e.setItem(Xt,JSON.stringify(r)),t?.removeItem(Xt),r):null}function pr(e,t=Ge(),n=Us(t)){t.setItem(Xt,JSON.stringify(e)),n?.removeItem(Xt)}function yi(e=Ge(),t=Us(e)){e.removeItem(Xt),t?.removeItem(Xt)}function Ll(e,t=Date.now()){if(!e.expiresAt)return!1;const n=new Date(e.expiresAt).getTime();return Number.isFinite(n)&&n<t}async function $l(e){const t=await e.text().catch(()=>"");try{const n=JSON.parse(t);if(zs(n)&&n.error==="pair_window_expired")return new Cn("pair_window_expired","Pairing link expired.")}catch{}return new Cn("pairing_failed",t||"Pairing failed.")}async function Fl(e,t=Dl()){if(Ll(e))throw new Cn("pair_window_expired","Pairing link expired.");const n=await fetch("/pair/create",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({daemonId:e.daemonId,pairNonce:e.pairNonce,deviceId:t,deviceName:"Vibelet Web"})});if(!n.ok)throw await $l(n);const r=await n.json();return{daemonId:r.daemonId,displayName:r.displayName||e.displayName,deviceId:r.deviceId,pairToken:r.pairToken,pairedAt:new Date().toISOString(),webSocketUrl:Rl(e,r,window.location,!0)}}async function Ol(e,t){try{return await Fl(e,t?.deviceId)}catch(n){if(n instanceof Cn&&n.code==="pair_window_expired"&&t?.daemonId===e.daemonId)return t;throw n}}const gr=20*1024*1024;function ql(e,t){const n=jn(e),r=Gs(),[i,a]=o.useState(null),[c,l]=o.useState(null);return o.useEffect(()=>{if(!n)return;const d=new AbortController;let f;return a(null),l(null),(async()=>{try{if(!r)throw new Error("No pairing");const b=new URL(Wn(n,t));b.searchParams.set("w","1600");const S=await fetch(b,{headers:{authorization:`Bearer ${r.pairToken}`},signal:d.signal});if(!S.ok||Number(S.headers.get("content-length"))>gr)throw new Error("Image unavailable");const v=await S.blob();if(!v.type.startsWith("image/")||v.size>gr)throw new Error("Unsupported image");if(d.signal.aborted)return;f=URL.createObjectURL(v),a({src:e,url:f})}catch{d.signal.aborted||l(e)}})(),()=>{d.abort(),f&&URL.revokeObjectURL(f)}},[e,n,t,r?.pairToken,r?.webSocketUrl]),{url:n?i?.src===e?i.url:void 0:e,error:c===e,fail:()=>l(e)}}function Wl({src:e,alt:t,cwd:n,onOpen:r,gallery:i}){const a=jn(e),{url:c,error:l,fail:u}=ql(e,n),h=ps[He(Be().language)],d=t||_t(a??e);return s.jsx("button",{className:"message-image-preview",type:"button",title:a??e,"aria-label":`${h.preview}: ${d}`,onClick:async f=>{f.preventDefault(),f.stopPropagation();const x=await i?.()??[{src:e,alt:d,cwd:n}],b=x.findIndex(S=>S.src===e||a&&jn(S.src)===a);Yc({images:b<0?[{src:e,alt:d,cwd:n}]:x,index:Math.max(0,b),onOpen:r})},children:l?s.jsxs("span",{className:"message-image-placeholder",children:[s.jsx(za,{"aria-hidden":"true"}),d," · ",h.fileOpenFailed]}):c?s.jsx("img",{src:c,alt:d,loading:"lazy",onError:u}):s.jsxs("span",{className:"message-image-placeholder",children:[s.jsx(Rn,{className:"session-running-icon","aria-hidden":"true"}),d]})})}function Hl({message:e,t}){return s.jsx("pre",{className:"message-markdown-source",role:"region","aria-label":t.markdownSource,children:e.content})}function Bl({field:e}){return e.isDiff?s.jsxs("div",{className:"tool-field diff",children:[s.jsx("span",{children:e.label}),e.diffOld?s.jsxs("pre",{className:"tool-diff old",children:[s.jsx("b",{children:"-"}),e.diffOld]}):null,e.diffNew?s.jsxs("pre",{className:"tool-diff new",children:[s.jsx("b",{children:"+"}),e.diffNew]}):null]}):s.jsxs("div",{className:`tool-field ${e.isCode?"code":""} ${e.isFilePath?"path":""}`,children:[s.jsx("span",{children:e.label}),s.jsx("pre",{children:e.value})]})}function zl({message:e,onCopy:t,t:n}){const r=Kc(e.toolName,e.toolInput),i=Ws(e.content),a=qs(e.content),c=Vc(e.content)&&!r.length,l=e.toolName??n.tool;return s.jsxs("section",{className:"tool-detail-card",children:[s.jsxs("header",{children:[s.jsx("span",{className:"tool-detail-icon",children:s.jsx(_s,{"aria-hidden":"true"})}),s.jsxs("div",{children:[s.jsx("strong",{children:l}),i?s.jsx("small",{title:i,children:i}):null]}),s.jsx("button",{className:"icon-button",onClick:()=>t(e.content),type:"button",title:n.copyOutput,children:s.jsx(on,{"aria-hidden":"true"})})]}),r.length?s.jsx("div",{className:"tool-fields",children:r.map((u,h)=>s.jsx(Bl,{field:u},`${u.label}:${h}`))}):null,c?s.jsx("pre",{className:"json-box compact",children:a}):null]})}function bi({messages:e,showHeader:t=!0,onClose:n,onCopy:r,t:i}){if(!e.length)return null;const c=e.filter(d=>d.role==="tool").length||e.length,l=i.toolCallCount(c),u=oi(e),h=e.map(d=>d.content).join(`
|
|
8
|
+
|
|
9
|
+
`);return s.jsxs("section",{className:"tool-inline-panel","aria-label":i.toolDetails,children:[t?s.jsxs("header",{className:"inline-detail-header",children:[s.jsxs("div",{className:"inline-detail-title",children:[s.jsx("strong",{children:l}),s.jsx("span",{title:u,children:u||i.toolDetail})]}),s.jsxs("div",{className:"row-actions",children:[s.jsx("button",{className:"icon-button",onClick:()=>r(h),type:"button",title:i.copyOutput,children:s.jsx(on,{"aria-hidden":"true"})}),s.jsx("button",{className:"icon-button",onClick:n,type:"button",title:i.closeToolDetails,children:s.jsx(De,{"aria-hidden":"true"})})]})]}):null,s.jsx("div",{className:"tool-detail-list",children:e.map((d,f)=>s.jsx(zl,{message:d,onCopy:r,t:i},`${d.historyKey??d.timestamp??d.toolName??"tool"}:${f}`))})]})}const Ul=o.lazy(async()=>tt(()=>import("./mermaid-O7DHMXV3-BIyESbw5.js").then(e=>e.b),__vite__mapDeps([0,1,2,3,4])).then(e=>({default:e.MessageMarkdown})));function Gl({activeMatch:e,baseCwd:t,message:n,onCopy:r,onRewind:i,onCloseTool:a,onOpenAttachment:c,onOpenRemoteFile:l,onToggleSource:u,onToggleTool:h,sourceOpen:d,toolOpen:f,t:x}){const b=n.role==="tool"?Ws(n.content):"";return s.jsxs("article",{className:`message ${n.role} ${n.type==="info"?"info":""} ${e?"match":""}`,children:[s.jsxs("div",{className:"message-meta",children:[s.jsx("span",{children:ei(n,x)}),s.jsx("div",{className:"message-meta-side",children:s.jsx("time",{children:Xn(n.timestamp,Date.now(),x)})})]}),d?s.jsx(Hl,{message:n,t:x}):n.role==="tool"?s.jsxs("button",{className:"tool-inline-summary","aria-expanded":f,onClick:h,type:"button",children:[s.jsxs("span",{children:[s.jsx(Eo,{"aria-hidden":"true"}),n.toolName??x.tool]}),b?s.jsx("small",{children:b}):null]}):n.role==="assistant"||n.role==="user"?s.jsx(o.Suspense,{fallback:s.jsx("pre",{children:n.content}),children:s.jsx(Ul,{baseCwd:t,content:n.images?.length?n.content.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").trim():n.content,onOpenRemoteFile:l,additionalImages:n.images})}):s.jsx("pre",{children:n.content}),n.images?.length?s.jsxs("div",{className:"message-image-attachments",children:[n.images.map(S=>s.jsx(Wl,{src:S,cwd:t,onOpen:l,gallery:async()=>[...(await tt(async()=>{const{collectMessageImages:v}=await import("./collectMessageImages-BROUPbis.js").then(m=>m.q);return{collectMessageImages:v}},[])).collectMessageImages(n.content,t),...(n.images??[]).map(v=>({src:v,cwd:t}))]},S)),s.jsxs("button",{className:"file-pill",onClick:()=>c(n.images??[]),type:"button",children:[s.jsx(Na,{"aria-hidden":"true"}),x.preview]})]}):null,n.role==="tool"&&f?s.jsx(bi,{messages:[n],onClose:a,onCopy:r,t:x}):null,s.jsxs("div",{className:"message-actions","aria-label":x.messageActions,role:"group",children:[i&&n.role==="user"&&n.type!=="info"&&s.jsx("button",{type:"button",onClick:i,title:kn().rewind,"aria-label":kn().rewind,children:s.jsx(zr,{"aria-hidden":"true"})}),s.jsx("button",{"aria-label":x.copyMessage,onClick:()=>r(n.content),title:x.copyMessage,type:"button",children:s.jsx(on,{"aria-hidden":"true"})}),s.jsx("button",{"aria-label":x.viewMarkdownSource,"aria-expanded":d,onClick:u,title:d?x.hideMarkdownSource:x.viewMarkdownSource,type:"button",children:s.jsx(va,{"aria-hidden":"true"})})]})]})}function Vl({activeMatch:e,expanded:t,messages:n,onToggle:r}){const i=n.filter(l=>l.role==="tool").length||n.length,a=oi(n),c=i===1?"1 tool call":`${i} tool calls`;return s.jsx("button",{className:`tool-group-bubble ${e?"match":""} ${t?"expanded":""}`,type:"button",onClick:r,"aria-expanded":t,"aria-label":a?`${c}: ${a}`:c,children:s.jsxs("span",{className:"tool-group-header",children:[s.jsxs("span",{className:"tool-group-title",children:[s.jsx(Dr,{className:"tool-group-chevron","aria-hidden":"true"}),s.jsx(_s,{"aria-hidden":"true"}),s.jsx("strong",{children:c})]}),a?s.jsx("span",{className:"tool-group-summary",children:a}):null]})})}function Kl(e,t,n){const r=o.useRef(n);r.current=n;const i=o.useRef(!1),[a,c]=o.useState(0);o.useLayoutEffect(()=>{i.current=!1;const l=d=>{d.type==="focusin"&&d.target instanceof Element&&d.target.contains(e.current)||(i.current=d.target instanceof Element&&!!e.current?.contains(d.target)&&!d.target.closest("input,textarea,select")&&!d.target.isContentEditable)},h=[["pointerdown",l],["focusin",l],["keydown",d=>{!i.current||d.isComposing||(d.metaKey||d.ctrlKey)&&!d.altKey&&!d.shiftKey&&d.key.toLowerCase()==="a"&&(d.preventDefault(),r.current(),c(f=>f+1))}]];return h.forEach(([d,f])=>document.addEventListener(d,f,!0)),()=>h.forEach(([d,f])=>document.removeEventListener(d,f,!0))},[e,t]),o.useLayoutEffect(()=>{if(!i.current)return;const l=e.current?.querySelectorAll(".message-frame"),u=l?.[l.length-1];u&&window.getSelection()?.setBaseAndExtent(l[0],0,u,u.childNodes.length)},[a,e,t])}const Bn=160,Ql=120,mn=-1;function Qt(e){return Math.max(0,e-Bn)}function Zl(e,t){const n=t.length,[r,i]=o.useState(()=>({sessionId:e,start:Qt(n),total:n})),a=r.sessionId!==e?Qt(n):r.start===mn?mn:n>r.total&&r.start+Bn>=r.total?Qt(n):Math.min(r.start,Qt(n));o.useLayoutEffect(()=>{r.sessionId===e&&r.start===a&&r.total===n||i({sessionId:e,start:a,total:n})},[e,a,r,n]);const c=o.useCallback(()=>{i(x=>({sessionId:e,start:Math.max(0,(x.sessionId===e?x.start:Qt(n))-Ql),total:n}))},[e,n]),l=o.useCallback(x=>{const b=t.findIndex(v=>Zc(v,x));if(a===mn||b<0||b>=a&&b<a+Bn)return!1;const S=Math.min(Qt(n),Math.max(0,b-40));return i({sessionId:e,start:S,total:n}),!0},[t,e,a,n]),u=o.useCallback(()=>{i({sessionId:e,start:Qt(n),total:n})},[e,n]),h=()=>i({sessionId:e,start:mn,total:n}),d=Math.max(0,a),f=a===mn?n:Math.min(n,a+Bn);return{ensureMessageVisible:l,hiddenItemCount:d,hiddenLaterItemCount:Math.max(0,n-f),revealEarlier:c,revealLatest:u,revealAll:h,visibleItems:t.slice(d,f)}}const yr=()=>null,Jl=()=>()=>{};function Yl(e,t,n,r){const i=o.useSyncExternalStore(e.submission?.subscribe??Jl,e.submission?.getSnapshot??yr,yr),a=o.useRef(!1),c=async l=>{if(!a.current){a.current=!0;try{await l()}finally{a.current=!1}}};return{sending:!!i&&i.sessionId===r,submit:l=>{if(l?.preventDefault(),!!n)return c(()=>e())},retry:()=>c(t)}}function Xl({activeSession:e,activeUsage:t,messages:n,renameTitle:r,busy:i,t:a,onBrowseFiles:c,onClose:l,onExport:u,onJumpToMessage:h,onRename:d,onRenameTitleChange:f,onToggleArchived:x,onTogglePinned:b,onViewChanges:S}){const[v,m]=o.useState(""),p=o.useRef(null),y=En(l,p),g=o.useMemo(()=>si(e),[e]),j=o.useMemo(()=>{const w=v.trim().toLowerCase();return w?n.map((k,N)=>({message:k,index:N})).filter(({message:k})=>k.role!=="user"&&k.role!=="assistant"?!1:k.content.toLowerCase().includes(w)).slice(0,20):[]},[n,v]);return s.jsxs("div",{"aria-labelledby":"session-detail-title","aria-modal":"true",className:"session-detail-drawer",ref:y,role:"dialog",tabIndex:-1,children:[s.jsx("div",{className:"drawer-backdrop",onClick:l,"aria-hidden":"true"}),s.jsxs("aside",{className:"session-detail-panel",children:[s.jsxs("header",{className:"drawer-header",children:[s.jsxs("div",{children:[s.jsx("span",{className:"eyebrow",children:e.agent}),s.jsx("strong",{id:"session-detail-title",title:St(e),children:s.jsx(ii,{title:St(e),draft:r,label:a.rename,disabled:i,onDraftChange:f,onCommit:d},e.sessionId)})]}),s.jsx("button",{"aria-label":a.closeSessionDetails,className:"icon-button",onClick:l,ref:p,type:"button",children:s.jsx(De,{"aria-hidden":"true"})})]}),s.jsxs("div",{className:"detail-info-grid",children:[s.jsxs("div",{children:[s.jsx(zn,{"aria-hidden":"true"}),s.jsx("span",{children:a.workingDirectory}),s.jsx("strong",{title:e.cwd,children:e.cwd})]}),s.jsxs("div",{children:[s.jsx(qr,{"aria-hidden":"true"}),s.jsx("span",{children:a.messages}),s.jsx("strong",{children:n.filter(w=>w.role==="user"||w.role==="assistant").length})]}),s.jsxs("div",{children:[s.jsx(Ha,{"aria-hidden":"true"}),s.jsx("span",{children:a.session}),s.jsx("strong",{title:e.sessionId,children:e.sessionId})]}),s.jsxs("div",{children:[s.jsx(_s,{"aria-hidden":"true"}),s.jsx("span",{children:a.runtime}),s.jsx("strong",{children:e.runtime.state})]})]}),e.branch||e.diffStat?s.jsxs("button",{className:"detail-command-card detail-changes-card",type:"button",onClick:S,children:[s.jsx(Qn,{"aria-hidden":"true"}),s.jsx("span",{className:"detail-change-label",children:e.branch??a.changes}),s.jsx("span",{className:"detail-change-stats",role:"group","aria-label":a.changes,children:e.diffStat?s.jsxs(s.Fragment,{children:[s.jsxs("span",{className:"diff-add",children:["+",e.diffStat.additions]}),s.jsxs("span",{className:"diff-del",children:["-",e.diffStat.deletions]})]}):null})]}):null,s.jsxs("label",{className:"detail-search",children:[s.jsx(wn,{"aria-hidden":"true"}),s.jsx("input",{value:v,onChange:w=>m(w.target.value),placeholder:a.searchMessages}),v.trim()?s.jsx("small",{children:a.searchResultCount(j.length)}):null]}),v.trim()&&j.length?s.jsx("div",{className:"detail-search-results",children:j.map(({message:w,index:k})=>s.jsxs("button",{type:"button",onClick:()=>{h(k,v),l()},children:[s.jsx("span",{children:ei(w,a)}),s.jsx("strong",{children:w.content})]},`${w.historyKey??w.timestamp??k}:${k}`))}):null,v.trim()?null:s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:"detail-command-card",type:"button",onClick:c,children:[s.jsx(zn,{"aria-hidden":"true"}),s.jsx("span",{children:a.browseFiles})]}),s.jsxs("button",{className:"detail-command-card",type:"button",onClick:()=>{navigator.clipboard?.writeText(g)},children:[s.jsx(pa,{"aria-hidden":"true"}),s.jsx("span",{title:g,children:g})]}),s.jsxs("div",{className:"detail-action-grid",children:[s.jsxs("button",{className:"icon-text-button",disabled:i,type:"button",onClick:b,children:[s.jsx(Zn,{"aria-hidden":"true"}),e.pinned?a.unpin:a.pin]}),s.jsxs("button",{className:"icon-text-button",disabled:i,type:"button",onClick:x,children:[s.jsx(Ms,{"aria-hidden":"true"}),e.archived?a.unarchive:a.archive]}),s.jsxs("button",{className:"icon-text-button",type:"button",onClick:u,children:[s.jsx(Kn,{"aria-hidden":"true"}),a.exportSession]})]}),t?s.jsxs("p",{className:"detail-usage",children:[a.usage,": ",t.limits?.fiveHour?.usedPercent??"-","% 5h ·"," ",t.limits?.weekly?.usedPercent??"-","% weekly"]}):null,s.jsxs("p",{className:"detail-usage",children:[a.created," ",Xn(e.createdAt,Date.now(),a)]})]})]})]})}function ed({activeSession:e,activeSessionId:t,activeModelOptions:n,activeQueue:r,queueControls:i,activeUsage:a,agent:c,approvalMode:l,attachments:u,busy:h,cwd:d,draft:f,effort:x,errorText:b,failedSend:S,fastMode:v,historyLoading:m,messages:p,messagesSessionId:y,model:g,phase:j,quickReplies:w,renameTitle:k,respondingSessionIds:N,sendShortcut:D,skills:I,uploadBusy:W,detailsOpen:K,t:_,onApprovalModeChange:be,onBrowseFiles:Te,onCancelQueuedTurn:X,onClearInterrupt:ae,onDraftChange:ve,onDetailsOpenChange:de,onEffortChange:Ne,onExportActiveSession:A,onRewindMessage:R,onFastModeChange:q,onRetryFailedSend:H,onModelChange:B,onOpenRemoteFile:G,onInterrupt:V,onRetry:oe,onDismissError:$,onRefreshSkills:U,onRenameSession:Q,onRenameTitleChange:Ve,onRemoveAttachment:xe,onSubmit:Ae,onToggleArchived:se,onTogglePinned:we,onUploadFiles:ue,onViewChanges:ie}){const te=Yl(Ae,H,j==="connected"&&!h&&!!f.trim(),t),[me,ze]=o.useState(""),[Se,Ee]=o.useState(0),[Ze,Je]=o.useState(null),[Ye,ke]=o.useState(null),[Me,Le]=o.useState(!1),[Ue,$e]=o.useState([]),J=o.useRef(null),Z=o.useRef([]),z=o.useRef(null),he=o.useRef(null),ge=o.useRef(!1),ne=o.useRef(!1),Fe=o.useRef(!0),C=o.useRef(0),Oe=o.useMemo(()=>Qc(p),[p]),{ensureMessageVisible:qe,hiddenItemCount:We,hiddenLaterItemCount:ye,revealAll:Nt,revealEarlier:mt,revealLatest:pt,visibleItems:gt}=Zl(t,Oe),At=o.useMemo(()=>!!(S&>.some(T=>T.type==="message"&&T.message.historyKey===S.historyKey)),[S,gt]),it=o.useRef(null),{copyText:kt,feedback:yt}=Fc(_.messageCopied,_.copyFailed),Pe=o.useMemo(()=>{const T=me.trim().toLowerCase();return T?p.map((F,ce)=>({index:ce,message:F})).filter(({message:F})=>F.content.toLowerCase().includes(T)):[]},[me,p]),jt=T=>{Fe.current=!1,C.current=0;const F=qe(T),ce=()=>Z.current[T]?.scrollIntoView({behavior:"smooth",block:"center"});F?requestAnimationFrame(()=>requestAnimationFrame(ce)):ce()},Et=()=>{if(!Pe.length)return;const T=Se%Pe.length,F=Pe[T]?.index;typeof F=="number"&&jt(F),Ee(ce=>(ce+1)%Pe.length)},Ke=o.useCallback(()=>{const T=J.current;T&&(Fe.current=!0,C.current=0,T.scrollTop=T.scrollHeight,Le(!1))},[]),bt=o.useCallback(T=>{Fe.current=!0,C.current=0,ne.current=!0,ge.current=!1,it.current=null;const F=J.current,ce=F?F.scrollHeight-F.scrollTop-F.clientHeight:0,Ce=T??(ye===0&&F&&ce<=F.clientHeight?"smooth":"auto"),Xe=()=>{const Re=J.current;Re&&(Re.scrollTo({top:Re.scrollHeight,behavior:Ce}),Le(!1),requestAnimationFrame(()=>{ne.current=!1}))};ye>0?(pt(),requestAnimationFrame(()=>requestAnimationFrame(Xe))):Xe()},[ye,pt]),at=()=>{const T=J.current;if(!T)return;const F=T.querySelector(".message-frame");it.current={element:F,top:F?F.getBoundingClientRect().top-T.getBoundingClientRect().top:T.scrollTop,height:T.scrollHeight}},vt=()=>{const T=J.current;if(!T)return;T.scrollTop<160&&We>0&&!ge.current&&!ne.current&&(ge.current=!0,at(),mt());const F=T.scrollHeight-T.scrollTop-T.clientHeight;performance.now()-C.current<1e3&&!ne.current&&!ge.current&&(Fe.current=F<240&&ye===0),Le(F>180||ye>0)};o.useLayoutEffect(()=>{ye>0&&Le(!0)},[ye]);const ot=()=>{he.current=null,C.current=performance.now()},ct=o.useMemo(()=>{const T=p.at(-1);return T?`${p.length}:${T.historyKey??""}:${T.timestamp??""}:${T.content.length}`:"0"},[p]);o.useLayoutEffect(()=>{const T=it.current,F=J.current;if(T&&F){if(T.element?.isConnected){const Re=T.element.getBoundingClientRect().top-F.getBoundingClientRect().top;F.scrollTop+=Re-T.top}else F.scrollTop+=F.scrollHeight-T.height;it.current=null,ge.current=!1;return}if(z.current!==t&&(z.current=t,he.current=t,Je(null),ke(null)),!J.current)return;const Ce=y===t;if(t!==null&&he.current===t&&Ce&&(!m||p.length>0)){Ke();let Re=0,nt=-1,pe=0;const xt=performance.now(),st=()=>{if(he.current!==t)return;Ke();const _e=J.current?.scrollHeight??0;pe=_e===nt?pe+1:0,nt=_e;const rt=performance.now()-xt>=1400;if(!m&&pe>=4||!m&&rt){he.current=null;return}rt||(Re=requestAnimationFrame(st))};return Re=requestAnimationFrame(st),Le(!1),()=>cancelAnimationFrame(Re)}Fe.current&&ye===0&&Ke()},[t,We,ye,m,ct,p.length,y,j,Ke]),o.useLayoutEffect(()=>{const T=J.current;if(!T)return;const F=new ResizeObserver(()=>{Fe.current&&ye===0&&Ke()});F.observe(T);for(const ce of T.children)F.observe(ce);return()=>F.disconnect()},[t,ct,We,ye,Ke]);const lt=Pe.length&&me.trim()?Pe[(Se+Pe.length-1)%Pe.length]?.index:void 0;return Kl(J,t,()=>{at(),Nt()}),s.jsxs("section",{className:"chat-pane","aria-label":_.chat,children:[s.jsx(Lc,{activeSession:e,agent:c,cwd:d,t:_,onOpenDetails:()=>e&&de(!0),renameTitle:k,busy:h,onRename:Q,onRenameTitleChange:Ve,onViewChanges:ie,search:{query:me,matchCount:Pe.length,onChange:T=>{ze(T),Ee(0)},onNext:Et}}),s.jsxs("div",{className:"chat-notices","aria-live":"polite",children:[b?s.jsx(qc,{message:b,retryLabel:_.retry,onRetry:oe,closeLabel:_.close,onDismiss:$}):null,S&&!At?s.jsx(ar,{failedSend:S,onRetry:()=>{te.retry()},t:_}):null,e?.interruptReason?s.jsxs("div",{className:"notice warning",children:[s.jsx(nn,{"aria-hidden":"true"}),s.jsx("span",{children:e.interruptReason.humanText||e.interruptReason.kind}),s.jsx("button",{className:"icon-text-button",disabled:h,onClick:ae,type:"button",children:_.clear})]}):null,e?.stallWarning?s.jsxs("div",{className:"notice warning",children:[s.jsx(ya,{"aria-hidden":"true"}),s.jsx("span",{children:e.stallWarning.humanText||_.agentMayBeStalled})]}):null]}),s.jsxs("div",{className:"message-scroll","aria-busy":m,"data-history-loading":m?"true":"false","data-rendered-items":gt.length,"data-hidden-items":We,"data-hidden-later-items":ye,"data-total-messages":p.length,ref:J,onScroll:vt,onPointerDown:ot,onTouchStart:ot,onWheel:ot,onKeyDown:ot,children:[m&&p.length===0?s.jsx(Wc,{label:_.loadingHistory}):null,!m&&p.length===0?s.jsxs("div",{className:"empty-state compact",children:[s.jsx(Ps,{"aria-hidden":"true"}),s.jsx("h2",{children:e?_.noVisibleMessages:_.startDaemonSession}),s.jsx("p",{children:_.emptyChatHint})]}):null,We>0?s.jsx("div",{className:"conversation-window-gate",children:s.jsx("button",{type:"button",onClick:()=>{ge.current=!0,at(),mt()},children:_.showEarlierMessages(We)})}):null,gt.map(T=>{if(T.type==="toolGroup"){const pe=T.entries.map(_e=>_e.message),xt=T.entries.some(_e=>lt===_e.index),st=Ye===T.id;return s.jsx("div",{className:"message-frame tool info",ref:_e=>{for(const rt of T.entries)Z.current[rt.index]=_e},children:s.jsxs("div",{className:"inline-message-stack",children:[s.jsx(Vl,{activeMatch:xt,expanded:st,messages:pe,onToggle:()=>ke(_e=>_e===T.id?null:T.id)}),st?s.jsx(bi,{messages:pe,showHeader:!1,onClose:()=>ke(null),onCopy:kt,t:_}):null]})},T.id)}const{index:F,message:ce}=T,Ce=ci(ce,F),Xe=Ze===Ce,Re=Ye===Ce,nt=S?.historyKey===ce.historyKey?S:null;return s.jsxs("div",{className:`message-frame ${ce.role} ${ce.type==="info"?"info":""}`,ref:pe=>{Z.current[F]=pe},children:[s.jsx(Gl,{activeMatch:lt===F,baseCwd:e?.cwd,message:ce,onCopy:kt,onRewind:h||N.has(t??"")?void 0:()=>R(ce),onCloseTool:()=>ke(null),onOpenAttachment:$e,onOpenRemoteFile:G,onToggleSource:()=>Je(pe=>pe===Ce?null:Ce),onToggleTool:()=>ke(pe=>pe===Ce?null:Ce),sourceOpen:Xe,toolOpen:Re,t:_}),nt?s.jsx(ar,{failedSend:nt,onRetry:()=>{te.retry()},t:_}):null]},Ce)}),ye>0?s.jsx("div",{className:"conversation-window-gate",children:s.jsx("button",{type:"button",onClick:()=>bt("auto"),children:_.showLatestMessages(ye)})}):null,s.jsx("div",{"aria-hidden":"true",className:"message-latest-anchor"}),Me?s.jsx(Hc,{label:_.newMessages,onClick:()=>bt()}):null]}),s.jsx(Oc,{feedback:yt}),s.jsx(Pc,{activeModelOptions:n,activeQueue:r,queueControls:i,agent:c,approvalMode:l,attachments:u,busy:h,sending:te.sending,responding:N.has(t??""),onStop:V,draft:f,effort:x,fastMode:v,model:g,phase:j,quickReplies:w,sendShortcut:D,skills:I,uploadBusy:W,onApprovalModeChange:be,onCancelQueuedTurn:X,onDraftChange:ve,onEffortChange:Ne,onFastModeChange:q,onModelChange:B,onRemoveAttachment:xe,onRefreshSkills:U,onSubmit:T=>(bt("auto"),te.submit(T)),onUploadFiles:ue,t:_},t),K&&e?s.jsx(Xl,{activeSession:e,activeUsage:a,busy:h,messages:p,renameTitle:k,t:_,onBrowseFiles:()=>{de(!1),Te()},onClose:()=>de(!1),onExport:A,onJumpToMessage:(T,F)=>{ze(F),Ee(0),jt(T)},onRename:Q,onRenameTitleChange:Ve,onToggleArchived:se,onTogglePinned:we,onViewChanges:()=>{de(!1),ie(e.sessionId)}}):null,s.jsx(_c,{cwd:e?.cwd,paths:Ue,t:_,onClose:()=>$e([]),onOpenRemoteFile:G})]})}const td="https://service.lifeos.vip/feedback",vi=8e3,nd=6e4,br=4,sd=20*1024*1024,xi=["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"],wi=["authorization","proxy-authorization"],Si=["cookie","set-cookie"],rd=[...wi,...Si],ts=(e,t)=>t.length-e.length,ki=[...xi].sort(ts).join("|"),id=xi.filter(e=>!rd.includes(e)).sort(ts).join("|"),ad=[...wi].sort(ts).join("|"),od=[...Si].sort(ts).join("|"),cd=new RegExp(`(?:${ki}|credential|private[-_ ]?key|session[-_ ]?id|e-?mail|phone|mobile|address)`,"i"),ld=new RegExp(`(["']?(?:${ad})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|(?:Basic|Bearer)\\s+[^\\s,;}]+|AWS4-HMAC-SHA256[^\\r\\n]*(?=\\r?$)|[^\\s,;}]+)`,"gim"),dd=new RegExp(`(["']?(?:${od})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\r\\n]+)`,"gi"),ud=new RegExp(`(["']?(?:${id})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\s,;}&]+)`,"gi"),hd=new RegExp(`([?&](?:${ki})=)[^&\\s]+`,"gi");function fd(e,t="[REDACTED]"){const n=(r,i,a)=>{const c=a[0]==='"'||a[0]==="'"?a[0]:"";if(!c)return`${i}${t}`;const l=a.slice(1,-1).trim(),u=/^(Basic|Bearer)\b/i.exec(l)?.[1];return`${i}${c}${u?`${u} `:""}${t}${c}`};return e.replace(/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gi,t).replace(ld,n).replace(dd,n).replace(ud,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(hd,`$1${t}`)}function md(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 an(e){return md(fd(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]")}function pd(e,t={}){if(!e)return{};const n=Math.max(0,t.characterBudget??6e4),r=Math.max(0,t.maxArrayEntries??50),i=Math.max(0,t.maxDepth??8),a=Math.max(0,t.maxObjectEntries??80),c=Math.max(0,t.maxStringLength??4e3),l={remaining:n},u=new WeakSet,h=(d,f)=>{if(l.remaining<=0)return"[TRUNCATED]";if(d===null||typeof d=="boolean"||typeof d=="number")return d;if(typeof d=="bigint")return d.toString();if(typeof d=="string"){const S=an(d).slice(0,Math.min(c,l.remaining));return l.remaining-=S.length,S}if(f>=i)return"[MAX_DEPTH]";if(typeof d!="object")return an(String(d)).slice(0,Math.min(200,l.remaining));if(u.has(d))return"[Circular]";if(u.add(d),Array.isArray(d))return d.slice(0,r).map(b=>h(b,f+1));const x={};for(const[b,S]of Object.entries(d).slice(0,a)){if(l.remaining<=0)break;const v=an(b).slice(0,Math.min(120,l.remaining));l.remaining-=v.length,x[v]=cd.test(b)?"[REDACTED]":h(S,f+1)}return x};return h(e,0)}function gd(e,t=nd){const n=an(e);return n.length<=t?n:`[truncated ${n.length-t} chars]
|
|
10
|
+
${n.slice(-t)}`}function yd(e){return an(e.trim()).slice(0,vi)}function bd(e){try{const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}async function vd(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 xd(e,t={}){const n=new AbortController,r=Number.isFinite(t.timeoutMs)&&(t.timeoutMs??0)>0?t.timeoutMs:15e3;let i;try{const a=(t.transport??vd)({url:t.endpoint??td,method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:n.signal}),c=new Promise((h,d)=>{i=setTimeout(()=>{n.abort(),d(new Error("Feedback request timed out"))},r)}),l=await Promise.race([a,c]),u=bd(l.body);if(l.status<200||l.status>=300||u.code!==0)throw new Error(u.message||l.statusText||"Feedback request failed");if(typeof u.data?.id!="string"||!u.data.id||typeof u.data.createdAt!="string")throw new Error("Feedback response is invalid");return{id:u.data.id,createdAt:u.data.createdAt,issueFingerprint:typeof u.data?.issueFingerprint=="string"?u.data.issueFingerprint:void 0,issueOccurrence:typeof u.data?.issueOccurrence=="number"?u.data.issueOccurrence:void 0}}finally{i&&clearTimeout(i)}}const wd=["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"],Sd=new Set(wd);function kd(e){const t={contextSchemaVersion:1};if(e)for(const[n,r]of Object.entries(e))Sd.has(n)&&r!==void 0&&(t[n]=r);return pd(t)}const jd={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"},Cd={title:"意见反馈",subtitle:"报告问题,或告诉我们希望改进的地方。",bug:"问题",feature:"建议",description:"详细说明",descriptionPlaceholder:"发生了什么,或者你希望我们怎样改进?",email:"邮箱(选填)",emailPlaceholder:"便于我们回复你",includeDiagnostics:"附带经过隐私处理的诊断信息",privacyNotice:"仅在需要时附带诊断信息;发送前会移除已识别的凭据、个人标识和本地路径。",submit:"发送反馈",sending:"正在发送…",success:"感谢反馈,已经发送成功。",error:"发送失败,请稍后重试。",close:"关闭"},Id={title:"意見回饋",subtitle:"回報問題,或告訴我們希望改善的地方。",bug:"問題",feature:"建議",description:"詳細說明",descriptionPlaceholder:"發生了什麼,或你希望我們如何改善?",email:"電子郵件(選填)",emailPlaceholder:"方便我們回覆你",includeDiagnostics:"附上經過隱私處理的診斷資訊",privacyNotice:"僅在需要時附上診斷資訊;傳送前會移除已識別的憑證、個人識別資訊和本機路徑。",submit:"傳送回饋",sending:"正在傳送…",success:"感謝回饋,已成功傳送。",error:"傳送失敗,請稍後再試。",close:"關閉"};function ji(e){const t=e?.trim().toLowerCase().replace(/_/g,"-")??"";return/^zh(?:-(?:tw|hk|mo|hant))(?:-|$)/u.test(t)?Id:t.startsWith("zh")?Cd:jd}const Nd=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function Ad(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}function Ed(e){if(!e?.length)return;if(e.length>br)throw new Error(`Feedback supports at most ${br} images`);const t=e.map(r=>{if(!Nd.has(r.mimeType))throw new Error("Feedback image type is not supported");const i=Ad(r.base64);if(!Number.isSafeInteger(r.size)||r.size<=0||i!==r.size)throw new Error("Feedback image size does not match its data");return{name:an(r.name.trim()||"image").slice(0,255),mimeType:r.mimeType,size:r.size,base64:r.base64}});if(t.reduce((r,i)=>r+i.size,0)>sd)throw new Error("Feedback images are too large");return t}function Rd(e){const t=yd(e.description);if(!t)throw new Error("Feedback description is required");const n=e.includeLogs===!1||!e.logs?"":gd(e.logs),r=e.email?.trim().slice(0,320);return{product:e.product,source:e.source,type:e.type,description:t,email:r||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:!!n,logs:n||void 0,metadata:kd(e.metadata),images:Ed(e.images)}}function Td({language:e,entry:t="web-settings"}){const n=He(e),r=o.useMemo(()=>ji(n),[n]),[i,a]=o.useState("bug"),[c,l]=o.useState(""),[u,h]=o.useState(""),[d,f]=o.useState("idle"),x=async()=>{if(!(!c.trim()||d==="sending")){f("sending");try{await xd(Rd({product:"vibelet",source:re().kind==="desktop"?"desktop":"web",type:i,description:c,email:u,appVersion:re().appVersion||"web",locale:n,platform:navigator.platform||"web",metadata:{app:re().kind==="desktop"?"vibelet-desktop":"vibelet-web",entry:t,screen:t==="connection-guide"?"connection-guide":"settings/language",module:"feedback",action:"manual-submit",userAgent:navigator.userAgent}})),l(""),f("success")}catch{f("error")}}};return s.jsxs("section",{className:"control-section compact-section",children:[s.jsx("h2",{children:r.title}),s.jsx("p",{className:"empty-copy",children:r.subtitle}),s.jsxs("div",{className:"feedback-type-grid",children:[s.jsx("button",{className:i==="bug"?"primary-button":"",type:"button","aria-pressed":i==="bug",onClick:()=>a("bug"),children:r.bug}),s.jsx("button",{className:i==="feature"?"primary-button":"",type:"button","aria-pressed":i==="feature",onClick:()=>a("feature"),children:r.feature})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:r.description}),s.jsx("textarea",{rows:5,maxLength:vi,value:c,placeholder:r.descriptionPlaceholder,onChange:b=>l(b.target.value)})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:r.email}),s.jsx("input",{type:"email",maxLength:320,value:u,placeholder:r.emailPlaceholder,onChange:b=>h(b.target.value)})]}),s.jsx("button",{className:"primary-button",type:"button",disabled:!c.trim()||d==="sending",onClick:()=>{x()},children:d==="sending"?r.sending:r.submit}),d==="success"?s.jsx("p",{className:"empty-copy success-copy",children:r.success}):null,d==="error"?s.jsx("p",{className:"empty-copy error-copy",children:r.error}):null]})}const us="vibelet --access=quick";function Md({errorText:e,t}){const[n,r]=o.useState("idle"),[i,a]=o.useState(!1),c=Be().language,l=ji(c),u=async()=>{try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(us);else{const h=document.createElement("textarea");h.value=us,h.style.position="fixed",h.style.opacity="0",document.body.append(h),h.select();const d=document.execCommand("copy");if(h.remove(),!d)throw new Error("copy failed")}r("success")}catch{r("error")}window.setTimeout(()=>r("idle"),1800)};return s.jsx("main",{className:"connection-guide",id:"vibelet-main-content",tabIndex:-1,children:s.jsxs("section",{className:"connection-guide-content","aria-labelledby":"connection-guide-title",children:[s.jsx("span",{className:"connection-guide-mark","aria-hidden":"true",children:s.jsx(Yn,{})}),s.jsx("span",{className:"connection-guide-eyebrow",children:"Vibelet Web"}),s.jsx("h1",{id:"connection-guide-title",children:t.openDaemonWebLink}),s.jsx("p",{children:t.openDaemonWebLinkHint}),s.jsxs("div",{className:"connection-command",children:[s.jsx("code",{children:us}),s.jsxs("button",{className:"primary-button",onClick:()=>{u()},type:"button",children:[n==="success"?s.jsx(Dt,{"aria-hidden":"true"}):s.jsx(on,{"aria-hidden":"true"}),s.jsx("span",{children:n==="success"?t.commandCopied:n==="error"?t.copyFailed:t.copyStartCommand})]})]}),s.jsx("p",{className:"connection-guide-footnote",children:t.connectionGuideFootnote}),e?s.jsx("p",{className:"connection-guide-error",children:e}):null,s.jsxs("button",{className:"connection-feedback-toggle",type:"button","aria-expanded":i,onClick:()=>a(h=>!h),children:[s.jsx(qr,{"aria-hidden":"true"}),l.title]}),i?s.jsx("div",{className:"connection-feedback-panel",children:s.jsx(Td,{language:c,entry:"connection-guide"})}):null]})})}const Pd=o.lazy(()=>tt(()=>import("./ImageViewer-BQ9YKQDY.js"),__vite__mapDeps([5,1,2,6,7])));function _d(){const[e,t]=o.useState(null);return o.useEffect(()=>{const n=r=>t(r.detail);return window.addEventListener(vs,n),()=>window.removeEventListener(vs,n)},[]),e?s.jsx(o.Suspense,{fallback:null,children:s.jsx(Pd,{request:e,onClose:()=>t(null)},e.images[e.index].src)}):null}function Dd(){const e=o.useRef(null),t=o.useRef({browser:0,terminal:0}),[n,r]=o.useState(0),[i,a]=o.useState([]),[c,l]=o.useState(null),[u,h]=o.useState({}),[d,f]=o.useState({}),x=o.useCallback((y,g,j,w,k,N)=>{const D=crypto.randomUUID(),I=y==="diff"?"center":"right";return y!=="diff"&&(g=`${g} ${++t.current[y]}`),a(W=>[...W,{id:D,kind:y,title:g,cwd:j,session:w,scope:k,path:N,location:I}]),I==="center"?l(D):h(W=>({...W,[y]:D})),D},[]),b=o.useCallback((y,g)=>{const j=i.find(w=>w.id===y);j&&(a(w=>w.map(k=>k.id===y?{...k,location:g}:k)),g==="center"?(l(y),h(w=>({...w,[j.kind]:i.find(k=>k.id!==y&&k.kind===j.kind&&k.location==="right")?.id}))):(h(w=>({...w,[j.kind]:y})),e.current?.(j.kind),c===y&&l(null)))},[i,c]),S=o.useCallback(y=>{const g=i.find(j=>j.id===y);a(j=>j.filter(w=>w.id!==y)),c===y&&l(null),g&&u[g.kind]===y&&h(j=>({...j,[g.kind]:i.find(w=>w.id!==y&&w.kind===g.kind&&w.location==="right")?.id}))},[i,c,u]),v=o.useCallback((y,g)=>a(j=>j.map(w=>w.id===y&&w.title!==g?{...w,title:g}:w)),[]),m=o.useCallback((y,g)=>f(j=>{if(j[y]===g||!j[y]&&!g)return j;const w={...j};return g?w[y]=g:delete w[y],w}),[]),p=o.useCallback(()=>{a([]),l(null),h({}),r(y=>y+1)},[]);return o.useMemo(()=>({openRight:e,epoch:n,items:i,center:c,right:u,hosts:d,add:x,move:b,close:S,rename:v,register:m,reset:p,setCenter:l,setRight:h}),[n,i,c,u,d,x,b,S,v,m,p])}const Vs=o.createContext(null);function Ld({children:e}){const t=Dd();return s.jsx(Vs.Provider,{value:t,children:e})}function Tn(){const e=o.useContext(Vs);if(!e)throw new Error("Dock workspace provider missing");return e}function Ci(){return o.useContext(Vs)}const Cs="application/x-vibelet-workspace-tab",$d={browser:Fr,terminal:Yn,diff:Qn};function Ks(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 Is({location:e,kind:t,t:n,cwd:r}){const i=Tn(),a=Ks(n),c=o.useRef(null),l=i.items.filter(u=>u.location===e&&(!t||u.kind===t));return o.useEffect(()=>{e==="right"&&t&&!i.items.some(u=>u.kind===t)&&i.add(t,n[t==="browser"?"browser":"terminal"],r)},[e,t,i.epoch]),o.useEffect(()=>{if(e!=="right"||!c.current)return;const u=c.current.querySelector('.dock-tab[data-active="true"]');u&&(c.current.scrollLeft=Math.max(0,u.offsetLeft-c.current.offsetLeft))},[e,t,i.right,l.map(u=>u.title).join("|")]),s.jsxs("div",{className:"dock-tabs",role:e==="right"?"tablist":"group","aria-label":t?n[t==="browser"?"browser":"terminal"]:void 0,children:[e==="right"&&t&&i.right[t]&&s.jsx("button",{type:"button",className:"dock-move dock-move-first","aria-label":a.center,title:a.center,onClick:()=>i.move(i.right[t],"center"),children:s.jsx(sa,{})}),s.jsx("div",{className:"dock-tab-items",ref:c,children:l.map(u=>{const h=e==="center"?i.center===u.id:i.right[u.kind]===u.id,d=$d[u.kind];return s.jsxs("div",{className:"document-tab dock-tab","data-active":h,"data-dock-id":u.id,draggable:!0,onDragStart:f=>{f.dataTransfer.setData(Cs,u.id),f.dataTransfer.effectAllowed="move"},children:[s.jsxs("button",{type:"button",role:"tab","aria-selected":h,title:u.title,onClick:()=>e==="center"?i.setCenter(u.id):i.setRight(f=>({...f,[u.kind]:u.id})),children:[s.jsx(d,{}),s.jsx("span",{children:u.title})]}),h&&e==="center"&&s.jsx("button",{type:"button",className:"dock-move","aria-label":a.right,title:a.right,onClick:()=>i.move(u.id,"right"),children:s.jsx(ia,{})}),s.jsx("button",{type:"button",className:"document-tab-close","aria-label":`${n.close} ${u.title}`,title:n.close,onClick:()=>i.close(u.id),children:s.jsx(De,{})})]},u.id)})}),e==="right"&&t&&s.jsx("button",{type:"button",className:"dock-new","aria-label":a.create,title:a.create,onClick:()=>i.add(t,n[t==="browser"?"browser":"terminal"],r),children:s.jsx(Jn,{})})]})}function Gn({location:e,kind:t}){const n=Tn(),r=e==="center"?"center":`right-${t}`,i=o.useCallback(a=>n.register(r,a),[n.register,r]);return s.jsx("div",{ref:i,className:"dock-slot","data-dock-location":e,"data-dock-kind":t})}function Qs(e,t){const n=Ci();return n?{onDragOver:r=>{r.dataTransfer.types.includes(Cs)&&(r.preventDefault(),r.dataTransfer.dropEffect="move",r.currentTarget.classList.add("dock-drop-target"))},onDragLeave:r=>{r.currentTarget.contains(r.relatedTarget)||r.currentTarget.classList.remove("dock-drop-target")},onDrop:r=>{r.currentTarget.classList.remove("dock-drop-target");const i=r.dataTransfer.getData(Cs),a=n.items.find(c=>c.id===i);a&&(r.preventDefault(),r.stopPropagation(),document.body.classList.remove("dock-dragging"),n.move(i,e),t?.(a.kind))}}:{}}const Fd=o.lazy(()=>tt(()=>import("./BrowserControlPanel-dQOp1WlN.js"),__vite__mapDeps([8,1,2,6]))),Od=o.lazy(()=>tt(()=>import("./TerminalControlPanel-DCmHOa9Y.js"),__vite__mapDeps([9,1,2]))),qd=o.lazy(()=>tt(()=>import("./DiffDrawer-CHjkoGPE.js"),__vite__mapDeps([10,1,2])).then(e=>({default:e.DiffDrawer})));function Wd({item:e,...t}){const n=Tn(),r=Qs(e.location),[i]=o.useState(()=>document.createElement("div")),a=e.location==="right",c=a?e.kind==="diff"?n.right.diff===e.id:t.rightVisible&&t.controlTab===e.kind&&n.right[e.kind]===e.id:n.center===e.id,l=n.hosts[a?`right-${e.kind}`:"center"]??n.hosts.parking,u=n.hosts.parking;o.useLayoutEffect(()=>{u&&i.parentElement!==u&&u.appendChild(i)},[i,u]),o.useLayoutEffect(()=>{i.className="dock-surface",i.dataset.dockId=e.id,i.dataset.location=e.location,i.dataset.kind=e.kind,i.hidden=!c;const d=a&&e.kind==="diff",f=()=>{const b=l?.getBoundingClientRect();Object.assign(i.style,d?{left:"0px",top:"0px",width:"100vw",height:"100vh"}:{left:`${b?.left??0}px`,top:`${b?.top??0}px`,width:`${b?.width??0}px`,height:`${b?.height??0}px`})};f();const x=new ResizeObserver(f);return l&&x.observe(l),window.addEventListener("resize",f),window.addEventListener("scroll",f,!0),()=>{x.disconnect(),window.removeEventListener("resize",f),window.removeEventListener("scroll",f,!0)}},[i,l,c,e.id,e.location,e.kind,a]),o.useLayoutEffect(()=>()=>i.remove(),[i]);const h=()=>n.move(e.id,a?"center":"right");return It.createPortal(s.jsx("div",{className:"dock-surface-content",...r,children:s.jsx(o.Suspense,{fallback:s.jsx("p",{className:"control-panel-loading",children:t.t.loading}),children:e.kind==="browser"?s.jsx(Fd,{t:t.t,onTitleChange:d=>n.rename(e.id,d)}):e.kind==="terminal"?s.jsx(Od,{client:t.client,cwd:e.cwd??"",deviceName:t.deviceName,visible:c,t:t.t}):e.session&&t.client?s.jsx(qd,{client:t.client,sessionId:e.session.sessionId,cwd:e.session.cwd,sessionTitle:e.title,t:t.t,onClose:()=>n.close(e.id),onDock:h,dockLabel:Ks(t.t).center,presentation:a?"drawer":"workspace",initialScope:e.scope,initialPath:e.path}):null})}),i)}function Hd(e){const t=Tn();t.openRight.current=r=>{(r==="browser"||r==="terminal")&&e.onOpenRight?.(r)};const n=o.useCallback(r=>t.register("parking",r),[t.register]);return o.useEffect(()=>{t.reset()},[e.daemonId]),s.jsxs(s.Fragment,{children:[s.jsx("div",{className:"dock-parking",ref:n}),s.jsx("div",{className:"dock-overlay-slot",children:s.jsx(Gn,{location:"right",kind:"diff"})}),t.items.map(r=>s.jsx(Wd,{item:r,...e},r.id))]})}const vr=new WeakMap,Ii=5e3;function Zs(e,t,n){let r=vr.get(e);r||vr.set(e,r=new Map);const i=JSON.stringify([t.sessionId,t.cwd,n]);let a=r.get(i);return a||(r.size>=12&&r.delete(r.keys().next().value),r.set(i,a={updated:0,patches:new Map})),a}function Yh(e,t,n){return Zs(e,t,n)}function Bd(e,t,n){const r=Zs(e,t,n);return r.pending?r.pending:r.data&&Date.now()-r.updated<Ii?Promise.resolve(r.data):(r.pending=e.request({action:"session.gitDiff.list",id:e.makeId("gitDiffList"),...t,scope:n}).then(i=>(r.data=i,r.updated=Date.now(),r.patches.clear(),i)).finally(()=>{r.pending=void 0}),r.pending)}function zd(e,t,n,r){const i=Zs(e,t,n),a=i.patches.get(r);if(a?.pending)return a.pending;if(a?.data&&Date.now()-i.updated<Ii)return Promise.resolve(a.data);i.patches.size>=12&&i.patches.delete(i.patches.keys().next().value);const c={};return i.patches.set(r,c),c.pending=e.request({action:"session.gitDiff.file",id:e.makeId("gitDiffFile"),...t,scope:n,path:r}).then(l=>(c.data=l,l)).finally(()=>{c.pending=void 0}),c.pending}async function Ud(e,t){const n=await Bd(e,t,"unstaged");n.files[0]&&await zd(e,t,"unstaged",n.files[0].path)}function Gd({t:e,onClose:t}){const n=o.useRef(null),r=En(t,n);return s.jsxs("div",{className:"diff-drawer",role:"dialog","aria-modal":"true","aria-label":e.changes,ref:r,tabIndex:-1,children:[s.jsx("div",{className:"diff-drawer-backdrop",onClick:t,"aria-hidden":"true"}),s.jsxs("div",{className:"diff-drawer-panel",children:[s.jsxs("header",{className:"diff-drawer-header",children:[s.jsx("strong",{children:e.changes}),s.jsx("button",{ref:n,type:"button",className:"icon-button","aria-label":e.closeChanges,onClick:t,children:s.jsx(De,{})})]}),s.jsxs("div",{className:"diff-empty",role:"status",children:[s.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),e.loadingPatch]})]})]})}const Vd=o.lazy(async()=>tt(()=>import("./FilesControlPanel-A7LFhjRm.js"),__vite__mapDeps([11,1,2,12,13])).then(e=>({default:e.FilesControlPanel}))),Kd=o.lazy(async()=>tt(()=>import("./LanguageSettingsPanel-Benilh-Y.js"),__vite__mapDeps([14,1,2,15])).then(e=>({default:e.LanguageSettingsPanel}))),Qd=o.lazy(async()=>tt(()=>import("./ThemeSettingsPanel-DNDIWk0L.js"),__vite__mapDeps([16,1,2,15])).then(e=>({default:e.ThemeSettingsPanel}))),Zd=o.lazy(async()=>tt(()=>import("./NotificationSettingsPanel-B_k_PfhC.js"),__vite__mapDeps([17,1,2])).then(e=>({default:e.NotificationSettingsPanel}))),Ni=()=>tt(()=>import("./DiffDrawer-CHjkoGPE.js"),__vite__mapDeps([10,1,2])).then(e=>({default:e.DiffDrawer})),Jd=o.lazy(Ni);function xr({t:e}){return s.jsxs("div",{className:"control-panel-loading","aria-live":"polite","aria-busy":"true",children:[s.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),s.jsx("span",{children:e.loadingControls})]})}function Yd({client:e,id:t,activeSession:n,sessions:r,t:i,close:a}){const c=Ci(),l=n?.sessionId,u=n?.cwd,h=n?.runtime.isResponding;o.useEffect(()=>{if(!e||!l)return;const f=window.setTimeout(()=>{document.visibilityState!=="hidden"&&(Ni().catch(()=>{}),Ud(e,{sessionId:l,cwd:u}).catch(()=>{}))},350);return()=>window.clearTimeout(f)},[e,l,u,h]);const d=r.find(f=>f.sessionId===t);return!d||!e?null:s.jsx(o.Suspense,{fallback:s.jsx(Gd,{t:i,onClose:a}),children:s.jsx(Jd,{client:e,sessionId:d.sessionId,cwd:d.cwd,sessionTitle:St(d),t:i,onClose:a,dockLabel:Ks(i).center,onDock:c?({scope:f,path:x})=>{c.add("diff",St(d),d.cwd,d,f,x),a()}:void 0},d.sessionId)})}const Xd="/web/assets/logo-SQcOtj-8.png";function eu({activeDaemonId:e,busy:t,fallbackName:n,phase:r,statusText:i,t:a,targets:c,onConnect:l,onRename:u}){const[h,d]=o.useState(!1),[f,x]=o.useState(null),[b,S]=o.useState(""),v=o.useRef(null),p=c.find(j=>j.daemonId===e)?.label||n||e?.slice(0,10)||"Vibelet Web";o.useEffect(()=>{if(!h)return;const j=k=>{k.target instanceof Node&&!v.current?.contains(k.target)&&d(!1)},w=k=>{k.key==="Escape"&&d(!1)};return document.addEventListener("pointerdown",j),document.addEventListener("keydown",w),()=>{document.removeEventListener("pointerdown",j),document.removeEventListener("keydown",w)}},[h]);const y=j=>{x(j.daemonId),S(j.label)},g=()=>{!f||!b.trim()||(u(f,b),x(null))};return s.jsxs("div",{className:"device-switcher",ref:v,children:[s.jsxs("button",{"aria-expanded":h,"aria-haspopup":"menu",className:"device-switcher-trigger",onClick:()=>d(j=>!j),title:p,type:"button",children:[s.jsx("strong",{children:p}),s.jsx(_r,{"aria-hidden":"true"})]}),s.jsxs("span",{className:`brand-connection ${r}`,children:[s.jsx("i",{"aria-hidden":"true"}),r==="connected"?a.connected:i]}),h?s.jsxs("div",{"aria-label":a.savedDevices,className:"device-switcher-menu",role:"menu",children:[c.map(j=>{const w=j.daemonId===e;return s.jsx("div",{className:"device-switcher-row",children:f===j.daemonId?s.jsxs("form",{className:"device-rename-form",onSubmit:k=>{k.preventDefault(),g()},children:[s.jsx("input",{"aria-label":a.rename,autoFocus:!0,onChange:k=>S(k.target.value),value:b}),s.jsx("button",{"aria-label":a.rename,disabled:!b.trim(),type:"submit",children:s.jsx(Dt,{"aria-hidden":"true"})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:"device-connect-button",disabled:t||w,onClick:()=>{l(j),d(!1)},role:"menuitem",type:"button",children:[w?s.jsx(Dt,{"aria-hidden":"true"}):s.jsx(Br,{"aria-hidden":"true"}),s.jsxs("span",{children:[s.jsx("strong",{children:j.label}),s.jsx("small",{children:w?a.active:j.displayName||j.daemonId})]})]}),s.jsx("button",{"aria-label":`${a.rename} ${j.label}`,className:"device-rename-button",onClick:()=>y(j),type:"button",children:s.jsx(so,{"aria-hidden":"true"})})]})},j.daemonId)}),c.length===0?s.jsx("p",{className:"empty-copy",children:a.noSavedDevices}):null]}):null]})}function Ai({label:e,value:t,options:n,onChange:r}){const i=o.useId();return s.jsxs("div",{className:"filter-section",children:[s.jsx("span",{className:"filter-section-label",id:i,children:e}),s.jsx("div",{className:"filter-choice-list",role:"radiogroup","aria-labelledby":i,children:n.map(a=>s.jsxs("label",{className:"filter-menu-row",children:[s.jsx("input",{type:"radio",name:i,value:a.value,checked:t===a.value,onChange:()=>r(a.value)}),s.jsx("span",{children:a.label}),s.jsx(Dt,{className:"filter-menu-check","aria-hidden":"true","data-checked":t===a.value})]},a.value))})]})}function tu({folder:e,initialValue:t,t:n,onClose:r,onSave:i}){const[a,c]=o.useState(t),l=o.useRef(null),u=En(r,l),h=d=>{d.preventDefault(),i(a)};return It.createPortal(s.jsxs("div",{"aria-labelledby":"folder-tag-dialog-title","aria-modal":"true",className:"folder-tag-dialog-layer",ref:u,role:"dialog",tabIndex:-1,children:[s.jsx("div",{"aria-hidden":"true",className:"folder-tag-dialog-backdrop",onClick:r}),s.jsxs("form",{className:"folder-tag-dialog",onSubmit:h,children:[s.jsxs("header",{children:[s.jsx("span",{className:"folder-tag-dialog-icon","aria-hidden":"true",children:s.jsx(Vr,{})}),s.jsxs("div",{children:[s.jsx("strong",{id:"folder-tag-dialog-title",children:n.editDirectoryTags}),s.jsx("span",{title:e,children:e})]}),s.jsx("button",{"aria-label":n.cancel,className:"mini-button",onClick:r,type:"button",children:s.jsx(De,{"aria-hidden":"true"})})]}),s.jsxs("label",{className:"folder-tag-dialog-field",children:[s.jsx("span",{children:n.directoryTags}),s.jsx("textarea",{"aria-describedby":"folder-tag-dialog-help",placeholder:n.directoryTagsPlaceholder,ref:l,rows:3,value:a,onChange:d=>c(d.target.value)})]}),s.jsx("p",{id:"folder-tag-dialog-help",children:n.directoryTagsDescription}),s.jsxs("footer",{children:[s.jsx("button",{className:"icon-text-button",onClick:r,type:"button",children:n.cancel}),s.jsx("button",{className:"primary-button",type:"submit",children:n.saveDirectoryTags})]})]})]}),document.body)}function nu({search:e,busy:t,connected:n,filtersOpen:r,filtersActive:i,t:a,onSearchChange:c,onSearchCommit:l,onToggleFilters:u,onCreate:h}){const[d,f]=o.useState(!!e),x=o.useRef(null);return s.jsxs(s.Fragment,{children:[s.jsxs("div",{className:"rail-list-heading",children:[s.jsx("span",{children:a.sessions}),s.jsxs("div",{className:"rail-heading-actions",children:[s.jsx("button",{"aria-label":a.searchSessions,"aria-expanded":d,className:"rail-create-button",title:a.searchSessions,type:"button",onClick:()=>{f(!0),requestAnimationFrame(()=>x.current?.focus())},children:s.jsx(wn,{"aria-hidden":"true"})}),s.jsx("button",{"aria-label":a.newSession,className:"rail-create-button",disabled:t||!n,onClick:h,title:a.newSession,type:"button",children:s.jsx(Jn,{"aria-hidden":"true"})}),s.jsx("button",{"aria-expanded":r,"aria-label":a.sessionFilters,className:`filter-toggle ${r||i?"selected":""}`,onClick:u,title:a.sessionFilters,type:"button",children:s.jsx(Da,{"aria-hidden":"true"})})]})]}),(d||e)&&s.jsxs("div",{className:"search-box",children:[s.jsx(wn,{"aria-hidden":"true"}),s.jsx("input",{ref:x,"aria-label":a.searchSessions,value:e,onBlur:l,onChange:b=>c(b.target.value),placeholder:a.searchSessions,onKeyDown:b=>{b.key==="Enter"&&l(),b.key==="Escape"&&(c(""),l(),f(!1))}}),s.jsx("button",{className:"filter-toggle","aria-label":a.cancel,type:"button",onClick:()=>{c(""),f(!1),x.current?.blur()},children:s.jsx(De,{"aria-hidden":"true"})})]})]})}function su({menu:e,pending:t,t:n,onOpen:r,onDetails:i,onCopyResumeCommand:a,onTogglePinned:c,onToggleArchived:l,onDelete:u}){return s.jsxs("div",{className:"session-context-menu",role:"menu",style:{left:e.x,top:e.y},onPointerDown:h=>h.stopPropagation(),children:[s.jsxs("button",{type:"button",role:"menuitem",onClick:r,children:[s.jsx(Pr,{"aria-hidden":"true"}),n.open]}),s.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:i,children:[s.jsx(Or,{"aria-hidden":"true"}),n.details]}),s.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:a,children:[s.jsx(on,{"aria-hidden":"true"}),n.copyResumeCommand]}),s.jsx("span",{className:"context-menu-separator"}),s.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:c,children:[s.jsx(Zn,{"aria-hidden":"true"}),e.session.pinned?n.unpin:n.pin]}),s.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:l,children:[s.jsx(Ms,{"aria-hidden":"true"}),e.session.archived?n.unarchive:n.archive]}),s.jsxs("button",{className:"danger",type:"button",role:"menuitem",onClick:u,children:[s.jsx(Kr,{"aria-hidden":"true"}),n.delete]})]})}function wr({session:e,active:t,responding:n,tagLabels:r,showFolder:i=!0,t:a,onSelect:c,onContextMenu:l}){const u=St(e),h=e.cwd?.split(/[\\/]/).filter(Boolean).at(-1)||e.cwd||".";return s.jsxs("div",{className:"session-item",children:[s.jsxs("button",{className:`session-row ${t?"active":""} ${e.archived?"archived":""} ${n?"responding":""}`,"data-session-id":e.sessionId,"aria-current":t?"true":void 0,onContextMenu:l,onClick:c,title:u,type:"button",children:[s.jsxs("span",{className:"session-row-head",children:[s.jsx("strong",{children:u}),n?s.jsx(Rn,{className:"session-running-icon","aria-label":a.agentResponding}):null]}),r?.length?s.jsx("span",{className:"directory-tag-row",title:a.directoryTags,children:r.map(d=>s.jsx("em",{children:d},d))}):null,s.jsx("span",{className:"session-row-footer",children:s.jsxs("small",{title:i?e.cwd:void 0,children:[i?s.jsxs("span",{className:"session-row-folder",children:[h," · "]}):null,e.agent," · ",Xn(e.lastActivityAt,Date.now(),a),e.branch?` · ${e.branch}`:"",e.pinned?` · ${a.pinned}`:"",e.archived?` · ${a.archived}`:""]})})]}),e.pullRequest&&s.jsxs("a",{className:"session-pr-link",href:e.pullRequest.url,target:"_blank",rel:"noopener noreferrer",title:`${e.branch||""} · ${e.pullRequest.title}`,children:["PR #",e.pullRequest.number]})]})}function ru({activeSessionId:e,busy:t,collapsedFolders:n,folderCounts:r,getFolderTags:i,groupFolders:a,groupedSessions:c,phase:l,respondingSessionIds:u,t:h,visibleSessions:d,onEditFolderTags:f,onOpenCreateMenu:x,onOpenSessionMenu:b,onSelectSession:S,onToggleFolder:v}){const m=o.useId();return a?s.jsxs(s.Fragment,{children:[c.map(p=>{const y=!!n[p.folder],g=`${m}-${encodeURIComponent(p.folder)}`,j=p.kind==="folder"?r[p.folder]??p.sessions.length:p.sessions.length,w=p.kind==="attention"?h.needsAttentionSessionsGroup:p.kind==="running"?h.runningSessionsGroup:p.kind==="pinned"?h.pinnedSessionsGroup:p.folder;return s.jsxs("div",{className:`folder-group ${p.kind!=="folder"?"virtual-session-group":""}`,children:[s.jsxs("div",{className:"folder-heading",children:[s.jsxs("div",{className:"folder-header",children:[s.jsxs("button",{"aria-expanded":!y,"aria-controls":g,title:w,onClick:()=>v(p.folder),type:"button",children:[s.jsx(Dr,{className:"folder-disclosure","aria-hidden":"true"}),p.kind==="attention"?s.jsx(Or,{"aria-hidden":"true"}):p.kind==="running"?s.jsx(Zi,{"aria-hidden":"true"}):p.kind==="pinned"?s.jsx(Zn,{"aria-hidden":"true"}):y?s.jsx(Pa,{"aria-hidden":"true"}):s.jsx(zn,{"aria-hidden":"true"}),s.jsx("span",{children:p.kind==="folder"?p.folder.split(/[\\/]/).filter(Boolean).at(-1)||p.folder:w})]}),p.kind==="folder"?s.jsxs(s.Fragment,{children:[s.jsx("button",{"aria-label":i(p.folder).length?h.editDirectoryTags:h.addDirectoryTags,className:"mini-button folder-hover-action",onClick:()=>f(p.folder),title:i(p.folder).length?h.editDirectoryTags:h.addDirectoryTags,type:"button",children:s.jsx(Vr,{"aria-hidden":"true"})}),s.jsx("button",{"aria-label":h.newSession,className:"mini-button folder-hover-action",disabled:t||l!=="connected",onClick:k=>x(k,p.folder),title:h.newSession,type:"button",children:s.jsx(Jn,{"aria-hidden":"true"})})]}):null,s.jsx("small",{className:"folder-session-count",title:`${j} ${h.sessions}`,children:j})]}),p.kind==="folder"&&i(p.folder).length?s.jsx("div",{className:"folder-tag-row",children:i(p.folder).map(k=>s.jsx("span",{children:k},k))}):null]}),s.jsx("div",{className:"folder-session-list",id:g,hidden:y,children:y?null:p.sessions.map(k=>s.jsx(wr,{active:k.sessionId===e,responding:u.has(k.sessionId),session:k,showFolder:p.kind!=="folder",tagLabels:i(k.cwd),t:h,onContextMenu:N=>b(N,k),onSelect:()=>S(k.sessionId)},k.sessionId))})]},p.folder)}),d.length===0?s.jsx("p",{className:"empty-copy",children:h.noSessionsMatch}):null]}):s.jsxs(s.Fragment,{children:[d.map(p=>s.jsx(wr,{active:p.sessionId===e,responding:u.has(p.sessionId),session:p,tagLabels:i(p.cwd),t:h,onContextMenu:y=>b(y,p),onSelect:()=>S(p.sessionId)},p.sessionId)),d.length===0?s.jsx("p",{className:"empty-copy",children:h.noSessionsMatch}):null]})}function iu({agentFilter:e,t,onAgentFilterChange:n}){return s.jsx(Ai,{label:t.agentFilterLabel,value:e,options:[{value:"all",label:t.agentFilterAll},{value:"claude",label:t.agentFilterClaude},{value:"codex",label:t.agentFilterCodex}],onChange:n})}function au({groupFolders:e,hideArchived:t,separatePinnedGroup:n,showNeedsAttentionGroup:r,showRunningGroup:i,t:a,onToggleGroupFolders:c,onToggleHideArchived:l,onToggleNeedsAttentionGroup:u,onToggleRunningGroup:h,onToggleSeparatePinnedGroup:d}){const f=[[a.showNeedsAttentionGroup,r,u],[a.showRunningGroup,i,h],[a.separatePinnedGroup,n,d]];return s.jsxs("div",{className:"filter-section",children:[s.jsx("span",{className:"filter-section-label",children:a.filterViewOptions}),s.jsxs("div",{className:"filter-view-list",children:[s.jsxs("button",{"aria-pressed":e,className:"filter-menu-row",onClick:c,type:"button",children:[s.jsx("span",{children:a.groupByFolder}),s.jsx(Dt,{className:"filter-menu-check","aria-hidden":"true","data-checked":e})]}),f.map(([x,b,S])=>s.jsxs("button",{"aria-pressed":e&&b,className:"filter-menu-row nested-filter-option",disabled:!e,onClick:S,type:"button",children:[s.jsx("span",{children:x}),s.jsx(Dt,{className:"filter-menu-check","aria-hidden":"true","data-checked":e&&b})]},x)),s.jsxs("button",{"aria-pressed":t,className:"filter-menu-row",onClick:l,type:"button",children:[s.jsx("span",{children:a.hideArchived}),s.jsx(Dt,{className:"filter-menu-check","aria-hidden":"true","data-checked":t})]})]})]})}function ou(e,t){const n=o.useRef(null),r=o.useRef(null),i=o.useRef(t),[a,c]=o.useState(null),l=!!(e?.lastActivityAt&&e.sessionId),u=l?`${e?.lastActivityAt}:${e?.sessionId}`:null;return o.useEffect(()=>{i.current=t},[t]),o.useEffect(()=>{const h=n.current;if(!h||!e||!u){r.current=null,c(null);return}const d=h.closest(".session-list");if(!(d instanceof HTMLElement))return;let f=!0,x;c(null);const b=new IntersectionObserver(S=>{!S.some(v=>v.isIntersecting)||r.current===u||(r.current=u,c(u),i.current(e).catch(()=>{f&&(x=window.setTimeout(()=>{f&&(r.current=null,b.unobserve(h),b.observe(h))},1500))}).finally(()=>{f&&c(v=>v===u?null:v)}))},{root:d,rootMargin:"0px 0px 240px 0px",threshold:.01});return b.observe(h),()=>{f=!1,x!==void 0&&window.clearTimeout(x),b.disconnect()}},[u,e]),{canLoadMore:l,loading:a===u,sentinelRef:n}}function cu(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function lu({activeSessionId:e,busy:t,collapsedFolders:n,currentCwd:r,activeDaemonId:i,displayName:a,savedTargets:c,directoryTags:l,folderCounts:u,groupFolders:h,groupedSessions:d,hideArchived:f,separatePinnedGroup:x,showNeedsAttentionGroup:b,showRunningGroup:S,inventoryVersion:v,nextCursor:m,phase:p,pendingSessionIds:y,respondingSessionIds:g,search:j,sessionAgentFilter:w,sessionsCount:k,sinceFilter:N,statusText:D,t:I,visibleSessions:W,onLoadMore:K,onCopyResumeCommand:_,onConnectTarget:be,onRequestNewSession:Te,onDeleteSession:X,onEditFolderTags:ae,onOpenSessionDetails:ve,onResetFilters:de,onRenameTarget:Ne,onSearchChange:A,onSearchCommit:R,onSelectSession:q,onToggleSessionArchived:H,onToggleSessionPinned:B,onSessionAgentFilterChange:G,onSinceFilterChange:V,onToggleFolder:oe,onToggleGroupFolders:$,onToggleHideArchived:U,onToggleNeedsAttentionGroup:Q,onToggleRunningGroup:Ve,onToggleSeparatePinnedGroup:xe}){const[Ae,se]=o.useState(!1),[we,ue]=o.useState(null),[ie,te]=o.useState(null),me=o.useRef(null),ze=w!=="all"||N!=="30d"||!h||h&&(b||S||x)||f,Se=ou(m,K),Ee=ie?!!y?.has(ie.session.sessionId):!1,Ze=Z=>l[cu(Z)??"/"]??[],Je=p==="connected"?`${W.length}/${k} sessions · v${v??"-"}`:I.sameOriginAccess,Ye=`${D} · ${Je}`;o.useEffect(()=>{if(!Ae&&!ie)return;const Z=he=>{const ge=he.target;ge instanceof Node&&me.current?.contains(ge)||(se(!1),te(null))},z=he=>{he.key==="Escape"&&(se(!1),te(null))};return document.addEventListener("pointerdown",Z),document.addEventListener("keydown",z),()=>{document.removeEventListener("pointerdown",Z),document.removeEventListener("keydown",z)}},[ie,Ae]);const ke=(Z,z)=>{te(null),se(!1),Te(z)},Me=(Z,z)=>{Z.preventDefault(),te({session:z,x:Math.min(Z.clientX,window.innerWidth-224-10),y:Math.min(Z.clientY,window.innerHeight-306-10)})},Le=()=>te(null),Ue=Z=>{se(!1),te(null),ue({folder:Z,value:Ze(Z).join(", ")})},$e=Z=>{we&&(ae(we.folder,Z),ue(null))},J=Z=>{if(!ie)return;const{session:z}=ie;Le(),Z(z)};return s.jsxs("aside",{className:"session-rail","aria-label":I.sessions,children:[s.jsxs("div",{className:"brand-block",title:Ye,children:[s.jsx("div",{className:"brand-mark","aria-hidden":"true",children:s.jsx("img",{alt:"",className:"brand-logo",height:"40",src:Xd,width:"40"})}),s.jsx(eu,{activeDaemonId:i,busy:t,fallbackName:a,phase:p,statusText:D,t:I,targets:c,onConnect:be,onRename:Ne})]}),s.jsxs("div",{className:"search-filter-wrap",ref:me,children:[s.jsx(nu,{search:j,busy:t,connected:p==="connected",filtersOpen:Ae,filtersActive:ze,t:I,onSearchChange:A,onSearchCommit:R,onToggleFilters:()=>se(Z=>!Z),onCreate:ke}),Ae?s.jsxs("div",{className:"filter-popover",role:"dialog","aria-label":I.sessionFilters,children:[s.jsx(iu,{agentFilter:w,t:I,onAgentFilterChange:G}),s.jsx(Ai,{label:I.searchTimeRangeLabel,value:N,options:[{value:"all",label:I.searchTimeRangeAllTime},{value:"7d",label:I.searchTimeRangeLast7Days},{value:"30d",label:I.searchTimeRangeLast30Days},{value:"90d",label:I.searchTimeRangeLast90Days}],onChange:V}),s.jsx(au,{groupFolders:h,hideArchived:f,separatePinnedGroup:x,showNeedsAttentionGroup:b,showRunningGroup:S,t:I,onToggleGroupFolders:$,onToggleHideArchived:U,onToggleNeedsAttentionGroup:Q,onToggleRunningGroup:Ve,onToggleSeparatePinnedGroup:xe}),ze?s.jsx("button",{className:"filter-reset-button",onClick:de,type:"button",children:I.resetFilters}):null]}):null]}),s.jsxs("div",{className:"session-list",children:[s.jsx(ru,{activeSessionId:e,busy:t,collapsedFolders:n,folderCounts:u,getFolderTags:Ze,groupFolders:h,groupedSessions:d,phase:p,respondingSessionIds:g,t:I,visibleSessions:W,onEditFolderTags:Ue,onOpenCreateMenu:ke,onOpenSessionMenu:Me,onSelectSession:q,onToggleFolder:oe}),Se.canLoadMore?s.jsx("div",{"aria-live":"polite",className:`session-load-sentinel ${Se.loading?"loading":""}`,ref:Se.sentinelRef,role:"status",children:Se.loading?s.jsxs(s.Fragment,{children:[s.jsx(Rn,{className:"spin","aria-hidden":"true"}),s.jsx("span",{children:I.loadingMore})]}):null}):null]}),we?s.jsx(tu,{folder:we.folder,initialValue:we.value,t:I,onClose:()=>ue(null),onSave:$e}):null,ie?s.jsx(su,{menu:ie,pending:Ee,t:I,onOpen:()=>J(Z=>q(Z.sessionId)),onDetails:()=>J(ve),onCopyResumeCommand:()=>J(_),onTogglePinned:()=>J(B),onToggleArchived:()=>J(H),onDelete:()=>J(X)}):null]})}function du({collapsed:e,children:t,onExpand:n,onResize:r,t:i}){const a=re().toolbarTarget?.("left"),c=s.jsx("button",{"aria-label":e?i.expandSessionSidebar:i.collapseSessionSidebar,className:"sidebar-titlebar-toggle",onClick:n,title:e?i.expandSessionSidebar:i.collapseSessionSidebar,type:"button",children:s.jsx(Ya,{"aria-hidden":"true"})});return s.jsxs(s.Fragment,{children:[a?It.createPortal(c,a):c,s.jsx("div",{className:"session-sidebar-motion",inert:e,"aria-hidden":e,children:t}),s.jsx("button",{"aria-label":i.resizeSessionSidebar,"aria-hidden":e,className:"resize-handle",disabled:e,onPointerDown:r,title:i.resizeSessionSidebar,type:"button",children:s.jsx("span",{})})]})}const Js={version:"",latestVersion:"",loading:!1,error:null};function Sr(e){const t=e.match(/^\d+/);return t?Number(t[0]):0}function uu(e,t){const n=e.split(/[+-]/,1)[0].split(".").map(Sr),r=t.split(/[+-]/,1)[0].split(".").map(Sr),i=Math.max(n.length,r.length);for(let a=0;a<i;a+=1){const c=n[a]??0,l=r[a]??0;if(c<l)return-1;if(c>l)return 1}return 0}function Ei(e,t){return uu(e,t)<0}function hu(e){const t=e.toLowerCase();if(t.includes("alpha"))return"alpha";if(t.includes("beta"))return"beta";if(e.trim())return"latest"}function fu(e,t,n){const r=e?.webSocketUrl?e.webSocketUrl:t.origin;try{const i=new URL(r);return i.protocol==="ws:"&&(i.protocol="http:"),i.protocol==="wss:"&&(i.protocol="https:"),i.pathname="/health",i.search="",i.hash="",i.toString()}catch{return new URL("/health",t.origin).toString()}}function mu(e){if(!e||typeof e!="object")return{version:"",latestVersion:""};const t=e;return{version:typeof t.version=="string"?t.version.trim():"",latestVersion:typeof t.latestVersion=="string"?t.latestVersion.trim():""}}function pu({busy:e,connected:t,dismissed:n,feedback:r,synced:i,t:a,onPull:c,onPushMerge:l,onPushReplace:u,onSkip:h}){const d=!t||e!==null;return s.jsxs("section",{className:"control-section compact-section archive-sync-panel",children:[s.jsx("h2",{children:a.archiveSyncTitle}),s.jsx("p",{className:"empty-copy",children:i?a.archiveSyncSynced:n?a.archiveSyncSkippedState:a.archiveSyncBody}),s.jsxs("div",{className:"action-grid archive-sync-actions",children:[s.jsxs("button",{className:"icon-text-button",disabled:d,onClick:l,type:"button",children:[s.jsx(Oa,{"aria-hidden":"true"}),e==="pushMerge"?a.archiveSyncSyncing:a.archiveSyncPushMerge]}),s.jsxs("button",{className:"icon-text-button",disabled:d,onClick:c,type:"button",children:[s.jsx(Kn,{"aria-hidden":"true"}),e==="pull"?a.archiveSyncSyncing:a.archiveSyncPull]}),s.jsxs("button",{className:"icon-text-button",disabled:d,onClick:u,type:"button",children:[s.jsx(No,{"aria-hidden":"true"}),e==="pushReplace"?a.archiveSyncSyncing:a.archiveSyncPushReplace]}),s.jsxs("button",{className:"icon-text-button",disabled:d,onClick:h,type:"button",children:[s.jsx(Yi,{"aria-hidden":"true"}),a.archiveSyncSkip]})]}),r?s.jsx("p",{className:`empty-copy ${r.tone==="error"?"error-copy":"success-copy"}`,children:r.message}):null]})}function gu({pairing:e,phase:t,t:n,onForgetPairing:r}){const i=t==="connected"?"connected":e?t:n.notPaired;return s.jsxs("section",{className:"control-section compact-section",children:[s.jsx("h2",{children:n.currentDevice}),s.jsxs("dl",{children:[s.jsxs("div",{children:[s.jsx("dt",{children:n.daemon}),s.jsx("dd",{children:e?.displayName??e?.daemonId??n.notPaired})]}),s.jsxs("div",{children:[s.jsx("dt",{children:n.status}),s.jsx("dd",{children:i})]})]}),s.jsx("div",{className:"action-grid",children:s.jsxs("button",{className:"danger-button",disabled:!e,onClick:r,type:"button",children:[s.jsx(Va,{"aria-hidden":"true"}),n.forget]})})]})}function yu({connected:e,metadata:t,showUpdate:n,updateBusy:r,restartBusy:i,t:a,updateStatus:c,onUpdate:l,onRestart:u}){const h=t.version&&t.latestVersion&&n?`${t.version} -> ${t.latestVersion}`:t.version||a.unknown;return s.jsxs("section",{className:"control-section compact-section",children:[s.jsx("h2",{children:a.desktopConnector}),s.jsx("dl",{children:s.jsxs("div",{children:[s.jsx("dt",{children:a.version}),s.jsx("dd",{children:t.loading?a.checking:h})]})}),s.jsxs("div",{className:"action-grid",children:[n?s.jsxs("button",{className:"primary-button",disabled:!e||r||i,onClick:l,type:"button",children:[s.jsx(Kn,{"aria-hidden":"true"}),r?a.updating:a.update]}):null,s.jsxs("button",{className:"danger-button",disabled:!e||i,onClick:u,type:"button",children:[s.jsx(xn,{"aria-hidden":"true"}),i?a.restarting:a.restart]})]}),t.error?s.jsx("p",{className:"empty-copy",children:t.error}):null,c?s.jsx("p",{className:"empty-copy",children:c}):null]})}function bu({activeDaemonId:e,busy:t,t:n,targets:r,onConnect:i,onForget:a}){return s.jsxs("section",{className:"control-section compact-section",children:[s.jsx("h2",{children:n.savedDevices}),s.jsxs("div",{className:"stack-list",children:[r.map(c=>s.jsxs("div",{className:"data-row target-row",children:[s.jsxs("div",{children:[s.jsxs("strong",{children:[c.label,c.daemonId===e?` · ${n.active}`:""]}),s.jsxs("span",{children:[c.displayName??c.daemonId," ·"," ",c.lastConnectedAt?Xn(c.lastConnectedAt,Date.now(),n):n.notConnectedRecently]})]}),s.jsxs("div",{className:"row-actions",children:[s.jsx("button",{"aria-label":`Connect to ${c.label}`,className:"icon-button",disabled:t,onClick:()=>i(c),type:"button",children:s.jsx(Br,{"aria-hidden":"true"})}),s.jsx("button",{"aria-label":`Forget ${c.label}`,className:"icon-button danger-icon",disabled:t,onClick:()=>a(c.daemonId),type:"button",children:s.jsx(Kr,{"aria-hidden":"true"})})]})]},c.daemonId)),r.length===0?s.jsx("p",{className:"empty-copy",children:n.noSavedDevices}):null]})]})}function kr({workspace:e,portalOnly:t=!1}){const[n,r]=o.useState(()=>re().settingsTarget?.()??null);o.useEffect(()=>{const l=()=>r(re().settingsTarget?.()??null);return window.addEventListener("vibelet.settings.target.changed",l),l(),()=>window.removeEventListener("vibelet.settings.target.changed",l)},[]);const i=e,a=s.jsxs(s.Fragment,{children:[s.jsx(gu,{pairing:i.pairing,phase:i.phase,t:i.t,onForgetPairing:i.clearPairing}),s.jsx(bu,{activeDaemonId:i.pairing?.daemonId,busy:i.busy,t:i.t,targets:i.savedTargets,onConnect:i.connectSavedTarget,onForget:i.forgetSavedTarget}),s.jsx(pu,{busy:i.archiveSyncBusy,connected:i.phase==="connected",dismissed:i.archiveSyncDismissed,feedback:i.archiveSyncStatus,synced:i.archiveSynced,t:i.t,onPull:()=>{i.runArchiveSync("pull")},onPushMerge:()=>{i.runArchiveSync("pushMerge")},onPushReplace:()=>{i.runArchiveSync("pushReplace")},onSkip:i.skipArchiveSync}),s.jsx(yu,{connected:i.phase==="connected",metadata:i.daemonMetadata,restartBusy:i.admin.loading&&i.admin.action==="restart",showUpdate:!!(i.daemonMetadata.version&&i.daemonMetadata.latestVersion&&Ei(i.daemonMetadata.version,i.daemonMetadata.latestVersion)),t:i.t,updateBusy:i.admin.loading&&i.admin.action==="update",updateStatus:i.admin.statusText,onRestart:()=>{i.runAdminAction("restart")},onUpdate:()=>{i.runAdminAction("update")}})]}),c=s.jsx("div",{className:"remote-workspace-settings",children:a});return t?n?It.createPortal(c,n):null:c}function vu(){const e=re().polishSettings,t=He(Be().language)!=="en",[n,r]=o.useState(),[i,a]=o.useState({...as}),[c,l]=o.useState(""),[u,h]=o.useState(!1),[d,f]=o.useState(""),[x,b]=o.useState(!1);if(o.useEffect(()=>{let v=!0;return e?.status().then(m=>{v&&(r(m),a(m.settings))}).catch(()=>{v&&(b(!0),f(t?"无法读取润色设置。":"Could not load polishing settings."))}),()=>{v=!1}},[e]),!e)return null;const S=async v=>{h(!0),f(""),b(!1);try{const m=await e.save(i,v);r(m),a(m.settings),l(""),f(t?"已保存":"Saved"),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch{b(!0),f(t?"保存失败,请检查 HTTPS API 地址、模型和提示词。":"Save failed. Check the HTTPS API URL, model and prompts.")}finally{h(!1)}};return s.jsxs("section",{className:"control-section compact-section speech-polish-settings",children:[s.jsx("h2",{children:t?"语音润色":"Voice polishing"}),s.jsxs("label",{className:"speech-enabled",children:[s.jsx("input",{type:"checkbox",role:"switch","aria-checked":i.enabled,className:"settings-switch",checked:i.enabled,disabled:!n||u,onChange:async v=>{const m={...i,enabled:v.target.checked};a(m),h(!0),f(""),b(!1);try{const p=await e.save({...n.settings,enabled:m.enabled});r(p),a(m),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch{a(i),b(!0),f(t?"无法保存开关设置":"Could not save setting")}finally{h(!1)}}}),t?"启用语音润色":"Enable voice polishing"]}),i.enabled&&s.jsxs("fieldset",{disabled:!n||u,className:"speech-polish-fields",children:[s.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."}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:t?"API 地址":"API URL"}),s.jsx("input",{type:"url",value:i.baseUrl,onChange:v=>a({...i,baseUrl:v.target.value}),autoComplete:"off"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:t?"模型":"Model"}),s.jsx("input",{value:i.model,onChange:v=>a({...i,model:v.target.value}),autoComplete:"off"})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:t?"润色 API Key":"Polishing API Key"}),s.jsx("input",{type:"password",autoComplete:"off",value:c,onChange:v=>l(v.target.value),placeholder:n?.configured?t?"已保存 · 留空保留":"Saved · leave blank to keep":"API Key"})]}),s.jsx("p",{className:"empty-copy",children:n?.persistence==="encrypted"?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."}),i.enabled&&!n?.configured&&!c.trim()&&s.jsx("p",{className:"empty-copy",children:t?"请填写 API Key 并保存,润色才能生效。":"Enter and save an API key to use polishing."}),s.jsxs("details",{className:"speech-polish-advanced",children:[s.jsx("summary",{children:t?"自定义提示词":"Custom prompts"}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:t?"中文提示词":"Chinese prompt"}),s.jsx("textarea",{rows:5,value:i.promptZh,onChange:v=>a({...i,promptZh:v.target.value})})]}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:t?"英文提示词":"English prompt"}),s.jsx("textarea",{rows:5,value:i.promptEn,onChange:v=>a({...i,promptEn:v.target.value})})]}),s.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>a({...i,promptZh:as.promptZh,promptEn:as.promptEn}),children:t?"恢复默认提示词":"Reset prompts"})]}),s.jsxs("div",{className:"attention-actions",children:[s.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{S(c.trim()||void 0)},children:t?"保存润色设置":"Save polishing settings"}),n?.configured&&s.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{S("")},children:t?"移除润色密钥":"Remove polishing key"})]})]}),d&&s.jsx("p",{role:x?"alert":"status",className:x?"error-copy":"empty-copy",children:d})]})}const xu={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 wu(){const e=re().speechSettings,t=xu[He(Be().language)],[n,r]=o.useState(),[i,a]=o.useState(""),[c,l]=o.useState(!1),[u,h]=o.useState(""),[d,f]=o.useState(Ge().getItem("vibelet.web.voice.enabled")==="true"),x=!!(globalThis.isSecureContext&&typeof globalThis.navigator?.mediaDevices?.getUserMedia=="function"&&globalThis.MediaRecorder?.isTypeSupported("audio/webm"));o.useEffect(()=>{let p=!0;return e?.status().then(y=>{p&&r(y)}).catch(()=>{p&&h("Unable to load speech settings.")}),()=>{p=!1}},[e]);const b=p=>{f(p),Ge().setItem("vibelet.web.voice.enabled",String(p)),window.dispatchEvent(new Event("vibelet.speech.changed"))},S=async p=>{if(!(!e||c)){l(!0),h("");try{r(await e.saveKey(p)),a(""),p||b(!1),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch(y){h(y instanceof Error?y.message:String(y))}finally{l(!1)}}};if(!e)return null;const v=n?.engine==="volcengine",m=[...n?.systemAvailable?[{value:"system",label:"macOS · Apple"}]:[],{value:"deepgram",label:"Deepgram · Nova-3"},{value:"volcengine",label:He(Be().language)==="en"?"Volcengine · ASR Flash":"火山引擎 · 录音识别"}];return s.jsxs(s.Fragment,{children:[s.jsxs("section",{className:"control-section compact-section speech-input-settings",children:[s.jsx("h2",{children:t.title}),s.jsxs("label",{className:"speech-enabled",children:[s.jsx("input",{type:"checkbox",role:"switch","aria-checked":d,className:"settings-switch",checked:d,disabled:!x,onChange:p=>b(p.target.checked)}),t.enabled]}),d&&s.jsxs(s.Fragment,{children:[e.setEngine&&s.jsxs("div",{className:"field speech-engine-field",children:[s.jsx("span",{children:He(Be().language)==="en"?"Recognition engine":"识别引擎"}),s.jsx(gn,{icon:Wr,menuLabel:"Speech engine",label:m.find(p=>p.value===n?.engine)?.label??"Deepgram · Nova-3",options:m,value:n?.engine??"deepgram",disabled:c,onSelect:async p=>{l(!0),h(""),a("");try{r(await e.setEngine(p)),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch(y){h(y instanceof Error?y.message:String(y))}finally{l(!1)}}})]}),s.jsx("p",{className:"empty-copy",children:n?.engine==="system"?He(Be().language)==="en"?"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。文字只填入草稿,不会自动发送。":v?He(Be().language)==="en"?"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,文字只追加到草稿。":t.disclosure}),n?.engine!=="system"&&s.jsxs(s.Fragment,{children:[s.jsx("p",{className:"empty-copy",children:n?.persistence==="encrypted"?t.secure:t.session}),s.jsxs("label",{className:"field",children:[s.jsx("span",{children:v?"火山引擎 API Key":"Deepgram API Key"}),s.jsx("input",{type:"password",autoComplete:"off",value:i,onChange:p=>a(p.target.value),placeholder:n?.configured?t.saved:"API Key"})]}),s.jsxs("div",{className:"attention-actions",children:[s.jsx("button",{type:"button",className:"icon-text-button",disabled:c||!i.trim(),onClick:()=>{S(i)},children:t.save}),n?.configured&&s.jsx("button",{type:"button",className:"icon-text-button",disabled:c,onClick:()=>{S("")},children:t.remove})]})]})]}),!x&&s.jsx("p",{className:"empty-copy",children:t.unsupported}),u&&s.jsx("p",{role:"alert",className:"error-copy",children:u})]}),d&&s.jsx(vu,{})]})}function Su({value:e,t,showSession:n=!0,onChange:r}){const i=[...n?[{tab:"session",label:t.session,Icon:Ur}]:[],{tab:"files",label:t.files,Icon:zn},{tab:"terminal",label:t.terminal,Icon:Yn},{tab:"browser",label:t.browser,Icon:Fr}];return s.jsx("div",{className:"control-tabs",children:i.map(({tab:a,label:c,Icon:l})=>s.jsxs("button",{"aria-label":c,"aria-pressed":e===a,className:e===a?"selected":"",onClick:()=>r(a),title:c,type:"button",children:[s.jsx(l,{"aria-hidden":"true"}),s.jsx("span",{children:c})]},a))})}function ku({children:e,t,onClose:n}){const r=o.useRef(null);return o.useEffect(()=>{const i=document.getElementById("vibelet-workspace");return i&&(i.inert=!0),r.current?.focus(),()=>{i&&(i.inert=!1)}},[]),It.createPortal(s.jsxs("section",{className:"browser-settings-page","aria-label":t.settings,onKeyDown:i=>{if(i.key==="Escape"&&!i.defaultPrevented&&(i.preventDefault(),n()),i.key!=="Tab")return;const a=[...i.currentTarget.querySelectorAll("button:not(:disabled),input:not(:disabled),a[href]")].filter(u=>u.getBoundingClientRect().width>0),c=a[0],l=a.at(-1);i.shiftKey&&document.activeElement===c&&(i.preventDefault(),l?.focus()),!i.shiftKey&&document.activeElement===l&&(i.preventDefault(),c?.focus())},children:[s.jsxs("button",{ref:r,type:"button",className:"icon-text-button",onClick:n,children:["← ",t.chat]}),s.jsx("h1",{children:t.settings}),s.jsxs("div",{className:"browser-settings-body",children:[s.jsx(Qr,{}),e]})]}),document.body)}function ju({children:e,collapsed:t,t:n,value:r,showSession:i,onChange:a,onResize:c}){const l=Qs("right",d=>{(d==="terminal"||d==="browser")&&a(d)}),u=re().toolbarTarget?.("controls"),h=s.jsx(Su,{value:r,t:n,showSession:i,onChange:a});return r==="admin"&&re().kind==="browser"?s.jsx(ku,{t:n,onClose:()=>a("files"),children:e}):s.jsxs(s.Fragment,{children:[u&&!t?It.createPortal(h,u):null,s.jsx("button",{"aria-label":n.resizeControlsSidebar,"aria-hidden":t,className:"resize-handle right-resize-handle",disabled:t,onPointerDown:c,title:n.resizeControlsSidebar,type:"button",children:s.jsx("span",{})}),s.jsx("div",{className:"workspace-control-sidebar-motion",inert:t,"aria-hidden":t,children:s.jsxs("aside",{"aria-label":n.controls,className:"control-pane",...l,children:[!u&&s.jsx("div",{className:"control-pane-toolbar",children:h}),e]})})]})}function Xh(e){return/\.(md|mdx|markdown|mdown)$/i.test(e)}function Vn(e,t,n){const r=t.split(";")[0].trim().toLowerCase();return r.startsWith("image/")?"image":r==="text/html"||/\.html?$/i.test(e)?"html":r==="application/pdf"||/\.pdf$/i.test(e)?"pdf":r.startsWith("audio/")||/\.(mp3|wav|m4a|ogg|flac)$/i.test(e)?"audio":r.startsWith("video/")||/\.(mp4|webm|mov)$/i.test(e)?"video":n?"text":"unsupported"}function Cu(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 Iu({file:e}){const[t,n]=o.useState(!1),r=En(()=>n(!1),void 0,t),i=kn(),a=He(Be().language),c=a==="en"?"Close":a==="zh-TW"?"關閉":"关闭",l=re().pdfPreviewUrl?.(e.path,e.cwd)??e.objectUrl;return s.jsxs(s.Fragment,{children:[s.jsxs("button",{className:"icon-text-button",type:"button",onClick:()=>n(!0),children:[s.jsx($r,{"aria-hidden":"true"}),i.pdfPreview]}),t&&It.createPortal(s.jsx("div",{className:"remote-document-layer",onPointerDown:u=>{u.target===u.currentTarget&&n(!1)},children:s.jsxs("div",{ref:r,className:"remote-document-dialog","aria-label":i.pdfPreview,role:"dialog","aria-modal":"true",tabIndex:-1,children:[s.jsxs("header",{children:[s.jsx("span",{children:e.path.split("/").pop()}),s.jsx("button",{className:"icon-button",type:"button","aria-label":c,onClick:()=>n(!1),children:s.jsx(De,{"aria-hidden":"true"})})]}),s.jsx("iframe",{title:i.pdfPreview,src:`${l}#toolbar=1&navpanes=0&view=Fit`})]})}),document.body)]})}function Ri({file:e}){const[t,n]=o.useState(!1),r=kn(),i=Vn(e.path,e.contentType,e.kind==="text");if(t)return s.jsx("p",{className:"empty-copy",role:"status",children:r.mediaError});if(i==="html"){const a=e.dirty?void 0:re().htmlPreviewUrl?.(e.path,e.cwd);return s.jsx("iframe",{className:"remote-document-preview",sandbox:"allow-scripts",title:r.htmlPreview,src:a,srcDoc:a?void 0:Cu(e.text)})}return e.objectUrl?i==="image"?s.jsx("img",{className:"remote-image",src:e.objectUrl,alt:e.path,onError:()=>n(!0)}):i==="audio"?s.jsx("audio",{"aria-label":r.audioPreview,controls:!0,preload:"metadata",src:e.objectUrl,onError:()=>n(!0)}):i==="video"?s.jsx("video",{"aria-label":r.videoPreview,controls:!0,playsInline:!0,preload:"metadata",src:e.objectUrl,onError:()=>n(!0)}):i==="pdf"?s.jsx(Iu,{file:e}):s.jsx("p",{className:"empty-copy",children:r.mediaError}):null}const Nu=o.lazy(()=>tt(()=>import("./file-editor-FileCodeEditor-CTEWh6kV.js").then(e=>e.Q),__vite__mapDeps([18,1,2,19])).then(e=>({default:e.FileCodeEditor})));function Au({file:e,onOpenRemoteFile:t,onTextChange:n}){const[r,i]=o.useState("preview"),a=Vn(e.path,e.contentType,!0)==="html",c=He(Be().language)!=="en";return s.jsxs(s.Fragment,{children:[a&&s.jsxs("div",{className:"segmented editor-mode-tabs",children:[s.jsx("button",{type:"button",className:r==="edit"?"selected":"",onClick:()=>i("edit"),children:c?"编辑":"Edit"}),s.jsx("button",{type:"button",className:r==="preview"?"selected":"",onClick:()=>i("preview"),children:c?"预览":"Preview"})]}),a&&r==="preview"?s.jsx(Ri,{file:e}):s.jsx(o.Suspense,{fallback:s.jsx("pre",{className:"remote-editor",children:e.text}),children:s.jsx(Nu,{path:e.path,cwd:e.cwd,text:e.text,onChange:n,onOpenFile:t})})]})}const Ns="vibelet:file-operation-before",As="vibelet:file-operation-done";function sn(e,t=""){const n=e.replace(/\\/g,"/"),r=/^(\/|[a-z]:\/|~)/i.test(n)?n:`${t.replace(/\\/g,"/")}/${n}`,i=[];for(const a of r.split("/"))!a||a==="."||(a===".."?i.pop():i.push(a));return`${r.startsWith("/")?"/":""}${i.join("/")}`}function hs(e,t,n){const r=sn(e,n),i=sn(t,n);return r===i||r.startsWith(`${i}/`)}async function ef(e,t){const n=new CustomEvent(Ns,{cancelable:!0,detail:{...e,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd}});if(!window.dispatchEvent(n))throw new Error("unsaved_changes");const r=await fetch("/file-operation",{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.pairToken}`},body:JSON.stringify(e)}),i=await r.text();let a;try{a=JSON.parse(i)}catch{throw new Error(r.status===404?"daemon_update_required":"operation_failed")}if(r.status===404&&a.error!=="ENOENT")throw new Error("daemon_update_required");if(!r.ok)throw new Error(a.error??"operation_failed");return Gs()?.daemonId===t.daemonId&&window.dispatchEvent(new CustomEvent(As,{detail:{...a,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd,source:e.path}})),a}function Eu(e){const t=o.useRef(e);t.current=e,o.useEffect(()=>{const n=i=>{const{detail:a}=i,c=t.current;if(c.daemonId!==a.daemonId||a.action==="copy"||a.action==="restore")return;[...Object.values(c.files),c.remoteFile].filter(Boolean).some(u=>u.dirty&&hs(u.path,a.path,a.cwd))&&i.preventDefault()},r=i=>{const{detail:a}=i,c=t.current;if(c.daemonId!==a.daemonId||a.action==="copy"||a.action==="restore")return;const l=a.source??a.path,u=f=>{if(!hs(f.path,l,a.cwd))return f;if(a.action==="delete")return null;const x=`${a.target}${sn(f.path,a.cwd).slice(sn(l,a.cwd).length)}`;return{...f,path:x}};c.setFiles(f=>Object.fromEntries(Object.values(f).flatMap(x=>{const b=u(x);return b?[[b.path,b]]:[]}))),c.active&&c.files[c.active]&&c.setActive(u(c.files[c.active])?.path??null),c.setRemoteFile(f=>f&&u(f));const h=new URL(window.location.href),d=h.searchParams.get("file");d&&hs(d,l,a.cwd)&&(a.action==="delete"?h.searchParams.delete("file"):h.searchParams.set("file",`${a.target}${sn(d,a.cwd).slice(sn(l,a.cwd).length)}`),window.history.replaceState(null,"",h.href))};return window.addEventListener(Ns,n),window.addEventListener(As,r),()=>{window.removeEventListener(Ns,n),window.removeEventListener(As,r)}},[])}function Ru({workspace:e,children:t}){const n=Tn(),r=Qs("center"),[i,a]=o.useState({}),[c,l]=o.useState(null),[u,h]=o.useState(null),d=o.useRef({files:i,remoteFile:e.remoteFile,daemonId:e.pairing?.daemonId});d.current={files:i,remoteFile:e.remoteFile,daemonId:e.pairing?.daemonId};const f=o.useRef(null),x=He(Be().language)!=="en";o.useEffect(()=>{a({}),l(null),f.current=null},[e.pairing?.daemonId]),o.useEffect(()=>{if(!e.remoteFile){f.current=null;return}const g=e.remoteFile;a(j=>({...j,[g.path]:g})),f.current!==g.path&&(l(g.path),n.setCenter(null)),f.current=g.path},[e.remoteFile]),o.useEffect(()=>{l(null),f.current=null},[e.activeSessionId]);const b=g=>{n.setCenter(null),e.setRemoteFile(i[g]),l(g)},S=async g=>{const j=i[g],w=e.pairing?.daemonId;if(!j)return;const k=rn();j.dirty&&!await gs({title:k.discard,message:g,confirmLabel:k.discardAction,danger:!0})||d.current.daemonId!==w||d.current.files[g]?.text!==j.text||(a(N=>{const D={...N};return delete D[g],D}),g===c&&(l(null),f.current=null,e.setRemoteFile(null)))};Eu({daemonId:e.pairing?.daemonId,files:i,active:c,remoteFile:e.remoteFile,setFiles:a,setActive:l,setRemoteFile:e.setRemoteFile});const v=c?i[c]:null,m=async()=>{const g=e.remoteFile;!g||!await gs({message:e.t.confirmOverwrite(_t(g.path)),danger:!0})||d.current.remoteFile===g&&await e.saveRemoteFile({force:!0})},p=re().toolbarTarget?.("conversation"),y=v&&!n.center&&s.jsxs("header",{className:"document-file-header",role:"toolbar","aria-label":x?"文件操作":"File actions",children:[s.jsx("button",{type:"button",title:e.t.download,"aria-label":e.t.download,onClick:()=>{e.downloadRemoteFile()},children:s.jsx(Kn,{})}),s.jsx("button",{type:"button",title:e.t.copyPath,"aria-label":e.t.copyPath,onClick:()=>{navigator.clipboard.writeText(v.path)},children:s.jsx(on,{})}),v.kind==="text"&&s.jsx("button",{type:"button",title:e.t.saveFile,"aria-label":e.t.saveFile,disabled:!v.dirty||e.busy,onClick:()=>{e.saveRemoteFile()},children:s.jsx(uo,{})}),s.jsx("button",{type:"button",className:"document-tab-close",title:e.t.close,"aria-label":`${e.t.close} ${_t(v.path)}`,onClick:()=>S(v.path),children:s.jsx(De,{})})]});return s.jsx(ai.Provider,{value:u,children:s.jsxs("div",{className:"workspace-documents",...r,children:[!p&&s.jsx("div",{className:"chat-header document-conversation-header",ref:h}),(Object.keys(i).length>0||n.items.some(g=>g.location==="center"))&&s.jsxs("div",{className:"document-tabs",children:[s.jsxs("div",{className:"document-tab-items",role:"tablist","aria-label":x?"工作区标签页":"Workspace tabs",children:[s.jsx("button",{role:"tab","aria-selected":!c&&!n.center,onClick:()=>{l(null),n.setCenter(null),f.current=null},type:"button",children:e.t.chat}),Object.values(i).map(g=>s.jsxs("div",{className:"document-tab","data-active":!n.center&&c===g.path,children:[s.jsxs("button",{type:"button",role:"tab","aria-selected":!n.center&&c===g.path,title:g.path,onClick:()=>b(g.path),children:[s.jsx($r,{}),_t(g.path),g.dirty?" ·":""]}),(g.path!==c||n.center)&&s.jsx("button",{type:"button",className:"document-tab-close",title:e.t.close,"aria-label":`${e.t.close} ${_t(g.path)}`,onClick:()=>S(g.path),children:s.jsx(De,{})})]},g.path)),s.jsx(Is,{location:"center",t:e.t})]}),y]}),s.jsx("div",{hidden:!!c||!!n.center,className:"document-chat",children:t}),s.jsx("div",{hidden:!n.center,className:"dock-center-content",children:s.jsx(Gn,{location:"center"})}),v&&!n.center&&s.jsxs("section",{className:"document-file",role:"tabpanel","aria-label":_t(v.path),children:[v.kind==="text"?s.jsx(Au,{file:v,onOpenRemoteFile:(g,j)=>{e.openRemoteFile(g,j,{updateRoute:!0})},onTextChange:g=>e.setRemoteFile(j=>j&&{...j,text:g,dirty:!0})},v.path):s.jsx(Ri,{file:v},v.path),e.remoteFileConflict&&s.jsxs("div",{role:"alert",className:"inline-notice warning",children:[s.jsx("span",{children:e.t.remoteFileConflict(v.path)}),s.jsx("button",{type:"button",onClick:()=>{m()},children:e.t.forceSave})]})]})]})})}const Ti="vibelet.web.savedTargets",Mi=12;function Tu(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Mu(e){if(!Tu(e)||typeof e.daemonId!="string"||typeof e.deviceId!="string"||typeof e.pairToken!="string"||typeof e.pairedAt!="string")return null;const t=typeof e.displayName=="string"?e.displayName:void 0,n=typeof e.label=="string"&&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:typeof e.webSocketUrl=="string"?e.webSocketUrl:void 0,label:n,lastConnectedAt:typeof e.lastConnectedAt=="string"?e.lastConnectedAt:void 0}}function Pi(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const r of e){const i=Mu(r);if(!(!i||t.has(i.daemonId))&&(t.add(i.daemonId),n.push(i),n.length>=Mi))break}return n}function Pu(e=Ge()){const t=e.getItem(Ti);if(!t)return[];try{return Pi(JSON.parse(t))}catch{return[]}}function _i(e,t=Ge()){t.setItem(Ti,JSON.stringify(Pi(e)))}function _u(e,t,n=new Date().toISOString()){const r=e.find(a=>a.daemonId===t.daemonId);return[{...t,label:r?.label||t.displayName||t.daemonId.slice(0,10),lastConnectedAt:n},...e.filter(a=>a.daemonId!==t.daemonId)].slice(0,Mi)}function Du(e,t,n){const r=n.trim();return r?e.map(i=>i.daemonId===t?{...i,label:r}:i):e}function Lu(e,t){return e.filter(n=>n.daemonId!==t)}function $u(e){return e.filter(t=>t.archived===!0).map(t=>t.sessionId)}function Fu(e,t,n){return e.ok?{tone:"success",message:t.replace("{n}",String(e.archivedSessionIds.length))}:e.error==="timeout"?{tone:"error",message:n.timeout}:e.error==="not_connected"?{tone:"error",message:n.disconnected}:{tone:"error",message:n.generic.replace("{error}",e.error)}}async function Ou(e,t,n){if(!e?.isConnected)return{ok:!1,error:"not_connected"};try{const r=await e.request({action:"sessions.archiveSync",id:e.makeId("archive_sync"),mode:t,...t==="pull"?{}:{archivedSessionIds:n??[]}});return{ok:!0,archivedSessionIds:Array.isArray(r.archivedSessionIds)?r.archivedSessionIds.filter(i=>typeof i=="string"&&i.length>0):[]}}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}}function qu(e){const t=o.useCallback((m,p)=>{e.updateSessionListPreferences(y=>({...y,archiveSyncedDaemonIds:p==="synced"?{...y.archiveSyncedDaemonIds,[m]:!0}:y.archiveSyncedDaemonIds,archiveSyncCardDismissedDaemonIds:{...y.archiveSyncCardDismissedDaemonIds,[m]:!0}}))},[e]),n=o.useCallback((m,p)=>{const y=m==="pull"?e.t.archiveSyncSuccessPull:m==="pushMerge"?e.t.archiveSyncSuccessMerge:e.t.archiveSyncSuccessPush;if(e.setArchiveSyncStatus(Fu(p,y,{timeout:e.t.archiveSyncFailedTimeout,disconnected:e.t.archiveSyncFailedDisconnected,generic:e.t.archiveSyncFailedGeneric})),!p.ok)return;const g=new Set(p.archivedSessionIds);e.setSessions(j=>j.map(w=>({...w,archived:g.has(w.sessionId)}))),e.pairingRef.current?.daemonId&&t(e.pairingRef.current.daemonId,"synced"),e.requestSessions({force:!0})},[t,e]),r=o.useCallback(async m=>{if(e.archiveSyncBusy)return;e.setArchiveSyncBusy(m),e.setArchiveSyncStatus(null);const p=await Ou(e.clientRef.current,m,$u(e.displaySessions));n(m,p),e.setArchiveSyncBusy(null)},[n,e]),i=o.useCallback(()=>{e.pairing?.daemonId&&(t(e.pairing.daemonId,"dismissed"),e.setArchiveSyncStatus({tone:"success",message:e.t.archiveSyncSkipped}))},[t,e]),a=o.useCallback(async m=>{const p=e.clientRef.current;if(p?.isConnected&&!(m==="update"&&!await yn(rn().update))&&!(m==="restart"&&!await yn(rn().restart))&&!(e.clientRef.current!==p||!p.isConnected)){e.setAdmin(y=>({...y,loading:!0,action:m,statusText:""})),e.setErrorText(null);try{if(m==="update"){const y=hu(e.daemonMetadata.version),g=await p.request({action:"daemon.update",id:p.makeId("daemon_update"),...y?{channel:y}:{}});e.setAdmin(j=>({...j,loading:!1,action:null,statusText:g.alreadyRunning?"Connector update already running":"Connector update started"}));return}await p.request({action:"daemon.restart",id:p.makeId("daemon_restart")}),e.setAdmin(y=>({...y,loading:!1,action:null,statusText:"Connector restart requested"})),e.refreshDaemonMetadata()}catch(y){e.setAdmin(g=>({...g,loading:!1,action:null})),e.setErrorText(y instanceof Error?y.message:String(y))}}},[e]),c=o.useCallback(async()=>{if(!e.activeSession)return;const m=pc(e.activeSession,e.messages);yc(mc(St(e.activeSession),e.activeSession.sessionId),m),await navigator.clipboard?.writeText(m).catch(()=>{})},[e.activeSession,e.messages]),l=o.useCallback(async()=>{if(!("Notification"in window)){e.setNotificationPermission("unsupported"),e.setErrorText("Browser notifications are not supported.");return}const m=await Notification.requestPermission();e.notificationPermissionRef.current=m,e.setNotificationPermission(m),m==="granted"&&e.updateNotificationSettings({enabled:!0}),e.setStatusText(m==="granted"?"Browser notifications enabled":"Browser notifications not enabled")},[e]),u=o.useCallback(async()=>{const m=e.pairingRef.current;!await yn(rn().forget)||e.pairingRef.current!==m||(e.intentionalDisconnectRef.current=!0,e.connectionAttemptIdRef.current+=1,yi(),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(Js),e.setPhase("missing-pair"),e.setStatusText(e.t.missingPair))},[e]),h=o.useCallback(m=>{if(m&&e.notificationPermission==="default"){l();return}e.updateNotificationSettings({enabled:m})},[e,l]),d=o.useCallback(m=>{e.connectWithPairingRef.current(m,!0)},[e]),f=o.useCallback(m=>e.saveTargets(Lu(e.savedTargets,m)),[e]),x=o.useCallback(m=>{e.setActiveSessionId(m.sessionId),e.setRenameTitle(m.customTitle??m.title??""),e.setDetailsOpen(!0)},[e]),b=o.useCallback((m,p)=>{const y=Hi(p);e.updateSessionListPreferences(g=>({...g,directoryTags:Bi(g.directoryTags,m,y)}))},[e]),S=o.useCallback(m=>{e.setControlTab("files"),e.listDirectory(m,{updateRoute:!0})},[e]),v=o.useCallback(m=>{navigator.clipboard?.writeText(si(m)).catch(()=>{})},[]);return{runArchiveSync:r,skipArchiveSync:i,runAdminAction:a,exportActiveSession:c,clearPairing:u,setNotificationsEnabled:h,connectSavedTarget:d,forgetSavedTarget:f,openSessionDetails:x,editFolderTags:b,browseFolder:S,copyResumeCommand:v}}function jr(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function Wu(e,t=window.location,n=!0){const i=`${t.protocol==="https:"?"wss:":"ws:"}//${t.host}`;return n&&gi(t.hostname)?i:e?.webSocketUrl?e.webSocketUrl:i}class Hu{capabilities={};socket=null;pending=new Map;messageListeners=new Set;closeListeners=new Set;async connect(t){this.disconnect();const n=new WebSocket(Wu(t));this.socket=n;const r=new Promise((a,c)=>{n.onopen=()=>a(),n.onerror=()=>c(new Error("WebSocket connection failed."))});n.onmessage=a=>this.handleSocketMessage(a.data),n.onclose=()=>{this.socket===n&&(this.socket=null),this.rejectPending(new Error("WebSocket disconnected.")),this.closeListeners.forEach(a=>a())},await r;const i=await this.request({action:"auth.hello",id:jr("auth"),pairToken:t.pairToken,daemonId:t.daemonId,deviceId:t.deviceId,locale:navigator.language});return this.capabilities=i.capabilities??{},i}request(t,n={}){return!this.socket||this.socket.readyState!==WebSocket.OPEN?Promise.reject(new Error("WebSocket is not connected.")):new Promise((r,i)=>{const a={resolve:r,reject:i};n.timeoutMs&&n.timeoutMs>0&&(a.timeoutId=setTimeout(()=>{this.pending.delete(t.id),i(new Error(n.timeoutMessage||"Request timed out."))},n.timeoutMs)),this.pending.set(t.id,a),this.socket?.send(JSON.stringify(t))})}send(t){this.socket?.readyState===WebSocket.OPEN&&this.socket.send(JSON.stringify(t))}onMessage(t){return this.messageListeners.add(t),()=>this.messageListeners.delete(t)}onClose(t){return this.closeListeners.add(t),()=>this.closeListeners.delete(t)}get supportsSessionSteer(){return this.isConnected&&this.capabilities.sessionSteer===!0}get supportsQueueSendNow(){return this.isConnected&&this.capabilities.queueSendNow===!0}disconnect(){this.capabilities={},this.rejectPending(new Error("WebSocket disconnected.")),this.socket?.close(1e3,"client disconnect"),this.socket=null}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}makeId(t){return jr(t)}handleSocketMessage(t){if(typeof t!="string")return;let n;try{n=JSON.parse(t)}catch{return}if(n.type!=="pong"){if(n.type==="response"){const r=this.pending.get(n.id);if(r){this.pending.delete(n.id),r.timeoutId&&clearTimeout(r.timeoutId),n.ok?r.resolve(n.data):r.reject(new Error(n.error||"Request failed."));return}}this.messageListeners.forEach(r=>r(n))}}rejectPending(t){for(const n of this.pending.values())n.timeoutId&&clearTimeout(n.timeoutId),n.reject(t);this.pending.clear()}}const Di="vibelet.web.sessionListCache",Li=120;function Bu(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function zu(e){if(!Bu(e)||typeof e.daemonId!="string"||!e.daemonId)return null;const t=ni(e.page);return{daemonId:e.daemonId,page:{...t,sessions:t.sessions.slice(0,Li)},cachedAt:typeof e.cachedAt=="string"?e.cachedAt:new Date(0).toISOString()}}function Uu(e,t=Ge()){if(!e)return null;try{const n=t.getItem(Di);if(!n)return null;const r=zu(JSON.parse(n));return r?.daemonId===e?r.page:null}catch{return null}}function Gu(e,t,n=Ge(),r=new Date().toISOString()){if(!e)return;const i={daemonId:e,page:{...t,sessions:t.sessions.slice(0,Li)},cachedAt:r};n.setItem(Di,JSON.stringify(i))}function Vu(e){return e instanceof Error&&e.message==="auth_failed"}function Ku(e,t){return e instanceof Cn&&e.code==="pair_window_expired"?t.pairingLinkExpired:e instanceof Error?e.message:String(e)}function Qu(e){const t=o.useRef(null),n=o.useRef(e);n.current=e;const r=o.useCallback(a=>{const c=n.current,l=a??c.pairingRef.current;!l||c.intentionalDisconnectRef.current||(c.reconnectTimerRef.current&&window.clearTimeout(c.reconnectTimerRef.current),c.reconnectTimerRef.current=window.setTimeout(()=>{c.reconnectTimerRef.current=null,c.connectWithPairingRef.current(l,!0)},nc))},[]),i=o.useCallback(async(a,c=!1)=>{const l=n.current;l.reconnectTimerRef.current&&(window.clearTimeout(l.reconnectTimerRef.current),l.reconnectTimerRef.current=null),l.intentionalDisconnectRef.current=!1,l.setPhase("connecting"),l.setStatusText(c?l.t.reconnectingToDaemon:l.t.connectingToDaemon),l.setErrorText(null);const u=new Hu,h=l.connectionAttemptIdRef.current+1;l.connectionAttemptIdRef.current=h;const d=l.clientRef.current;l.clientRef.current=u,d?.disconnect();const f=()=>l.connectionAttemptIdRef.current===h&&l.clientRef.current===u;u.onMessage(l.handleServerMessage),u.onClose(()=>{l.clientRef.current===u&&(l.clientRef.current=null,!l.intentionalDisconnectRef.current&&(l.setPhase("connecting"),l.setStatusText(l.t.reconnectingToDaemon),l.setErrorText(l.t.webSocketClosedRetrying),r(l.pairingRef.current??a)))});try{let x=a,b;try{b=await u.connect(a)}catch(m){if(!a.webSocketUrl)throw m;x={...a,webSocketUrl:void 0},l.setStatusText(l.t.reconnectingToDaemon),b=await u.connect(x)}if(!f())return;const S={...x,displayName:b.displayName??x.displayName};l.historyCacheDaemonIdRef.current&&l.historyCacheDaemonIdRef.current!==S.daemonId&&(l.historyCacheRef.current={},l.messagesSessionIdRef.current=null,l.lastHistorySessionIdRef.current=null,l.setMessages([])),l.historyCacheDaemonIdRef.current=S.daemonId,l.setPairing(S),l.pairingRef.current=S,pr(S);const v=Uu(S.daemonId);v&&l.setSessionsFromPage(v,!1),l.setSavedTargets(m=>{const p=_u(m,S);return _i(p),p}),l.setPhase("connected"),l.setStatusText(l.t.connectedTo(b.displayName??a.displayName??"Vibelet Daemon")),l.refreshDaemonMetadata(S),await l.requestReconnectSnapshot(),await l.fetchAgentResources(l.agent,l.cwd),l.reportLog("web.connected",{reconnecting:c})}catch(x){if(!f())return;Vu(x)&&yi(),l.setPhase("error"),l.setStatusText(l.t.connectionFailed),l.setErrorText(x instanceof Error?x.message:String(x)),r(a)}},[r]);o.useEffect(()=>{const a=n.current;a.connectWithPairingRef.current=i},[i]),o.useEffect(()=>{const a=n.current;let c=!1;async function l(){const u=Pl(),d=Gs()??a.rememberedTarget;if(!u&&!d){a.setPhase("missing-pair"),a.setStatusText(a.t.missingPair);return}try{a.setPhase("pairing"),u&&t.current?.pairNonce!==u.pairNonce&&(t.current={pairNonce:u.pairNonce,promise:Ol(u,d)});const f=u?await t.current?.promise:d;if(!f||c)return;u&&(pr(f),t.current=null,_l()),await a.connectWithPairingRef.current(f)}catch(f){if(c)return;u&&(t.current=null),a.setPhase("error"),a.setStatusText(a.t.pairingFailed),a.setErrorText(Ku(f,a.t))}}return l(),()=>{c=!0,a.intentionalDisconnectRef.current=!0,a.connectionAttemptIdRef.current+=1,a.reconnectTimerRef.current&&window.clearTimeout(a.reconnectTimerRef.current),a.clientRef.current?.disconnect()}},[e.t]),o.useEffect(()=>{const a=n.current;if(a.phase!=="connected")return;const c=window.setTimeout(()=>{a.requestSessions({force:!0}).catch(l=>a.setErrorText(l instanceof Error?l.message:String(l)))},260);return()=>window.clearTimeout(c)},[e.phase,e.requestSessions,e.search,e.sinceFilter]),o.useEffect(()=>{const a=n.current;a.phase==="connected"&&a.fetchAgentResources(a.agent,a.cwd)},[e.agent,e.cwd,e.fetchAgentResources,e.phase])}function Zu(e){const[t,n]=o.useState(!1),r=o.useRef(!1),i=e.clientRef.current,a=e.activeSessionId,c=!a||!!(e.pendingApprovals[a]||e.pendingQuestions[a]),l=!c&&i?.supportsSessionSteer===!0&&!!a&&e.respondingSessions.has(a)&&e.activeSession?.runtime.state!=="externalRunning",u=!c&&i?.supportsQueueSendNow===!0;return{busy:t,canGuide:l,canSendNow:u,onAction:async(d,f)=>{if(!a||!i?.isConnected||r.current||!(f==="guide"?l:u))return;const x=new Set(d.map(S=>S.clientMessageId).filter(Boolean)),b=e.activeQueue.filter(S=>S.clientMessageId&&x.has(S.clientMessageId));if(b.length){r.current=!0,n(!0),e.setErrorText(null);try{if(f==="sendNow")await i.request({action:"session.queue.sendNow",id:i.makeId("queue_now"),sessionId:a,clientMessageIds:b.map(S=>S.clientMessageId)},{timeoutMs:15e3});else for(const S of b)await i.request({action:"session.steer",id:i.makeId("queue_guide"),sessionId:a,clientMessageId:S.clientMessageId,message:S.content,images:S.images},{timeoutMs:15e3}),e.setPendingQueues(v=>({...v,[a]:(v[a]??[]).filter(m=>m.clientMessageId!==S.clientMessageId)}))}catch(S){e.setErrorText(S instanceof Error?S.message:String(S))}finally{r.current=!1,n(!1)}}}}}function ns(e,t){return!!t&&Object.hasOwn(e,t)}function Ju(e,t){const n=e.map(r=>({...r}));return t?Ls(Fs(n,t)):n}function Yu(e,t,n){return t?{...e,[t]:n.map(r=>({...r}))}:e}function $i(e,t,n){return!t||n.length===0?e:{...e,[t]:Zo(e[t]??[],n)}}function Xu(e,t,n){return n.historyKey&&e[t]?.some(r=>r.historyKey===n.historyKey)?e:$i(e,t,[n])}function eh(e,t,n){return!t||!n?e:{...e,[t]:Ls(Fs(e[t]??[],n))}}function th(e,t,n){if(!t||!n||t===n||!ns(e,t))return e;const r={...e};return r[n]=e[t],delete r[t],r}function nh(e,t){if(!ns(e,t))return e;const n={...e};return delete n[t],n}function Zt(e,t,n){const r=new Set(e);return n?r.add(t):r.delete(t),r}function sh(e){const t=o.useCallback((n,r,i,a,c)=>{const l=e.notificationSettingsRef.current;if(!l[a]||e.notifiedEventsRef.current.has(n))return;Vo(r,i,{onClick:()=>{window.focus(),c&&e.setActiveSessionId(c)},permission:e.notificationPermissionRef.current,settings:l,tag:n,visibilityState:document.visibilityState})&&e.notifiedEventsRef.current.add(n)},[e]);return o.useCallback(n=>{switch(n.type){case"response":{vn(n.data)&&typeof n.data.oldSessionId=="string"&&typeof n.data.sessionId=="string"&&e.remapLocalSessionState(n.data.oldSessionId,n.data.sessionId);break}case"sessions.changed":e.requestSessions({force:!0,preserveLoaded:!0}).catch(r=>e.setErrorText(r instanceof Error?r.message:String(r)));break;case"session.history":e.setPendingQueues(r=>({...r,[n.sessionId]:n.pendingQueue??[]})),e.clearHistoryLoading(n.sessionId),e.mergeCachedHistoryPage(n.sessionId,Ju(n.messages,n.partialReplyText),n.historyPage),n.sessionId===e.activeSessionIdRef.current&&(e.setPendingApprovals(r=>{const i={...r};return n.pendingApproval?i[n.sessionId]={type:"approval.request",sessionId:n.sessionId,...n.pendingApproval}:delete i[n.sessionId],i}),e.setPendingQuestions(r=>{const i={...r};if(n.pendingQuestion){const a={type:"question.request",sessionId:n.sessionId,...n.pendingQuestion};i[n.sessionId]=a,e.setQuestionAnswers(Os(a))}else delete i[n.sessionId];return i})),e.setRespondingSessions(r=>{const i=Zt(r,n.sessionId,!!(n.isResponding||n.externallyResponding));return e.respondingSessionsRef.current=i,i});break;case"session.history.append":e.appendCachedHistory(n.sessionId,n.messages);break;case"text.delta":e.appendCachedDelta(n.sessionId,n.content),e.respondingSessionsRef.current=Zt(e.respondingSessionsRef.current,n.sessionId,!0),e.setRespondingSessions(r=>Zt(r,n.sessionId,!0));break;case"tool.call":e.appendCachedHistory(n.sessionId,[{role:"tool",type:"info",toolName:n.toolName,toolInput:n.input,content:`${e.t.toolCallLabel}: ${n.toolName}
|
|
11
|
+
|
|
12
|
+
${oc(n.input)}`,timestamp:new Date().toISOString()}]);break;case"tool.result":e.appendCachedHistory(n.sessionId,[{role:"tool",type:"info",content:n.output,timestamp:new Date().toISOString()}]);break;case"approval.request":e.setPendingApprovals(r=>({...r,[n.sessionId]:n})),t(`approval:${n.sessionId}:${n.requestId}`,e.t.notificationApprovalTitle,n.description||n.toolName,"approvals",n.sessionId);break;case"question.request":e.setPendingQuestions(r=>({...r,[n.sessionId]:n})),t(`question:${n.sessionId}:${n.requestId}`,e.t.notificationQuestionTitle,e.t.notificationQuestionCount(n.questions.length),"questions",n.sessionId);break;case"question.cleared":e.setPendingQuestions(r=>{const i={...r};return i[n.sessionId]?.requestId===n.requestId&&delete i[n.sessionId],i});break;case"session.queue":e.setLivePendingQueue(n.sessionId,n.pending);break;case"session.stall_warning":e.setSessions(r=>r.map(i=>i.sessionId===n.sessionId?{...i,stallWarning:n.warning}:i));break;case"session.interrupted_notice":e.setSessions(r=>r.map(i=>i.sessionId===n.sessionId?{...i,interruptReason:n.reason,stallWarning:void 0}:i));break;case"session.done":if(e.respondingSessionsRef.current.has(n.sessionId)){const r=(e.turnNotificationCountsRef.current[n.sessionId]??0)+1;e.turnNotificationCountsRef.current[n.sessionId]=r,t(`done:${n.sessionId}:${r}`,e.t.notificationReplyTitle,e.t.notificationReplyBody,"replies",n.sessionId)}e.respondingSessionsRef.current=Zt(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(r=>Zt(r,n.sessionId,!1)),n.sessionId===e.activeSessionIdRef.current&&(e.setPendingApprovals(r=>{const i={...r};return delete i[n.sessionId],i}),e.setPendingQuestions(r=>{const i={...r};return delete i[n.sessionId],i})),n.usage&&e.setSessions(r=>r.map(i=>i.sessionId===n.sessionId?{...i,lastUsage:n.usage}:i)),e.requestSessions({force:!0,preserveLoaded:!0}).catch(r=>e.setErrorText(r instanceof Error?r.message:String(r)));break;case"session.interrupted":e.respondingSessionsRef.current=Zt(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(r=>Zt(r,n.sessionId,!1)),e.requestSessions({force:!0,preserveLoaded:!0}).catch(r=>e.setErrorText(r instanceof Error?r.message:String(r)));break;case"session.renamed":e.setSessions(r=>r.map(i=>i.sessionId===n.sessionId?{...i,customTitle:n.title}:i));break;case"error":e.setErrorText(n.message);break}},[e,t])}const Fi="vibelet.web.composerDrafts",Es={draftsBySessionId:{},newSessionDraft:""};function Cr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Oi(e){return Cr(e)?{draftsBySessionId:Cr(e.draftsBySessionId)?Object.fromEntries(Object.entries(e.draftsBySessionId).filter(n=>typeof n[1]=="string")):{},newSessionDraft:typeof e.newSessionDraft=="string"?e.newSessionDraft:""}:Es}function rh(e=Ge()){const t=e.getItem(Fi);if(!t)return Es;try{return Oi(JSON.parse(t))}catch{return Es}}function In(e,t=Ge()){t.setItem(Fi,JSON.stringify(Oi(e)))}function Nn(e,t,n){if(!t)return{...e,newSessionDraft:n};const r={...e.draftsBySessionId};return n.trim()?r[t]=n:delete r[t],{...e,draftsBySessionId:r}}function An(e,t){return t?e.draftsBySessionId[t]??"":e.newSessionDraft}function ih(e,t,n){if(!t||!n||t===n)return e;const r=e.draftsBySessionId[t];if(r===void 0)return e;const i={...e.draftsBySessionId};return delete i[t],r.trim()&&(i[n]=r),{...e,draftsBySessionId:i}}function ah(e,t,n,r=!1){if(!r)return{...e,[t]:[n]};const i=e[t]??[],a=i.includes(n)?i.filter(c=>c!==n):[...i,n];return{...e,[t]:a}}function oh(e){const t=o.useCallback(async m=>{const p=e.clientRef.current;if(!(!p?.isConnected||!e.activeApproval)){e.setBusy(!0),e.setErrorText(null);try{await p.request({action:"session.approve",id:p.makeId("approve"),sessionId:e.activeApproval.sessionId,requestId:e.activeApproval.requestId,approved:m}),e.setPendingApprovals(y=>{const g={...y};return g[e.activeApproval.sessionId]?.requestId===e.activeApproval.requestId&&delete g[e.activeApproval.sessionId],g})}catch(y){e.setErrorText(y instanceof Error?y.message:String(y))}finally{e.setBusy(!1)}}},[e]),n=o.useCallback(async()=>{const m=e.clientRef.current;if(!(!m?.isConnected||!e.activeQuestion)){e.setBusy(!0),e.setErrorText(null);try{await m.request({action:"session.respondQuestion",id:m.makeId("question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId,answers:e.questionAnswers}),e.setPendingQuestions(p=>{const y={...p};return y[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete y[e.activeQuestion.sessionId],y})}catch(p){e.setErrorText(p instanceof Error?p.message:String(p))}finally{e.setBusy(!1)}}},[e]),r=o.useCallback(async()=>{const m=e.clientRef.current;if(!(!m?.isConnected||!e.activeQuestion)){e.setBusy(!0),e.setErrorText(null);try{await m.request({action:"session.cancelQuestion",id:m.makeId("cancel_question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId}),e.setPendingQuestions(p=>{const y={...p};return y[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete y[e.activeQuestion.sessionId],y})}catch(p){e.setErrorText(p instanceof Error?p.message:String(p))}finally{e.setBusy(!1)}}},[e]),i=o.useCallback((m,p,y)=>{e.setQuestionAnswers(g=>ah(g,m,p,!!y))},[e]),a=o.useCallback(async m=>{const p=e.clientRef.current,y=e.activeSession,g=y?.sessionId??(m==="session.interrupt"?e.activeSessionIdRef.current:null);if(!p?.isConnected||!g||m!=="session.interrupt"&&!y||m==="session.delete"&&!await yn(rn().deleteSession(St(y)))||e.clientRef.current!==p||!p.isConnected)return!1;e.setBusy(!0),e.setErrorText(null);try{return m==="session.resume"?await p.request({action:m,id:p.makeId("resume"),sessionId:g,agent:y.agent}):await p.request({action:m,id:p.makeId(m.split(".").at(-1)??"session"),sessionId:g}),m==="session.delete"&&(e.removeCachedHistory(y.sessionId),e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([])),m!=="session.interrupt"&&await e.requestSessions({force:!0,preserveLoaded:!0}),!0}catch(j){return e.setErrorText(j instanceof Error?j.message:String(j)),!1}finally{e.setBusy(!1)}},[e]),c=o.useCallback(async m=>{const p=e.clientRef.current;if(!e.activeSession){e.setApprovalMode(m);return}if(p?.isConnected){e.setErrorText(null);try{await p.request({action:"session.setApprovalMode",id:p.makeId("approval_mode"),sessionId:e.activeSession.sessionId,approvalMode:m}),e.activeSessionIdRef.current===e.activeSession.sessionId&&e.setApprovalMode(m),e.setSessions(y=>y.map(g=>g.sessionId===e.activeSession.sessionId?{...g,approvalMode:m}:g))}catch(y){e.setErrorText(y instanceof Error?y.message:String(y))}}},[e]),l=o.useCallback(async m=>{const p=e.clientRef.current;if(!p?.isConnected||!e.activeSessionId||!m.clientMessageId)return;const y=e.activeSessionId;let g=-1;e.setPendingQueues(j=>{const w=j[y]??[];return g=w.findIndex(k=>k.clientMessageId===m.clientMessageId),{...j,[y]:w.filter(k=>k.clientMessageId!==m.clientMessageId)}}),e.setBusy(!0),e.setErrorText(null);try{await p.request({action:"session.queue.cancel",id:p.makeId("queue_cancel"),sessionId:y,clientMessageId:m.clientMessageId})}catch(j){e.setPendingQueues(w=>{const k=w[y]??[];if(k.some(D=>D.clientMessageId===m.clientMessageId))return w;const N=Math.min(Math.max(g,0),k.length);return{...w,[y]:[...k.slice(0,N),m,...k.slice(N)]}}),e.setErrorText(j instanceof Error?j.message:String(j))}finally{e.setBusy(!1)}},[e]),u=o.useCallback(async(m,p)=>{if(e.pendingSessions[m.sessionId])return;const y=e.clientRef.current;if(y?.isConnected){e.setBusy(!0),e.setErrorText(null);try{const g=p?Date.now():void 0;await y.request({action:"session.setPinned",id:y.makeId("pin"),sessionId:m.sessionId,pinned:p,...g?{pinnedAt:g}:{}}),e.setSessions(j=>j.map(w=>w.sessionId===m.sessionId?{...w,pinned:p,pinnedAt:g}:w)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(g){e.setErrorText(g instanceof Error?g.message:String(g))}finally{e.setBusy(!1)}}},[e]),h=o.useCallback(async(m,p)=>{if(e.pendingSessions[m.sessionId])return;const y=e.clientRef.current;if(y?.isConnected){e.setBusy(!0),e.setErrorText(null);try{await y.request({action:"session.setArchived",id:y.makeId("archive"),sessionId:m.sessionId,archived:p}),e.setSessions(g=>g.map(j=>j.sessionId===m.sessionId?{...j,archived:p}:j)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(g){e.setErrorText(g instanceof Error?g.message:String(g))}finally{e.setBusy(!1)}}},[e]),d=o.useCallback(async m=>{if(e.pendingSessions[m.sessionId]){e.removeCachedHistory(m.sessionId),e.setPendingSessions(y=>{const g={...y};return delete g[m.sessionId],g}),e.setComposerDrafts(y=>{const g=Nn(y,m.sessionId,"");return e.composerDraftsRef.current=g,In(g),g}),e.activeSessionIdRef.current===m.sessionId&&(e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([]),e.setDraft(An(e.composerDraftsRef.current,null)),e.setDetailsOpen(!1));return}const p=e.clientRef.current;if(!(!p?.isConnected||!await yn(rn().deleteSession(St(m))))&&!(e.clientRef.current!==p||!p.isConnected)){e.setBusy(!0),e.setErrorText(null);try{await p.request({action:"session.delete",id:p.makeId("delete"),sessionId:m.sessionId}),e.removeCachedHistory(m.sessionId),e.setOptimisticSessions(y=>{if(!y[m.sessionId])return y;const g={...y};return delete g[m.sessionId],g}),e.activeSessionIdRef.current===m.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(y){e.setErrorText(y instanceof Error?y.message:String(y))}finally{e.setBusy(!1)}}},[e]),f=o.useCallback(async()=>{e.activeSession&&await u(e.activeSession,!e.activeSession.pinned)},[e.activeSession,u]),x=o.useCallback(async()=>{e.activeSession&&await h(e.activeSession,!e.activeSession.archived)},[e.activeSession,h]),b=o.useCallback(()=>{const m=e.activeSessionId;m&&a("session.interrupt").then(p=>{p&&(e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current),e.respondingSessionsRef.current.delete(m),e.setRespondingSessions(y=>{const g=new Set(y);return g.delete(m),g}))})},[e,a]),S=o.useCallback(()=>{e.setErrorText(null),e.phase==="connected"?e.requestSessions({force:!0,preserveLoaded:!0}):window.location.reload()},[e]),v=o.useCallback(async()=>{const m=e.renameTitle.trim();if(e.activeSession&&e.pendingSessions[e.activeSession.sessionId]){e.setPendingSessions(y=>{const g=y[e.activeSession.sessionId];return g?{...y,[e.activeSession.sessionId]:{...g,title:m||g.title,customTitle:m||void 0}}:y});return}const p=e.clientRef.current;if(!(!p?.isConnected||!e.activeSession)){e.setBusy(!0),e.setErrorText(null);try{await p.request({action:"session.rename",id:p.makeId("rename"),sessionId:e.activeSession.sessionId,title:m||void 0}),e.setSessions(y=>y.map(g=>g.sessionId===e.activeSession.sessionId?{...g,customTitle:m||void 0}:g))}catch(y){e.setErrorText(y instanceof Error?y.message:String(y))}finally{e.setBusy(!1)}}},[e]);return{respondApproval:t,respondQuestion:n,cancelQuestion:r,setQuestionChoice:i,requestActiveAction:a,interruptActiveSession:b,retrySessions:S,updateApprovalMode:c,cancelQueuedTurn:l,setSessionPinned:u,setSessionArchived:h,deleteSession:d,updatePinned:f,updateArchived:x,renameSession:v}}async function Rs(e){return{[e]:"desktop-free"}}function ch(){let e=null,t=null;const n=new Set,r=()=>n.forEach(i=>i());return{getSnapshot:()=>e,subscribe:i=>(n.add(i),()=>{n.delete(i)}),start(i){const a={sessionId:i};return t=a,e=a,r(),{remap(c){t===a&&(e={sessionId:c},r())},finish(){t===a&&(t=null,e=null,r())}}}}}function Ir(e){const t=e.toLowerCase();return/subscription|required|upgrade|billing/u.test(t)?"subscription":/skillnotfound|not found|missing/u.test(t)?"missing-resource":/permission|forbidden|unauthorized|denied/u.test(t)?"permission":/timeout|timed out/u.test(t)?"timeout":/websocket|network|disconnect|connection|offline|closed/u.test(t)?"network":"unknown"}const Nr=15e3,Ar="Session send timed out.";function pn(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function lh(e){const[t]=o.useState(ch),[n,r]=o.useState(null),i=o.useCallback(h=>{e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current),e.respondingSessionsRef.current.delete(h),e.setRespondingSessions(d=>{const f=new Set(d);return f.delete(h),f})},[e]),a=o.useCallback((h,d,f)=>{const x=pn(h)??pn(e.cwd)??Qe,b=d??e.agent,S=cc(),v=lc({sessionId:S,agent:b,cwd:x,approvalMode:f?.approvalMode??e.approvalMode,model:$n(f?.model??e.model),effort:e.effort||void 0,fastMode:e.fastMode,title:b==="codex"?e.t.newCodexSession:e.t.newClaudeSession}),m=f?.draft??(e.activeSessionIdRef.current?"":An(e.composerDraftsRef.current,null));return e.setPendingSessions(p=>({...p,[S]:v})),e.setComposerDrafts(p=>{let y=Nn(p,S,m);return e.activeSessionIdRef.current||(y=Nn(y,null,"")),e.composerDraftsRef.current=y,In(y),y}),e.setCwd(x),e.setAgent(b),e.setActiveSessionId(S),e.lastHistorySessionIdRef.current=S,e.messagesSessionIdRef.current=S,e.clearHistoryLoading(),e.setMessages([]),e.setDraft(m),e.setErrorText(null),e.reportLog("web.session.pending_create",{sessionId:S,agent:b,cwd:x}),S},[e]),c=o.useCallback(async(h,d,f)=>{const x=e.clientRef.current;if(!x?.isConnected)return e.setErrorText(e.t.webSocketNotConnected),null;const b=f?e.pendingSessions[f]:void 0,S=pn(h)??pn(b?.cwd)??pn(e.cwd)??Qe,v=d??b?.agent??e.agent,m=b?.approvalMode??e.approvalMode,p=b?.model??$n(e.model),y=b?.effort??(e.effort||void 0),g=b?.fastMode??e.fastMode;e.setErrorText(null);try{const j=await x.request({action:"session.create",id:x.makeId("create"),agent:v,cwd:S,approvalMode:m,continueSession:e.continueSession,model:p,effort:y,fastMode:g,...f?{clientSessionId:f}:{}}),w=ic(j);if(!w)throw new Error(e.t.sessionIdMissing);const k=vn(j)&&typeof j.oldSessionId=="string"?j.oldSessionId:f;return e.setCwd(S),e.setAgent(v),e.setActiveSessionId(w),e.lastHistorySessionIdRef.current=w,e.messagesSessionIdRef.current=w,e.clearHistoryLoading(),f&&b?(e.setPendingSessions(N=>{const D={...N};return delete D[f],k&&k!==f&&delete D[k],D}),e.setOptimisticSessions(N=>({...N,[w]:dc(b,w)})),k&&k!==w&&e.remapLocalSessionState(k,w),f!==w&&e.remapLocalSessionState(f,w)):await e.requestSessions({force:!0}),e.reportLog("web.session.create",{sessionId:w,clientSessionId:f,agent:v,cwd:S}),w}catch(j){return e.setErrorText(j instanceof Error?j.message:String(j)),null}},[e]),l=o.useCallback(async h=>{h?.preventDefault();const d=e.draft.trim();if(!d||e.busy)return;const f=e.clientRef.current;if(!f?.isConnected){e.setErrorText(e.t.webSocketNotConnected);return}const x=t.start(e.activeSessionId);try{const b=ir(d)?"agentSkills":e.attachments.length===0&&Xs(d,e.activeSession?.agent??e.agent)?"agentCommands":void 0;let S;if(b){e.setBusy(!0);try{S=await Rs(b)}catch(I){e.setErrorText(I instanceof Error?I.message:String(I));return}finally{e.setBusy(!1)}}e.setBusy(!0),e.setErrorText(null),e.updateDraft("");const v=e.attachments;e.setAttachments([]);let m=e.activeSessionId,p=e.activeSession?.agent??e.agent;if(m&&e.pendingSessions[m]){const I=await c(e.pendingSessions[m].cwd,e.pendingSessions[m].agent,m);if(!I){e.setBusy(!1),e.updateDraft(d),e.setAttachments(v);return}m=I,p=e.pendingSessions[e.activeSessionId??""]?.agent??p}else m||(m=await c());if(!m){e.setBusy(!1),e.updateDraft(d),e.setAttachments(v);return}x.remap(m);const y=v.length===0?Xs(d,p):null;if(y){const I=Ho(y.command),W=I?f.makeId("cmd_msg"):void 0;I&&(e.messagesSessionIdRef.current=m,e.appendCachedHistory(m,[{role:"user",content:I,timestamp:new Date().toISOString()}]),e.renderCachedHistory(m));try{const K=await f.request({action:"session.command",id:f.makeId("command"),sessionId:m,agent:p,command:y.command,...W?{clientMessageId:W}:{},featureEntitlements:S});await e.handleSessionCommandResponse(m,y.command,K)}catch(K){const _=K instanceof Error?K.message:String(K);e.appendInfoMessage(m,er(_)),e.setErrorText(er(_))}finally{e.setBusy(!1)}return}const g=Wo(d),j=v.map(I=>I.path),w=f.makeId("msg"),k=`client:${w}`;e.messagesSessionIdRef.current=m,e.appendCachedHistory(m,[{role:"user",content:g,timestamp:new Date().toISOString(),historyKey:k,...j.length?{images:j}:{}}]),e.renderCachedHistory(m),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(m),e.setRespondingSessions(I=>new Set(I).add(m));const N=ir(g)??void 0,D=N?S:void 0;try{const I=await f.request({action:"session.send",id:f.makeId("send"),sessionId:m,agent:p,message:g,clientMessageId:w,images:j.length?j:void 0,model:$n(e.model),effort:e.effort||void 0,fastMode:e.fastMode,skillInvocation:N,featureEntitlements:D},{timeoutMs:Nr,timeoutMessage:Ar});vn(I)&&typeof I.oldSessionId=="string"&&typeof I.sessionId=="string"&&(x.remap(I.sessionId),e.remapLocalSessionState(I.oldSessionId,I.sessionId)),e.reportLog("web.telemetry.send_accepted",{attachmentCount:j.length}),r(W=>W?.historyKey===k?null:W)}catch(I){const W=I instanceof Error?I.message:String(I),K=Ir(rr(W,!!N));e.setErrorText(null),r({sessionId:m,agent:p,message:g,clientMessageId:w,historyKey:k,kind:K,retrying:!1,...j.length?{images:j}:{},model:$n(e.model),effort:e.effort||void 0,fastMode:e.fastMode,skillInvocation:N,featureEntitlements:D}),e.reportLog("web.telemetry.send_failed",{attachmentCount:j.length,failureKind:K},"warn"),i(m)}finally{e.setBusy(!1)}}finally{x.finish()}},[i,c,e,t]),u=o.useCallback(async()=>{if(!n||n.retrying||e.busy)return;const h=e.clientRef.current;if(!h?.isConnected){r(f=>f?{...f,kind:"network"}:null);return}const d=t.start(n.sessionId);r(f=>f?{...f,retrying:!0}:null),e.ensureCachedHistoryEntry(n.sessionId,{role:"user",content:n.message,historyKey:n.historyKey,...n.images?.length?{images:n.images}:{}}),e.setBusy(!0),e.setErrorText(null),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(n.sessionId),e.setRespondingSessions(f=>new Set(f).add(n.sessionId));try{const f=await h.request({action:"session.send",id:h.makeId("retry_send"),sessionId:n.sessionId,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 Rs("agentSkills"):void 0},{timeoutMs:Nr,timeoutMessage:Ar});vn(f)&&typeof f.oldSessionId=="string"&&typeof f.sessionId=="string"&&(d.remap(f.sessionId),e.remapLocalSessionState(f.oldSessionId,f.sessionId)),e.reportLog("web.telemetry.retry_accepted",{attachmentCount:n.images?.length??0}),r(null)}catch(f){const x=f instanceof Error?f.message:String(f),b=Ir(rr(x,!!n.skillInvocation));r(S=>S?{...S,kind:b,retrying:!1}:null),e.reportLog("web.telemetry.retry_failed",{attachmentCount:n.images?.length??0,failureKind:b},"warn"),i(n.sessionId)}finally{e.setBusy(!1),d.finish()}},[i,n,e,t]);return{failedSend:n,retryFailedSend:u,stagePendingSession:a,sendDraft:Object.assign(l,{submission:t})}}function dh(e,t){const n=e.indexOf(t);if(n>=0)return n;const r=t.historyKey;if(r)return e.findIndex(c=>c.historyKey===r);const i=t.rewindPoint;if(i)return e.findIndex(c=>JSON.stringify(c.rewindPoint)===JSON.stringify(i));const a=e.flatMap((c,l)=>c.role===t.role&&c.type===t.type&&c.content===t.content&&c.timestamp===t.timestamp&&JSON.stringify(c.images)===JSON.stringify(t.images)?[l]:[]);return a.length===1?a[0]:-1}function uh(e){const t=o.useRef(!1);return async n=>{const r=e.activeSession,i=e.clientRef.current;if(!r||!i?.isConnected||t.current||e.busy)return;const a=kn(),c=e.historyCacheRef.current[r.sessionId]??[],l=dh(c,n);if(l<0||n.role!=="user"||n.type==="info"){e.setErrorText(a.unavailable);return}if((e.historyPageStartRef.current[r.sessionId]??0)>0){e.setErrorText(a.incompleteHistory);return}t.current=!0;let u=!1;try{u=await gs({message:a.confirmRewind})}finally{t.current=!1}if(!(!u||e.clientRef.current!==i||!i.isConnected||e.activeSessionIdRef.current!==r.sessionId)){t.current=!0,e.setBusy(!0),e.setErrorText(null);try{const h=await i.request({action:"session.rewind",id:i.makeId("rewind"),sessionId:r.sessionId,agent:r.agent,targetUserMessageIndex:c.slice(0,l+1).filter(f=>f.role==="user"&&f.type!=="info").length-1,featureEntitlements:await Rs("sessionRewind")},{timeoutMs:15e4,timeoutMessage:a.rewindFailed});if(!h||typeof h.sessionId!="string"||!h.sessionId||h.sessionId===r.sessionId||h.sourceSessionId!==r.sessionId||h.archivedSource!==!0||!Array.isArray(h.messages)||h.messages.some(f=>!f||typeof f.content!="string"||!["user","assistant","tool"].includes(f.role)))throw new Error(a.invalidResponse);const d={...r,sessionId:h.sessionId,archived:!1};e.setOptimisticSessions(f=>{const x={...f};return delete x[r.sessionId],x[h.sessionId]=d,x}),e.setSessions(f=>[...f.filter(x=>x.sessionId!==h.sessionId).map(x=>x.sessionId===r.sessionId?{...x,archived:!0,pinned:!1}:x),d]),e.replaceCachedHistory(h.sessionId,h.messages),e.lastHistorySessionIdRef.current=h.sessionId,e.activeSessionIdRef.current=h.sessionId,e.setActiveSessionId(h.sessionId),e.renderCachedHistory(h.sessionId),e.updateDraft(n.content),e.setAttachments((n.images??[]).map(f=>({path:f,name:f.split("/").pop()??f,type:"application/octet-stream",size:0}))),await e.requestSessions({force:!0}).catch(()=>{})}catch(h){e.setErrorText(h instanceof Error?h.message:a.rewindFailed)}finally{t.current=!1,e.setBusy(!1)}}}}function hh(e,t,n,r,i){if(t===n)return e;const a=!t&&i?i:r||Qe;return a===e.path?e:{path:a,entries:[],loading:!1,loaded:!1}}function fs(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Yt(e=window.location.search){const t=new URLSearchParams(e),n=fs(t.get("folder")),r=fs(t.get("file")),i=fs(t.get("cwd"));return{...n?{folder:n}:{},...r?{file:r}:{},...i?{cwd:i}:{}}}function fh(e,t,n=[]){const r=new URLSearchParams(e);for(const a of n)r.delete(a);for(const[a,c]of Object.entries(t))c?r.set(a,c):r.delete(a);const i=r.toString();return i?`?${i}`:""}function Er(e,t={}){const n=t.history??window.history,r=t.location??window.location,i=[];e.folder&&i.push("file","cwd"),e.file&&i.push("folder");const a=fh(r.search,e,i),c=`${r.pathname}${a}${r.hash}`;if(t.replace){n.replaceState(null,"",c);return}n.pushState(null,"",c)}function Jt(e,t){o.useEffect(()=>{e.current=t},[e,t])}function mh({activeSessionIdRef:e,composerDraftsRef:t,setComposerDrafts:n,setDraft:r}){const i=o.useCallback(c=>{r(c),n(l=>{const u=Nn(l,e.current,c);return t.current=u,In(u),u})},[e,t,n,r]),a=o.useCallback(c=>{n(l=>{const u=Nn(l,null,c);return t.current=u,In(u),u}),e.current||r(c)},[e,t,n,r]);return{updateDraft:i,updateNewSessionDraft:a}}function ph(e,t,n){return!e||e.path!==t.path||e.cwd!==t.cwd?e:{...e,dirty:e.text!==t.text,etag:typeof n.etag=="string"?n.etag:e.etag,lastModified:typeof n.lastModified=="string"?n.lastModified:e.lastModified,size:typeof n.size=="number"?n.size:e.size}}function gh(e){const{clientRef:t,pairing:n,cwd:r,phase:i,controlTab:a,setControlTab:c,setBusy:l,setErrorText:u,t:h}=e,d=o.useRef(!1),[f,x]=o.useState([]),[b,S]=o.useState(!1),[v,m]=o.useState({path:Yt().folder||Yt().cwd||Qe,entries:[],loading:!1,loaded:!1}),[p,y]=o.useState(""),[g,j]=o.useState(null),[w,k]=o.useState(!1),N=o.useRef(null),D=o.useRef(0),I=o.useRef(v.path);o.useEffect(()=>{I.current!==v.path&&(D.current++,I.current=v.path)},[v.path]),o.useEffect(()=>(D.current++,m({path:Yt().folder||Yt().cwd||r||Qe,entries:[],loading:!1,loaded:!1}),j(null),()=>{D.current++,N.current?.abort()}),[n?.pairToken]),o.useEffect(()=>{v.path!==Qe||Yt().folder||(D.current++,m(A=>({...A,entries:[],loaded:!1,loading:!1})))},[r]);const W=o.useRef(new Set);o.useEffect(()=>{g?.objectUrl&&W.current.add(g.objectUrl)},[g?.objectUrl]),o.useEffect(()=>()=>{for(const A of W.current)URL.revokeObjectURL(A);W.current.clear()},[n?.pairToken]);const K=o.useCallback(async A=>{if(!(!A?.length||!n)){S(!0),u(null);try{const R=[];for(const q of Array.from(A)){const H=await fetch(`/upload?name=${encodeURIComponent(q.name)}`,{method:"POST",headers:{authorization:`Bearer ${n.pairToken}`,"content-type":q.type||"application/octet-stream"},body:q});if(!H.ok)throw new Error(await H.text().catch(()=>h.uploadFailed)||h.uploadFailed);const B=ac(await H.json());if(!B)throw new Error(h.uploadPathMissing);R.push({path:B,name:q.name,type:q.type||"application/octet-stream",size:q.size})}x(q=>[...q,...R])}catch(R){u(R instanceof Error?R.message:String(R))}finally{S(!1)}}},[n,u,h.uploadFailed,h.uploadPathMissing]),_=o.useCallback(async(A,R,q)=>{if(!n)return;N.current?.abort();const H=new AbortController;N.current=H,u(null);try{const B=/^(?:https?:\/\/|data:image\/|blob:)/i.test(A),G=await fetch(B?A:Wn(A,R),{headers:B?{}:{authorization:`Bearer ${n.pairToken}`},signal:H.signal});if(!G.ok)throw new Error(await G.text().catch(()=>h.fileOpenFailed)||h.fileOpenFailed);const V=G.headers.get("content-type")??"application/octet-stream";if(B&&!V.startsWith("image/"))throw new Error(h.fileOpenFailed);const oe=Vn(A,V,!1);if(oe==="html"||oe==="unsupported"&&hc(A,V)){const $=await G.text();if(H.signal.aborted)return;j({path:A,cwd:R,kind:"text",contentType:V,text:$,etag:Fn(G.headers,"etag"),lastModified:Fn(G.headers,"last-modified"),size:Number(G.headers.get("content-length"))||void 0,dirty:!1})}else{const $=await G.blob();if(H.signal.aborted)return;const U=Vn(A,V,!1)==="pdf"?new Blob([$],{type:"application/pdf"}):$;j({path:A,cwd:R,kind:fc(A,V)?"image":"binary",contentType:V,text:"",objectUrl:URL.createObjectURL(U),etag:Fn(G.headers,"etag"),lastModified:Fn(G.headers,"last-modified"),size:$.size,dirty:!1})}k(!1),c("files"),q?.updateRoute&&Er({file:A,...R?{cwd:R}:{}},{replace:q.replaceRoute})}catch(B){if(H.signal.aborted)return;u(B instanceof Error?B.message:String(B))}},[n,c,u]),be=o.useCallback(async A=>{if(!(!n||!g||g.kind!=="text")){l(!0),u(null);try{const R=await fetch(Wn(g.path,g.cwd),{method:"PUT",headers:{authorization:`Bearer ${n.pairToken}`,"content-type":"text/markdown; charset=utf-8",...g.etag&&!A?.force?{"if-match":g.etag}:{}},body:g.text});if(!R.ok)throw R.status===409?(k(!0),new Error(h.remoteFileConflict(g.path))):new Error(await R.text().catch(()=>h.fileSaveFailed)||h.fileSaveFailed);k(!1);const q=await R.json().catch(()=>({}));j(H=>ph(H,g,q))}catch(R){u(R instanceof Error?R.message:String(R))}finally{l(!1)}}},[n,g,l,u]),Te=o.useCallback(async()=>{if(!(!n||!g))try{const A=/^(?:https?:\/\/|data:image\/|blob:)/i.test(g.path),R=await fetch(A?g.path:Wn(g.path,g.cwd),{headers:A?{}:{authorization:`Bearer ${n.pairToken}`}});if(!R.ok)throw new Error(h.downloadFailed);const q=URL.createObjectURL(await R.blob()),H=document.createElement("a");H.href=q,H.download=_t(g.path),H.click(),URL.revokeObjectURL(q)}catch(A){u(A instanceof Error?A.message:String(A))}},[n,g,u]),X=o.useCallback(async(A=v.path,R)=>{const q=t.current;if(!q?.isConnected)return;I.current=A;const H=++D.current;m(B=>({...B,path:A,entries:A===B.path?B.entries:[],loading:!0,loaded:!1,error:void 0}));try{const B=await q.request({action:"dirs.list",id:q.makeId("dirs"),path:A,cwd:r||void 0});if(H!==D.current)return;m({path:A,entries:B.entries??[],loading:!1,loaded:!0}),R?.updateRoute&&Er({folder:A},{replace:R.replaceRoute})}catch(B){if(H!==D.current)return;m(G=>({...G,loading:!1,loaded:!0,error:B instanceof Error?B.message:String(B)}))}},[t,r,v.path]),ae=o.useCallback(async A=>{const R=t.current;if(!R?.isConnected)throw new Error(h.webSocketNotConnected);return(await R.request({action:"dirs.list",id:R.makeId("dirs"),path:A,cwd:r||void 0},{timeoutMs:1e4,timeoutMessage:h.directoryListTimedOut})).entries??[]},[t,r]),ve=o.useCallback(async A=>(await ae(A)).filter(R=>R.isDirectory),[ae]);o.useEffect(()=>{!d.current||a!=="files"||i!=="connected"||v.loading||v.loaded||X(v.path||r||Qe)},[a,r,v.loaded,v.loading,v.path,X,i]),o.useEffect(()=>{if(i!=="connected"||d.current)return;const A=Yt();if(!A.folder&&!A.file){d.current=!0;return}if(d.current=!0,c("files"),A.folder){X(A.folder,{updateRoute:!1});return}A.file&&(A.cwd&&m(R=>({...R,path:A.cwd,loaded:!1})),_(A.file,A.cwd,{updateRoute:!1}))},[X,_,i,c]);const de=o.useCallback(async()=>{const A=t.current;if(!(!A?.isConnected||p.trim().length===0)){l(!0),u(null);try{await A.request({action:"dirs.create",id:A.makeId("mkdir"),path:uc(v.path,p),cwd:r||void 0}),y(""),await X(v.path)}catch(R){u(R instanceof Error?R.message:String(R))}finally{l(!1)}}},[t,r,v.path,X,p,l,u]),Ne=o.useCallback(async A=>{const R=t.current;if(!R?.isConnected)throw new Error(h.webSocketNotConnected);await R.request({action:"dirs.create",id:R.makeId("mkdir"),path:A,cwd:r||void 0},{timeoutMs:1e4,timeoutMessage:h.directoryCreationTimedOut})},[t,r]);return{attachments:f,setAttachments:x,uploadBusy:b,directory:v,setDirectory:m,newDirName:p,setNewDirName:y,remoteFile:g,setRemoteFile:j,remoteFileConflict:w,uploadFiles:K,openRemoteFile:_,saveRemoteFile:be,downloadRemoteFile:Te,listDirectory:X,listSessionDirectories:ve,listFileTreeDirectory:ae,createDirectory:de,createSessionDirectory:Ne}}function yh({clientRef:e,setSessions:t}){return o.useCallback(async n=>{const r=e.current;if(!r?.isConnected)return;const i=[...new Set(n.map(c=>c.cwd).filter(Boolean))];if(i.length===0)return;const a=new Set(i);try{const c=await r.request({action:"sessions.gitMetadata",id:r.makeId("git"),cwds:i});t(l=>l.map(u=>a.has(u.cwd)?{...u,pullRequest:c.pullRequests?.[u.cwd],branch:c.branches[u.cwd]??u.branch,diffStat:c.diffStats[u.cwd]??u.diffStat}:u))}catch{}},[])}const Ts=15e3,Rr=500,ms=1e3;function bh(e){const t=o.useRef({}),n=o.useRef(null),r=o.useRef({}),i=o.useRef(null),[a,c]=o.useState(!1),[l,u]=o.useState([]),h=o.useCallback(w=>w&&n.current&&n.current!==w?!1:(n.current=null,c(!1),!0),[]),d=o.useCallback(w=>ns(t.current,w)?(i.current=w,u(t.current[w]??[]),!0):!1,[]),f=o.useCallback((w,k,N)=>{t.current=Yu(t.current,w,k);const D=t.current[w]??[];return N?.renderActive!==!1&&w===e.activeSessionIdRef.current&&(i.current=w,u(D)),D},[e.activeSessionIdRef]),x=o.useCallback((w,k,N)=>{if(!N)return r.current[w]=void 0,f(w,k);const D=r.current[w],I=t.current[w]??[],W=N.start+k.length;if(D===void 0||W<D||N.start>D+I.length)return r.current[w]=N.start,f(w,k);r.current[w]=Math.min(D,N.start);const K=I.slice(0,Math.max(0,N.start-D)),_=I.slice(Math.max(0,W-D),Math.max(0,N.total-D));return f(w,[...K,...k,..._])},[f]),b=o.useCallback((w,k)=>{r.current[w]=0;const N=f(w,k,{renderActive:!1});i.current=w,u(N)},[f]),S=o.useCallback((w,k)=>{t.current=$i(t.current,w,k),w===e.activeSessionIdRef.current&&(i.current=w,u(t.current[w]??[]))},[e.activeSessionIdRef]),v=o.useCallback((w,k)=>{t.current=Xu(t.current,w,k),w===e.activeSessionIdRef.current&&(i.current=w,u(t.current[w]??[]))},[e.activeSessionIdRef]),m=o.useCallback((w,k)=>{t.current=eh(t.current,w,k),w===e.activeSessionIdRef.current&&(i.current=w,u(t.current[w]??[]))},[e.activeSessionIdRef]),p=o.useCallback((w,k)=>{S(w,[{role:"assistant",type:"info",content:k,timestamp:new Date().toISOString()}])},[S]),y=o.useCallback(w=>{t.current=nh(t.current,w),delete r.current[w]},[]),g=o.useCallback((w,k)=>{t.current=th(t.current,w,k),r.current[k]=r.current[w],delete r.current[w]},[]),j=o.useCallback(async w=>{const k=e.clientRef.current;if(!k?.isConnected)return;const N=d(w.sessionId);N?h(w.sessionId):(n.current=w.sessionId,delete r.current[w.sessionId],c(!0),e.setErrorText(null));try{const D=r.current[w.sessionId]??0,I=t.current[w.sessionId]?.length??0;if(N&&(D===0||I>=ms)){const _=(await k.request({action:"reconnect.snapshot",id:k.makeId("snapshot"),activeSessionId:w.sessionId,activeAgent:w.agent,skipActiveSessionHistory:!0,skipGitMetadata:!0})).snapshot.activeSession;_?.sessionId===w.sessionId&&e.setPendingQueues(be=>({...be,[w.sessionId]:_.pendingQueue??[]}));return}await k.request({action:"session.history",id:k.makeId("history"),sessionId:w.sessionId,agent:w.agent,limit:Rr},{timeoutMessage:e.historyTimeoutMessage,timeoutMs:Ts});let W=r.current[w.sessionId];for(;typeof W=="number"&&W>0&&(t.current[w.sessionId]?.length??0)<ms;){const K=t.current[w.sessionId]?.length??0;await k.request({action:"session.history",id:k.makeId("history_older"),sessionId:w.sessionId,agent:w.agent,before:W,limit:Math.min(Rr,ms-K)},{timeoutMessage:e.historyTimeoutMessage,timeoutMs:Ts});const _=r.current[w.sessionId];if(typeof _!="number"||_>=W)break;W=_}}catch(D){e.activeSessionIdRef.current===w.sessionId&&e.setErrorText(D instanceof Error?D.message:String(D))}finally{h(w.sessionId)}},[h,e.activeSessionIdRef,e.clientRef,e.historyTimeoutMessage,e.setErrorText,e.setPendingQueues,d]);return{appendCachedDelta:m,appendCachedHistory:S,appendInfoMessage:p,clearHistoryLoading:h,ensureCachedHistoryEntry:v,historyCacheRef:t,historyLoading:a,historyPageStartRef:r,hydrateVisibleHistory:b,messages:l,messagesSessionIdRef:i,mergeCachedHistoryPage:x,remapCachedHistory:g,removeCachedHistory:y,renderCachedHistory:d,replaceCachedHistory:f,requestHistory:j,setMessages:u}}function vh(e){const t=async n=>{(n==="needsAttention"?e.setShowNeedsAttentionGroup:n==="running"?e.setShowRunningGroup:e.setSeparatePinnedGroup)(i=>!i)};return{showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup,separatePinnedGroup:e.separatePinnedGroup,toggleSessionViewGroup:t}}function xh(e,t){const n=t.trim().toLowerCase();return n?[St(e),e.cwd,e.agent,e.branch??"",...e.titleAliases??[]].some(r=>r.toLowerCase().includes(n)):!0}function wh(e,t){return e.filter(n=>t.hideArchived&&n.archived||t.agentFilter!=="all"&&n.agent!==t.agentFilter?!1:xh(n,t.search))}function Sh(e){const t=o.useRef([]),n=o.useMemo(()=>bs(bs(e.sessions,Object.values(e.optimisticSessions)),Object.values(e.pendingSessions)),[e.optimisticSessions,e.pendingSessions,e.sessions]),r=o.useMemo(()=>new Set(Object.keys(e.pendingSessions)),[e.pendingSessions]),i=o.useMemo(()=>n.find(b=>b.sessionId===e.activeSessionId)??null,[e.activeSessionId,n]),a=Object.values(e.pendingApprovals)[0]??null,c=Object.values(e.pendingQuestions)[0]??null,l=o.useMemo(()=>wh(n,{search:e.search,hideArchived:e.hideArchived,agentFilter:e.sessionAgentFilter}),[n,e.hideArchived,e.search,e.sessionAgentFilter]),u=o.useMemo(()=>new Set([...Object.keys(e.pendingApprovals),...Object.keys(e.pendingQuestions)]),[e.pendingApprovals,e.pendingQuestions]),h=l.filter(b=>e.respondingSessionIds.has(b.sessionId)).map(b=>b.sessionId),d=new Set(h),f=t.current.filter(b=>d.has(b));for(const b of h)f.includes(b)||f.push(b);t.current=f;const x=o.useMemo(()=>tc(l,{needsAttentionSessionIds:u,respondingSessionIds:e.respondingSessionIds,runningSessionOrder:f,separatePinnedGroup:e.separatePinnedGroup,showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup}),[u,e.respondingSessionIds,e.separatePinnedGroup,e.showNeedsAttentionGroup,e.showRunningGroup,l,f]);return{activeApproval:a,activeQuestion:c,activeSession:i,displaySessions:n,groupedSessions:x,pendingSessionIds:r,visibleSessions:l}}const kh=new Set(["attachmentCount","domNodes","durationMs","errorKind","failureKind","longTaskCount","maxLongTaskMs","online","phase","visibilityState"]);function jh(e){const t={};for(const[n,r]of Object.entries(e))kh.has(n)&&(typeof r=="string"?t[n]=r.slice(0,48):typeof r=="number"&&Number.isFinite(r)?t[n]=Math.round(r):typeof r=="boolean"&&(t[n]=r));return t}function Tr(e){return e instanceof TypeError?"TypeError":e instanceof RangeError?"RangeError":e instanceof SyntaxError?"SyntaxError":e instanceof Error?"Error":typeof e=="string"?"string":typeof e}function Ch(e){o.useEffect(()=>{const t=performance.now(),n=(h,d,f="info")=>e(h,jh(d),f),r=h=>{n("web.telemetry.runtime_error",{errorKind:Tr(h.error)},"error")},i=h=>{n("web.telemetry.unhandled_rejection",{errorKind:Tr(h.reason)},"error")},a=window.setTimeout(()=>{n("web.telemetry.workspace_ready",{durationMs:performance.now()-t,domNodes:document.getElementsByTagName("*").length,online:navigator.onLine,visibilityState:document.visibilityState})},1500);let c=0,l=0,u=null;return typeof PerformanceObserver<"u"&&PerformanceObserver.supportedEntryTypes.includes("longtask")&&(u=new PerformanceObserver(h=>{for(const d of h.getEntries())c+=1,l=Math.max(l,d.duration)}),u.observe({entryTypes:["longtask"]})),window.addEventListener("error",r),window.addEventListener("unhandledrejection",i),()=>{window.clearTimeout(a),window.removeEventListener("error",r),window.removeEventListener("unhandledrejection",i),u?.disconnect(),c>0&&n("web.telemetry.long_tasks",{longTaskCount:c,maxLongTaskMs:l},"warn")}},[e])}const Ih=6;function Nh(e,t){return t.has(e.sessionId)||e.runtime?.isResponding===!0||e.runtime?.state==="daemonActive"||e.runtime?.state==="externalRunning"}function Ah(e,t,n,r,i=Ih){if(i<=0)return[];const a=[];for(const c of e){if(a.length>=i)break;!c.sessionId||!Nh(c,n)||ns(t,c.sessionId)||r.has(c.sessionId)||a.push(c)}return a}function Eh(e,t,n=!1){const r=new Set(t.map(i=>i.sessionId));return bs(n?e:e.filter(i=>r.has(i.sessionId)),t)}class Rh{cleared=new Map;live(t,n,r){const i=new Set(r.map(c=>c.clientMessageId)),a=this.cleared.get(n)??new Set;for(const c of t[n]??[])c.clientMessageId&&!i.has(c.clientMessageId)&&a.add(c.clientMessageId);for(const c of i)c&&a.delete(c);return this.cleared.set(n,a),{...t,[n]:r}}snapshot(t){return Object.fromEntries(Object.entries(t).map(([n,r])=>[n,r.filter(i=>!i.clientMessageId||!this.cleared.get(n)?.has(i.clientMessageId))]))}remap(t,n){const r=this.cleared.get(t);r&&(this.cleared.set(n,new Set([...this.cleared.get(n)??[],...r])),this.cleared.delete(t))}}function Th(){const e=o.useRef(new Rh),[t,n]=o.useState({}),r=o.useCallback(c=>{n(l=>e.current.snapshot(typeof c=="function"?c(l):c))},[]),i=o.useCallback((c,l)=>{n(u=>e.current.live(u,c,l))},[]),a=o.useCallback((c,l)=>{e.current.remap(c,l)},[]);return{pendingQueues:t,setPendingQueues:r,setLivePendingQueue:i,remapPendingQueue:a}}function Mh(e,t,n=1/0){return Math.min(Math.max(Math.round(e),t),n)}function Ph(e,t){const n=e.leftCollapsed?0:e.leftPaneWidth,r=e.rightCollapsed?0:e.rightPaneWidth,i=n+r,a=i>t?Math.max(0,t)/i:1;return{leftPaneWidth:e.leftCollapsed?e.leftPaneWidth:Math.floor(n*a),rightPaneWidth:e.rightCollapsed?e.rightPaneWidth:Math.floor(r*a)}}function _h(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`}}}const Mr=96,Dh=64,Lh=252,$h=234;function Fh(e,t){const[n,r]=o.useState(288),[i,a]=o.useState(297),[c,l]=o.useState(()=>window.innerWidth);o.useEffect(()=>{const d=()=>l(window.innerWidth);return window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)},[]);const u=Ph({leftCollapsed:e,rightCollapsed:t,leftPaneWidth:n,rightPaneWidth:i},c-Mr-Dh),h=o.useCallback(d=>f=>{f.preventDefault();const x=f.clientX,b=d==="left"?u.leftPaneWidth:u.rightPaneWidth,S=f.currentTarget.closest(".workspace")?.querySelector(".chat-pane"),v=b+Math.max(0,(S?.getBoundingClientRect().width??0)-Mr),m=y=>{const g=(y.clientX-x)*(d==="left"?1:-1),j=Mh(b+g,d==="left"?Lh:$h,v);d==="left"?r(j):a(j)},p=()=>{document.body.classList.remove("pane-resizing"),window.removeEventListener("pointermove",m),window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p),window.removeEventListener("blur",p)};document.body.classList.add("pane-resizing"),window.addEventListener("pointermove",m),window.addEventListener("pointerup",p,{once:!0}),window.addEventListener("pointercancel",p,{once:!0}),window.addEventListener("blur",p,{once:!0})},[u.leftPaneWidth,u.rightPaneWidth]);return{...u,beginPaneResize:h}}function Oh(e,t){const[n,r]=o.useState(e);o.useEffect(()=>{const $=()=>{const U=Be();r(Q=>({...Q,theme:U.theme,language:U.language,composer:U.composer}))};return window.addEventListener("vibelet.preferences.changed",$),()=>window.removeEventListener("vibelet.preferences.changed",$)},[]);const[i,a]=o.useState(""),[c,l]=o.useState(e.sessionList.searchHistory),[u,h]=o.useState(e.sessionList.sinceFilter),[d,f]=o.useState(e.sessionList.hideArchived),[x,b]=o.useState(e.sessionList.groupFolders),[S,v]=o.useState(e.sessionList.showNeedsAttentionGroup),[m,p]=o.useState(e.sessionList.showRunningGroup),[y,g]=o.useState(e.sessionList.separatePinnedGroup),[j,w]=o.useState(e.sessionList.collapsedFolders),[k,N]=o.useState(e.sessionList.agentFilter),[D,I]=o.useState(t),[W,K]=o.useState(e.layout.leftSidebarCollapsed),[_,be]=o.useState(e.layout.rightSidebarCollapsed),{leftPaneWidth:Te,rightPaneWidth:X,beginPaneResize:ae}=Fh(W,_),ve=n.sessionList.directoryTags,de=n.sessionList.archiveSyncedDaemonIds,Ne=n.sessionList.archiveSyncCardDismissedDaemonIds,A=n.composer,R=_h({leftCollapsed:W,rightCollapsed:_,leftPaneWidth:Te,rightPaneWidth:X});o.useEffect(()=>{r($=>{const U={...$,sessionList:{...$.sessionList,searchHistory:c,sinceFilter:u,hideArchived:d,groupFolders:x,showNeedsAttentionGroup:S,showRunningGroup:m,separatePinnedGroup:y,collapsedFolders:j,agentFilter:k},layout:{...$.layout,leftSidebarCollapsed:W,rightSidebarCollapsed:_}};return hn(U),U})},[j,x,d,W,_,c,y,k,S,m,u]);const q=o.useCallback(()=>{l($=>zi($,i))},[i]),H=o.useCallback($=>{I($),_i($)},[]),B=o.useCallback($=>{r(U=>{const Q={...U,language:$};return hn(Q),Q})},[]),G=o.useCallback($=>{r(U=>{const Q={...U,theme:$};return hn(Q),Q})},[]),V=o.useCallback($=>{r(U=>{const Q={...U,sessionList:$(U.sessionList)};return hn(Q),Q})},[]),oe=o.useCallback($=>{r(U=>{const Q={...U,composer:$(U.composer)};return hn(Q),Q})},[]);return{webPreferences:n,search:i,setSearch:a,sinceFilter:u,setSinceFilter:h,hideArchived:d,setHideArchived:f,groupFolders:x,setGroupFolders:b,showNeedsAttentionGroup:S,setShowNeedsAttentionGroup:v,showRunningGroup:m,setShowRunningGroup:p,separatePinnedGroup:y,setSeparatePinnedGroup:g,collapsedFolders:j,setCollapsedFolders:w,sessionAgentFilter:k,setSessionAgentFilter:N,directoryTags:ve,archiveSyncedDaemonIds:de,archiveSyncCardDismissedDaemonIds:Ne,composerPreferences:A,savedTargets:D,setSavedTargets:I,leftSidebarCollapsed:W,setLeftSidebarCollapsed:K,rightSidebarCollapsed:_,setRightSidebarCollapsed:be,workspaceClassName:R.workspaceClassName,wideMainClassName:R.wideMainClassName,workspaceStyle:R.style,beginPaneResize:ae,commitSearch:q,saveTargets:H,setLanguagePreference:B,setThemePreference:G,updateSessionListPreferences:V,updateComposerPreferences:oe}}function qh(e){o.useEffect(()=>{const t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>Ui(e,document.documentElement,t.matches);if(n(),e==="system")return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[e])}function Wh(){const e=o.useRef(null),t=o.useRef(async()=>{}),n=o.useRef(null),r=o.useRef(bn()),i=o.useRef(ys()),a=o.useRef(Be()),c=o.useRef(rh()),l=o.useRef(Pu()),u=o.useRef(r.current),h=o.useRef(i.current),d=o.useRef(c.current),f=o.useRef(null),x=o.useRef(null),b=o.useRef(new Set),S=o.useRef(null),v=o.useRef(new Set),m=o.useRef(null),p=o.useRef(0),y=o.useRef(new Set),g=o.useRef({}),j=o.useRef(!1),[w,k]=o.useState("connecting"),[N,D]=o.useState(()=>ps[He(a.current.language)].preparingVibeletWeb),[I,W]=o.useState(null),[K,_]=o.useState(null),[be,Te]=o.useState([]),[X,ae]=o.useState({}),[ve,de]=o.useState({}),[Ne,A]=o.useState(),[R,q]=o.useState({}),[H,B]=o.useState(),[G,V]=o.useState(null),[oe,$]=o.useState(null),[U,Q]=o.useState(()=>new Set),[Ve,xe]=o.useState({}),[Ae,se]=o.useState({}),[we,ue]=o.useState({}),{pendingQueues:ie,setPendingQueues:te,setLivePendingQueue:me,remapPendingQueue:ze}=Th(),[Se,Ee]=o.useState("claude"),[Ze,Je]=o.useState(Qe),[Ye,ke]=o.useState($s),[Me]=o.useState(!1),[Le,Ue]=o.useState(""),[$e,J]=o.useState(""),[Z,z]=o.useState(!1),[he,ge]=o.useState(""),[ne,Fe]=o.useState(c.current),[C,Oe]=o.useState(()=>An(c.current,null)),{webPreferences:qe,setRightSidebarCollapsed:We,search:ye,setSearch:Nt,sinceFilter:mt,setSinceFilter:pt,hideArchived:gt,setHideArchived:At,groupFolders:it,setGroupFolders:kt,showNeedsAttentionGroup:yt,setShowNeedsAttentionGroup:Pe,showRunningGroup:jt,setShowRunningGroup:Et,separatePinnedGroup:Ke,setSeparatePinnedGroup:bt,collapsedFolders:at,setCollapsedFolders:vt,sessionAgentFilter:ot,setSessionAgentFilter:ct,directoryTags:lt,archiveSyncedDaemonIds:T,archiveSyncCardDismissedDaemonIds:F,composerPreferences:ce,savedTargets:Ce,setSavedTargets:Xe,leftSidebarCollapsed:Re,setLeftSidebarCollapsed:nt,rightSidebarCollapsed:pe,workspaceClassName:xt,wideMainClassName:st,workspaceStyle:_e,beginPaneResize:rt,commitSearch:Lt,saveTargets:Wt,setLanguagePreference:Rt,setThemePreference:Ht,updateSessionListPreferences:wt,updateComposerPreferences:dt}=Oh(a.current,l.current),ut=He(qe.language),Tt=ps[ut],[Bt,$t]=o.useState(!1),[zt,Ft]=o.useState("session"),[Ot,Mt]=o.useState(!1);qh(qe.theme);const Ut=o.useCallback(Ln=>{Ft(Ln),We(!1)},[We]),[Gt,M]=o.useState({}),[P,O]=o.useState({}),[Y,je]=o.useState([]),[ht,Pt]=o.useState({statusText:"",loading:!1,action:null}),[en,tn]=o.useState(Js),[cn,Mn]=o.useState(i.current),[Pn,_n]=o.useState(r.current),[ln,Dn]=o.useState(null),[dn,un]=o.useState(null);return{clientRef:e,connectWithPairingRef:t,activeSessionIdRef:n,initialNotificationPermissionRef:r,initialNotificationSettingsRef:i,initialPreferencesRef:a,initialComposerDraftsRef:c,initialSavedTargetsRef:l,notificationPermissionRef:u,notificationSettingsRef:h,composerDraftsRef:d,lastHistorySessionIdRef:f,historyCacheDaemonIdRef:x,historyPrefetchingSessionIdsRef:b,pairingRef:S,notifiedEventsRef:v,reconnectTimerRef:m,connectionAttemptIdRef:p,respondingSessionsRef:y,turnNotificationCountsRef:g,intentionalDisconnectRef:j,phase:w,setPhase:k,statusText:N,setStatusText:D,errorText:I,setErrorText:W,pairing:K,setPairing:_,sessions:be,setSessions:Te,pendingSessions:X,setPendingSessions:ae,optimisticSessions:ve,setOptimisticSessions:de,nextCursor:Ne,setNextCursor:A,folderCounts:R,setFolderCounts:q,inventoryVersion:H,setInventoryVersion:B,activeSessionId:G,setActiveSessionId:V,diffSessionId:oe,setDiffSessionId:$,respondingSessions:U,setRespondingSessions:Q,pendingApprovals:Ve,setPendingApprovals:xe,pendingQuestions:Ae,setPendingQuestions:se,questionAnswers:we,setQuestionAnswers:ue,pendingQueues:ie,setPendingQueues:te,setLivePendingQueue:me,remapPendingQueue:ze,agent:Se,setAgent:Ee,cwd:Ze,setCwd:Je,approvalMode:Ye,setApprovalMode:ke,continueSession:Me,model:Le,setModel:Ue,effort:$e,setEffort:J,fastMode:Z,setFastMode:z,renameTitle:he,setRenameTitle:ge,composerDrafts:ne,setComposerDrafts:Fe,draft:C,setDraft:Oe,webPreferences:qe,search:ye,setSearch:Nt,sinceFilter:mt,setSinceFilter:pt,hideArchived:gt,setHideArchived:At,groupFolders:it,setGroupFolders:kt,showNeedsAttentionGroup:yt,setShowNeedsAttentionGroup:Pe,showRunningGroup:jt,setShowRunningGroup:Et,separatePinnedGroup:Ke,setSeparatePinnedGroup:bt,collapsedFolders:at,setCollapsedFolders:vt,sessionAgentFilter:ot,setSessionAgentFilter:ct,directoryTags:lt,archiveSyncedDaemonIds:T,archiveSyncCardDismissedDaemonIds:F,composerPreferences:ce,savedTargets:Ce,setSavedTargets:Xe,leftSidebarCollapsed:Re,setLeftSidebarCollapsed:nt,rightSidebarCollapsed:pe,setRightSidebarCollapsed:We,workspaceClassName:xt,wideMainClassName:st,workspaceStyle:_e,beginPaneResize:rt,commitSearch:Lt,saveTargets:Wt,setLanguagePreference:Rt,setThemePreference:Ht,updateSessionListPreferences:wt,updateComposerPreferences:dt,language:ut,t:Tt,busy:Bt,setBusy:$t,controlTab:zt,setControlTab:Ft,detailsOpen:Ot,setDetailsOpen:Mt,setControlTabAndOpen:Ut,modelOptions:Gt,setModelOptions:M,usageLimits:P,setUsageLimits:O,skills:Y,setSkills:je,admin:ht,setAdmin:Pt,daemonMetadata:en,setDaemonMetadata:tn,notificationSettings:cn,setNotificationSettings:Mn,notificationPermission:Pn,setNotificationPermission:_n,archiveSyncBusy:ln,setArchiveSyncBusy:Dn,archiveSyncStatus:dn,setArchiveSyncStatus:un}}function Hh(){const e=Wh(),t=vh(e),{clientRef:n,activeSessionIdRef:r,notificationPermissionRef:i,notificationSettingsRef:a,composerDraftsRef:c,lastHistorySessionIdRef:l,historyPrefetchingSessionIdsRef:u,pairingRef:h,reconnectTimerRef:d,respondingSessionsRef:f,phase:x,setStatusText:b,setErrorText:S,pairing:v,setSessions:m,setOptimisticSessions:p,setNextCursor:y,setFolderCounts:g,setInventoryVersion:j,activeSessionId:w,setActiveSessionId:k,respondingSessions:N,setRespondingSessions:D,pendingApprovals:I,setPendingApprovals:W,pendingQuestions:K,setPendingQuestions:_,setQuestionAnswers:be,pendingQueues:Te,setPendingQueues:X,agent:ae,setAgent:ve,cwd:de,setCwd:Ne,setApprovalMode:A,composerDrafts:R,setComposerDrafts:q,search:H,sinceFilter:B,hideArchived:G,sessionAgentFilter:V,setRightSidebarCollapsed:oe,t:$,controlTab:U,setControlTab:Q,setControlTabAndOpen:Ve,modelOptions:xe,setModelOptions:Ae,usageLimits:se,setUsageLimits:we,setSkills:ue,setDaemonMetadata:ie,notificationSettings:te,setNotificationSettings:me,notificationPermission:ze,setNotificationPermission:Se,sessions:Ee,pendingSessions:Ze,optimisticSessions:Je,setDraft:Ye,setBusy:ke}=e,{remoteFile:Me,attachments:Le,setAttachments:Ue,uploadBusy:$e,directory:J,setDirectory:Z,newDirName:z,setNewDirName:he,setRemoteFile:ge,remoteFileConflict:ne,uploadFiles:Fe,openRemoteFile:C,saveRemoteFile:Oe,downloadRemoteFile:qe,listDirectory:We,listSessionDirectories:ye,listFileTreeDirectory:Nt,createDirectory:mt,createSessionDirectory:pt}=gh({clientRef:n,pairing:v,cwd:de,phase:x,controlTab:U,setControlTab:Ve,setBusy:ke,setErrorText:S,t:$}),gt=Object.keys(I).length+Object.keys(K).length,At=w?Te[w]??[]:[],it=xe[ae]??[],kt=se[ae],{activeSession:yt,activeApproval:Pe,activeQuestion:jt,displaySessions:Et,groupedSessions:Ke,pendingSessionIds:bt,visibleSessions:at}=Sh({activeSessionId:w,hideArchived:G,optimisticSessions:Je,pendingApprovals:I,pendingQuestions:K,pendingSessions:Ze,respondingSessionIds:N,search:H,separatePinnedGroup:t.separatePinnedGroup,sessionAgentFilter:V,sessions:Ee,showNeedsAttentionGroup:t.showNeedsAttentionGroup,showRunningGroup:t.showRunningGroup}),{historyCacheRef:vt,historyPageStartRef:ot,hydrateVisibleHistory:ct,messagesSessionIdRef:lt,remapCachedHistory:T,appendCachedDelta:F,appendCachedHistory:ce,appendInfoMessage:Ce,clearHistoryLoading:Xe,ensureCachedHistoryEntry:Re,historyLoading:nt,messages:pe,mergeCachedHistoryPage:xt,removeCachedHistory:st,renderCachedHistory:_e,replaceCachedHistory:rt,requestHistory:Lt,setMessages:Wt}=bh({activeSessionIdRef:r,clientRef:n,historyTimeoutMessage:$.historyRequestTimedOut,setPendingQueues:X,setErrorText:S});Jt(r,w),Jt(h,v),Jt(f,N),Jt(a,te),Jt(i,ze),Jt(c,R);const{updateNewSessionDraft:Rt,updateDraft:Ht}=mh({activeSessionIdRef:r,composerDraftsRef:c,setComposerDrafts:q,setDraft:Ye});o.useEffect(()=>{Gi();const M=Vi();M&&(Rt(M),Q("session"),Ki())},[Rt]),o.useEffect(()=>{const M=()=>{me(ys()),Se(bn())};return window.addEventListener("vibelet.notifications.changed",M),()=>window.removeEventListener("vibelet.notifications.changed",M)},[]),o.useEffect(()=>{U==="admin"&&Se(bn())},[U]),o.useEffect(()=>()=>{d.current&&window.clearTimeout(d.current),Me?.objectUrl&&URL.revokeObjectURL(Me.objectUrl)},[Me?.objectUrl]);const wt=o.useCallback((M,P=!1)=>{m(O=>Eh(O,M.sessions,P)),p(O=>{const Y=new Set(M.sessions.map(ht=>ht.sessionId)),je=Object.fromEntries(Object.entries(O).filter(([ht])=>!Y.has(ht)));return Object.keys(je).length===Object.keys(O).length?O:je}),y(M.nextCursor),j(M.inventoryVersion),M.folderCounts&&g(M.folderCounts),P||Gu(h.current?.daemonId,M),b(M.inventoryBackfillInFlight?$.connectedIndexing:$.connected)},[$.connected,$.connectedIndexing]),dt=yh({clientRef:n,setSessions:m}),ut=o.useCallback((M,P=f.current)=>{const O=n.current;if(!O?.isConnected||M.length===0)return;const Y=Ah(M,vt.current,P,u.current);for(const je of Y)u.current.add(je.sessionId),O.request({action:"session.history",id:O.makeId("history_prefetch"),sessionId:je.sessionId,agent:je.agent},{timeoutMessage:$.historyPrefetchTimedOut,timeoutMs:Ts}).catch(()=>{}).finally(()=>{u.current.delete(je.sessionId)})},[$.historyPrefetchTimedOut]),Tt=o.useCallback(M=>{const P=bc(M,{currentActiveSessionId:r.current,currentCwd:de});wt(P.page,!1),y(P.page.nextCursor),j(P.page.inventoryVersion),P.messages&&P.activeSessionId&&ct(P.activeSessionId,P.messages),k(P.activeSessionId),P.activeAgent&&ve(P.activeAgent),P.activeCwd&&Ne(P.activeCwd),P.activeApprovalMode&&A(P.activeApprovalMode),P.questionAnswers&&be(P.questionAnswers),f.current=new Set(P.respondingSessionIds),D(f.current),W(P.pendingApprovals),_(P.pendingQuestions),X(P.pendingQueues),dt(M.sessions),ut(M.sessions,new Set(P.respondingSessionIds))},[de,dt,ct,ut,wt]),Bt=o.useCallback(async()=>{const M=n.current;if(!M?.isConnected)return;const P=await M.request({action:"reconnect.snapshot",id:M.makeId("snapshot"),activeSessionId:r.current??void 0,activeAgent:yt?.agent??ae,agent:V==="all"?void 0:V,search:H.trim()||void 0,sinceMs:nr(B),hideArchived:G,skipGitMetadata:!0});Tt(P.snapshot)},[yt?.agent,ae,Tt,G,H,V,B]),$t=o.useRef(Ee.length);Jt($t,Ee.length);const zt=o.useCallback(async M=>{const P=n.current;if(!P?.isConnected)return;const O=await P.request({action:"sessions.list",id:P.makeId(M?.append?"sessions_more":"sessions"),limit:M?.preserveLoaded?Math.max(tr,$t.current):tr,cursor:M?.cursor,agent:V==="all"?void 0:V,search:H.trim()||void 0,sinceMs:nr(B),hideArchived:G,skipGitMetadata:!0,force:M?.force}),Y=ni(O);wt(Y,M?.append),k(je=>je??Y.sessions[0]?.sessionId??null),dt(Y.sessions),ut(Y.sessions)},[G,dt,ut,H,V,wt,B]),Ft=o.useCallback(async(M,P)=>{const O=n.current;if(O?.isConnected)try{const[Y,je,ht]=await Promise.all([O.request({action:"models.list",id:O.makeId("models"),agent:M}),O.request({action:"usage.limits.fetch",id:O.makeId("usage"),agent:M}),O.request({action:"skills.list",id:O.makeId("skills"),cwd:P||void 0})]);Ae(Pt=>({...Pt,[M]:Y.options??[]})),we(Pt=>({...Pt,[M]:je})),ue(Array.isArray(ht.skills)?ht.skills:[])}catch(Y){S(Y instanceof Error?Y.message:String(Y))}},[]),Ot=o.useCallback((M,P,O="info")=>{const Y=n.current;Y?.isConnected&&Y.request({action:"log.report",id:Y.makeId("log"),entries:[{level:O,event:M,data:P,ts:new Date().toISOString()}]}).catch(()=>{})},[]);Ch(Ot);const Mt=o.useCallback(async(M=h.current)=>{if(!M){ie(Js);return}ie(P=>({...P,loading:!0,error:null}));try{const P=await fetch(fu(M,window.location,{sameOrigin:!1}),{cache:"no-store"});if(!P.ok)throw new Error(`HTTP ${P.status}`);const O=mu(await P.json().catch(()=>null));ie({...O,loading:!1,error:null})}catch{ie(P=>({...P,loading:!1,error:$.connectorVersionFailed}))}},[$.connectorVersionFailed]);o.useEffect(()=>{const M=()=>{me(ys()),Se(bn())};return window.addEventListener("vibelet.notifications.changed",M),()=>window.removeEventListener("vibelet.notifications.changed",M)},[]),o.useEffect(()=>{U==="admin"&&x==="connected"&&Mt()},[U,x,Mt]);const Ut=o.useCallback(M=>{me(P=>{const O={...P,...M};return a.current=O,Uo(O),O})},[]),Gt=o.useCallback((M,P)=>{!M||!P||M===P||(k(O=>O===M?P:O),l.current===M&&(l.current=P),lt.current===M&&(lt.current=P),T(M,P),f.current=sr(f.current,M,P),D(O=>sr(O,M,P)),W(O=>ls(O,M,P)),_(O=>ls(O,M,P)),e.remapPendingQueue(M,P),X(O=>ls(O,M,P)),p(O=>{const Y=O[M];if(!Y)return O;const je={...O};return delete je[M],je[P]={...Y,sessionId:P},je}),q(O=>{const Y=ih(O,M,P);return Y!==O&&(c.current=Y,In(Y)),Y}))},[]);return{...e,...t,attachments:Le,setAttachments:Ue,uploadBusy:$e,directory:J,setDirectory:Z,newDirName:z,setNewDirName:he,remoteFile:Me,setRemoteFile:ge,remoteFileConflict:ne,uploadFiles:Fe,openRemoteFile:C,saveRemoteFile:Oe,downloadRemoteFile:qe,listDirectory:We,listSessionDirectories:ye,listFileTreeDirectory:Nt,createDirectory:mt,createSessionDirectory:pt,pendingActionsCount:gt,activeQueue:At,activeModelOptions:it,activeUsage:kt,activeApproval:Pe,activeQuestion:jt,activeSession:yt,displaySessions:Et,groupedSessions:Ke,pendingSessionIds:bt,visibleSessions:at,appendCachedDelta:F,appendCachedHistory:ce,appendInfoMessage:Ce,clearHistoryLoading:Xe,ensureCachedHistoryEntry:Re,historyCacheRef:vt,historyLoading:nt,historyPageStartRef:ot,hydrateVisibleHistory:ct,messages:pe,messagesSessionIdRef:lt,mergeCachedHistoryPage:xt,remapCachedHistory:T,removeCachedHistory:st,renderCachedHistory:_e,replaceCachedHistory:rt,requestHistory:Lt,setMessages:Wt,updateDraft:Ht,updateNewSessionDraft:Rt,setSessionsFromPage:wt,hydrateGitMetadata:dt,prefetchActiveHistories:ut,applyReconnectSnapshot:Tt,requestReconnectSnapshot:Bt,requestSessions:zt,fetchAgentResources:Ft,reportLog:Ot,refreshDaemonMetadata:Mt,updateNotificationSettings:Ut,remapLocalSessionState:Gt}}function Bh(){const e=Hh(),t=o.useRef(void 0),n=uh(e),{initialSavedTargetsRef:r,composerDraftsRef:i,lastHistorySessionIdRef:a,respondingSessionsRef:c,phase:l,setErrorText:u,pairing:h,setSessions:d,pendingSessions:f,activeSessionId:x,setActiveSessionId:b,setRespondingSessions:S,setPendingApprovals:v,setPendingQuestions:m,setPendingQueues:p,setLivePendingQueue:y,agent:g,setAgent:j,cwd:w,setCwd:k,setApprovalMode:N,setModel:D,setEffort:I,setFastMode:W,setRenameTitle:K,setDraft:_,archiveSyncedDaemonIds:be,archiveSyncCardDismissedDaemonIds:Te,setControlTabAndOpen:X,daemonMetadata:ae,notificationPermission:ve,setDirectory:de,displaySessions:Ne,appendInfoMessage:A,clearHistoryLoading:R,messagesSessionIdRef:q,renderCachedHistory:H,replaceCachedHistory:B,requestHistory:G,setMessages:V,requestSessions:oe,remapLocalSessionState:$,attachments:U,setAttachments:Q,listDirectory:Ve,activeApproval:xe,activeQuestion:Ae,activeSession:se,appendCachedDelta:we,appendCachedHistory:ue,ensureCachedHistoryEntry:ie,historyCacheRef:te,messages:me,mergeCachedHistoryPage:ze,removeCachedHistory:Se,updateDraft:Ee,setSessionsFromPage:Ze,requestReconnectSnapshot:Je,fetchAgentResources:Ye,reportLog:ke,refreshDaemonMetadata:Me,updateNotificationSettings:Le,clientRef:Ue,connectWithPairingRef:$e,activeSessionIdRef:J,notificationPermissionRef:Z,notificationSettingsRef:z,historyCacheDaemonIdRef:he,pairingRef:ge,notifiedEventsRef:ne,reconnectTimerRef:Fe,connectionAttemptIdRef:C,turnNotificationCountsRef:Oe,intentionalDisconnectRef:qe,setPhase:We,setStatusText:ye,setPairing:Nt,setPendingSessions:mt,setOptimisticSessions:pt,questionAnswers:gt,setQuestionAnswers:At,approvalMode:it,continueSession:kt,model:yt,effort:Pe,fastMode:jt,renameTitle:Et,setComposerDrafts:Ke,draft:bt,search:at,sinceFilter:vt,savedTargets:ot,setSavedTargets:ct,saveTargets:lt,updateSessionListPreferences:T,t:F,busy:ce,setBusy:Ce,setDetailsOpen:Xe,setAdmin:Re,setDaemonMetadata:nt,setNotificationPermission:pe,archiveSyncBusy:xt,setArchiveSyncBusy:st,setArchiveSyncStatus:_e}=e,rt=o.useCallback(async(ee,Kt,ft)=>{const E=typeof ft.sessionId=="string"?ft.sessionId:ee,fe=typeof ft.oldSessionId=="string"?ft.oldSessionId:ee;fe&&E&&fe!==E&&$(fe,E),Kt.name==="clear"?(B(E,[]),p(et=>{const le={...et};return delete le[E],delete le[fe],le}),v(et=>{const le={...et};return delete le[E],delete le[fe],le}),m(et=>{const le={...et};return delete le[E],delete le[fe],le}),b(E)):Kt.name==="new"?(b(E),q.current=E,H(E)):Kt.name==="exit"?(d(et=>et.map(le=>le.sessionId===E?{...le,archived:!0}:le)),b(null),q.current=null,a.current=null,V([])):Kt.name==="goal"&&"goal"in ft&&A(E,Bo(ft.goal)),ft.turnStarted&&!ft.queued&&(c.current=new Set(c.current).add(E),S(et=>new Set(et).add(E))),await oe({force:!0})},[A,$,H,B,oe]),Lt=sh({notificationSettingsRef:z,notifiedEventsRef:ne,notificationPermissionRef:Z,activeSessionIdRef:J,respondingSessionsRef:c,turnNotificationCountsRef:Oe,t:F,setActiveSessionId:b,setErrorText:u,setPendingQueues:p,setLivePendingQueue:y,setPendingApprovals:v,setPendingQuestions:m,setQuestionAnswers:At,setRespondingSessions:S,setSessions:d,remapLocalSessionState:$,requestSessions:oe,clearHistoryLoading:R,replaceCachedHistory:B,mergeCachedHistoryPage:ze,appendCachedHistory:ue,appendCachedDelta:we});Qu({clientRef:Ue,connectWithPairingRef:$e,pairingRef:ge,reconnectTimerRef:Fe,connectionAttemptIdRef:C,intentionalDisconnectRef:qe,historyCacheRef:te,historyCacheDaemonIdRef:he,messagesSessionIdRef:q,lastHistorySessionIdRef:a,rememberedTarget:r.current[0]??null,agent:g,cwd:w,phase:l,search:at,sinceFilter:vt,t:F,handleServerMessage:Lt,setPhase:We,setStatusText:ye,setErrorText:u,setMessages:V,setPairing:Nt,setSavedTargets:ct,setSessionsFromPage:Ze,refreshDaemonMetadata:Me,requestReconnectSnapshot:Je,fetchAgentResources:Ye,reportLog:ke,requestSessions:oe}),o.useEffect(()=>{const ee=Ne.find(fe=>fe.sessionId===x);if(!ee){a.current=null,q.current=null,R(),V([]),_(An(i.current,null));return}j(ee.agent),k(ee.cwd||Qe),D(ee.model??""),I(ee.effort??""),W(ee.fastMode??!1),N(ee.approvalMode??$s),K(ee.customTitle??ee.title??""),_(An(i.current,ee.sessionId));const Kt=t.current,ft=`${h?.daemonId}:${ee.sessionId}`;t.current=ft;const E=Yt();if(de(fe=>hh(fe,Kt,ft,ee.cwd||Qe,E.folder||E.cwd)),f[ee.sessionId]){a.current=ee.sessionId,R(),q.current!==ee.sessionId&&(q.current=ee.sessionId,V([]));return}if(H(ee.sessionId)){const fe=a.current!==ee.sessionId;a.current=ee.sessionId,R(ee.sessionId),fe&&G(ee);return}a.current!==ee.sessionId&&(a.current=ee.sessionId,q.current!==ee.sessionId&&(q.current=ee.sessionId,V([])),G(ee))},[x,R,Ne,f,H,G]);const{stagePendingSession:Wt,failedSend:Rt,retryFailedSend:Ht,sendDraft:wt}=lh({clientRef:Ue,activeSessionIdRef:J,composerDraftsRef:i,lastHistorySessionIdRef:a,messagesSessionIdRef:q,respondingSessionsRef:c,agent:g,cwd:w,approvalMode:it,continueSession:kt,model:yt,effort:Pe,fastMode:jt,activeSessionId:x,activeSession:se,pendingSessions:f,draft:bt,busy:ce,attachments:U,t:F,setPendingSessions:mt,setOptimisticSessions:pt,setComposerDrafts:Ke,setCwd:k,setAgent:j,setActiveSessionId:b,setMessages:V,setDraft:_,setErrorText:u,setBusy:Ce,setAttachments:Q,setRespondingSessions:S,clearHistoryLoading:R,reportLog:ke,remapLocalSessionState:$,requestSessions:oe,updateDraft:Ee,appendCachedHistory:ue,ensureCachedHistoryEntry:ie,renderCachedHistory:H,handleSessionCommandResponse:rt,appendInfoMessage:A}),{respondApproval:dt,respondQuestion:ut,cancelQuestion:Tt,setQuestionChoice:Bt,requestActiveAction:$t,interruptActiveSession:zt,retrySessions:Ft,updateApprovalMode:Ot,cancelQueuedTurn:Mt,setSessionPinned:Ut,setSessionArchived:Gt,deleteSession:M,updatePinned:P,updateArchived:O,renameSession:Y}=oh({clientRef:Ue,activeSessionIdRef:J,composerDraftsRef:i,lastHistorySessionIdRef:a,messagesSessionIdRef:q,respondingSessionsRef:c,activeApproval:xe,activeQuestion:Ae,activeSession:se,activeSessionId:x,questionAnswers:gt,pendingSessions:f,phase:l,renameTitle:Et,setBusy:Ce,setErrorText:u,setPendingApprovals:v,setPendingQuestions:m,setQuestionAnswers:At,setPendingQueues:p,setActiveSessionId:b,setMessages:V,setApprovalMode:N,setSessions:d,setPendingSessions:mt,setComposerDrafts:Ke,setDraft:_,setDetailsOpen:Xe,setRespondingSessions:S,setOptimisticSessions:pt,removeCachedHistory:Se,requestSessions:oe}),{runArchiveSync:je,skipArchiveSync:ht,runAdminAction:Pt,exportActiveSession:en,clearPairing:tn,setNotificationsEnabled:cn,connectSavedTarget:Mn,forgetSavedTarget:Pn,openSessionDetails:_n,editFolderTags:ln,browseFolder:Dn,copyResumeCommand:dn}=qu({clientRef:Ue,pairingRef:ge,connectWithPairingRef:$e,notificationPermissionRef:Z,intentionalDisconnectRef:qe,connectionAttemptIdRef:C,historyCacheRef:te,historyCacheDaemonIdRef:he,messagesSessionIdRef:q,lastHistorySessionIdRef:a,displaySessions:Ne,pairing:h,t:F,archiveSyncBusy:xt,daemonMetadata:ae,activeSession:se,messages:me,notificationPermission:ve,savedTargets:ot,setArchiveSyncBusy:st,setArchiveSyncStatus:_e,setSessions:d,setAdmin:Re,setErrorText:u,setNotificationPermission:pe,setStatusText:ye,setMessages:V,setPairing:Nt,setDaemonMetadata:nt,setPhase:We,setActiveSessionId:b,setRenameTitle:K,setDetailsOpen:Xe,setControlTab:X,updateSessionListPreferences:T,requestSessions:oe,refreshDaemonMetadata:Me,updateNotificationSettings:Le,saveTargets:lt,listDirectory:Ve}),un=ve==="denied"||ve==="unsupported",Ln=!!(ae.version&&ae.latestVersion&&Ei(ae.version,ae.latestVersion)),Vt=h?.daemonId,ss=!!(Vt&&be[Vt]),rs=!!(Vt&&Te[Vt]),is=Zu(e);return{...e,queueControls:is,rewindMessage:n,handleSessionCommandResponse:rt,handleServerMessage:Lt,failedSend:Rt,retryFailedSend:Ht,stagePendingSession:Wt,sendDraft:wt,respondApproval:dt,respondQuestion:ut,cancelQuestion:Tt,setQuestionChoice:Bt,requestActiveAction:$t,interruptActiveSession:zt,retrySessions:Ft,updateApprovalMode:Ot,cancelQueuedTurn:Mt,setSessionPinned:Ut,setSessionArchived:Gt,deleteSession:M,updatePinned:P,updateArchived:O,renameSession:Y,runArchiveSync:je,skipArchiveSync:ht,runAdminAction:Pt,exportActiveSession:en,clearPairing:tn,setNotificationsEnabled:cn,connectSavedTarget:Mn,forgetSavedTarget:Pn,openSessionDetails:_n,editFolderTags:ln,browseFolder:Dn,copyResumeCommand:dn,notificationsBlocked:un,hasDaemonUpdate:Ln,activeDaemonId:Vt,archiveSynced:ss,archiveSyncDismissed:rs}}const zh=o.lazy(()=>tt(()=>import("./NewSessionDialog-B0YMv6RR.js"),__vite__mapDeps([20,1,2,12,21]))),Uh=o.lazy(()=>tt(()=>import("./GlobalPendingDialog-BeOMI3dc.js"),__vite__mapDeps([22,1,2])));function Gh(){return s.jsx(Ld,{children:s.jsx(Vh,{})})}function Vh(){const[e,t]=o.useState(!0),[n,r]=o.useState(!1),i=Bh(),[a,c]=o.useState(null);o.useEffect(()=>{const E=()=>c(le=>le??{cwd:i.cwd}),fe=re().subscribeCommand?.(le=>{le==="new-session"&&E()}),et=le=>{re().kind==="browser"&&(le.metaKey||le.ctrlKey)&&!le.altKey&&!le.shiftKey&&le.key.toLowerCase()==="n"&&(le.preventDefault(),E())};return window.addEventListener("keydown",et),()=>{fe?.(),window.removeEventListener("keydown",et)}},[i.cwd]),o.useEffect(()=>{i.controlTab==="browser"&&t(!0)},[i.controlTab]),o.useEffect(()=>{i.controlTab==="terminal"&&r(!0)},[i.controlTab]),o.useEffect(()=>{(i.controlTab==="session"||re().kind==="desktop"&&i.controlTab==="admin")&&i.setControlTab("files");const E=()=>i.setControlTabAndOpen("admin");return window.addEventListener("vibelet.browser.settings",E),()=>window.removeEventListener("vibelet.browser.settings",E)},[i.controlTab,i.setControlTab,i.setControlTabAndOpen]),o.useEffect(()=>{i.activeQuestion&&i.setQuestionAnswers(Os(i.activeQuestion))},[i.activeQuestion,i.setQuestionAnswers]);const{clientRef:l,phase:u,statusText:h,errorText:d,pairing:f,sessions:x,nextCursor:b,folderCounts:S,inventoryVersion:v,activeSessionId:m,setActiveSessionId:p,diffSessionId:y,setDiffSessionId:g,respondingSessions:j,questionAnswers:w,agent:k,cwd:N,approvalMode:D,model:I,setModel:W,effort:K,setEffort:_,fastMode:be,setFastMode:Te,renameTitle:X,setRenameTitle:ae,draft:ve,webPreferences:de,search:Ne,setSearch:A,sinceFilter:R,setSinceFilter:q,hideArchived:H,setHideArchived:B,groupFolders:G,setGroupFolders:V,showNeedsAttentionGroup:oe,setShowNeedsAttentionGroup:$,showRunningGroup:U,setShowRunningGroup:Q,separatePinnedGroup:Ve,setSeparatePinnedGroup:xe,collapsedFolders:Ae,setCollapsedFolders:se,sessionAgentFilter:we,setSessionAgentFilter:ue,directoryTags:ie,composerPreferences:te,savedTargets:me,leftSidebarCollapsed:ze,setLeftSidebarCollapsed:Se,rightSidebarCollapsed:Ee,setRightSidebarCollapsed:Ze,workspaceClassName:Je,wideMainClassName:Ye,workspaceStyle:ke,beginPaneResize:Me,commitSearch:Le,saveTargets:Ue,setLanguagePreference:$e,setThemePreference:J,updateComposerPreferences:Z,t:z,busy:he,rewindMessage:ge,controlTab:ne,setControlTab:Fe,detailsOpen:C,setDetailsOpen:Oe,setControlTabAndOpen:qe,skills:We,admin:ye,daemonMetadata:Nt,notificationSettings:mt,notificationPermission:pt,archiveSyncBusy:gt,archiveSyncStatus:At,attachments:it,setAttachments:kt,uploadBusy:yt,directory:Pe,newDirName:jt,setNewDirName:Et,remoteFile:Ke,uploadFiles:bt,openRemoteFile:at,listDirectory:vt,listSessionDirectories:ot,listFileTreeDirectory:ct,createDirectory:lt,createSessionDirectory:T,pendingActionsCount:F,activeQueue:ce,activeModelOptions:Ce,activeUsage:Xe,activeApproval:Re,activeQuestion:nt,activeSession:pe,displaySessions:xt,groupedSessions:st,pendingSessionIds:_e,visibleSessions:rt,historyLoading:Lt,messages:Wt,messagesSessionIdRef:Rt,updateDraft:Ht,requestReconnectSnapshot:wt,requestSessions:dt,fetchAgentResources:ut,failedSend:Tt,retryFailedSend:Bt,stagePendingSession:$t,sendDraft:zt,respondApproval:Ft,respondQuestion:Ot,cancelQuestion:Mt,setQuestionChoice:Ut,requestActiveAction:Gt,interruptActiveSession:M,retrySessions:P,updateApprovalMode:O,cancelQueuedTurn:Y,setSessionPinned:je,setSessionArchived:ht,deleteSession:Pt,updatePinned:en,updateArchived:tn,renameSession:cn,runArchiveSync:Mn,skipArchiveSync:Pn,runAdminAction:_n,exportActiveSession:ln,clearPairing:Dn,setNotificationsEnabled:dn,connectSavedTarget:un,forgetSavedTarget:Ln,openSessionDetails:Vt,editFolderTags:ss,copyResumeCommand:rs,notificationsBlocked:is,hasDaemonUpdate:ee,archiveSynced:Kt,archiveSyncDismissed:ft}=i;return u==="missing-pair"?s.jsxs(s.Fragment,{children:[s.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:z.skipToConversation}),s.jsx(Md,{errorText:d,t:z})]}):s.jsxs("main",{className:Je,id:"vibelet-workspace",style:ke,children:[a&&s.jsx(o.Suspense,{fallback:null,children:s.jsx(zh,{cwd:a.cwd,agent:k,device:f?.daemonId??"disconnected",connected:u==="connected",approvalMode:D,model:I,t:z,onClose:()=>c(null),onCreate:$t,onListDirectories:ot,onCreateDirectory:T})}),s.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:z.skipToConversation}),s.jsx(du,{collapsed:ze,onExpand:()=>Se(E=>!E),onResize:Me("left"),t:z,children:s.jsx(lu,{activeDaemonId:f?.daemonId,activeSessionId:m,busy:he,collapsedFolders:Ae,currentCwd:N,directoryTags:ie,displayName:f?.displayName,savedTargets:me,folderCounts:S,groupFolders:G,groupedSessions:st,hideArchived:H,separatePinnedGroup:Ve,showNeedsAttentionGroup:oe,showRunningGroup:U,inventoryVersion:v,nextCursor:b,phase:u,respondingSessionIds:j,search:Ne,sessionAgentFilter:we,sessionsCount:xt.length,sinceFilter:R,statusText:h,t:z,visibleSessions:rt,onLoadMore:E=>dt({append:!0,cursor:E}),onCopyResumeCommand:rs,onConnectTarget:un,pendingSessionIds:_e,onRequestNewSession:E=>c({cwd:E??N}),onDeleteSession:E=>{Pt(E)},onEditFolderTags:ss,onOpenSessionDetails:Vt,onResetFilters:()=>{ue("all"),q("30d"),B(!1),V(!0),$(!1),Q(!1),xe(!1)},onRenameTarget:(E,fe)=>Ue(Du(me,E,fe)),onSearchChange:A,onSearchCommit:Le,onSelectSession:p,onToggleSessionArchived:E=>{ht(E,!E.archived)},onToggleSessionPinned:E=>{je(E,!E.pinned)},onSessionAgentFilterChange:ue,onSinceFilterChange:q,onToggleFolder:E=>se(fe=>({...fe,[E]:!fe[E]})),onToggleGroupFolders:()=>V(E=>!E),onToggleHideArchived:()=>B(E=>!E),onToggleNeedsAttentionGroup:()=>{i.toggleSessionViewGroup("needsAttention")},onToggleRunningGroup:()=>{i.toggleSessionViewGroup("running")},onToggleSeparatePinnedGroup:()=>{i.toggleSessionViewGroup("pinned")},onToggleCollapse:()=>Se(!0)})}),s.jsxs("section",{className:Ye,"aria-label":z.vibeletWorkspace,id:"vibelet-main-content",tabIndex:-1,children:[s.jsx(Ru,{workspace:i,children:s.jsx(ed,{activeSession:pe,activeSessionId:m,activeModelOptions:Ce,activeQueue:ce,activeUsage:Xe,agent:k,approvalMode:D,attachments:it,busy:he,cwd:N,draft:ve,effort:K,errorText:d,failedSend:Tt,fastMode:be,historyLoading:Lt,messages:Wt,messagesSessionId:Rt.current,model:I,phase:u,quickReplies:te.quickReplies,renameTitle:X,respondingSessionIds:j,sendShortcut:te.sendShortcut,skills:We,uploadBusy:yt,detailsOpen:C,t:z,onApprovalModeChange:E=>{O(E)},onBrowseFiles:()=>{const E=pe?.cwd||N||Qe;qe("files"),vt(E,{updateRoute:!0})},queueControls:i.queueControls,onCancelQueuedTurn:E=>{Y(E)},onClearInterrupt:()=>{Gt("session.clearInterrupt")},onDraftChange:Ht,onDetailsOpenChange:Oe,onEffortChange:_,onExportActiveSession:()=>{ln()},onRewindMessage:E=>{ge(E)},onFastModeChange:Te,onRetryFailedSend:Bt,onModelChange:W,onOpenRemoteFile:(E,fe)=>{at(E,fe,{updateRoute:!0})},onInterrupt:M,onDismissError:()=>i.setErrorText(null),onRetry:P,onRenameSession:()=>{cn()},onRenameTitleChange:ae,onRemoveAttachment:E=>kt(fe=>fe.filter(et=>et.path!==E)),onRefreshSkills:()=>{ut(pe?.agent??k,N)},onSubmit:zt,onToggleArchived:()=>{tn()},onTogglePinned:()=>{en()},onUploadFiles:bt,onViewChanges:g})}),s.jsxs(ju,{collapsed:Ee,t:z,value:ne,showSession:!1,onChange:Fe,onResize:Me("right"),children:[ne==="files"?s.jsx(o.Suspense,{fallback:s.jsx(xr,{t:z}),children:s.jsx(Vd,{busy:he,cwd:N,directory:Pe,onLoadChildren:ct,newDirName:jt,remoteFile:Ke,t:z,onCreateDirectory:()=>{lt()},onListDirectory:E=>{vt(E,{updateRoute:!0})},onNewDirNameChange:Et,onOpenRemoteFile:(E,fe)=>{at(E,fe,{updateRoute:!0})}},`${f?.daemonId}:${N}`)}):null,n?s.jsxs("div",{hidden:ne!=="terminal",className:"terminal-tab-content",children:[s.jsx(Is,{location:"right",kind:"terminal",t:z,cwd:N===Qe?Pe.path:N}),s.jsx(Gn,{location:"right",kind:"terminal"})]}):null,e?s.jsxs("div",{hidden:ne!=="browser",className:"browser-tab-content",children:[s.jsx(Is,{location:"right",kind:"browser",t:z}),s.jsx(Gn,{location:"right",kind:"browser"})]}):null,ne==="admin"?s.jsxs(o.Suspense,{fallback:s.jsx(xr,{t:z}),children:[s.jsx(Kd,{language:de.language,t:z,onLanguageChange:$e}),!re().settingsTarget&&s.jsx(wu,{}),s.jsx(Qd,{t:z,theme:de.theme,onThemeChange:J}),s.jsx(Zd,{notificationsBlocked:is,permission:pt,settings:mt,t:z,onToggleEnabled:dn}),!re().settingsTarget&&s.jsx(kr,{workspace:i})]}):null]})]}),re().settingsTarget&&s.jsx(kr,{workspace:i,portalOnly:!0}),s.jsx("div",{className:"workspace-header-actions",children:s.jsx(Do,{activeSession:pe,busy:he,controlsOpen:!Ee,t:z,onOpenControls:()=>{Ee&&F===0&&ne==="session"&&Fe("files"),Ze(E=>!E)},onRefreshSessions:()=>{dt({force:!0})},onRestoreSnapshot:()=>{wt()},onToggleArchived:()=>{tn()},onTogglePinned:()=>{en()},onViewChanges:g})}),F>0&&s.jsx(o.Suspense,{fallback:null,children:s.jsx(Uh,{activeApproval:Re,activeQuestion:nt,pendingCount:F,requestKey:JSON.stringify([...Object.values(i.pendingApprovals),...Object.values(i.pendingQuestions)].map(E=>JSON.stringify([E.sessionId,E.requestId])).sort()),sessions:x,busy:he,errorText:d,questionAnswers:w,t:z,onCancelQuestion:()=>{Mt()},onQuestionChoice:Ut,onRespondApproval:E=>{Ft(E)},onRespondQuestion:()=>{Ot()}})}),s.jsx(_d,{}),s.jsx(Hd,{onOpenRight:qe,client:u==="connected"?l.current:null,daemonId:f?.daemonId,deviceName:f?.displayName??"",controlTab:ne,rightVisible:!Ee,t:z}),s.jsx(Yd,{activeSession:pe,client:l.current,close:()=>g(null),id:y,sessions:x,t:z})]})}const tf=Object.freeze(Object.defineProperty({__proto__:null,App:Gh},Symbol.toStringTag,{value:"Module"}));export{sa as A,Yn as B,Dt as C,tf as D,Td as F,Fr as G,za as I,Va as K,Rn as L,Wl as M,so as P,xn as R,Ps as S,Kr as T,De as X,on as a,zd as b,$r as c,oc as d,zn as e,_t as f,gn as g,Gs as h,Qh as i,uc as j,ef as k,Bd as l,oa as m,sn as n,Pa as o,Yh as p,_r as q,jn as r,Dr as s,St as t,ql as u,Xh as v,$c as w,Zh as x,Jh as y,Jn as z};
|