vibelet 1.2.227 → 1.2.230
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/inventory-scan-worker.cjs +1 -1
- package/dist/remoteDirect/vibelet-remote-direct-darwin-amd64 +0 -0
- package/dist/remoteDirect/vibelet-remote-direct-darwin-arm64 +0 -0
- package/dist/remoteDirect/vibelet-remote-direct-linux-amd64 +0 -0
- package/dist/remoteDirect/vibelet-remote-direct-linux-arm64 +0 -0
- package/dist/remoteDirect/vibelet-remote-direct-win32-amd64.exe +0 -0
- package/dist/remoteDirect/vibelet-remote-direct-win32-arm64.exe +0 -0
- package/dist/runtime-version.cjs +1 -1
- package/dist/web/assets/App-94_jdzMk.css +1 -0
- package/dist/web/assets/App-CapuoJH2.js +18 -0
- package/dist/web/assets/BrowserControlPanel-BTBKDi0n.js +1 -0
- package/dist/web/assets/{ChipGroup-FQF2g0Fr.js → ChipGroup-ImS6VTKx.js} +1 -1
- package/dist/web/assets/{DiffDrawer-CHjkoGPE.js → DiffDrawer-sMBIj4bW.js} +2 -2
- package/dist/web/assets/{FilesControlPanel-A7LFhjRm.js → FilesControlPanel-4hHS85Mr.js} +1 -1
- package/dist/web/assets/GlobalPendingDialog-BCLMQc_r.js +1 -0
- package/dist/web/assets/ImageViewer-BvBKQ6wE.js +1 -0
- package/dist/web/assets/LanguageSettingsPanel-DTDvB4l2.js +1 -0
- package/dist/web/assets/NewSessionDialog-LttGZHY7.js +1 -0
- package/dist/web/assets/NewSessionDialog-cuN6a01X.css +1 -0
- package/dist/web/assets/{NotificationSettingsPanel-B_k_PfhC.js → NotificationSettingsPanel-BS01O3sC.js} +1 -1
- package/dist/web/assets/TerminalControlPanel-B7S_ebVy.js +13 -0
- package/dist/web/assets/{ThemeSettingsPanel-DNDIWk0L.js → ThemeSettingsPanel-DVaJ6nGu.js} +1 -1
- package/dist/web/assets/{arrow-right-Boi1uHFr.js → arrow-right-ORILUMdJ.js} +1 -1
- package/dist/web/assets/{collectMessageImages-BROUPbis.js → collectMessageImages-lfAaZW_Y.js} +1 -1
- package/dist/web/assets/{file-editor-FileCodeEditor-CTEWh6kV.js → file-editor-FileCodeEditor-ZAqN9Q2f.js} +3 -3
- package/dist/web/assets/{file-editor-MarkdownLivePreview-Blr8OOKh.js → file-editor-MarkdownLivePreview-DXTFwUnj.js} +1 -1
- package/dist/web/assets/{file-editor-index-iFiQtQEr.js → file-editor-index-BBHGMD89.js} +1 -1
- package/dist/web/assets/{file-editor-index-CxU5Gq1E.js → file-editor-index-BC0Bqs8t.js} +1 -1
- package/dist/web/assets/{file-editor-index-DvdSLdIk.js → file-editor-index-Bo2dEHVF.js} +1 -1
- package/dist/web/assets/{file-editor-index-Cj9yLeGr.js → file-editor-index-Byun61j6.js} +1 -1
- package/dist/web/assets/{file-editor-index-Dv8iMJMj.js → file-editor-index-C4S-qKVH.js} +1 -1
- package/dist/web/assets/{file-editor-index-Ckq0jexT.js → file-editor-index-DKQvp2Qx.js} +1 -1
- package/dist/web/assets/{file-editor-index-C1T947NK.js → file-editor-index-Dc2gxJQY.js} +1 -1
- package/dist/web/assets/{file-editor-index-DvenUGpC.js → file-editor-index-Dj3dV82Z.js} +1 -1
- package/dist/web/assets/{folder-plus-tHXFtdSw.js → folder-plus-DHw5YJHP.js} +1 -1
- package/dist/web/assets/{highlighted-body-TPN3WLV5-D5c7I9mI.js → highlighted-body-TPN3WLV5-DDb5MlJt.js} +1 -1
- package/dist/web/assets/index-Be6TVbvo.css +1 -0
- package/dist/web/assets/index-ConcKf33.js +71 -0
- package/dist/web/assets/{mermaid-O7DHMXV3-BIyESbw5.js → mermaid-O7DHMXV3-D-5FgaAx.js} +3 -3
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/web/assets/App-DfyOZYmt.js +0 -12
- package/dist/web/assets/App-t0H-03RW.css +0 -1
- package/dist/web/assets/BrowserControlPanel-dQOp1WlN.js +0 -1
- package/dist/web/assets/GlobalPendingDialog-BeOMI3dc.js +0 -1
- package/dist/web/assets/ImageViewer-BQ9YKQDY.js +0 -1
- package/dist/web/assets/LanguageSettingsPanel-Benilh-Y.js +0 -1
- package/dist/web/assets/NewSessionDialog-B0YMv6RR.js +0 -1
- package/dist/web/assets/NewSessionDialog-CxPwD87T.css +0 -1
- package/dist/web/assets/TerminalControlPanel-DCmHOa9Y.js +0 -13
- package/dist/web/assets/index-CoCv7_xG.css +0 -1
- package/dist/web/assets/index-P4_gSQhN.js +0 -71
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid-O7DHMXV3-D-5FgaAx.js","assets/index-ConcKf33.js","assets/index-Be6TVbvo.css","assets/collectMessageImages-lfAaZW_Y.js","assets/mermaid-O7DHMXV3-tkqeC_Xz.css","assets/ImageViewer-BvBKQ6wE.js","assets/arrow-right-ORILUMdJ.js","assets/ImageViewer-L8SQkFy1.css","assets/BrowserControlPanel-BTBKDi0n.js","assets/TerminalControlPanel-B7S_ebVy.js","assets/DiffDrawer-sMBIj4bW.js","assets/FilesControlPanel-4hHS85Mr.js","assets/folder-plus-DHw5YJHP.js","assets/FilesControlPanel-DsKJrFYk.css","assets/LanguageSettingsPanel-DTDvB4l2.js","assets/ChipGroup-ImS6VTKx.js","assets/ThemeSettingsPanel-DVaJ6nGu.js","assets/NotificationSettingsPanel-BS01O3sC.js","assets/file-editor-FileCodeEditor-ZAqN9Q2f.js","assets/FileCodeEditor-yqSvo7VZ.css","assets/NewSessionDialog-LttGZHY7.js","assets/NewSessionDialog-cuN6a01X.css","assets/GlobalPendingDialog-BCLMQc_r.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as L,m as Ze,e as Ye,l as Xe,j as r,r as c,i as dt,k as ee,S as ua,n as ha,t as It,u as Dn,E as Qr,o as js,_ as at,D as ts,p as gs,q as hn,v as Cs,w as In,x as fa,y as ma,z as pa,A as ga,s as wn,B as ya,C as ba,F as va,G as xa,H as wa}from"./index-ConcKf33.js";const Sa=[["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"}]],Zr=L("activity",Sa);const ka=[["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"}]],ja=L("archive-restore",ka);const Ca=[["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"}]],ns=L("archive",Ca);const Ia=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Na=L("arrow-down",Ia);const Ea=[["path",{d:"M3 19V5",key:"rwsyhb"}],["path",{d:"m13 6-6 6 6 6",key:"1yhaz7"}],["path",{d:"M7 12h14",key:"uoisry"}]],Jr=L("arrow-left-to-line",Ea);const Ra=[["path",{d:"M17 12H3",key:"8awo09"}],["path",{d:"m11 18 6-6-6-6",key:"8c2y43"}],["path",{d:"M21 5v14",key:"nzette"}]],Aa=L("arrow-right-to-line",Ra);const Ma=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Ta=L("arrow-up",Ma);const Pa=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],_t=L("check",Pa);const Da=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Yr=L("chevron-down",Da);const _a=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Xr=L("chevron-right",_a);const La=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],$a=L("chevron-up",La);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"}]],ei=L("circle-alert",Fa);const Oa=[["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"}]],qa=L("clipboard",Oa);const Wa=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],za=L("clock-3",Wa);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"}]],Ha=L("code-xml",Ba);const Ka=[["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"}]],mn=L("copy",Ka);const Ua=[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M4 20v-7a4 4 0 0 1 4-4h12",key:"1lu4f8"}]],Ga=L("corner-up-right",Ua);const Va=[["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"}]],ys=L("cpu",Va);const Qa=[["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"}]],Za=L("ellipsis",Qa);const Ja=[["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"}]],Ya=L("eye",Ja);const Xa=[["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"}]],eo=L("file-pen-line",Xa);const to=[["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"}]],ti=L("file-text",to);const no=[["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"}]],Qn=L("folder-open",no);const so=[["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"}]],ro=L("folder",so);const io=[["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"}]],ao=L("funnel",io);const oo=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Pt=L("gauge",oo);const co=[["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"}]],ss=L("git-compare",co);const lo=[["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"}]],uo=L("git-merge",lo);const ho=[["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"}]],ni=L("globe",ho);const fo=[["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"}]],mo=L("hash",fo);const po=[["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"}]],go=L("image-off",po);const yo=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],si=L("info",yo);const bo=[["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"}]],vo=L("key-round",bo);const xo=[["path",{d:"M10 5h11",key:"1hkqpe"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 19h11",key:"14g2nv"}],["path",{d:"m3 10 3-3-3-3",key:"i7pm08"}],["path",{d:"m3 20 3-3-3-3",key:"20gx1n"}]],wo=L("list-collapse",xo);const So=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],rs=L("loader-circle",So);const ko=[["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"}]],ri=L("message-circle",ko);const jo=[["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"}]],ii=L("mic",jo);const Co=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],Io=L("panel-left",Co);const No=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],Eo=L("panel-right",No);const Ro=[["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"}]],ai=L("paperclip",Ro);const Ao=[["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"}]],Mo=L("pencil",Ao);const To=[["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"}]],_n=L("pin",To);const Po=[["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"}]],oi=L("plug-zap",Po);const Do=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Ln=L("plus",Do);const _o=[["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"}]],En=L("refresh-cw",_o);const Lo=[["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"}]],ci=L("rotate-ccw",Lo);const $o=[["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"}]],Fo=L("save",$o);const Oo=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Rn=L("search",Oo);const qo=[["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"}]],Wo=L("send",qo);const zo=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],Bo=L("settings-2",zo);const Ho=[["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"}]],Ko=L("settings",Ho);const Uo=[["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"}]],Hs=L("shield-check",Uo);const Go=[["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"}]],li=L("sliders-horizontal",Go);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"}]],Qo=L("sparkles",Vo);const Zo=[["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"}]],is=L("square-terminal",Zo);const Jo=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],di=L("square",Jo);const Yo=[["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"}]],ui=L("tag",Yo);const Xo=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Ks=L("terminal",Xo);const ec=[["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"}]],hi=L("trash-2",ec);const tc=[["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"}]],nc=L("upload",tc);const sc=[["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"}]],rc=L("wrench",sc);const ic=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],$e=L("x",ic);const ac=[["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"}]],dn=L("zap",ac),Is="vibelet.shortcuts.changed",Ns="vibelet.workspace.command",en=[{id:"leftSidebar",zh:"显示 / 隐藏左侧栏",en:"Toggle left sidebar",default:"mod+alt+["},{id:"rightSidebar",zh:"显示 / 隐藏右侧栏",en:"Toggle right sidebar",default:"mod+alt+]"},{id:"searchSessions",zh:"搜索会话",en:"Search sessions",default:"mod+shift+f"},{id:"files",zh:"打开文件树",en:"Open files",default:"mod+alt+e"},{id:"terminal",zh:"打开终端",en:"Open terminal",default:"mod+j"},{id:"browser",zh:"打开浏览器",en:"Open browser",default:"mod+alt+b"},{id:"newTab",zh:"新建终端 / 浏览器标签",en:"New terminal / browser tab",default:"mod+t"},{id:"previousTab",zh:"上一个标签",en:"Previous tab",default:"mod+shift+["},{id:"nextTab",zh:"下一个标签",en:"Next tab",default:"mod+shift+]"},{id:"closeTab",zh:"关闭当前标签",en:"Close current tab",default:"mod+alt+w"},{id:"moveTab",zh:"在中间区域与右侧栏间移动标签",en:"Move tab between workspace and sidebar",default:"mod+shift+m"},{id:"diff",zh:"查看 Git 变更",en:"View Git changes",default:"mod+alt+g"}];function fi(){return/Mac|iPhone|iPad/.test(navigator.platform)}const oc={BracketLeft:"[",BracketRight:"]",Comma:",",Period:".",Slash:"/",Backslash:"\\",Minus:"-",Equal:"=",Space:"space"};function mi(e,t=fi()){const n=oc[e.code]||(/^Key[A-Z]$/.test(e.code)?e.code.slice(3).toLowerCase():/^Digit\d$/.test(e.code)?e.code.slice(5):e.key.toLowerCase());return["meta","control","alt","shift","dead"].includes(n)||!(e.metaKey||e.ctrlKey||e.altKey)?null:[t?e.metaKey&&"mod":e.ctrlKey&&"mod",t?e.ctrlKey&&"ctrl":e.metaKey&&"meta",e.altKey&&"alt",e.shiftKey&&"shift",n].filter(Boolean).join("+")}function pi(e,t=fi()){const n=t?{mod:"⌘",ctrl:"⌃",meta:"⌘",alt:"⌥",shift:"⇧",space:"Space"}:{mod:"Ctrl",ctrl:"Ctrl",meta:"Win",alt:"Alt",shift:"Shift",space:"Space"};return e.split("+").map(s=>n[s]||s.toUpperCase()).join(t?"":"+")}function cc(e,t={}){return t[e]??en.find(n=>n.id===e).default}function lc(e,t,n){return t?["mod+n","mod+,","mod+q","mod+w","mod+c","mod+v","mod+x","mod+a","mod+z","mod+shift+z","mod+s","mod+f","mod+r","mod+h","mod+m","mod+-","mod+=","mod+shift+="].includes(t)?"reserved":en.find(s=>s.id!==e&&cc(s.id,n)===t)?.id??null:null}const gi="vibelet.web.shortcuts";function Zn(){try{const e=JSON.parse(Ze().getItem(gi)||"{}");return Object.fromEntries(en.filter(t=>typeof e?.[t.id]=="string").map(t=>[t.id,e[t.id]]))}catch{return{}}}function Us(e,t=Zn()){return t[e]??en.find(n=>n.id===e).default}function dc(e){Ze().setItem(gi,JSON.stringify(e)),window.dispatchEvent(new Event(Is))}function $n(e,t){const n=Us(t);return n?`${e} (${pi(n)})`:e}const uc="data:image/svg+xml,%3csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='-3%20-3%2041%2041'%20shape-rendering='crispEdges'%3e%3cpath%20fill='%23ffffff'%20d='M-3%20-3h41v41H-3z'/%3e%3cpath%20stroke='%23000000'%20d='M1%201.5h7m2%200h2m2%200h1m2%200h1m1%200h2m1%200h1m1%200h1m2%200h7M1%202.5h1m5%200h1m2%200h1m3%200h5m3%200h1m2%200h1m1%200h1m5%200h1M1%203.5h1m1%200h3m1%200h1m1%200h1m1%200h1m2%200h1m1%200h2m1%200h6m2%200h1m1%200h3m1%200h1M1%204.5h1m1%200h3m1%200h1m1%200h3m3%200h4m1%200h4m1%200h1m1%200h1m1%200h3m1%200h1M1%205.5h1m1%200h3m1%200h1m1%200h1m2%200h3m1%200h1m1%200h3m1%200h2m3%200h1m1%200h3m1%200h1M1%206.5h1m5%200h1m1%200h2m2%200h6m3%200h2m3%200h1m5%200h1M1%207.5h7m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h1m1%200h7M9%208.5h1m1%200h1m4%200h1m3%200h4M1%209.5h1m1%200h5m2%200h1m1%200h7m1%200h1m2%200h1m1%200h1m1%200h5M3%2010.5h2m1%200h1m2%200h2m1%200h1m3%200h2m1%200h4m1%200h1m2%200h2m1%200h2M1%2011.5h2m1%200h1m2%200h5m4%200h1m4%200h1m1%200h1m1%200h2m2%200h1m1%200h2M1%2012.5h3m1%200h1m2%200h3m2%200h1m1%200h1m3%200h2m1%200h3m1%200h1m2%200h5M2%2013.5h1m1%200h1m2%200h3m1%200h3m2%200h1m2%200h1m3%200h2m1%200h1m1%200h1m1%200h1m1%200h1M2%2014.5h3m1%200h1m3%200h2m3%200h3m1%200h3m2%200h2m6%200h2M1%2015.5h2m1%200h1m1%200h2m4%200h3m3%200h1m2%200h2m2%200h3m1%200h4M1%2016.5h1m1%200h3m2%200h1m2%200h2m1%200h1m2%200h1m1%200h1m1%200h8m1%200h2M3%2017.5h7m1%200h2m1%200h2m1%200h2m4%200h4m1%200h2m1%200h1m1%200h1M2%2018.5h2m4%200h1m1%200h2m1%200h1m2%200h13m1%200h4M1%2019.5h1m2%200h5m1%200h1m1%200h7m7%200h1m1%200h2m1%200h1M1%2020.5h3m5%200h1m1%200h2m1%200h1m2%200h8m2%200h5m1%200h1M1%2021.5h1m1%200h6m1%200h1m1%200h1m1%200h1m2%200h1m2%200h1m1%200h2m1%200h2m1%200h3M1%2022.5h1m1%200h2m1%200h1m1%200h2m1%200h6m1%200h2m1%200h2m1%200h1m2%200h1m2%200h1m2%200h1M1%2023.5h1m2%200h2m1%200h5m2%200h4m1%200h1m1%200h1m3%200h2m2%200h1m2%200h1M1%2024.5h1m2%200h1m5%200h1m1%200h5m3%200h4m1%200h3m1%200h3m1%200h1M1%2025.5h1m3%200h3m4%200h3m1%200h1m1%200h1m4%200h7m1%200h2M9%2026.5h1m1%200h2m1%200h2m3%200h2m1%200h1m1%200h2m3%200h1m1%200h1m1%200h1M1%2027.5h7m2%200h1m1%200h2m1%200h3m1%200h1m1%200h1m2%200h2m1%200h1m1%200h1m1%200h2M1%2028.5h1m5%200h1m1%200h9m3%200h5m3%200h3m1%200h1M1%2029.5h1m1%200h3m1%200h1m1%200h2m2%200h2m1%200h1m2%200h1m1%200h1m3%200h6M1%2030.5h1m1%200h3m1%200h1m1%200h4m1%200h5m2%200h1m1%200h2m1%200h1m2%200h2m1%200h2M1%2031.5h1m1%200h3m1%200h1m1%200h2m1%200h2m7%200h2m1%200h5m1%200h2M1%2032.5h1m5%200h1m2%200h2m2%200h2m1%200h1m1%200h4m1%200h1m2%200h1m1%200h3M1%2033.5h7m1%200h5m4%200h1m2%200h1m1%200h3m1%200h2m3%200h1'/%3e%3c/svg%3e",hc="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 Jn(){const e=Ye(Xe().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 yi(){const e=Jn();return r.jsxs("section",{className:"mobile-companion-panel control-section",children:[r.jsx("p",{className:"mobile-companion-free",children:e.free}),r.jsx("h2",{children:e.title}),r.jsx("p",{children:e.description}),r.jsx("div",{className:"mobile-companion-downloads",children:[{label:e.ios,qr:hc,url:"https://apps.apple.com/app/id6761245790"},{label:e.android,qr:uc,url:"https://www.feishu.cn/file/RUnbb7INMocEFjxj5AWcC7WEn6d"}].map(t=>r.jsxs("div",{children:[r.jsx("img",{src:t.qr,alt:`${t.label} · ${e.download}`,width:"140",height:"140"}),r.jsx("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",children:t.label})]},t.url))}),r.jsx("p",{children:e.pairing}),r.jsx("p",{className:"mobile-companion-hint",children:e.pro})]})}function fc({onClose:e}){const t=c.useRef(null);c.useEffect(()=>{const s=document.activeElement,i=document.getElementById("vibelet-workspace"),a=i?.inert;return i&&(i.inert=!0),t.current?.focus(),()=>{i&&(i.inert=!!a),s?.focus()}},[]);const n=Jn().title;return dt.createPortal(r.jsx("div",{className:"mobile-companion-backdrop",onClick:s=>{s.target===s.currentTarget&&e()},children:r.jsxs("section",{ref:t,className:"mobile-companion-dialog",role:"dialog","aria-modal":"true","aria-label":n,tabIndex:-1,onKeyDown:s=>{if(s.key==="Escape"&&(s.preventDefault(),s.stopPropagation(),e()),s.key!=="Tab")return;const i=Array.from(s.currentTarget.querySelectorAll("button,a[href]")),a=i[0],o=i.at(-1);s.shiftKey&&(document.activeElement===a||document.activeElement===t.current)?(s.preventDefault(),o?.focus()):!s.shiftKey&&document.activeElement===o&&(s.preventDefault(),a?.focus())},children:[r.jsx("button",{type:"button",className:"icon-button mobile-companion-close","aria-label":Jn().close,onClick:e,children:r.jsx($e,{"aria-hidden":"true"})}),r.jsx(yi,{})]})}),document.body)}function mc({activeSession:e,busy:t,controlsOpen:n,t:s,onOpenControls:i,onRefreshSessions:a,onRestoreSnapshot:o,onToggleArchived:l,onTogglePinned:u,onViewChanges:h}){const[d,m]=c.useState(!1),[b,p]=c.useState(!1),S=c.useRef(null);c.useEffect(()=>{if(!b)return;const x=j=>{j.target instanceof Node&&!S.current?.contains(j.target)&&p(!1)},v=j=>{j.key==="Escape"&&p(!1)};return document.addEventListener("pointerdown",x),document.addEventListener("keydown",v),()=>{document.removeEventListener("pointerdown",x),document.removeEventListener("keydown",v)}},[b]);const w=x=>{p(!1),x()},y=ee(),g=r.jsxs("div",{className:"header-actions",children:[d&&r.jsx(fc,{onClose:()=>m(!1)}),e?null:r.jsx("button",{"aria-label":s.refreshSessions,className:"icon-button",onClick:a,title:s.refreshSessions,type:"button",children:r.jsx(En,{"aria-hidden":"true"})}),r.jsx("button",{"aria-expanded":n,"aria-label":n?s.collapseControlsSidebar:s.workspaceTools,title:$n(n?s.collapseControlsSidebar:s.workspaceTools,"rightSidebar"),className:"header-tool-button",onClick:i,type:"button",children:r.jsx(Eo,{"aria-hidden":"true"})}),e||y.openSettings?r.jsxs("div",{className:"header-more-wrap",ref:S,children:[r.jsx("button",{"aria-expanded":b,"aria-haspopup":"menu","aria-label":s.moreActions,className:"icon-button",onClick:()=>p(x=>!x),title:s.moreActions,type:"button",children:r.jsx(Za,{"aria-hidden":"true"})}),b?r.jsxs("div",{className:"header-action-menu",role:"menu",children:[e&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:()=>w(()=>h(e.sessionId)),role:"menuitem",type:"button",children:[r.jsx(ss,{"aria-hidden":"true"}),r.jsx("span",{children:s.viewChanges})]}),r.jsxs("button",{disabled:t,onClick:()=>w(u),role:"menuitem",type:"button",children:[r.jsx(_n,{"aria-hidden":"true"}),r.jsx("span",{children:e.pinned?s.unpin:s.pin})]}),r.jsxs("button",{disabled:t,onClick:()=>w(l),role:"menuitem",type:"button",children:[r.jsx(ns,{"aria-hidden":"true"}),r.jsx("span",{children:e.archived?s.unarchive:s.archive})]}),r.jsxs("button",{onClick:()=>w(o),role:"menuitem",type:"button",children:[r.jsx(ci,{"aria-hidden":"true"}),r.jsx("span",{children:s.restoreSnapshot})]})]}),r.jsxs("button",{role:"menuitem",type:"button",onClick:()=>w(()=>m(!0)),children:[r.jsx(ua,{"aria-hidden":"true"}),r.jsx("span",{children:Jn().title})]}),y.openSettings&&r.jsxs("button",{role:"menuitem",type:"button",onClick:()=>w(y.openSettings),children:[r.jsx(Ko,{"aria-hidden":"true"}),r.jsx("span",{children:s.settings})]}),r.jsxs("button",{onClick:()=>w(a),role:"menuitem",type:"button",children:[r.jsx(En,{"aria-hidden":"true"}),r.jsx("span",{children:s.refreshSessions})]})]}):null]}):null]}),f=y.toolbarTarget?.("right");return f?dt.createPortal(g,f):g}const pc=/^[A-Za-z][A-Za-z0-9_-]*$/,gc=[{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 bi(e){return gc.filter(t=>!e||t.agents.includes(e))}function Gs(e){return e.trim().toLowerCase()}function Hn(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&&!pc.test(n)?null:{start:0,end:e.length,keyword:Gs(n)}}function yc(e,t,n=8){const s=Gs(t);return(s?e.filter(a=>a.name.includes(s)||a.title.toLowerCase().includes(s)).sort((a,o)=>mr(a,s)-mr(o,s)):[...e]).slice(0,n)}function mr(e,t){return e.name===t?0:e.name.startsWith(t)?1:e.name.includes(t)?2:3}function bc(e,t,n){return`${e.slice(0,t.start)}${vi(n,"")}${e.slice(t.end)}`}function vc(e,t,n){return t?bc(e,t,n):`${vi(n,e)}${e}`}function vi(e,t){const n=t.length>0,s=n&&!/^\s/.test(t),i=!!(e.argsHint&&!n);return`/${e.name}${i||s?" ":""}`}function pr(e,t){const n=e.trim();if(!n.startsWith("/")||n.startsWith("//"))return null;const s=/^\/([A-Za-z][A-Za-z0-9_-]*)(?:\s+([\s\S]*))?$/.exec(n);if(!s)return null;const i=Gs(s[1]??""),a=bi(t).find(l=>l.name===i);if(!a)return null;const o=s[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=o.toLowerCase();return!o||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:o}}}}}function xc(e){return e.startsWith("//")?e.slice(1):e}function wc(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 Sc(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 gr(e){return e==="subscriptionRequired"?"Error: Agent commands require an active Pro subscription.":`Error: ${e||"Command failed."}`}function kc(e,t){return!t||!Hn(e)?e:t.draftBeforeInsertion}function xi(e){return/^[a-zA-Z0-9._/~-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function jc(e){const t=e.approvalMode??e.observedApprovalMode,n=e.agent==="claude"?["claude","--resume",e.sessionId]:["codex","resume",e.sessionId];return t==="autoApprove"?n.push(e.agent==="claude"?"--dangerously-skip-permissions":"--dangerously-bypass-approvals-and-sandbox"):e.agent==="claude"&&t==="acceptEdits"&&n.push("--permission-mode","acceptEdits"),n.map(xi).join(" ")}function wi(e){return`cd ${xi(e.cwd||".")} && ${jc(e)}`}const Si="vibelet.web.notificationSettings",Bt={enabled:!1,approvals:!0,questions:!0,replies:!0,hiddenOnly:!0};function Es(e=Ze()){try{const t=e.getItem(Si);if(!t)return{...Bt};const n=JSON.parse(t);return Xt(n)?{enabled:typeof n.enabled=="boolean"?n.enabled:Bt.enabled,approvals:typeof n.approvals=="boolean"?n.approvals:Bt.approvals,questions:typeof n.questions=="boolean"?n.questions:Bt.questions,replies:typeof n.replies=="boolean"?n.replies:Bt.replies,hiddenOnly:typeof n.hiddenOnly=="boolean"?n.hiddenOnly:Bt.hiddenOnly}:{...Bt}}catch{return{...Bt}}}function Cc(e,t=Ze()){t.setItem(Si,JSON.stringify(e))}function Nn(e=typeof Notification>"u"?void 0:Notification){return ee().notifications?ee().notifications.permission():e?.permission??"unsupported"}function Ic(e,t,n=typeof document>"u"?"visible":document.visibilityState){return!(!e.enabled||t!=="granted"||e.hiddenOnly&&n==="visible")}function Nc(e,t,n={}){const s=n.notificationFactory??(typeof Notification>"u"?void 0:Notification);if(!s&&!ee().notifications)return!1;const i=n.settings??{enabled:!0,hiddenOnly:!1},a=n.permission??Nn(),o=n.visibilityState??(typeof document>"u"?"visible":document.visibilityState);if(!Ic(i,a,o))return!1;if(ee().notifications)return ee().notifications.show(e,t,n.onClick),!0;const l=new s(e,{body:t,tag:n.tag});return n.onClick&&(l.onclick=n.onClick),!0}function Rs(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 Ec(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??"")&&Rs(e,t)}function Rc(e){for(let t=e.length-1;t>=0;t-=1)if(e[t]?.role==="user")return t;return-1}function ki(e,t){const n=e.slice(),s=new Map,i=[];n.forEach((o,l)=>{o.historyKey&&!s.has(o.historyKey)&&s.set(o.historyKey,l),(!o.historyKey||o.historyKey.startsWith("client:"))&&i.push(l)});const a=new Set;for(const o of t){const l=o.historyKey?s.get(o.historyKey)??-1:-1;if(l>=0){o.delivery==="accepted"&&(n[l]={...n[l],...o,localDelivery:"delivered"});continue}const h=(o.historyKey?i:n.map((d,m)=>m)).find(d=>{const m=n[d];if(a.has(d))return!1;if(Ec(m,o))return!0;if(m.historyKey&&!m.historyKey.startsWith("client:"))return!1;if(m.liveReply&&(d===n.length-1||n.slice(d+1).every(b=>b.localClientMessageId&&b.historyKey?.startsWith("client:")))&&o.role==="assistant"&&o.type!=="info")return m.content.length>0&&o.content.startsWith(m.content);if(m.localClientMessageId&&o.historyKey&&!o.historyKey.startsWith("client:")&&Rs(m,o)){const b=Date.parse(m.timestamp??""),p=Date.parse(o.timestamp??"");if(Number.isFinite(b)&&Number.isFinite(p))return p>=b-1e3}return!!(o.historyKey&&!o.historyKey.startsWith("client:")&&m.historyKey?.startsWith("client:")&&m.role==="user"&&d===Rc(n)&&n.slice(d+1).every(b=>b.role!=="assistant"||b.type==="info"||b.liveReply)&&Rs(m,o))})??-1;if(h<0)o.historyKey&&s.set(o.historyKey,n.length),(!o.historyKey||o.historyKey.startsWith("client:"))&&i.push(n.length),n.push({...o});else{a.add(h);const d=n[h].historyKey;d&&d!==o.historyKey&&s.delete(d),n[h]={...n[h],...o},n[h].historyKey&&s.set(n[h].historyKey,h),n[h].localClientMessageId&&o.historyKey&&!o.historyKey.startsWith("client:")&&(n[h].localDelivery="delivered"),delete n[h].liveReply}}return n}function Vs(e){const t=e.at(-1);return t?.role==="assistant"&&t.type!=="info"?[...e.slice(0,-1),{...t,liveReply:!0}]:e.slice()}const Ac=".",Mc="@vibelet/needs-attention",Tc="@vibelet/running",Pc="@vibelet/pinned";function Dc(e,t={}){const n=new Map,s=[],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))?s.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||Ac;n.set(d,[...n.get(d)??[],l])}const o=[];if(s.length>0&&o.push({folder:Mc,kind:"attention",sessions:s}),i.length>0){const l=new Map(t.runningSessionOrder?.map((u,h)=>[u,h]));o.push({folder:Tc,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&&o.push({folder:Pc,kind:"pinned",sessions:[...a].sort((l,u)=>Date.parse(u.lastActivityAt)-Date.parse(l.lastActivityAt))}),[...o,...Array.from(n.entries()).map(([l,u])=>({folder:l,kind:"folder",sessions:u}))]}function as(e,t=Date.now(),n=ha){if(!e)return n.timeUnknown;const s=Date.parse(e);if(!Number.isFinite(s))return n.timeUnknown;const i=t-s,a=60*1e3,o=60*a,l=24*o;return i<a?n.timeNow:i<o?n.timeMinutesAgo(Math.floor(i/a)):i<l?n.timeHoursAgo(Math.floor(i/o)):n.timeDaysAgo(Math.floor(i/l))}function ji(e,t){return e.type==="info"?t.messageInfoRole:{user:t.messageUserRole,assistant:t.messageAssistantRole,tool:t.messageToolRole}[e.role]}function Ci(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 it=".",Qs="normal",yr=80,_c=1600,Lc="pending_local_";function Xt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $c(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 Zs(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 Ii(e){const t=e;return{sessions:Array.isArray(t.sessions)?t.sessions:[],nextCursor:Ci(t.nextCursor),inventoryVersion:t.inventoryVersion,inventoryBackfillInFlight:t.inventoryBackfillInFlight,folderCounts:t.folderCounts}}function Fc(e){const t=e;return typeof t.sessionId=="string"?t.sessionId:null}function Oc(e){const t=e;return typeof t.path=="string"?t.path:null}function Dt(e){return e.split("/").filter(Boolean).at(-1)??e}function qc(e){return Object.entries(e).length===0?"No structured input.":JSON.stringify(e,null,2)}function Js(e){return Object.fromEntries(e.questions.map(t=>[t.id,t.options[0]?[t.options[0].label]:[]]))}function Kn(e){return e.trim()||void 0}function Ni(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 As(e,t){const n=new Map;for(const s of e)n.set(s.sessionId,s);for(const s of t)n.set(s.sessionId,{...n.get(s.sessionId),...s,interruptReason:s.interruptReason});return Array.from(n.values()).sort((s,i)=>{const a=s.pinned?s.pinnedAt??0:0,o=i.pinned?i.pinnedAt??0:0;return a!==o?o-a:Date.parse(i.lastActivityAt)-Date.parse(s.lastActivityAt)})}let bs=0;function Wc(e=Date.now()){return bs=(bs+1)%1e4,`${Lc}${e}_${bs}`}function zc(e){const t=e.now??new Date().toISOString();return{sessionId:e.sessionId,agent:e.agent,cwd:e.cwd||it,...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 Bc(e,t,n=new Date().toISOString()){return{...e,sessionId:t,lastActivityAt:n}}function vs(e,t,n){if(!t||!n||t===n||!Object.hasOwn(e,t))return e;const{[t]:s,...i}=e;return{...i,[n]:s}}function br(e,t,n){if(!t||!n||t===n||!e.has(t))return e;const s=new Set(e);return s.delete(t),s.add(n),s}function Hc(e,t){const n=e.replace(/\\/g,"/").replace(/\/+$/,"");return!n||n==="."?t:`${n}/${t}`}function Jf(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 Kc(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 Uc(e,t){return t.startsWith("image/")||/\.(png|jpe?g|gif|webp|heic|heif|svg)$/i.test(e)}function Un(e,t,n=window.location.origin){const s=new URL("/file",n);return s.searchParams.set("path",e),t&&s.searchParams.set("cwd",t),s.toString()}function zn(e,t){return e.get(t)||void 0}function Gc(e,t){return`${e.replace(/[<>:"/\\|?*\u0000-\u001F]/g," ").replace(/\s+/g," ").trim().slice(0,80)||t.slice(0,12)||"session"}.txt`}function Vc(e,t){const n=[`# ${It(e)}`,"",`- Agent: ${e.agent}`,`- Session: \`${e.sessionId}\``,`- Working directory: \`${e.cwd}\``,`- Created: ${e.createdAt}`,`- Exported: ${new Date().toISOString()}`,""];for(const s of t){if(s.role!=="user"&&s.role!=="assistant")continue;const i=s.content.trim(),a=(s.images??[]).map(o=>`- Attachment: \`${o}\``);!i&&a.length===0||(n.push(`## ${s.role==="user"?"User":"Assistant"}`,""),i&&n.push(i,""),a.length&&n.push(...a,""))}return n.join(`
|
|
3
|
+
`).trimEnd()}function Qc(e,t){const n=URL.createObjectURL(new Blob([t],{type:"text/plain;charset=utf-8"})),s=document.createElement("a");s.href=n,s.download=e,s.click(),URL.revokeObjectURL(n)}function Zc(e,t={}){const n=new Set,s={},i={},a={};for(const p of e.sessions)(p.runtime.isResponding||p.runtime.state==="daemonActive")&&n.add(p.sessionId);for(const p of e.pendingApprovals??[])s[p.sessionId]={type:"approval.request",...p};for(const p of e.pendingQuestions??[])i[p.sessionId]={type:"question.request",...p};let o=null,l,u,h,d,m,b;if(e.activeSession){const p=e.activeSession,S=e.sessions.find(y=>y.sessionId===p.sessionId);o=p.sessionId,l=p.agent,u=S?.cwd||t.currentCwd||it,h=p.approvalMode??S?.approvalMode??Qs,d=p.approvalMode??null;const w=p.messages??[];if(m=p.partialReplyText?Vs(Zs(w,p.partialReplyText)):w,(p.isResponding||p.externallyResponding)&&n.add(p.sessionId),p.pendingApproval&&(s[p.sessionId]={type:"approval.request",sessionId:p.sessionId,...p.pendingApproval}),p.pendingQuestion){const y={type:"question.request",sessionId:p.sessionId,...p.pendingQuestion};i[p.sessionId]=y,b=Js(y)}p.pendingQueue?.length&&(a[p.sessionId]=p.pendingQueue)}else{const p=t.currentActiveSessionId??null;if(p){const S=e.sessionAliases?.[p];S?o=S:e.sessions.some(w=>w.sessionId===p)&&(o=p)}o=o??e.sessions[0]?.sessionId??null}return{page:{sessions:e.sessions,nextCursor:Ci(e.nextCursor),inventoryVersion:e.inventoryVersion,inventoryBackfillInFlight:e.inventoryBackfillInFlight},activeSessionId:o,activeAgent:l,activeCwd:u,activeApprovalMode:h,activeApprovalOverride:d,messages:m,respondingSessionIds:Array.from(n),pendingApprovals:s,pendingQuestions:i,pendingQueues:a,questionAnswers:b}}function vr(e,t){if(e==="subscriptionRequired"){const n=typeof window>"u"?"en":Ye(Xe().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 Jc=/^[A-Za-z_][A-Za-z0-9._:-]*$/,Yc=/(?:^|\s)\$([A-Za-z_][A-Za-z0-9._:-]*|)$/;function An(e){return e.trim().toLowerCase()}function xr(e){const t=e.trim(),n=/^\$([A-Za-z_][A-Za-z0-9._:-]*)(?:\s+([\s\S]*))?$/.exec(t);return n?{name:An(n[1]??""),...n[2]?.trim()?{args:n[2].trim()}:{}}:null}function Gn(e){const t=Yc.exec(e);if(!t||t.index+t[0].length!==e.length)return null;const n=t[1]??"";if(n&&!Jc.test(n))return null;const s=t[0].lastIndexOf("$");return{start:t.index+s,end:e.length,keyword:An(n)}}function Xc(e,t,n){return`${e.slice(0,t.start)}$${An(n)} ${e.slice(t.end)}`}function el(e,t){if(!t)return e;const n=Gn(e);if(!n||n.start!==t.triggerStart)return e;const s=n.start>t.draftBeforeInsertion.length?" ":"";return e.slice(0,n.start)!==`${t.draftBeforeInsertion}${s}`?e:t.draftBeforeInsertion}function tl(e,t,n=8){const s=An(t);return(s?e.filter(a=>An(a.name).includes(s)):e).slice(0,n)}function Cn({icon:e,label:t,menuLabel:n,options:s,value:i,onSelect:a,align:o="left",disabled:l,selected:u,wide:h}){const[d,m]=c.useState(!1),b=c.useRef(null),p=c.useRef(null),S=s.some(w=>w.icon);return c.useEffect(()=>{if(!d)return;const w=b.current?.querySelectorAll('[role="menuitemradio"]:not(:disabled)');([...w??[]].find(f=>f.getAttribute("aria-checked")==="true")??w?.[0])?.focus();const g=f=>{f.target instanceof Node&&!b.current?.contains(f.target)&&m(!1)};return document.addEventListener("pointerdown",g),()=>document.removeEventListener("pointerdown",g)},[d]),r.jsxs("div",{className:"composer-menu",ref:b,onBlur:w=>{const y=w.relatedTarget;(!y||!w.currentTarget.contains(y))&&m(!1)},onKeyDown:w=>{if(w.key==="Escape"&&d&&(w.stopPropagation(),w.preventDefault(),m(!1),p.current?.focus()),!["ArrowDown","ArrowUp","Home","End"].includes(w.key))return;if(w.preventDefault(),!d){m(!0);return}const y=[...w.currentTarget.querySelectorAll('[role="menuitemradio"]:not(:disabled)')];if(!y.length)return;const g=y.indexOf(document.activeElement),f=w.key==="Home"?0:w.key==="End"?y.length-1:(g+(w.key==="ArrowDown"?1:-1)+y.length)%y.length;y[f]?.focus()},children:[r.jsxs("button",{ref:p,"aria-expanded":d,"aria-haspopup":"menu",className:`composer-option-button ${d||u?"selected":""}`,disabled:l,onClick:()=>m(w=>!w),title:n,type:"button",children:[r.jsx(e,{"aria-hidden":"true"}),r.jsx("span",{children:t}),d?r.jsx($a,{"aria-hidden":"true"}):r.jsx(Yr,{"aria-hidden":"true"})]}),d?r.jsx("div",{"aria-label":n,className:`composer-option-popover ${S?"":"without-icons"} ${h?"wide":""} ${o==="right"?"align-right":""}`,role:"menu",children:s.map(w=>{const y=w.icon,g=w.value===i;return r.jsxs("button",{"aria-checked":g,className:g?"selected":"",disabled:w.disabled,onClick:()=>{a(w.value),m(!1),p.current?.focus()},role:"menuitemradio",title:w.description??w.label,type:"button",children:[S&&r.jsx("span",{className:"composer-menu-icon",children:y?r.jsx(y,{"aria-hidden":"true"}):null}),r.jsxs("span",{className:"composer-menu-copy",children:[r.jsx("strong",{children:w.label}),w.description?r.jsx("small",{children:w.description}):null]}),r.jsx("span",{className:"composer-menu-indicator","aria-hidden":"true",children:g?r.jsx(_t,{className:"composer-menu-check"}):null})]},w.value)})}):null]})}function Ei(e,t,n){const s=c.useRef(null);return c.useEffect(()=>{n&&document.getElementById(`${e}-${t}`)?.scrollIntoView({block:"nearest"})},[e,t,n]),s}function nl({visible:e,listId:t,selectedIndex:n,onHighlight:s,skills:i,onClose:a,onSelect:o,t:l}){const u=Ei(t,n,e);return e?r.jsxs("div",{className:"skill-suggestion-popover",children:[r.jsxs("header",{children:[r.jsx("strong",{children:l.skills}),r.jsx("button",{type:"button",className:"icon-button",onClick:a,title:l.closeSkills,children:r.jsx($e,{"aria-hidden":"true"})})]}),i.length?r.jsx("div",{className:"skill-suggestion-list",id:t,role:"listbox",ref:u,children:i.map((h,d)=>r.jsxs("button",{id:`${t}-${d}`,role:"option","aria-selected":n===d,onMouseEnter:()=>s(d),onClick:()=>o(h),title:h.description??h.name,type:"button",children:[r.jsxs("span",{children:[r.jsxs("strong",{children:["$",h.name]}),h.description?r.jsx("small",{children:h.description}):null]}),r.jsx("em",{children:h.source})]},`${h.source}:${h.name}`))}):r.jsx("p",{children:l.noSkillsFound})]}):null}function sl({visible:e,listId:t,selectedIndex:n,onHighlight:s,commands:i,onClose:a,onSelect:o,t:l}){const u=Ei(t,n,e);return e?r.jsxs("div",{className:"skill-suggestion-popover command-suggestion-popover",children:[r.jsxs("header",{children:[r.jsx("strong",{children:l.commands}),r.jsx("button",{type:"button",className:"icon-button",onClick:a,title:l.closeCommands,children:r.jsx($e,{"aria-hidden":"true"})})]}),i.length?r.jsx("div",{className:"skill-suggestion-list",id:t,role:"listbox",ref:u,children:i.map((h,d)=>r.jsxs("button",{id:`${t}-${d}`,role:"option","aria-selected":n===d,onMouseEnter:()=>s(d),onClick:()=>o(h),title:h.description,type:"button",children:[r.jsxs("span",{children:[r.jsxs("strong",{children:["/",h.name]}),r.jsx("small",{children:h.argsHint?`${h.title} ${h.argsHint}`:h.title})]}),r.jsx("em",{children:h.source})]},h.name))}):r.jsx("p",{children:l.noCommandsFound})]}):null}function rl({queue:e,controls:t,busy:n,t:s,onCancel:i}){const[a,o]=c.useState(new Set),l=e.filter(m=>m.clientMessageId),u=l.filter(m=>a.has(m.clientMessageId)),h=n||t.busy,d=u.length?u:l;return e.length?r.jsxs("section",{className:"composer-queue-banner","aria-label":s.queuedTurns(e.length),children:[r.jsxs("header",{className:"composer-queue-heading",children:[r.jsx("strong",{children:s.queuedTurns(e.length)}),r.jsx("button",{type:"button",disabled:h||!l.length,onClick:()=>o(l.length>0&&u.length===l.length?new Set:new Set(l.map(m=>m.clientMessageId))),children:l.length>0&&u.length===l.length?s.queueClearSelection:s.queueSelectAll})]}),r.jsx("div",{className:"composer-queue-list",children:e.map((m,b)=>r.jsxs("div",{className:"composer-queue-item","data-selected":!!m.clientMessageId&&a.has(m.clientMessageId)||void 0,children:[r.jsx("button",{type:"button",className:"queue-select-button","aria-label":s.selectQueuedTurn(b+1),"aria-pressed":!!m.clientMessageId&&a.has(m.clientMessageId),disabled:h||!m.clientMessageId,title:m.content,onClick:()=>o(p=>{const S=new Set(p),w=m.clientMessageId;return S.has(w)?S.delete(w):S.add(w),S}),children:r.jsx("span",{children:m.content||s.queuedTurnFallback})}),r.jsxs("div",{className:"queue-row-actions",children:[r.jsx("button",{type:"button",title:s.queueGuide,"aria-label":s.guideQueuedTurn(b+1),disabled:h||!m.clientMessageId||!t.canGuide,onClick:()=>{t.onAction([m],"guide")},children:r.jsx(Ga,{"aria-hidden":"true"})}),r.jsx("button",{type:"button",title:s.queueSendNow,"aria-label":s.sendQueuedTurnNow(b+1),disabled:h||!m.clientMessageId||!t.canSendNow,onClick:()=>{t.onAction([m],"sendNow")},children:r.jsx(Wo,{"aria-hidden":"true"})}),r.jsx("button",{type:"button",className:"queue-withdraw-button",title:s.withdraw,"aria-label":s.withdrawQueuedTurn(b+1),disabled:h||!m.clientMessageId,onClick:()=>i(m),children:r.jsx($e,{"aria-hidden":"true"})})]})]},m.clientMessageId||`${m.enqueuedAt}:${b}`))}),r.jsxs("footer",{className:"queue-batch-actions",children:[u.length>0&&r.jsx("span",{children:s.queueSelectedCount(u.length)}),r.jsxs("button",{type:"button",disabled:h||d.length<2,onClick:()=>{t.onCollect(d)},children:[r.jsx(wo,{"aria-hidden":"true"}),u.length?s.queueCollectSelected:s.queueCollectAll]}),r.jsx("button",{type:"button",disabled:h||!d.length||!t.canGuide,onClick:()=>{t.onAction(d,"guide")},children:u.length?s.queueGuideSelected:s.queueGuideAll}),r.jsx("button",{type:"button",disabled:h||!d.length||!t.canSendNow,onClick:()=>{t.onAction(d,"sendNow")},children:u.length?s.queueSendSelected:s.queueSendAll})]})]}):null}function il({connected:e,busy:t,sending:n,responding:s,hasDraft:i,shortcut:a,onStop:o,t:l}){const u=n?"sending":s?"replying":"ready",h=s&&!n&&!i,d=n?l.sendingMessage:h?l.stopGenerating:l.send,m=n?l.sendingMessage:s?l.replyingMessage:l.send,b=n?rs:h?di:Ta;return r.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":m,title:h?`${m} · ${l.stopGenerating}`:n?m:`${s?`${m} · `:""}${l.send} · ${a==="enter"?l.sendShortcutEnter:l.sendShortcutModEnter}`,onClick:h?o:void 0,children:[s&&!n&&r.jsx("span",{className:"composer-send-progress","aria-hidden":"true"}),r.jsx(b,{className:n?"composer-send-spinner":h?"composer-send-stop":void 0,"aria-hidden":"true"}),r.jsx("span",{className:"composer-send-status",role:"status","aria-live":"polite",children:m})]})}function al({context:e,count:t,onSelect:n,onClose:s}){const i=c.useId(),[a,o]=c.useState({context:"",index:0}),l=a.context===e?Math.min(a.index,Math.max(0,t-1)):0,u=d=>o({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(),s(),!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 ol(e){const t=new AudioContext;try{const n=await t.decodeAudioData(await e.arrayBuffer());if(n.duration>61||n.duration<=0)throw new Error("Invalid recording duration");const s=new Uint8Array(44+n.length*2),i=new DataView(s.buffer),a=(l,u)=>[...u].forEach((h,d)=>i.setUint8(l+d,h.charCodeAt(0)));a(0,"RIFF"),i.setUint32(4,s.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,s.length-44,!0);const o=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,o.reduce((h,d)=>h+d[l],0)/o.length));i.setInt16(44+l*2,u*(u<0?32768:32767),!0)}return s}finally{await t.close()}}function cl({onTranscript:e}){const t=ee(),[n,s]=c.useState("idle"),[i,a]=c.useState("");c.useEffect(()=>{if(!i||n!=="idle")return;const g=setTimeout(()=>a(""),5e3);return()=>clearTimeout(g)},[i,n]);const[o,l]=c.useState(0),u=c.useRef(!1);c.useEffect(()=>{if(n!=="recording")return;const g=Date.now();l(0);const f=setInterval(()=>l(Math.floor((Date.now()-g)/1e3)),1e3);return()=>clearInterval(f)},[n]);const[h,d]=c.useState(!1);c.useEffect(()=>{let g=!0;const f=()=>{t.speechSettings?.status().then(x=>{g&&d(x.configured)}).catch(()=>{g&&d(!1)})};return f(),window.addEventListener("vibelet.speech.changed",f),()=>{g=!1,window.removeEventListener("vibelet.speech.changed",f)}},[]);const m=c.useRef(null),b=c.useRef(!0),p=c.useRef(e);p.current=e;const S=Ye(Xe().language),w=S!=="en";if(c.useEffect(()=>(b.current=!0,()=>{b.current=!1,m.current?.stream.getTracks().forEach(g=>g.stop()),m.current?.state==="recording"&&m.current.stop()}),[]),!h||!t.transcribeAudio||Ze().getItem("vibelet.web.voice.enabled")!=="true")return null;const y=async()=>{if(!u.current){u.current=!0,a(""),s("starting");try{const g=await navigator.mediaDevices.getUserMedia({audio:!0});if(!b.current){g.getTracks().forEach(N=>N.stop());return}let f;try{f=new MediaRecorder(g,{mimeType:"audio/webm"})}catch(N){throw g.getTracks().forEach(k=>k.stop()),N}m.current=f;const x=[];let v=0;f.ondataavailable=N=>{x.push(N.data),v+=N.data.size,v>9*1024*1024&&f.state==="recording"&&f.stop()};const j=setTimeout(()=>{f.state==="recording"&&f.stop()},6e4);f.onstop=async()=>{if(clearTimeout(j),g.getTracks().forEach(N=>N.stop()),m.current=null,!!b.current){s("transcribing");try{const N=new Blob(x,{type:"audio/webm"}),k=await t.speechSettings?.status(),C=k?.engine==="system"||k?.engine==="volcengine"?await ol(N):new Uint8Array(await N.arrayBuffer()),I=await t.transcribeAudio(C,S==="zh-TW"?"zh-TW":w?"zh":"en");if(b.current)if(I.trim()){a("");let R=I;const z=await t.polishSettings?.status().catch(()=>{});if(!b.current)return;if(z?.settings.enabled&&t.polishTranscript){s("polishing");try{const A=await t.polishTranscript(I);R=A.text,b.current&&A.status==="fallback"&&a(w?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}catch{b.current&&a(w?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}}b.current&&p.current(R)}else a(w?"没有识别到语音,请靠近麦克风重试。":"No speech detected. Try speaking closer to the microphone.")}catch{b.current&&a(w?"语音识别失败,请检查麦克风权限、语音设置和网络。":"Speech failed. Check microphone access, speech settings and connection.")}finally{u.current=!1,b.current&&s("idle")}}};try{f.start(1e3)}catch(N){throw clearTimeout(j),g.getTracks().forEach(k=>k.stop()),m.current=null,N}s("recording")}catch{u.current=!1,b.current&&(s("idle"),a(w?"无法开启麦克风,请检查系统权限。":"Microphone unavailable. Check system permissions."))}}};return r.jsxs("span",{className:"voice-input-control","data-voice-state":n,children:[r.jsx("button",{className:"icon-button",type:"button",disabled:n!=="idle"&&n!=="recording","aria-label":w?n==="recording"?"停止录音":"语音输入":n==="recording"?"Stop recording":"Voice input",title:n==="recording"?w?"停止录音":"Stop recording":w?"语音输入(最长 60 秒)":"Voice input (up to 60 seconds)",onClick:()=>{n==="recording"?m.current?.state==="recording"&&m.current.stop():y()},children:n==="recording"?r.jsx(di,{"aria-hidden":"true"}):n==="idle"?r.jsx(ii,{"aria-hidden":"true"}):r.jsx(rs,{className:"voice-input-spinner","aria-hidden":"true"})}),n!=="idle"&&r.jsxs("span",{className:"voice-input-progress",children:[n==="recording"&&r.jsxs("span",{className:"voice-input-wave","aria-hidden":"true",children:[r.jsx("i",{}),r.jsx("i",{}),r.jsx("i",{})]}),r.jsx("span",{role:"status","aria-live":"polite",children:n==="recording"?w?"录音中":"Recording":n==="polishing"?w?"润色中":"Polishing":n==="transcribing"?w?"识别中":"Transcribing":w?"开启麦克风":"Opening microphone"}),n==="recording"&&r.jsxs("span",{className:"voice-input-time","aria-hidden":"true",children:["00:",String(o).padStart(2,"0")]})]}),n==="idle"&&i&&r.jsx("span",{className:"voice-input-error",role:"alert",children:i})]})}function ll(e){return[{value:"normal",label:e.approvalNormal,description:e.approvalNormalDescription,icon:Hs},{value:"plan",label:e.approvalPlan,description:e.approvalPlanDescription,icon:li},{value:"acceptEdits",label:e.approvalEdits,description:e.approvalEditsDescription,icon:eo},{value:"autoApprove",label:e.approvalAuto,description:e.approvalAutoDescription,icon:dn}]}function dl(e){return[{value:"",label:e.effort,description:e.useDaemonDefault,icon:Pt},{value:"minimal",label:e.effortMinimal,icon:Pt},{value:"low",label:e.effortLow,icon:Pt},{value:"medium",label:e.effortMedium,icon:Pt},{value:"high",label:e.effortHigh,icon:Pt},{value:"xhigh",label:e.effortXHigh,icon:Pt},{value:"max",label:e.effortMax,icon:Pt},{value:"ultra",label:e.effortUltra,icon:Pt}]}function ul({activeQueue:e,queueControls:t,agent:n,attachments:s,approvalMode:i,activeModelOptions:a,busy:o,sending:l,responding:u,onStop:h,draft:d,effort:m,fastMode:b,model:p,phase:S,quickReplies:w,sendShortcut:y,skills:g,uploadBusy:f,t:x,onApprovalModeChange:v,onCancelQueuedTurn:j,onDraftChange:N,onEffortChange:k,onFastModeChange:C,onModelChange:I,onRefreshSkills:R,onRemoveAttachment:z,onSubmit:A,onUploadFiles:M}){const F=c.useRef(null),G=c.useRef(null),[ne,ve]=c.useState(!1),[Se,ae]=c.useState(!1),[ke,fe]=c.useState(!1),[oe,ce]=c.useState(!1),[T,D]=c.useState(""),[W,U]=c.useState(""),O=c.useRef(null),V=c.useRef(null),B=S==="connected",X=c.useMemo(()=>bi(n),[n]),Q=c.useMemo(()=>Hn(d),[d]),He=Q?`${Q.start}:${Q.end}:${Q.keyword}`:"",me=!!(oe||Q&&W!==He),Je=c.useMemo(()=>yc(X,Q?.keyword??"",8),[X,Q?.keyword]),je=c.useMemo(()=>Gn(d),[d]),Fe=je?`${je.start}:${je.end}:${je.keyword}`:"",ue=!!(!me&&(ke||je&&T!==Fe)),he=c.useMemo(()=>tl(g,je?.keyword??"",8),[je?.keyword,g]),Ie=c.useMemo(()=>ll(x),[x]),Re=c.useMemo(()=>dl(x),[x]),Ue=a.find(E=>E.value===p)?.label??(p||x.defaultOption),ge=Ie.find(E=>E.value===i)?.label??i,Oe=Re.find(E=>E.value===m)?.label??m,Ge=a.map(E=>({value:E.value,label:E.label,description:E.desc,icon:ys}));Ge.some(E=>E.value==="")||Ge.unshift({value:"",label:x.defaultOption,description:x.useDaemonDefaultModel,icon:ys}),c.useEffect(()=>{je||(O.current=null,D(""),fe(!1))},[je]),c.useEffect(()=>{Q||(V.current=null,U(""),ce(!1))},[Q]);const Ve=async(E,ye)=>{await M(E),ye.value=""},et=async E=>{E.preventDefault(),ve(!1),B&&await M(E.dataTransfer.files)},qe=async E=>{!B||!E.clipboardData.files.length||await M(E.clipboardData.files)},tt=()=>{const E=el(d,O.current);O.current=null,E!==d&&N(E),Fe&&D(Fe),fe(!1),G.current?.focus()},xe=()=>{const E=kc(d,V.current);V.current=null,E!==d&&N(E),He&&U(He),ce(!1),G.current?.focus()},pe=()=>{if(me){xe();return}U(""),!Hn(d)&&d.length===0&&(V.current={draftBeforeInsertion:d},N("/")),ce(!0),G.current?.focus()},We=E=>{const ye=Hn(d),Me=vc(d,ye,E);N(Me),V.current=null,ce(!1),U(""),G.current?.focus()},rt=()=>{if(ue){tt();return}if(R(),D(""),!Gn(d)){const E=d.length===0||/\s$/.test(d)?"":" ";O.current={draftBeforeInsertion:d,triggerStart:d.length+E.length},N(`${d}${E}$`)}fe(!0),G.current?.focus()},J=E=>{const ye=Gn(d),Me=ye?Xc(d,ye,E.name):d.trim().length?`${d}${/\s$/.test(d)?"":" "}$${E.name} `:`$${E.name} `;N(Me),O.current=null,fe(!1),D(""),G.current?.focus()},te=al({context:me?`command:${He}:${Je.map(E=>E.name).join(",")}`:ue?`skill:${Fe}:${he.map(E=>`${E.source}:${E.name}`).join(",")}`:"",count:me?Je.length:ue?he.length:0,onSelect:E=>me?We(Je[E]):J(he[E]),onClose:me?xe:tt}),Ae=E=>{te.handleKeyDown(E)||E.key!=="Enter"||E.nativeEvent.isComposing||E.nativeEvent.keyCode===229||!(y==="enter"?!E.shiftKey:E.metaKey||E.ctrlKey)||(E.preventDefault(),A())};return r.jsxs("form",{className:`composer ${ne?"dragging":""}`,onDragEnter:E=>{E.preventDefault(),ve(!0)},onDragLeave:()=>ve(!1),onDragOver:E=>E.preventDefault(),onDrop:E=>{et(E)},onSubmit:E=>{A(E)},children:[r.jsx(rl,{queue:e,controls:t,busy:o,t:x,onCancel:j}),Se&&w.length?r.jsx("div",{className:"quick-reply-row",children:w.slice(0,6).map(E=>r.jsx("button",{onClick:()=>N(d?`${d}
|
|
4
|
+
${E}`:E),type:"button",children:E},E))}):null,r.jsx(nl,{visible:ue,skills:he,listId:te.listId,selectedIndex:te.selectedIndex,onHighlight:te.selectIndex,onClose:tt,onSelect:J,t:x}),r.jsx(sl,{visible:me,commands:Je,listId:te.listId,selectedIndex:te.selectedIndex,onHighlight:te.selectIndex,onClose:xe,onSelect:We,t:x}),r.jsx("textarea",{ref:G,"aria-controls":me||ue?te.listId:void 0,"aria-activedescendant":me&&Je.length||ue&&he.length?`${te.listId}-${te.selectedIndex}`:void 0,"aria-autocomplete":"list",value:d,onChange:E=>N(E.target.value),onPaste:E=>{qe(E)},onKeyDown:Ae,placeholder:x.messagePlaceholder,rows:3,disabled:!B}),r.jsxs("div",{className:"composer-toolbar",children:[r.jsxs("div",{className:"composer-leading-controls",children:[r.jsx(cl,{onTranscript:E=>N(d?`${d} ${E}`:E)}),r.jsx("button",{type:"button",className:"icon-button",onClick:()=>F.current?.click(),title:x.uploadFiles,disabled:!B||f,children:r.jsx(Ln,{"aria-hidden":"true"})}),w.length?r.jsx("button",{className:`icon-button ${Se?"selected":""}`,type:"button",title:Se?x.hideQuickReplies:x.showQuickReplies,onClick:()=>ae(E=>!E),children:r.jsx(Qo,{"aria-hidden":"true"})}):null,r.jsx("button",{className:`icon-button ${ue?"selected":""}`,type:"button",title:x.skills,onClick:rt,disabled:!B||f,children:r.jsx(dn,{"aria-hidden":"true"})}),r.jsx("button",{className:`icon-button ${me?"selected":""}`,type:"button",title:x.commands,onClick:pe,disabled:!B||f,children:r.jsx(is,{"aria-hidden":"true"})})]}),r.jsx("input",{ref:F,type:"file",multiple:!0,hidden:!0,onChange:E=>{Ve(E.currentTarget.files,E.currentTarget)}}),r.jsxs("div",{className:"composer-control-strip",children:[r.jsx(Cn,{icon:i==="autoApprove"?dn:Hs,label:ge,menuLabel:x.approvalMode,options:Ie,value:i,onSelect:v,wide:!0}),r.jsx(Cn,{icon:ys,label:Ue,menuLabel:x.model,options:Ge,value:p,onSelect:I,align:"right",wide:!0}),r.jsx(Cn,{icon:Pt,label:Oe||x.effort,menuLabel:x.effort,options:Re,value:m,onSelect:k,align:"right"}),r.jsx(Cn,{icon:dn,label:b?x.fast:x.normal,menuLabel:x.fastMode,options:[{value:"off",label:x.normal,description:x.standardExecution,icon:Pt},{value:"on",label:x.fast,description:x.preferFasterResponses,icon:dn}],value:b?"on":"off",onSelect:E=>C(E==="on"),align:"right",selected:b,wide:!0})]}),r.jsx(il,{connected:B,busy:o,sending:l,responding:u,hasDraft:!!d.trim(),shortcut:y,onStop:h,t:x})]}),s.length||f?r.jsx("div",{className:"attachment-row",children:s.length?r.jsx("div",{className:"attachment-list",children:s.map(E=>r.jsxs("span",{children:[r.jsx(ai,{"aria-hidden":"true"}),E.name||Dt(E.path),r.jsx("small",{children:$c(E.size)}),r.jsx("button",{type:"button",onClick:()=>z(E.path),title:x.removeAttachment,children:r.jsx($e,{"aria-hidden":"true"})})]},E.path))}):r.jsxs("span",{className:"attachment-empty",children:[r.jsx("span",{className:"loading-spinner small","aria-hidden":"true"}),x.uploading]})}):null]})}function hl({cwd:e,paths:t,t:n,onClose:s,onOpenRemoteFile:i}){const a=c.useRef(null),o=Dn(s,a,t.length>0);return t.length?r.jsxs("div",{"aria-labelledby":"attachment-preview-title","aria-modal":"true",className:"side-drawer",ref:o,role:"dialog",tabIndex:-1,children:[r.jsx("button",{className:"side-drawer-backdrop",onClick:s,type:"button","aria-label":n.closeAttachmentPreview}),r.jsxs("aside",{className:"side-drawer-panel",children:[r.jsxs("header",{className:"side-drawer-header",children:[r.jsxs("div",{children:[r.jsx("strong",{id:"attachment-preview-title",children:n.attachments}),r.jsx("span",{children:n.fileCount(t.length)})]}),r.jsx("button",{"aria-label":n.closeAttachmentPreview,className:"icon-button",onClick:s,ref:a,type:"button",children:r.jsx($e,{"aria-hidden":"true"})})]}),r.jsx("div",{className:"stack-list",children:t.map(l=>r.jsxs("button",{className:"data-row attachment-preview-row",onClick:()=>i(l,e),type:"button",children:[r.jsx(ai,{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:Dt(l)}),r.jsx("small",{children:l})]}),r.jsx(Qr,{"aria-hidden":"true"})]},l))})]})]}):null}async function Ys(e){const t=ee().writeClipboardText;if(t)return t(e);try{if(navigator.clipboard?.writeText){await navigator.clipboard.writeText(e);return}}catch{}const n=document.activeElement,s=window.getSelection(),i=s?Array.from({length:s.rangeCount},(l,u)=>s.getRangeAt(u).cloneRange()):[],a=n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement?[n.selectionStart,n.selectionEnd,n.selectionDirection]:void 0,o=document.createElement("textarea");o.value=e,o.setAttribute("readonly",""),o.style.position="fixed",o.style.opacity="0",document.body.append(o);try{if(o.focus({preventScroll:!0}),o.select(),!document.execCommand("copy"))throw new Error("Clipboard copy was rejected")}finally{if(o.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),s){s.removeAllRanges();for(const l of i)s.addRange(l)}}}function Xs(e,t){const[n,s]=c.useState(null),i=c.useRef(null);return c.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]),{copyText:c.useCallback(async o=>{try{await Ys(o),s({message:e,tone:"success"})}catch{s({message:t,tone:"error"})}i.current!==null&&window.clearTimeout(i.current),i.current=window.setTimeout(()=>s(null),2400)},[t,e]),feedback:n}}function er({feedback:e}){if(!e)return null;const t=e.tone==="success"?_t:$e;return r.jsxs("div",{className:`copy-feedback ${e.tone}`,role:"status",children:[r.jsx(t,{"aria-hidden":"true"}),e.message]})}function fl({message:e,retryLabel:t,onRetry:n,onDismiss:s,closeLabel:i}){return r.jsxs("div",{className:"notice error chat-error-notice",role:"alert",children:[s?r.jsx("button",{type:"button",className:"chat-notice-dismiss","aria-label":i,title:i,onClick:s,children:r.jsx($e,{"aria-hidden":"true"})}):r.jsx(ei,{"aria-hidden":"true"}),r.jsx("span",{children:e}),r.jsxs("button",{className:"chat-notice-retry",onClick:n,type:"button",children:[r.jsx(En,{"aria-hidden":"true"}),t]})]})}function ml({label:e}){return r.jsxs("div",{className:"history-loading-state","aria-busy":"true","aria-label":e,role:"status",children:[r.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),r.jsxs("div",{className:"history-loading-copy",children:[r.jsx("strong",{children:e}),r.jsx("span",{"aria-hidden":"true"}),r.jsx("span",{"aria-hidden":"true"}),r.jsx("span",{"aria-hidden":"true"})]})]})}function Ri({failedSend:e,onRetry:t,onDismiss:n,t:s}){const i={network:s.sendFailedNetwork,timeout:s.sendFailedTimeout,permission:s.sendFailedPermission,subscription:s.sendFailedSubscription,"missing-resource":s.sendFailedMissingResource,unknown:s.sendFailedUnknown}[e.kind];return r.jsxs("div",{className:"failed-send-notice",role:"alert",children:[r.jsx(ei,{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:s.sendFailed}),i]}),r.jsxs("button",{disabled:e.retrying,onClick:t,type:"button",children:[r.jsx(En,{"aria-hidden":"true",className:e.retrying?"spin":void 0}),e.retrying?s.retrying:s.retrySend]}),n&&r.jsx("button",{className:"chat-notice-dismiss",onClick:n,type:"button","aria-label":s.close,title:s.close,children:r.jsx($e,{"aria-hidden":"true"})})]})}function pl({label:e,onClick:t}){return r.jsx("button",{className:"scroll-latest-button",type:"button","aria-label":e,title:e,onClick:t,children:r.jsx(Na,{"aria-hidden":"true"})})}function gl({activeSession:e,busy:t,errorText:n,failedSend:s,failedSendVisibleInConversation:i,onClearInterrupt:a,onDismissError:o,onDismissFailedSend:l,onRetry:u,onRetryFailedSend:h,t:d}){return r.jsxs("div",{className:"chat-notices","aria-live":"polite",children:[n?r.jsx(fl,{message:n,retryLabel:d.retry,onRetry:u,closeLabel:d.close,onDismiss:o}):null,s&&!i?r.jsx(Ri,{failedSend:s,onRetry:h,onDismiss:l,t:d}):null,e?.interruptReason?r.jsxs("div",{className:"notice warning",children:[r.jsx(dn,{"aria-hidden":"true"}),r.jsx("span",{children:e.interruptReason.humanText||e.interruptReason.kind}),r.jsx("button",{className:"icon-text-button",disabled:t,onClick:a,type:"button",children:d.clear})]}):null,e?.stallWarning?r.jsxs("div",{className:"notice warning",children:[r.jsx(za,{"aria-hidden":"true"}),r.jsx("span",{children:e.stallWarning.humanText||d.agentMayBeStalled})]}):null]})}function Ai({title:e,draft:t,label:n,disabled:s,onDraftChange:i,onCommit:a}){const[o,l]=c.useState(!1),u=c.useRef(null),h=c.useRef(null),d=c.useRef(!1),m=c.useRef(!1);c.useLayoutEffect(()=>{o?(u.current?.focus(),u.current?.select()):d.current&&(d.current=!1,h.current?.focus()),o||(m.current=!1)},[o]);const b=()=>{d.current=!0,l(!1)};return o?r.jsx("input",{ref:u,className:"inline-session-title-input","aria-label":n,value:t,onChange:p=>i(p.target.value),onBlur:()=>{m.current||(t.trim()&&t.trim()!==e&&a(),l(!1))},onKeyDown:p=>{p.nativeEvent.isComposing||p.keyCode===229||(p.key==="Enter"?(p.preventDefault(),m.current=!0,t.trim()&&t.trim()!==e&&a(),b()):p.key==="Escape"&&(p.preventDefault(),p.stopPropagation(),m.current=!0,b()))}}):r.jsx("button",{ref:h,type:"button",className:"inline-session-title-button",title:e,"aria-label":`${n}: ${e}`,disabled:s,onClick:()=>{i(e),l(!0)},children:e})}const Mi=c.createContext(null);function yl({matchCount:e,query:t,onChange:n,onNext:s,onClose:i,t:a}){return r.jsxs("div",{className:"message-search-bar",id:"conversation-message-search",children:[r.jsx(Rn,{"aria-hidden":"true"}),r.jsx("input",{autoFocus:!0,"aria-label":a.searchThisSession,value:t,onChange:o=>n(o.target.value),onKeyDown:o=>{o.key==="Enter"&&s(),o.key==="Escape"&&(o.preventDefault(),i())},placeholder:a.searchThisSession}),r.jsx("span",{children:t.trim()?a.messageSearchMatches(e):a.allMessages}),r.jsx("button",{"aria-label":a.clearMessageSearch,className:"icon-button mini-button",onClick:i,type:"button",children:r.jsx($e,{"aria-hidden":"true"})})]})}function bl({activeSession:e,agent:t,cwd:n,t:s,onOpenDetails:i,onScrollToStart:a,renameTitle:o,busy:l,onRename:u,onRenameTitleChange:h,onViewChanges:d,search:m}){const[b,p]=c.useState(!1),S=c.useRef(null);c.useEffect(()=>{m.query&&p(!0)},[m.query]);const w=()=>{m.onChange(""),p(!1),S.current?.focus()},y=e?It(e):s.newSession,g=e?.cwd??(n.trim().length>0&&n!=="."?n:""),f=e?.agent??t,x=c.useContext(Mi),v=ee().toolbarTarget?.("conversation")??x,j=r.jsxs("div",{className:"chat-header-title-row",onClick:N=>{N.target instanceof Element&&N.target.closest('button,a,input,textarea,[contenteditable="true"]')||a()},children:[r.jsxs("div",{className:"chat-title-block",children:[r.jsxs("span",{className:"chat-title-line",children:[r.jsx("button",{className:`agent-status-pill chat-session-details-button ${f}`,type:"button",onClick:i,"aria-label":s.details,title:s.details,disabled:!e,children:f==="codex"?"Codex":"Claude"}),r.jsx("h1",{children:e?r.jsx(Ai,{title:y,draft:o,label:s.rename,disabled:l,onDraftChange:h,onCommit:u},e.sessionId):y})]}),g?r.jsx("p",{title:g,children:g}):null,e?.branch||e?.diffStat?r.jsxs("div",{className:"header-metadata",children:[e.branch?r.jsx("span",{children:e.branch}):null,e.runtime.state?r.jsx("span",{children:s.runtimeState(e.runtime.state)}):null,e.terminal?.mode?r.jsx("span",{children:e.terminal.mode}):null]}):null]}),r.jsx("button",{"aria-label":s.scrollToConversationStart,className:"chat-scroll-start-target",onClick:a,title:s.scrollToConversationStart,type:"button"}),e?r.jsxs("button",{className:"chat-changes-button",type:"button","aria-label":s.viewChanges,title:s.viewChanges,onClick:()=>d(e.sessionId),children:[r.jsx(ss,{"aria-hidden":"true"}),e.diffStat&&(e.diffStat.additions>0||e.diffStat.deletions>0)?r.jsxs("span",{className:"chat-changes-summary","aria-hidden":"true",children:[r.jsxs("span",{className:"diff-add",children:["+",e.diffStat.additions]}),r.jsxs("span",{className:"diff-del",children:["−",e.diffStat.deletions]})]}):null]}):null,r.jsx("button",{ref:S,className:"icon-button chat-search-toggle",type:"button","aria-label":s.searchThisSession,title:s.searchThisSession,"aria-expanded":b,"aria-controls":"conversation-message-search",onClick:()=>b?w():p(!0),children:r.jsx(Rn,{"aria-hidden":"true"})})]});return r.jsxs("header",{className:`chat-header chat-search-header ${v?"chat-header-in-titlebar":""}`,children:[v?dt.createPortal(j,v):j,b&&r.jsx(yl,{...m,t:s,onClose:w})]})}const vl=/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,xl=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\u00AD\u061C\u180E\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g,wl=new Set(["","{}","[]","null","undefined",'""']);function Bn(e){return e.replace(/\s+/g," ").trim()}function Le(e,t){return typeof e[t]=="string"?e[t]:""}function wr(e,t){return typeof e[t]=="number"?e[t]:void 0}function Sn(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function xs(e){const t=[],n=Le(e,"file_path")||Le(e,"filePath");n&&t.push({label:"Path",value:n,isFilePath:!0});const s=wr(e,"offset"),i=wr(e,"limit");if(s!==void 0||i!==void 0){const a=[];s!==void 0&&a.push(`line ${s+1}`),i!==void 0&&a.push(`to ${s!==void 0?s+i:i}`),t.push({label:"Range",value:a.join(" ")})}return t}function Sl(e){return typeof e!="string"?"":e.replace(/\r\n?/g,`
|
|
5
|
+
`).replace(vl,"").replace(xl,"").trim()}function tr(e){const t=Sl(e);return wl.has(t)?"":t}function kl(e){return tr(e).length>0}function nr(e){const t=tr(e);if(!t)return"";try{const n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)){const s=typeof n.query=="string"?Bn(n.query):"";if(s)return s;const i=typeof n.command=="string"?Bn(n.command):"";if(i)return i;const a=typeof n.description=="string"?Bn(n.description):"";if(a)return a}}catch{}return Bn(t)}function jl(e,t){if(!t)return[];switch((e??"").toLowerCase()){case"read":return xs(t);case"write":{const s=xs(t),i=Le(t,"content");return i&&s.push({label:"Content",isDiff:!0,value:"",diffNew:Sn(i,500)}),s}case"edit":{const s=xs(t),i=Le(t,"old_string")||Le(t,"oldString"),a=Le(t,"new_string")||Le(t,"newString");return(i||a)&&s.push({label:"Change",isDiff:!0,value:"",diffOld:Sn(i,300),diffNew:Sn(a,300)}),s}case"bash":{const s=Le(t,"command");return s?[{label:"Command",value:s,isCode:!0}]:[]}case"websearch":{const s=Le(t,"query");return s?[{label:"Query",value:s}]:[]}case"webfetch":{const s=[],i=Le(t,"url");i&&s.push({label:"URL",value:i});const a=Le(t,"prompt");return a&&s.push({label:"Prompt",value:Sn(a,200)}),s}case"glob":{const s=Le(t,"pattern");return s?[{label:"Pattern",value:s}]:[]}case"grep":{const s=[],i=Le(t,"pattern");i&&s.push({label:"Pattern",value:i,isCode:!0});const a=Le(t,"path");return a&&s.push({label:"In",value:a,isFilePath:!0}),s}default:{const s=[],i=Le(t,"command");if(i)return[{label:"Command",value:i,isCode:!0}];const a=Le(t,"file_path")||Le(t,"filePath");a&&s.push({label:"Path",value:a,isFilePath:!0});const o=Le(t,"description");o&&s.push({label:"Description",value:Sn(o,200)});const l=Le(t,"query");l&&s.push({label:"Query",value:l});const u=Le(t,"url");return u&&s.push({label:"URL",value:u}),s}}}function Sr(e){return e.role==="tool"?!0:e.type!=="info"?!1:!/^Error:/i.test(e.content.trim())}function Ti(e){const t=[];for(const s of e){const i=s.toolName?.trim();i&&!t.includes(i)&&t.push(i)}return t.length?t.join(", "):e.map(s=>nr(s.content)).find(Boolean)??""}function Pi(e,t){return`${e.historyKey??e.timestamp??e.toolName??e.content.slice(0,24)??"message"}:${t}`}function Cl(e){const t=[];for(let n=0;n<e.length;n+=1){const s=e[n];if(!Sr(s)){t.push({type:"message",index:n,message:s});continue}const i=[];let a=n;for(;a<e.length&&Sr(e[a]);)i.push({index:a,message:e[a]}),a+=1;t.push({type:"toolGroup",entries:i,id:`tool-group:${i.map(({index:o,message:l})=>Pi(l,o)).join("|")}`}),n=a-1}return t}function Il(e,t){return e.type==="message"?e.index===t:e.entries.some(n=>n.index===t)}function Nl(e,t){const n=t.trim().toLowerCase();return n?e.map((s,i)=>({index:i,message:s})).filter(({message:s})=>s.content.toLowerCase().includes(n)):[]}function El(e){const t=e.at(-1);return t?`${e.length}:${t.historyKey??""}:${t.timestamp??""}:${t.content.length}`:"0"}function Rl(e,t,n,s,i,a,o,l=0){const u=()=>{const h=t.current||s.current;n.current=null,s.current=!1,t.current=!1,i.current=performance.now();const d=e.current;a.current=d?.scrollTop??0,h&&d?.scrollTo({top:d.scrollTop,behavior:"auto"})};return{toStart:()=>{const h=e.current;h&&(n.current=null,s.current=!1,t.current=!1,i.current=performance.now(),a.current=0,h.scrollTo({top:h.scrollTop,behavior:"auto"}),l>0&&o?.(),requestAnimationFrame(()=>requestAnimationFrame(()=>e.current?.scrollTo({top:0,behavior:l>0?"auto":"smooth"}))))},onWheel:h=>{if(!h.deltaY)return;const d=e.current;(h.deltaY<0||d&&d.scrollHeight-d.scrollTop-d.clientHeight>2)&&u()},onPointerDown:h=>{const d=h.currentTarget.getBoundingClientRect();(h.button===1||h.clientX>=d.right-16)&&u()},onTouchStart:u,onKeyDown:h=>{h.target instanceof Element&&h.target.closest('input,textarea,[contenteditable="true"]')||["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(h.key)&&u()}}}function Al(e,t,n){const s=i=>i?.some(a=>a.localClientMessageId===n||a.historyKey===`client:${n}`);return s(e[t])?t:Object.entries(e).find(([,i])=>s(i))?.[0]??t}function Ml(e,t,n,s){const i=e.findIndex(o=>o.localClientMessageId===t||o.historyKey===`client:${t}`),a=e.slice();if(i<0)s&&a.push({role:"user",...s,timestamp:new Date().toISOString(),historyKey:`client:${t}`,localClientMessageId:t,localDelivery:n});else{const o=e[i],l=o.delivery==="accepted"||o.historyKey&&!o.historyKey.startsWith("client:");a[i]={...o,localClientMessageId:t,localDelivery:l&&n==="failed"?"delivered":n}}return a}function Tl(e,t){const n=e.delivery==="accepted"?"delivered":e.localDelivery;if(e.role!=="user"||!n)return null;const s=t.browser==="浏览器"?{sending:"发送中",delivered:"已送达",failed:"未确认送达",hint:"配对电脑已接收,可能仍在等待处理。"}:t.browser==="瀏覽器"?{sending:"傳送中",delivered:"已送達",failed:"未確認送達",hint:"配對電腦已接收,可能仍在等待處理。"}:{sending:"Sending",delivered:"Delivered",failed:"Delivery unconfirmed",hint:"Received by the paired computer; processing may still be pending."};return{state:n,label:s[n],title:n==="delivered"?s.hint:s[n]}}const Pl={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 Mn(){return Pl[Ye(Xe().language)]}const Ms="vibelet:image-gallery";function Dl(e){window.dispatchEvent(new CustomEvent(Ms,{detail:e}))}const _l="(?:png|jpg|jpeg|gif|webp|svg|heic|heif)",Ll="(?:~/|/|\\.{1,2}/|[A-Za-z0-9._-]+/)",$l="[^\\n`<>\"')\\]},。!?;:、]*?",Fl="(?::\\d+(?::\\d+)?|#[^\\s`<>\"')\\]},。!?;:、]+)?",Ol=`${Ll}${$l}\\.${_l}${Fl}`,kr=new RegExp(`(${Ol})`,"gi"),ql=[".png",".jpg",".jpeg",".gif",".webp",".svg",".heic",".heif"],Ts="\\s`<>\"')\\]},。!?;:、",jr="`<>\"')\\]},。!?;:、\\n\\r\\t",Wl=new RegExp(`(^|[\\s([{>])((?:~\\/|\\/|\\.{1,2}\\/)[^${Ts}]+|[A-Za-z0-9._-]+(?:\\/[A-Za-z0-9._-]+)+(?:\\.[A-Za-z0-9._-]+)?\\/?)`,"g"),zl=new RegExp(`(^|[\\s([{>])((?=[^${jr}]*\\/)[^${jr}]+?\\.[A-Za-z0-9._-]+(?::\\d+(?::\\d+)?|#[^${Ts}]+)?)(?=$|[${Ts}])`,"g");function Ps(e){let t=e;for(;/[.,!?;:,。!?;:、]+$/.test(t);)t=t.slice(0,-1);return t}function Ds(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 os(e){let t=Ps(e.trim());if(!t)return"";const n=t.indexOf("#");if(n>0){const i=t.slice(0,n);Ds(i,{allowBareFilename:!0})&&(t=i)}const s=t.match(/^(.*?)(:\d+(?::\d+)?)$/);if(s){const i=s[1]??"";Ds(i,{allowBareFilename:!0})&&(t=i)}return Ps(t)}function Bl(e,t){return e.start<t.end&&t.start<e.end}function _s(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 Hl(e){if(_s(e.rawCandidate))return e;const t=e.rawCandidate.indexOf("/");if(t<=0)return e;const n=e.rawCandidate.slice(0,t);for(let s=n.indexOf(" ");s>=0;s=n.indexOf(" ",s+1)){const i=s+1,a=e.rawCandidate.slice(i);if(_s(a))return{start:e.start+i,end:e.end,rawCandidate:a}}return e}function Kl(e){const t=[];for(const n of e.matchAll(Wl)){const s=n[1]??"",i=n[2]??"",o=(n.index??0)+s.length;t.push({start:o,end:o+i.length,rawCandidate:i})}for(const n of e.matchAll(zl)){const s=n[1]??"",i=n[2]??"",o=(n.index??0)+s.length,l=Hl({start:o,end:o+i.length,rawCandidate:i}),u=t.filter(h=>Bl(h,l));if(u.length===0){t.push(l);continue}if(_s(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,s)=>n.start-s.start||n.end-s.end)}function sr(e,t){const n=os(e);return Ds(n,t)}function rr(e){const t=os(e).toLowerCase();return sr(t,{allowBareFilename:!0})&&ql.some(n=>t.endsWith(n))}function Ul(e){if(!e)return[];const t=[];let n=0;for(const s of Kl(e)){s.start>n&&t.push({type:"text",value:e.slice(n,s.start)});const i=Ps(s.rawCandidate),a=os(i),o=s.rawCandidate.slice(i.length);sr(i)&&!rr(i)?(t.push({type:"path",value:i,target:a||i}),o&&t.push({type:"text",value:o})):t.push({type:"text",value:s.rawCandidate}),n=s.end}return n<e.length&&t.push({type:"text",value:e.slice(n)}),t.length>0?t:[{type:"text",value:e}]}const Gl=/^[a-z][a-z0-9+.-]*:/i,Vl=/^[a-z]:[\\/]/i,Di=/\.(?:md|markdown)$/i,_i="https://vibelet.local",Li="/__vibelet_markdown__",Ql=`${_i}${Li}`;function Zl(e){try{return decodeURIComponent(e)}catch{return e}}function $i(e){const t=e?.trim()??"";if(!t||t.startsWith("#")||t.startsWith("//"))return null;const n=Jl(t);if(n)return n;if(Gl.test(t)&&!Vl.test(t))return null;const s=t.split(/[?#]/,1)[0]??"";return Di.test(s)?Zl(s):null}function Yf(e){const t=e.split(`
|
|
6
|
+
`);let n=null;return t.map(s=>{const i=s.match(/^ {0,3}(`{3,}|~{3,})/);if(i){const a=i[1][0];return n===a?n=null:n||(n=a),s}return n?s:Yl(s)}).join(`
|
|
7
|
+
`)}function Jl(e){let t;try{t=new URL(e)}catch{return null}if(t.origin!==_i||t.pathname!==Li)return null;const n=t.searchParams.get("path");return!n||!Di.test(n)?null:n}function Yl(e){let t="",n=0;for(;n<e.length;){if(e[n]==="`"){const s=Xl(e,n);t+=e.slice(n,s),n=s;continue}if(e[n]==="["&&e[n-1]!=="!"){const s=ed(e,n);if(s){t+=s.text,n=s.end;continue}}t+=e[n],n+=1}return t}function Xl(e,t){let n=0;for(;e[t+n]==="`";)n+=1;const s="`".repeat(n),i=e.indexOf(s,t+n);return i<0?e.length:i+n}function ed(e,t){const n=td(e,t);if(n<0||e[n+1]!=="(")return null;const s=n+2,i=nd(e,s);if(i<0)return null;const a=e.slice(s,i),o=sd(a);return o?{text:`${e.slice(t,s)}${o})`,end:i+1}:null}function td(e,t){let n=!1;for(let s=t+1;s<e.length;s+=1){const i=e[s];if(n){n=!1;continue}if(i==="\\"){n=!0;continue}if(i==="]")return s}return-1}function nd(e,t){let n=!1;for(let s=t;s<e.length;s+=1){const i=e[s];if(n){n=!1;continue}if(i==="\\"){n=!0;continue}if(i===")")return s}return-1}function sd(e){const t=e.match(/^\s*/)?.[0]??"",n=e.match(/\s*$/)?.[0]??"",s=e.slice(t.length,e.length-n.length);if(s.startsWith("<")){const o=s.indexOf(">");if(o<0)return null;const l=s.slice(1,o),u=Cr(l);return u?`${t}<${u}>${s.slice(o+1)}${n}`:null}const i=s.match(/^(\S+)([\s\S]*)$/);if(!i)return null;const a=Cr(i[1]);return a?`${t}${a}${i[2]}${n}`:null}function Cr(e){const t=$i(e);return t?`${Ql}?path=${encodeURIComponent(t)}`:null}const Fi="https://vibelet.local/__vibelet_file__";function Tn(e){if(!e)return null;const t=$i(e);if(t)return t;let n=e.trim();if(n.startsWith(Fi))try{const s=new URL(n);if(s.origin!=="https://vibelet.local"||s.pathname!=="/__vibelet_file__")return null;n=s.searchParams.get("path")??""}catch{return null}else if(/^file:\/\//i.test(n))try{const s=new URL(n);if(s.hostname&&s.hostname!=="localhost")return null;n=s.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=os(n),sr(n,{allowBareFilename:!0})?n:null}const Ls=e=>`${Fi}?path=${encodeURIComponent(e)}`;function Oi(e){return e.value??e.children?.map(Oi).join("")??""}function rd(e){const t=[],n=new RegExp(`(?:file://(?:localhost)?(?=/))?${kr.source}`,kr.flags);let s=0;const i=a=>{for(const o of Ul(a))t.push(o.type==="path"?{type:"link",url:Ls(o.target??o.value),children:[{type:"text",value:o.value}]}:{type:"text",value:o.value})};for(const a of e.matchAll(n)){const o=Tn(a[0]);!o||!rr(o)||(i(e.slice(s,a.index)),t.push({type:"image",url:Ls(o),alt:o.split(/[\\/]/).at(-1)}),s=a.index+a[0].length)}return i(e.slice(s)),t}function Xf(){return e=>{const t=n=>{if(n.type==="link"||n.type==="image"){const s=Tn(n.url);s&&(n.url=Ls(s),rr(s)&&(n.alt=n.alt||Oi(n)||s.split(/[\\/]/).at(-1),n.type="image",delete n.children));return}!n.children||["code","inlineCode","html"].includes(n.type)||(n.children=n.children.flatMap(s=>s.type==="text"?rd(s.value??""):(t(s),[s])))};t(e)}}const qi="pair",tn="vibelet.web.pairing",Ir="vibelet.web.deviceId";class Pn extends Error{constructor(t,n){super(n),this.code=t,this.name="PairingCreateError"}}function ir(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function id(e){const t=e.replace(/-/g,"+").replace(/_/g,"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return decodeURIComponent(Array.from(atob(n),s=>`%${s.charCodeAt(0).toString(16).padStart(2,"0")}`).join(""))}function ad(e){const[t,n,s,i,a,o]=e;return!n||!Number.isFinite(s)||s<=0?null:{kind:t==="relay"?"relay":"direct",host:n,port:Math.floor(s),source:i,stability:a,...o===!0?{secure:!0}:{}}}function od(e){if(!ir(e))return null;const{kind:t,host:n,port:s,source:i,stability:a,secure:o}=e;return t!=="direct"&&t!=="relay"||typeof n!="string"||!n.trim()||typeof s!="number"||!Number.isFinite(s)||s<=0||typeof i!="string"||typeof a!="string"?null:{kind:t,host:n.trim(),port:Math.floor(s),source:i,stability:a,...o===!0?{secure:!0}:{}}}function cd(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[s,i]=n;return s===10||s===172&&i>=16&&i<=31||s===192&&i===168}function Wi(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 s=n.map(Number);return s.every(i=>i>=0&&i<=255)&&s[0]===127}function ld(e){const t=e.trim();return t.includes(":")&&!t.startsWith("[")?`[${t}]`:t}function dd(e,t){return t.protocol==="https:"&&e.secure!==!0?null:`${e.secure===!0?"wss":"ws"}://${ld(e.host)}:${e.port}`}function Nr(e){return cd(e.host)?0:e.source==="local_network"?1:e.source==="configured_host"?2:3}function ud(e,t){const n=t?.port??e.port,s=t?.canonicalHost??e.canonicalHost;if(!s||typeof n!="number"||!Number.isFinite(n))return[];const i=Math.floor(n);return[{kind:"direct",host:s,port:i,source:"fallback",stability:"stable"},...[...t?.fallbackHosts??[],...e.fallbackHosts??[]].map(a=>({kind:"direct",host:a,port:i,source:"fallback",stability:"stable"}))]}function hd(e,t,n=window.location,s=!0){if(s&&Wi(n.hostname))return;const i=[...t?.connections??[],...e.connections??[],...ud(e,t)].map(od).filter(a=>!!a).filter(a=>a.kind==="direct").sort((a,o)=>Nr(a)-Nr(o));for(const a of i){const o=dd(a,n);if(o)return o}}function fd(e){if(!e.d||!e.c)return null;const t=Array.isArray(e.o)?e.o.map(ad).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 md(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 pd(e=window.location.hash){const t=e.startsWith("#")?e.slice(1):e,n=new URLSearchParams(t).get(qi);if(!n)return null;try{const s=JSON.parse(id(n));if(!ir(s))return null;if(s.t==="vp")return fd(s);if(s.type==="vibelet-pair")return md(s)}catch{return null}return null}function gd(){if(!window.location.hash.includes(`${qi}=`))return;const e=`${window.location.pathname}${window.location.search}`;window.history.replaceState(null,"",e)}function yd(e=Ze()){const t=e.getItem(Ir);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(Ir,n),n}function Er(e){const t=e.getItem(tn);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 ar(e){if(typeof window>"u")return null;try{return e===Ze()?window.sessionStorage:null}catch{return null}}function or(e=Ze(),t=ar(e)){const n=Er(e);if(n)return n;const s=t?Er(t):null;return s?(e.setItem(tn,JSON.stringify(s)),t?.removeItem(tn),s):null}function Rr(e,t=Ze(),n=ar(t)){t.setItem(tn,JSON.stringify(e)),n?.removeItem(tn)}function zi(e=Ze(),t=ar(e)){e.removeItem(tn),t?.removeItem(tn)}function bd(e,t=Date.now()){if(!e.expiresAt)return!1;const n=new Date(e.expiresAt).getTime();return Number.isFinite(n)&&n<t}async function vd(e){const t=await e.text().catch(()=>"");try{const n=JSON.parse(t);if(ir(n)&&n.error==="pair_window_expired")return new Pn("pair_window_expired","Pairing link expired.")}catch{}return new Pn("pairing_failed",t||"Pairing failed.")}async function xd(e,t=yd()){if(bd(e))throw new Pn("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 vd(n);const s=await n.json();return{daemonId:s.daemonId,displayName:s.displayName||e.displayName,deviceId:s.deviceId,pairToken:s.pairToken,pairedAt:new Date().toISOString(),webSocketUrl:hd(e,s,window.location,!0)}}async function wd(e,t){try{return await xd(e,t?.deviceId)}catch(n){if(n instanceof Pn&&n.code==="pair_window_expired"&&t?.daemonId===e.daemonId)return t;throw n}}const Ar=20*1024*1024;class Sd{constructor(t=128,n=64*1024*1024,s=3e4){this.maxEntries=t,this.maxBytes=n,this.ttl=s}scope="";bytes=0;entries=new Map;get(t,n,s){this.scope!==t&&(this.entries.clear(),this.bytes=0,this.scope=t);for(const[o,l]of this.entries)l.expires<=Date.now()&&this.remove(o,l);const i=this.entries.get(n);if(i)return this.entries.delete(n),this.entries.set(n,i),i.promise;const a={promise:Promise.resolve(new Blob),bytes:0,expires:1/0};return a.promise=Promise.resolve().then(s).then(o=>(this.entries.get(n)===a&&(a.bytes=o.size,a.expires=Date.now()+this.ttl,this.bytes+=o.size,this.trim()),o),o=>{throw this.remove(n,a),o}),this.entries.set(n,a),this.trim(),a.promise}remove(t,n){this.entries.get(t)===n&&(this.entries.delete(t),this.bytes-=n.bytes)}trim(){for(;this.entries.size>this.maxEntries||this.bytes>this.maxBytes;){const t=this.entries.entries().next().value;if(!t)return;this.remove(...t)}}}const kd=new Sd;function jd(e,t){return kd.get(t,e,async()=>{const n=await fetch(e,{headers:{authorization:`Bearer ${t}`}});if(!n.ok||Number(n.headers.get("content-length"))>Ar)throw new Error("Image unavailable");const s=await n.blob();if(!s.type.startsWith("image/")||s.size>Ar)throw new Error("Unsupported image");return s})}function Cd(e,t,n=1600){const s=Tn(e),i=or(),[a,o]=c.useState(null),[l,u]=c.useState(null);return c.useEffect(()=>{if(!s)return;const m=new AbortController;let b;return o(null),u(null),(async()=>{try{if(!i)throw new Error("No pairing");const S=new URL(Un(s,t));n!==null&&S.searchParams.set("w",String(n));const w=await jd(S.toString(),i.pairToken);if(m.signal.aborted)return;b=URL.createObjectURL(w),o({src:e,url:b})}catch{m.signal.aborted||u(e)}})(),()=>{m.abort(),b&&URL.revokeObjectURL(b)}},[e,s,t,n,i?.pairToken,i?.webSocketUrl]),{url:s?a?.src===e?a.url:void 0:e,error:l===e,fail:()=>u(e)}}function Id({src:e,alt:t,cwd:n,onOpen:s,gallery:i}){const a=Tn(e),{url:o,error:l,fail:u}=Cd(e,n),h=js[Ye(Xe().language)],d=t||Dt(a??e);return r.jsx("button",{className:"message-image-preview",type:"button",title:a??e,"aria-label":`${h.preview}: ${d}`,onClick:async m=>{m.preventDefault(),m.stopPropagation();const b=await i?.()??[{src:e,alt:d,cwd:n}],p=b.findIndex(S=>S.src===e||a&&Tn(S.src)===a);Dl({images:p<0?[{src:e,alt:d,cwd:n}]:b,index:Math.max(0,p),onOpen:s})},children:l?r.jsxs("span",{className:"message-image-placeholder",children:[r.jsx(go,{"aria-hidden":"true"}),d," · ",h.fileOpenFailed]}):o?r.jsx("img",{src:o,alt:d,loading:"lazy",onError:u}):r.jsxs("span",{className:"message-image-placeholder",children:[r.jsx(rs,{className:"session-running-icon","aria-hidden":"true"}),d]})})}function Nd({message:e,t}){return r.jsx("pre",{className:"message-markdown-source",role:"region","aria-label":t.markdownSource,children:e.content})}function Ed({field:e}){return e.isDiff?r.jsxs("div",{className:"tool-field diff",children:[r.jsx("span",{children:e.label}),e.diffOld?r.jsxs("pre",{className:"tool-diff old",children:[r.jsx("b",{children:"-"}),e.diffOld]}):null,e.diffNew?r.jsxs("pre",{className:"tool-diff new",children:[r.jsx("b",{children:"+"}),e.diffNew]}):null]}):r.jsxs("div",{className:`tool-field ${e.isCode?"code":""} ${e.isFilePath?"path":""}`,children:[r.jsx("span",{children:e.label}),r.jsx("pre",{children:e.value})]})}function Rd({message:e,onCopy:t,t:n}){const s=jl(e.toolName,e.toolInput),i=nr(e.content),a=tr(e.content),o=kl(e.content)&&!s.length,l=e.toolName??n.tool;return r.jsxs("section",{className:"tool-detail-card",children:[r.jsxs("header",{children:[r.jsx("span",{className:"tool-detail-icon",children:r.jsx(Ks,{"aria-hidden":"true"})}),r.jsxs("div",{children:[r.jsx("strong",{children:l}),i?r.jsx("small",{title:i,children:i}):null]}),r.jsx("button",{className:"icon-button",onClick:()=>t(e.content),type:"button",title:n.copyOutput,children:r.jsx(mn,{"aria-hidden":"true"})})]}),s.length?r.jsx("div",{className:"tool-fields",children:s.map((u,h)=>r.jsx(Ed,{field:u},`${u.label}:${h}`))}):null,o?r.jsx("pre",{className:"json-box compact",children:a}):null]})}function Bi({messages:e,showHeader:t=!0,onClose:n,onCopy:s,t:i}){if(!e.length)return null;const o=e.filter(d=>d.role==="tool").length||e.length,l=i.toolCallCount(o),u=Ti(e),h=e.map(d=>d.content).join(`
|
|
8
|
+
|
|
9
|
+
`);return r.jsxs("section",{className:"tool-inline-panel","aria-label":i.toolDetails,children:[t?r.jsxs("header",{className:"inline-detail-header",children:[r.jsxs("div",{className:"inline-detail-title",children:[r.jsx("strong",{children:l}),r.jsx("span",{title:u,children:u||i.toolDetail})]}),r.jsxs("div",{className:"row-actions",children:[r.jsx("button",{className:"icon-button",onClick:()=>s(h),type:"button",title:i.copyOutput,children:r.jsx(mn,{"aria-hidden":"true"})}),r.jsx("button",{className:"icon-button",onClick:n,type:"button",title:i.closeToolDetails,children:r.jsx($e,{"aria-hidden":"true"})})]})]}):null,r.jsx("div",{className:"tool-detail-list",children:e.map((d,m)=>r.jsx(Rd,{message:d,onCopy:s,t:i},`${d.historyKey??d.timestamp??d.toolName??"tool"}:${m}`))})]})}const Ad=c.lazy(async()=>at(()=>import("./mermaid-O7DHMXV3-D-5FgaAx.js").then(e=>e.b),__vite__mapDeps([0,1,2,3,4])).then(e=>({default:e.MessageMarkdown})));function Hi({label:e}){return r.jsxs("span",{className:"message-replying-indicator","aria-label":e,role:"status",children:[r.jsxs("span",{"aria-hidden":"true",className:"message-replying-dots",children:[r.jsx("i",{}),r.jsx("i",{}),r.jsx("i",{})]}),r.jsx("span",{children:e})]})}function Md({activeMatch:e,baseCwd:t,message:n,onCopy:s,onRewind:i,onCloseTool:a,onOpenAttachment:o,onOpenRemoteFile:l,onToggleSource:u,onToggleTool:h,sourceOpen:d,toolOpen:m,replying:b,t:p}){const S=Tl(n,p),w=n.role==="tool"?nr(n.content):"";return r.jsxs("article",{className:`message ${n.role} ${n.type==="info"?"info":""} ${e?"match":""}`,children:[r.jsxs("div",{className:"message-meta",children:[r.jsx("span",{children:ji(n,p)}),r.jsxs("div",{className:"message-meta-side",children:[S&&r.jsx("span",{className:"message-delivery","data-state":S.state,role:"status",title:S.title,children:S.label}),r.jsx("time",{children:as(n.timestamp,Date.now(),p)})]})]}),d?r.jsx(Nd,{message:n,t:p}):n.role==="tool"?r.jsxs("button",{className:"tool-inline-summary","aria-expanded":m,onClick:h,type:"button",children:[r.jsxs("span",{children:[r.jsx(rc,{"aria-hidden":"true"}),n.toolName??p.tool]}),w?r.jsx("small",{children:w}):null]}):n.role==="assistant"||n.role==="user"?r.jsx(c.Suspense,{fallback:r.jsx("pre",{children:n.content}),children:r.jsx(Ad,{baseCwd:t,content:n.images?.length?n.content.replace(/(?:^|\n)\[Attached image: [^\n]+\](?=\n|$)/g,"").trim():n.content,onOpenRemoteFile:l,additionalImages:n.images})}):r.jsx("pre",{children:n.content}),n.images?.length?r.jsxs("div",{className:"message-image-attachments",children:[n.images.map(y=>r.jsx(Id,{src:y,cwd:t,onOpen:l,gallery:async()=>[...(await at(async()=>{const{collectMessageImages:g}=await import("./collectMessageImages-lfAaZW_Y.js").then(f=>f.q);return{collectMessageImages:g}},[])).collectMessageImages(n.content,t),...(n.images??[]).map(g=>({src:g,cwd:t}))]},y)),r.jsxs("button",{className:"file-pill",onClick:()=>o(n.images??[]),type:"button",children:[r.jsx(Ya,{"aria-hidden":"true"}),p.preview]})]}):null,n.role==="tool"&&m?r.jsx(Bi,{messages:[n],onClose:a,onCopy:s,t:p}):null,b&&r.jsx(Hi,{label:p.replyingMessage}),r.jsxs("div",{className:"message-actions","aria-label":p.messageActions,role:"group",children:[i&&n.role==="user"&&n.type!=="info"&&r.jsx("button",{type:"button",onClick:i,title:Mn().rewind,"aria-label":Mn().rewind,children:r.jsx(ci,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":p.copyMessage,onClick:()=>s(n.content),title:p.copyMessage,type:"button",children:r.jsx(mn,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":p.viewMarkdownSource,"aria-expanded":d,onClick:u,title:d?p.hideMarkdownSource:p.viewMarkdownSource,type:"button",children:r.jsx(Ha,{"aria-hidden":"true"})})]})]})}function Td({activeMatch:e,expanded:t,messages:n,onToggle:s}){const i=n.filter(l=>l.role==="tool").length||n.length,a=Ti(n),o=i===1?"1 tool call":`${i} tool calls`;return r.jsx("button",{className:`tool-group-bubble ${e?"match":""} ${t?"expanded":""}`,type:"button",onClick:s,"aria-expanded":t,"aria-label":a?`${o}: ${a}`:o,children:r.jsxs("span",{className:"tool-group-header",children:[r.jsxs("span",{className:"tool-group-title",children:[r.jsx(Xr,{className:"tool-group-chevron","aria-hidden":"true"}),r.jsx("strong",{children:o})]}),a?r.jsx("span",{className:"tool-group-summary",children:a}):null]})})}function Pd(e,t,n){const s=c.useRef(n);s.current=n;const i=c.useRef(!1),[a,o]=c.useState(0);c.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(),s.current(),o(m=>m+1))}]];return h.forEach(([d,m])=>document.addEventListener(d,m,!0)),()=>h.forEach(([d,m])=>document.removeEventListener(d,m,!0))},[e,t]),c.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 Vn=160,Dd=120,kn=-1;function Zt(e){return Math.max(0,e-Vn)}function _d(e,t){const n=t.length,[s,i]=c.useState(()=>({sessionId:e,start:Zt(n),total:n})),a=s.sessionId!==e?Zt(n):s.start===kn?kn:n>s.total&&s.start+Vn>=s.total?Zt(n):Math.min(s.start,Zt(n));c.useLayoutEffect(()=>{s.sessionId===e&&s.start===a&&s.total===n||i({sessionId:e,start:a,total:n})},[e,a,s,n]);const o=c.useCallback(()=>{i(p=>({sessionId:e,start:Math.max(0,(p.sessionId===e?p.start:Zt(n))-Dd),total:n}))},[e,n]),l=c.useCallback(p=>{const S=t.findIndex(y=>Il(y,p));if(a===kn||S<0||S>=a&&S<a+Vn)return!1;const w=Math.min(Zt(n),Math.max(0,S-40));return i({sessionId:e,start:w,total:n}),!0},[t,e,a,n]),u=c.useCallback(()=>{i({sessionId:e,start:Zt(n),total:n})},[e,n]),h=c.useCallback(()=>{i({sessionId:e,start:0,total:n})},[e,n]),d=()=>i({sessionId:e,start:kn,total:n}),m=Math.max(0,a),b=a===kn?n:Math.min(n,a+Vn);return{ensureMessageVisible:l,hiddenItemCount:m,hiddenLaterItemCount:Math.max(0,n-b),revealEarlier:o,revealLatest:u,revealStart:h,revealAll:d,visibleItems:t.slice(m,b)}}const Mr=()=>null,Ld=()=>()=>{};function $d(e,t,n,s){const i=c.useSyncExternalStore(e.submission?.subscribe??Ld,e.submission?.getSnapshot??Mr,Mr),a=c.useRef(!1),o=async l=>{if(!a.current){a.current=!0;try{await l()}finally{a.current=!1}}};return{sending:!!i&&i.sessionId===s,submit:l=>{if(l?.preventDefault(),!!n)return o(()=>e())},retry:()=>o(t)}}function Fd({activeSession:e,activeUsage:t,messages:n,renameTitle:s,busy:i,t:a,onBrowseFiles:o,onClose:l,onExport:u,onJumpToMessage:h,onRename:d,onRenameTitleChange:m,onToggleArchived:b,onTogglePinned:p,onViewChanges:S}){const[w,y]=c.useState(""),{copyText:g,feedback:f}=Xs(a.commandCopied,a.copyResumeFailed),x=c.useRef(null),v=Dn(l,x),j=c.useMemo(()=>wi(e),[e]),N=c.useMemo(()=>{const k=w.trim().toLowerCase();return k?n.map((C,I)=>({message:C,index:I})).filter(({message:C})=>C.role!=="user"&&C.role!=="assistant"?!1:C.content.toLowerCase().includes(k)).slice(0,20):[]},[n,w]);return r.jsxs("div",{"aria-labelledby":"session-detail-title","aria-modal":"true",className:"session-detail-drawer",ref:v,role:"dialog",tabIndex:-1,children:[r.jsx("div",{className:"drawer-backdrop",onClick:l,"aria-hidden":"true"}),r.jsxs("aside",{className:"session-detail-panel",children:[r.jsxs("header",{className:"drawer-header",children:[r.jsxs("div",{children:[r.jsx("span",{className:"eyebrow",children:e.agent}),r.jsx("strong",{id:"session-detail-title",title:It(e),children:r.jsx(Ai,{title:It(e),draft:s,label:a.rename,disabled:i,onDraftChange:m,onCommit:d},e.sessionId)})]}),r.jsx("button",{"aria-label":a.closeSessionDetails,className:"icon-button",onClick:l,ref:x,type:"button",children:r.jsx($e,{"aria-hidden":"true"})})]}),r.jsxs("div",{className:"detail-info-grid",children:[r.jsxs("div",{children:[r.jsx(Qn,{"aria-hidden":"true"}),r.jsx("span",{children:a.workingDirectory}),r.jsx("strong",{title:e.cwd,children:e.cwd})]}),r.jsxs("div",{children:[r.jsx(ri,{"aria-hidden":"true"}),r.jsx("span",{children:a.messages}),r.jsx("strong",{children:n.filter(k=>k.role==="user"||k.role==="assistant").length})]}),r.jsxs("div",{children:[r.jsx(mo,{"aria-hidden":"true"}),r.jsx("span",{children:a.session}),r.jsx("strong",{title:e.sessionId,children:e.sessionId})]}),r.jsxs("div",{children:[r.jsx(Ks,{"aria-hidden":"true"}),r.jsx("span",{children:a.runtime}),r.jsx("strong",{children:a.runtimeState(e.runtime.state)})]})]}),e.branch||e.diffStat?r.jsxs("button",{className:"detail-command-card detail-changes-card",type:"button",onClick:S,children:[r.jsx(ss,{"aria-hidden":"true"}),r.jsx("span",{className:"detail-change-label",children:e.branch??a.changes}),r.jsx("span",{className:"detail-change-stats",role:"group","aria-label":a.changes,children:e.diffStat?r.jsxs(r.Fragment,{children:[r.jsxs("span",{className:"diff-add",children:["+",e.diffStat.additions]}),r.jsxs("span",{className:"diff-del",children:["-",e.diffStat.deletions]})]}):null})]}):null,r.jsxs("label",{className:"detail-search",children:[r.jsx(Rn,{"aria-hidden":"true"}),r.jsx("input",{value:w,onChange:k=>y(k.target.value),placeholder:a.searchMessages}),w.trim()?r.jsx("small",{children:a.searchResultCount(N.length)}):null]}),w.trim()&&N.length?r.jsx("div",{className:"detail-search-results",children:N.map(({message:k,index:C})=>r.jsxs("button",{type:"button",onClick:()=>{h(C,w),l()},children:[r.jsx("span",{children:ji(k,a)}),r.jsx("strong",{children:k.content})]},`${k.historyKey??k.timestamp??C}:${C}`))}):null,w.trim()?null:r.jsxs(r.Fragment,{children:[r.jsxs("button",{className:"detail-command-card",type:"button",onClick:o,children:[r.jsx(Qn,{"aria-hidden":"true"}),r.jsx("span",{children:a.browseFiles})]}),r.jsxs("button",{className:"detail-command-card",type:"button",onClick:()=>{g(j)},children:[r.jsx(qa,{"aria-hidden":"true"}),r.jsx("span",{title:j,children:j})]}),r.jsx(er,{feedback:f}),r.jsxs("div",{className:"detail-action-grid",children:[r.jsxs("button",{className:"icon-text-button",disabled:i,type:"button",onClick:p,children:[r.jsx(_n,{"aria-hidden":"true"}),e.pinned?a.unpin:a.pin]}),r.jsxs("button",{className:"icon-text-button",disabled:i,type:"button",onClick:b,children:[r.jsx(ns,{"aria-hidden":"true"}),e.archived?a.unarchive:a.archive]}),r.jsxs("button",{className:"icon-text-button",type:"button",onClick:u,children:[r.jsx(ts,{"aria-hidden":"true"}),a.exportSession]})]}),t?r.jsxs("p",{className:"detail-usage",children:[a.usage,": ",t.limits?.fiveHour?.usedPercent??"-","% 5h ·"," ",t.limits?.weekly?.usedPercent??"-","% weekly"]}):null,r.jsxs("p",{className:"detail-usage",children:[a.created," ",as(e.createdAt,Date.now(),a)]})]})]})]})}function Od({activeSession:e,activeSessionId:t,activeModelOptions:n,activeQueue:s,queueControls:i,activeUsage:a,agent:o,approvalMode:l,attachments:u,busy:h,cwd:d,draft:m,effort:b,errorText:p,failedSend:S,onDismissFailedSend:w,fastMode:y,historyLoading:g,messages:f,messagesSessionId:x,model:v,phase:j,quickReplies:N,renameTitle:k,respondingSessionIds:C,sendShortcut:I,skills:R,uploadBusy:z,detailsOpen:A,t:M,onApprovalModeChange:F,onBrowseFiles:G,onCancelQueuedTurn:ne,onClearInterrupt:ve,onDraftChange:Se,onDetailsOpenChange:ae,onEffortChange:ke,onExportActiveSession:fe,onRewindMessage:oe,onFastModeChange:ce,onRetryFailedSend:T,onModelChange:D,onOpenRemoteFile:W,onInterrupt:U,onRetry:O,onDismissError:V,onRefreshSkills:B,onRenameSession:X,onRenameTitleChange:Q,onRemoveAttachment:He,onSubmit:me,onToggleArchived:Je,onTogglePinned:je,onUploadFiles:Fe,onViewChanges:ue}){const he=$d(me,T,j==="connected"&&!h&&!!m.trim(),t),[Ie,Re]=c.useState(""),[Ke,Ue]=c.useState(0),[ge,Oe]=c.useState(null),[Ge,Ve]=c.useState(null),[et,qe]=c.useState(!1),[tt,xe]=c.useState([]),pe=c.useRef(null),We=c.useRef([]),rt=c.useRef(null),J=c.useRef(null),te=c.useRef(!1),Ae=c.useRef(!1),E=c.useRef(!0),ye=c.useRef(0),Me=c.useRef(0),bt=c.useMemo(()=>Cl(f),[f]),Te=!!(t&&C.has(t)),Pe=Te&&x===t&&!g,Z=Pe?f.reduce((_,K,ie)=>K.liveReply===!0?ie:_,-1):-1,{ensureMessageVisible:Ce,hiddenItemCount:be,hiddenLaterItemCount:re,revealAll:Wt,revealEarlier:Nt,revealLatest:vt,revealStart:Lt,visibleItems:ut}=_d(t,bt),Et=c.useMemo(()=>!!(S&&ut.some(_=>_.type==="message"&&_.message.historyKey===S.historyKey)),[S,ut]),ht=c.useRef(null),{copyText:Rt,feedback:At}=Xs(M.messageCopied,M.copyFailed),Qe=c.useMemo(()=>Nl(f,Ie),[Ie,f]),xt=_=>{E.current=!1,ye.current=0;const K=Ce(_),ie=()=>We.current[_]?.scrollIntoView({behavior:"smooth",block:"center"});K?requestAnimationFrame(()=>requestAnimationFrame(ie)):ie()},ft=()=>{if(!Qe.length)return;const _=Ke%Qe.length,K=Qe[_]?.index;typeof K=="number"&&xt(K),Ue(ie=>(ie+1)%Qe.length)},nt=c.useCallback(()=>{const _=pe.current;_&&(E.current=!0,ye.current=0,_.scrollTop=_.scrollHeight,qe(!1))},[]),mt=c.useCallback(_=>{E.current=!0,ye.current=0,Ae.current=!0,te.current=!1,ht.current=null;const K=pe.current,ie=K?K.scrollHeight-K.scrollTop-K.clientHeight:0,we=_??(re===0&&K&&ie<=K.clientHeight?"smooth":"auto"),ot=()=>{const ze=pe.current;!ze||!Ae.current||(ze.scrollTo({top:ze.scrollHeight,behavior:we}),qe(!1),requestAnimationFrame(()=>{Ae.current=!1}))};re>0?(vt(),requestAnimationFrame(()=>requestAnimationFrame(ot))):ot()},[re,vt]),wt=()=>{const _=pe.current;if(!_)return;const K=_.querySelector(".message-frame");ht.current={element:K,top:K?K.getBoundingClientRect().top-_.getBoundingClientRect().top:_.scrollTop,height:_.scrollHeight}},$t=()=>{const _=pe.current;if(!_)return;_.scrollTop<160&&be>0&&!te.current&&!Ae.current&&(te.current=!0,wt(),Nt());const K=_.scrollTop>Me.current;Me.current=_.scrollTop;const ie=_.scrollHeight-_.scrollTop-_.clientHeight;ye.current>0&&!Ae.current&&!te.current&&(E.current=K&&ie<=2&&re===0),qe(ie>180||re>0)};c.useLayoutEffect(()=>{re>0&&qe(!0)},[re]);const st=Rl(pe,E,J,Ae,ye,Me,Lt,be),Mt=El(f);c.useLayoutEffect(()=>{const _=ht.current,K=pe.current;if(_&&K){if(_.element?.isConnected){const ze=_.element.getBoundingClientRect().top-K.getBoundingClientRect().top;K.scrollTop+=ze-_.top}else K.scrollTop+=K.scrollHeight-_.height;ht.current=null,te.current=!1;return}if(rt.current!==t&&(rt.current=t,J.current=t,Oe(null),Ve(null)),!pe.current)return;const we=x===t;if(t!==null&&J.current===t&&we&&(!g||f.length>0)){nt();let ze=0,ct=-1,Ne=0;const pt=performance.now(),lt=()=>{if(J.current!==t)return;nt();const De=pe.current?.scrollHeight??0;Ne=De===ct?Ne+1:0,ct=De;const gt=performance.now()-pt>=1400;if(!g&&Ne>=4||!g&>){J.current=null;return}gt||(ze=requestAnimationFrame(lt))};return ze=requestAnimationFrame(lt),qe(!1),()=>cancelAnimationFrame(ze)}E.current&&re===0&&nt()},[t,be,re,g,Mt,f.length,x,j,Pe,nt]),c.useLayoutEffect(()=>{const _=pe.current;if(!_)return;const K=new ResizeObserver(()=>{E.current&&re===0&&nt()});K.observe(_);for(const ie of _.children)K.observe(ie);return()=>K.disconnect()},[t,Mt,be,re,Pe,nt]);const St=Qe.length&&Ie.trim()?Qe[(Ke+Qe.length-1)%Qe.length]?.index:void 0;return Pd(pe,t,()=>{wt(),Wt()}),r.jsxs("section",{className:"chat-pane","aria-label":M.chat,children:[r.jsx(bl,{activeSession:e,agent:o,cwd:d,t:M,onOpenDetails:()=>e&&ae(!0),onScrollToStart:st.toStart,renameTitle:k,busy:h,onRename:X,onRenameTitleChange:Q,onViewChanges:ue,search:{query:Ie,matchCount:Qe.length,onChange:_=>{Re(_),Ue(0)},onNext:ft}}),r.jsx(gl,{activeSession:e,busy:h,errorText:p,failedSend:S,failedSendVisibleInConversation:Et,onClearInterrupt:ve,onDismissError:V,onDismissFailedSend:w,onRetry:O,onRetryFailedSend:()=>{he.retry()},t:M}),r.jsxs("div",{className:"message-scroll","aria-busy":g,"data-history-loading":g?"true":"false","data-rendered-items":ut.length,"data-hidden-items":be,"data-hidden-later-items":re,"data-total-messages":f.length,ref:pe,onScroll:$t,...st,children:[g&&f.length===0?r.jsx(ml,{label:M.loadingHistory}):null,!g&&f.length===0&&!Pe?r.jsxs("div",{className:"empty-state compact",children:[r.jsx(Hs,{"aria-hidden":"true"}),r.jsx("h2",{children:e?M.noVisibleMessages:M.startDaemonSession}),r.jsx("p",{children:M.emptyChatHint})]}):null,be>0?r.jsx("div",{className:"conversation-window-gate",children:r.jsx("button",{type:"button",onClick:()=>{te.current=!0,wt(),Nt()},children:M.showEarlierMessages(be)})}):null,ut.map(_=>{if(_.type==="toolGroup"){const Ne=_.entries.map(De=>De.message),pt=_.entries.some(De=>St===De.index),lt=Ge===_.id;return r.jsx("div",{className:"message-frame tool info",ref:De=>{for(const gt of _.entries)We.current[gt.index]=De},children:r.jsxs("div",{className:"inline-message-stack",children:[r.jsx(Td,{activeMatch:pt,expanded:lt,messages:Ne,onToggle:()=>Ve(De=>De===_.id?null:_.id)}),lt?r.jsx(Bi,{messages:Ne,showHeader:!1,onClose:()=>Ve(null),onCopy:Rt,t:M}):null]})},_.id)}const{index:K,message:ie}=_,we=Pi(ie,K),ot=ge===we,ze=Ge===we,ct=S?.historyKey===ie.historyKey?S:null;return r.jsxs("div",{className:`message-frame ${ie.role} ${ie.type==="info"?"info":""}`,ref:Ne=>{We.current[K]=Ne},children:[r.jsx(Md,{activeMatch:St===K,baseCwd:e?.cwd,message:ie,replying:Pe&&re===0&&K===Z,onCopy:Rt,onRewind:h||C.has(t??"")?void 0:()=>oe(ie),onCloseTool:()=>Ve(null),onOpenAttachment:xe,onOpenRemoteFile:W,onToggleSource:()=>Oe(Ne=>Ne===we?null:we),onToggleTool:()=>Ve(Ne=>Ne===we?null:we),sourceOpen:ot,toolOpen:ze,t:M}),ct?r.jsx(Ri,{failedSend:ct,onRetry:()=>{he.retry()},onDismiss:w,t:M}):null]},we)}),Pe&&re===0&&Z<0?r.jsx("div",{className:"message-frame assistant","data-replying-placeholder":"true",children:r.jsx("div",{className:"message assistant replying-placeholder",children:r.jsx(Hi,{label:M.replyingMessage})})}):null,re>0?r.jsx("div",{className:"conversation-window-gate",children:r.jsx("button",{type:"button",onClick:()=>mt("auto"),children:M.showLatestMessages(re)})}):null,r.jsx("div",{"aria-hidden":"true",className:"message-latest-anchor"})]}),et?r.jsx(pl,{label:M.newMessages,onClick:()=>mt()}):null,r.jsx(er,{feedback:At}),r.jsx(ul,{activeModelOptions:n,activeQueue:s,queueControls:i,agent:o,approvalMode:l,attachments:u,busy:h,sending:he.sending,responding:Te,onStop:U,draft:m,effort:b,fastMode:y,model:v,phase:j,quickReplies:N,sendShortcut:I,skills:R,uploadBusy:z,onApprovalModeChange:F,onCancelQueuedTurn:ne,onDraftChange:Se,onEffortChange:ke,onFastModeChange:ce,onModelChange:D,onRemoveAttachment:He,onRefreshSkills:B,onSubmit:_=>(mt("auto"),he.submit(_)),onUploadFiles:Fe,t:M},t),A&&e?r.jsx(Fd,{activeSession:e,activeUsage:a,busy:h,messages:f,renameTitle:k,t:M,onBrowseFiles:()=>{ae(!1),G()},onClose:()=>ae(!1),onExport:fe,onJumpToMessage:(_,K)=>{Re(K),Ue(0),xt(_)},onRename:X,onRenameTitleChange:Q,onToggleArchived:Je,onTogglePinned:je,onViewChanges:()=>{ae(!1),ue(e.sessionId)}}):null,r.jsx(hl,{cwd:e?.cwd,paths:tt,t:M,onClose:()=>xe([]),onOpenRemoteFile:W})]})}const qd="https://service.lifeos.vip/feedback",Ki=8e3,Wd=6e4,Tr=4,zd=20*1024*1024,Ui=["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"],Gi=["authorization","proxy-authorization"],Vi=["cookie","set-cookie"],Bd=[...Gi,...Vi],cs=(e,t)=>t.length-e.length,Qi=[...Ui].sort(cs).join("|"),Hd=Ui.filter(e=>!Bd.includes(e)).sort(cs).join("|"),Kd=[...Gi].sort(cs).join("|"),Ud=[...Vi].sort(cs).join("|"),Gd=new RegExp(`(?:${Qi}|credential|private[-_ ]?key|session[-_ ]?id|e-?mail|phone|mobile|address)`,"i"),Vd=new RegExp(`(["']?(?:${Kd})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|(?:Basic|Bearer)\\s+[^\\s,;}]+|AWS4-HMAC-SHA256[^\\r\\n]*(?=\\r?$)|[^\\s,;}]+)`,"gim"),Qd=new RegExp(`(["']?(?:${Ud})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\r\\n]+)`,"gi"),Zd=new RegExp(`(["']?(?:${Hd})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\s,;}&]+)`,"gi"),Jd=new RegExp(`([?&](?:${Qi})=)[^&\\s]+`,"gi");function Yd(e,t="[REDACTED]"){const n=(s,i,a)=>{const o=a[0]==='"'||a[0]==="'"?a[0]:"";if(!o)return`${i}${t}`;const l=a.slice(1,-1).trim(),u=/^(Basic|Bearer)\b/i.exec(l)?.[1];return`${i}${o}${u?`${u} `:""}${t}${o}`};return e.replace(/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gi,t).replace(Vd,n).replace(Qd,n).replace(Zd,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(Jd,`$1${t}`)}function Xd(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 fn(e){return Xd(Yd(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 eu(e,t={}){if(!e)return{};const n=Math.max(0,t.characterBudget??6e4),s=Math.max(0,t.maxArrayEntries??50),i=Math.max(0,t.maxDepth??8),a=Math.max(0,t.maxObjectEntries??80),o=Math.max(0,t.maxStringLength??4e3),l={remaining:n},u=new WeakSet,h=(d,m)=>{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=fn(d).slice(0,Math.min(o,l.remaining));return l.remaining-=S.length,S}if(m>=i)return"[MAX_DEPTH]";if(typeof d!="object")return fn(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,s).map(p=>h(p,m+1));const b={};for(const[p,S]of Object.entries(d).slice(0,a)){if(l.remaining<=0)break;const w=fn(p).slice(0,Math.min(120,l.remaining));l.remaining-=w.length,b[w]=Gd.test(p)?"[REDACTED]":h(S,m+1)}return b};return h(e,0)}function tu(e,t=Wd){const n=fn(e);return n.length<=t?n:`[truncated ${n.length-t} chars]
|
|
10
|
+
${n.slice(-t)}`}function nu(e){return fn(e.trim()).slice(0,Ki)}function su(e){try{const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}async function ru(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 iu(e,t={}){const n=new AbortController,s=Number.isFinite(t.timeoutMs)&&(t.timeoutMs??0)>0?t.timeoutMs:15e3;let i;try{const a=(t.transport??ru)({url:t.endpoint??qd,method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:n.signal}),o=new Promise((h,d)=>{i=setTimeout(()=>{n.abort(),d(new Error("Feedback request timed out"))},s)}),l=await Promise.race([a,o]),u=su(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 au=["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"],ou=new Set(au);function cu(e){const t={contextSchemaVersion:1};if(e)for(const[n,s]of Object.entries(e))ou.has(n)&&s!==void 0&&(t[n]=s);return eu(t)}const lu={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"},du={title:"意见反馈",subtitle:"报告问题,或告诉我们希望改进的地方。",bug:"问题",feature:"建议",description:"详细说明",descriptionPlaceholder:"发生了什么,或者你希望我们怎样改进?",email:"邮箱(选填)",emailPlaceholder:"便于我们回复你",includeDiagnostics:"附带经过隐私处理的诊断信息",privacyNotice:"仅在需要时附带诊断信息;发送前会移除已识别的凭据、个人标识和本地路径。",submit:"发送反馈",sending:"正在发送…",success:"感谢反馈,已经发送成功。",error:"发送失败,请稍后重试。",close:"关闭"},uu={title:"意見回饋",subtitle:"回報問題,或告訴我們希望改善的地方。",bug:"問題",feature:"建議",description:"詳細說明",descriptionPlaceholder:"發生了什麼,或你希望我們如何改善?",email:"電子郵件(選填)",emailPlaceholder:"方便我們回覆你",includeDiagnostics:"附上經過隱私處理的診斷資訊",privacyNotice:"僅在需要時附上診斷資訊;傳送前會移除已識別的憑證、個人識別資訊和本機路徑。",submit:"傳送回饋",sending:"正在傳送…",success:"感謝回饋,已成功傳送。",error:"傳送失敗,請稍後再試。",close:"關閉"};function Zi(e){const t=e?.trim().toLowerCase().replace(/_/g,"-")??"";return/^zh(?:-(?:tw|hk|mo|hant))(?:-|$)/u.test(t)?uu:t.startsWith("zh")?du:lu}const hu=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function fu(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 mu(e){if(!e?.length)return;if(e.length>Tr)throw new Error(`Feedback supports at most ${Tr} images`);const t=e.map(s=>{if(!hu.has(s.mimeType))throw new Error("Feedback image type is not supported");const i=fu(s.base64);if(!Number.isSafeInteger(s.size)||s.size<=0||i!==s.size)throw new Error("Feedback image size does not match its data");return{name:fn(s.name.trim()||"image").slice(0,255),mimeType:s.mimeType,size:s.size,base64:s.base64}});if(t.reduce((s,i)=>s+i.size,0)>zd)throw new Error("Feedback images are too large");return t}function pu(e){const t=nu(e.description);if(!t)throw new Error("Feedback description is required");const n=e.includeLogs===!1||!e.logs?"":tu(e.logs),s=e.email?.trim().slice(0,320);return{product:e.product,source:e.source,type:e.type,description:t,email:s||void 0,appVersion:e.appVersion?.trim().slice(0,64)||"unknown",locale:e.locale?.trim().slice(0,64)||"unknown",platform:e.platform?.trim().slice(0,128)||"unknown",logsIncluded:!!n,logs:n||void 0,metadata:cu(e.metadata),images:mu(e.images)}}function gu({language:e,entry:t="web-settings"}){const n=Ye(e),s=c.useMemo(()=>Zi(n),[n]),[i,a]=c.useState("bug"),[o,l]=c.useState(""),[u,h]=c.useState(""),[d,m]=c.useState("idle"),b=async()=>{if(!(!o.trim()||d==="sending")){m("sending");try{await iu(pu({product:"vibelet",source:ee().kind==="desktop"?"desktop":"web",type:i,description:o,email:u,appVersion:ee().appVersion||"web",locale:n,platform:navigator.platform||"web",metadata:{app:ee().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(""),m("success")}catch{m("error")}}};return r.jsxs("section",{className:"control-section compact-section",children:[r.jsx("h2",{children:s.title}),r.jsx("p",{className:"empty-copy",children:s.subtitle}),r.jsxs("div",{className:"feedback-type-grid",children:[r.jsx("button",{className:i==="bug"?"primary-button":"",type:"button","aria-pressed":i==="bug",onClick:()=>a("bug"),children:s.bug}),r.jsx("button",{className:i==="feature"?"primary-button":"",type:"button","aria-pressed":i==="feature",onClick:()=>a("feature"),children:s.feature})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:s.description}),r.jsx("textarea",{rows:5,maxLength:Ki,value:o,placeholder:s.descriptionPlaceholder,onChange:p=>l(p.target.value)})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:s.email}),r.jsx("input",{type:"email",maxLength:320,value:u,placeholder:s.emailPlaceholder,onChange:p=>h(p.target.value)})]}),r.jsx("button",{className:"primary-button",type:"button",disabled:!o.trim()||d==="sending",onClick:()=>{b()},children:d==="sending"?s.sending:s.submit}),d==="success"?r.jsx("p",{className:"empty-copy success-copy",children:s.success}):null,d==="error"?r.jsx("p",{className:"empty-copy error-copy",children:s.error}):null]})}const Pr="vibelet --access=quick";function yu({errorText:e,t}){const[n,s]=c.useState("idle"),[i,a]=c.useState(!1),o=Xe().language,l=Zi(o),u=async()=>{try{await Ys(Pr),s("success")}catch{s("error")}window.setTimeout(()=>s("idle"),1800)};return r.jsx("main",{className:"connection-guide",id:"vibelet-main-content",tabIndex:-1,children:r.jsxs("section",{className:"connection-guide-content","aria-labelledby":"connection-guide-title",children:[r.jsx("span",{className:"connection-guide-mark","aria-hidden":"true",children:r.jsx(is,{})}),r.jsx("span",{className:"connection-guide-eyebrow",children:"Vibelet Web"}),r.jsx("h1",{id:"connection-guide-title",children:t.openDaemonWebLink}),r.jsx("p",{children:t.openDaemonWebLinkHint}),r.jsxs("div",{className:"connection-command",children:[r.jsx("code",{children:Pr}),r.jsxs("button",{className:"primary-button",onClick:()=>{u()},type:"button",children:[n==="success"?r.jsx(_t,{"aria-hidden":"true"}):r.jsx(mn,{"aria-hidden":"true"}),r.jsx("span",{children:n==="success"?t.commandCopied:n==="error"?t.copyFailed:t.copyStartCommand})]})]}),r.jsx("p",{className:"connection-guide-footnote",children:t.connectionGuideFootnote}),e?r.jsx("p",{className:"connection-guide-error",children:e}):null,r.jsxs("button",{className:"connection-feedback-toggle",type:"button","aria-expanded":i,onClick:()=>a(h=>!h),children:[r.jsx(ri,{"aria-hidden":"true"}),l.title]}),i?r.jsx("div",{className:"connection-feedback-panel",children:r.jsx(gu,{language:o,entry:"connection-guide"})}):null]})})}const bu=c.lazy(()=>at(()=>import("./ImageViewer-BvBKQ6wE.js"),__vite__mapDeps([5,1,2,6,7])));function vu(){const[e,t]=c.useState(null);return c.useEffect(()=>{const n=s=>t(s.detail);return window.addEventListener(Ms,n),()=>window.removeEventListener(Ms,n)},[]),e?r.jsx(c.Suspense,{fallback:null,children:r.jsx(bu,{request:e,onClose:()=>t(null)},e.images[e.index].src)}):null}function xu(){const e=c.useRef(null),t=c.useRef({browser:0,terminal:0}),[n,s]=c.useState(0),[i,a]=c.useState([]),[o,l]=c.useState(null),[u,h]=c.useState({}),[d,m]=c.useState({}),b=c.useCallback((f,x,v,j,N,k)=>{const C=crypto.randomUUID(),I=f==="diff"?"center":"right";return f!=="diff"&&(x=`${x} ${++t.current[f]}`),a(R=>[...R,{id:C,kind:f,title:x,cwd:v,session:j,scope:N,path:k,location:I}]),I==="center"?l(C):h(R=>({...R,[f]:C})),C},[]),p=c.useCallback((f,x)=>{const v=i.find(j=>j.id===f);v&&(a(j=>j.map(N=>N.id===f?{...N,location:x}:N)),x==="center"?(l(f),h(j=>({...j,[v.kind]:i.find(N=>N.id!==f&&N.kind===v.kind&&N.location==="right")?.id}))):(h(j=>({...j,[v.kind]:f})),e.current?.(v.kind),o===f&&l(null)))},[i,o]),S=c.useCallback(f=>{const x=i.find(v=>v.id===f);a(v=>v.filter(j=>j.id!==f)),o===f&&l(null),x&&u[x.kind]===f&&h(v=>({...v,[x.kind]:i.find(j=>j.id!==f&&j.kind===x.kind&&j.location==="right")?.id}))},[i,o,u]),w=c.useCallback((f,x)=>a(v=>v.map(j=>j.id===f&&j.title!==x?{...j,title:x}:j)),[]),y=c.useCallback((f,x)=>m(v=>{if(v[f]===x||!v[f]&&!x)return v;const j={...v};return x?j[f]=x:delete j[f],j}),[]),g=c.useCallback(()=>{a([]),l(null),h({}),s(f=>f+1)},[]);return c.useMemo(()=>({openRight:e,epoch:n,items:i,center:o,right:u,hosts:d,add:b,move:p,close:S,rename:w,register:y,reset:g,setCenter:l,setRight:h}),[n,i,o,u,d,b,p,S,w,y,g])}const cr=c.createContext(null);function wu({children:e}){const t=xu();return r.jsx(cr.Provider,{value:t,children:e})}function an(){const e=c.useContext(cr);if(!e)throw new Error("Dock workspace provider missing");return e}function Ji(){return c.useContext(cr)}const Yn="application/x-vibelet-workspace-tab",Su={browser:ni,terminal:is,diff:ss};function ls(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 $s({location:e,kind:t,t:n,cwd:s}){const i=an(),a=ls(n),o=c.useRef(null),l=i.items.filter(u=>u.location===e&&(!t||u.kind===t));return c.useEffect(()=>{e==="right"&&t&&!i.items.some(u=>u.kind===t)&&i.add(t,n[t==="browser"?"browser":"terminal"],s)},[e,t,i.epoch]),c.useEffect(()=>{if(e!=="right"||!o.current)return;const u=o.current.querySelector('.dock-tab[data-active="true"]');u&&(o.current.scrollLeft=Math.max(0,u.offsetLeft-o.current.offsetLeft))},[e,t,i.right,l.map(u=>u.title).join("|")]),e==="right"&&t&&l.length===1?null:r.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]&&r.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:r.jsx(Jr,{})}),r.jsx("div",{className:"dock-tab-items",ref:o,children:l.map(u=>{const h=e==="center"?i.center===u.id:i.right[u.kind]===u.id,d=Su[u.kind];return r.jsxs("div",{className:"document-tab dock-tab","data-active":h,"data-dock-id":u.id,draggable:!0,onDragStart:m=>{m.dataTransfer.setData(Yn,u.id),m.dataTransfer.effectAllowed="move"},children:[r.jsxs("button",{type:"button",role:"tab","aria-selected":h,title:u.title,onClick:()=>e==="center"?i.setCenter(u.id):i.setRight(m=>({...m,[u.kind]:u.id})),children:[r.jsx(d,{}),r.jsx("span",{children:u.title})]}),h&&e==="center"&&r.jsx("button",{type:"button",className:"dock-move","aria-label":a.right,title:a.right,onClick:()=>i.move(u.id,"right"),children:r.jsx(Aa,{})}),r.jsx("button",{type:"button",className:"document-tab-close","aria-label":`${n.close} ${u.title}`,title:n.close,onClick:()=>i.close(u.id),children:r.jsx($e,{})})]},u.id)})}),e==="right"&&t&&r.jsx("button",{type:"button",className:"dock-new","aria-label":a.create,title:$n(a.create,"newTab"),onClick:()=>i.add(t,n[t==="browser"?"browser":"terminal"],s),children:r.jsx(Ln,{})})]})}function ku({item:e,t}){const n=an(),s=ls(t);return r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button","aria-label":s.center,title:s.center,draggable:!0,onDragStart:i=>{i.dataTransfer.setData(Yn,e.id),i.dataTransfer.effectAllowed="move"},onClick:()=>n.move(e.id,"center"),children:r.jsx(Jr,{})}),r.jsx("button",{type:"button","aria-label":s.create,title:$n(s.create,"newTab"),onClick:()=>n.add(e.kind,t[e.kind==="browser"?"browser":"terminal"],e.cwd),children:r.jsx(Ln,{})})]})}function Xn({location:e,kind:t}){const n=an(),s=e==="center"?"center":`right-${t}`,i=c.useCallback(a=>n.register(s,a),[n.register,s]);return r.jsx("div",{ref:i,className:"dock-slot","data-dock-location":e,"data-dock-kind":t})}function lr(e,t){const n=Ji();return n?{onDragOver:s=>{s.dataTransfer.types.includes(Yn)&&(s.preventDefault(),s.dataTransfer.dropEffect="move",s.currentTarget.classList.add("dock-drop-target"))},onDragLeave:s=>{s.currentTarget.contains(s.relatedTarget)||s.currentTarget.classList.remove("dock-drop-target")},onDrop:s=>{s.currentTarget.classList.remove("dock-drop-target");const i=s.dataTransfer.getData(Yn),a=n.items.find(o=>o.id===i);a&&(s.preventDefault(),s.stopPropagation(),document.body.classList.remove("dock-dragging"),n.move(i,e),t?.(a.kind))}}:{}}const ju=c.lazy(()=>at(()=>import("./BrowserControlPanel-BTBKDi0n.js"),__vite__mapDeps([8,1,2,6]))),Cu=c.lazy(()=>at(()=>import("./TerminalControlPanel-B7S_ebVy.js"),__vite__mapDeps([9,1,2]))),Iu=c.lazy(()=>at(()=>import("./DiffDrawer-sMBIj4bW.js"),__vite__mapDeps([10,1,2])).then(e=>({default:e.DiffDrawer})));function Nu({item:e,...t}){const n=an(),s=lr(e.location),[i]=c.useState(()=>document.createElement("div")),a=e.location==="right",l=a&&n.items.filter(b=>b.location==="right"&&b.kind===e.kind).length===1?r.jsx(ku,{item:e,t:t.t}):void 0,u=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,h=n.hosts[a?`right-${e.kind}`:"center"]??n.hosts.parking,d=n.hosts.parking;c.useLayoutEffect(()=>{d&&i.parentElement!==d&&d.appendChild(i)},[i,d]),c.useLayoutEffect(()=>{i.className="dock-surface",i.dataset.dockId=e.id,i.dataset.location=e.location,i.dataset.kind=e.kind,i.hidden=!u;const b=a&&e.kind==="diff",p=()=>{const w=h?.getBoundingClientRect();Object.assign(i.style,b?{left:"0px",top:"0px",width:"100vw",height:"100vh"}:{left:`${w?.left??0}px`,top:`${w?.top??0}px`,width:`${w?.width??0}px`,height:`${w?.height??0}px`})};p();const S=new ResizeObserver(p);return h&&S.observe(h),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),()=>{S.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0)}},[i,h,u,e.id,e.location,e.kind,a]),c.useLayoutEffect(()=>()=>i.remove(),[i]);const m=()=>n.move(e.id,a?"center":"right");return dt.createPortal(r.jsx("div",{className:"dock-surface-content",...s,children:r.jsx(c.Suspense,{fallback:r.jsx("p",{className:"control-panel-loading",children:t.t.loading}),children:e.kind==="browser"?r.jsx(ju,{t:t.t,dockActions:l,onTitleChange:b=>n.rename(e.id,b)}):e.kind==="terminal"?r.jsx(Cu,{client:t.client,cwd:e.cwd??"",deviceName:t.deviceName,visible:u,t:t.t,dockActions:l}):e.session&&t.client?r.jsx(Iu,{client:t.client,sessionId:e.session.sessionId,cwd:e.session.cwd,sessionTitle:e.title,t:t.t,onClose:()=>n.close(e.id),onDock:m,dockLabel:ls(t.t).center,presentation:a?"drawer":"workspace",initialScope:e.scope,initialPath:e.path}):null})}),i)}function Eu(e){const t=an();t.openRight.current=s=>{(s==="browser"||s==="terminal")&&e.onOpenRight?.(s)};const n=c.useCallback(s=>t.register("parking",s),[t.register]);return c.useEffect(()=>{t.reset()},[e.daemonId]),r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"dock-parking",ref:n}),r.jsx("div",{className:"dock-overlay-slot",children:r.jsx(Xn,{location:"right",kind:"diff"})}),t.items.map(s=>r.jsx(Nu,{item:s,...e},s.id))]})}const Dr=new WeakMap,Yi=5e3;function dr(e,t,n){let s=Dr.get(e);s||Dr.set(e,s=new Map);const i=JSON.stringify([t.sessionId,t.cwd,n]);let a=s.get(i);return a||(s.size>=12&&s.delete(s.keys().next().value),s.set(i,a={updated:0,patches:new Map})),a}function em(e,t,n){return dr(e,t,n)}function Ru(e,t,n){const s=dr(e,t,n);return s.pending?s.pending:s.data&&Date.now()-s.updated<Yi?Promise.resolve(s.data):(s.pending=e.request({action:"session.gitDiff.list",id:e.makeId("gitDiffList"),...t,scope:n}).then(i=>(s.data=i,s.updated=Date.now(),s.patches.clear(),i)).finally(()=>{s.pending=void 0}),s.pending)}function Au(e,t,n,s){const i=dr(e,t,n),a=i.patches.get(s);if(a?.pending)return a.pending;if(a?.data&&Date.now()-i.updated<Yi)return Promise.resolve(a.data);i.patches.size>=12&&i.patches.delete(i.patches.keys().next().value);const o={};return i.patches.set(s,o),o.pending=e.request({action:"session.gitDiff.file",id:e.makeId("gitDiffFile"),...t,scope:n,path:s}).then(l=>(o.data=l,l)).finally(()=>{o.pending=void 0}),o.pending}async function Mu(e,t){const n=await Ru(e,t,"unstaged");n.files[0]&&await Au(e,t,"unstaged",n.files[0].path)}function Tu({t:e,onClose:t}){const n=c.useRef(null),s=Dn(t,n);return r.jsxs("div",{className:"diff-drawer",role:"dialog","aria-modal":"true","aria-label":e.changes,ref:s,tabIndex:-1,children:[r.jsx("div",{className:"diff-drawer-backdrop",onClick:t,"aria-hidden":"true"}),r.jsxs("div",{className:"diff-drawer-panel",children:[r.jsxs("header",{className:"diff-drawer-header",children:[r.jsx("strong",{children:e.changes}),r.jsx("button",{ref:n,type:"button",className:"icon-button","aria-label":e.closeChanges,onClick:t,children:r.jsx($e,{})})]}),r.jsxs("div",{className:"diff-empty",role:"status",children:[r.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),e.loadingPatch]})]})]})}const Pu=c.lazy(async()=>at(()=>import("./FilesControlPanel-4hHS85Mr.js"),__vite__mapDeps([11,1,2,12,13])).then(e=>({default:e.FilesControlPanel}))),Du=c.lazy(async()=>at(()=>import("./LanguageSettingsPanel-DTDvB4l2.js"),__vite__mapDeps([14,1,2,15])).then(e=>({default:e.LanguageSettingsPanel}))),_u=c.lazy(async()=>at(()=>import("./ThemeSettingsPanel-DVaJ6nGu.js"),__vite__mapDeps([16,1,2,15])).then(e=>({default:e.ThemeSettingsPanel}))),Lu=c.lazy(async()=>at(()=>import("./NotificationSettingsPanel-BS01O3sC.js"),__vite__mapDeps([17,1,2])).then(e=>({default:e.NotificationSettingsPanel}))),Xi=()=>at(()=>import("./DiffDrawer-sMBIj4bW.js"),__vite__mapDeps([10,1,2])).then(e=>({default:e.DiffDrawer})),$u=c.lazy(Xi);function _r({t:e}){return r.jsxs("div",{className:"control-panel-loading","aria-live":"polite","aria-busy":"true",children:[r.jsx("span",{className:"loading-spinner","aria-hidden":"true"}),r.jsx("span",{children:e.loadingControls})]})}function Fu({client:e,id:t,activeSession:n,sessions:s,t:i,close:a}){const o=Ji(),l=n?.sessionId,u=n?.cwd,h=n?.runtime.isResponding;c.useEffect(()=>{if(!e||!l)return;const m=window.setTimeout(()=>{document.visibilityState!=="hidden"&&(Xi().catch(()=>{}),Mu(e,{sessionId:l,cwd:u}).catch(()=>{}))},350);return()=>window.clearTimeout(m)},[e,l,u,h]);const d=s.find(m=>m.sessionId===t);return!d||!e?null:r.jsx(c.Suspense,{fallback:r.jsx(Tu,{t:i,onClose:a}),children:r.jsx($u,{client:e,sessionId:d.sessionId,cwd:d.cwd,sessionTitle:It(d),t:i,onClose:a,dockLabel:ls(i).center,onDock:o?({scope:m,path:b})=>{o.add("diff",It(d),d.cwd,d,m,b),a()}:void 0},d.sessionId)})}const Ou="/web/assets/logo-SQcOtj-8.png";function qu(e,t,n){const s=e.find(i=>i.daemonId===t&&n(i.daemonId))??e.find(i=>n(i.daemonId));return e.filter(i=>!n(i.daemonId)||i===s)}function Wu({activeDaemonId:e,busy:t,fallbackName:n,phase:s,statusText:i,t:a,targets:o,onConnect:l,onRename:u,onEditConnection:h}){const[d,m]=c.useState(!1),[b,p]=c.useState(null),[S,w]=c.useState(""),y=c.useRef(null),g=c.useRef(null),f=ee().isLocalDaemon??(()=>!1),x=qu(o,e,f),j=o.find(C=>C.daemonId===e)?.label||n||e?.slice(0,10)||"Vibelet Web";c.useEffect(()=>{d||p(null),b&&g.current?.select()},[d,b]),c.useEffect(()=>{if(!d)return;const C=R=>{R.target instanceof Node&&!y.current?.contains(R.target)&&m(!1)},I=R=>{R.key==="Escape"&&m(!1)};return document.addEventListener("pointerdown",C),document.addEventListener("keydown",I),()=>{document.removeEventListener("pointerdown",C),document.removeEventListener("keydown",I)}},[d]);const N=C=>{p(C.daemonId),w(C.label)},k=()=>{!b||!S.trim()||(u(b,S),p(null))};return r.jsxs("div",{className:"device-switcher",ref:y,children:[r.jsxs("button",{"aria-expanded":d,"aria-haspopup":"menu",className:"device-switcher-trigger",onClick:()=>m(C=>!C),title:j,type:"button",children:[r.jsx("strong",{children:j}),r.jsx(Yr,{"aria-hidden":"true"})]}),r.jsxs("span",{className:`brand-connection ${s}`,children:[r.jsx("i",{"aria-hidden":"true"}),s==="connected"?a.connected:i]}),d?r.jsxs("div",{"aria-label":a.savedDevices,className:"device-switcher-menu",role:"menu",children:[x.map(C=>{const I=C.daemonId===e;return r.jsx("div",{className:"device-switcher-row",children:b===C.daemonId?r.jsxs("form",{className:"device-rename-form",onSubmit:R=>{R.preventDefault(),k()},children:[r.jsx("input",{ref:g,"aria-label":a.rename,autoFocus:!0,onChange:R=>w(R.target.value),onKeyDown:R=>{R.key==="Escape"&&(R.stopPropagation(),p(null))},value:S}),r.jsx("button",{"aria-label":a.rename,title:a.rename,disabled:!S.trim(),type:"submit",children:r.jsx(_t,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":a.cancel,title:a.cancel,type:"button",onClick:()=>p(null),children:r.jsx($e,{"aria-hidden":"true"})})]}):r.jsxs(r.Fragment,{children:[r.jsxs("button",{className:"device-connect-button",disabled:t||I,onClick:()=>{l(C),m(!1)},role:"menuitem",type:"button",children:[I?r.jsx(_t,{"aria-hidden":"true"}):r.jsx(oi,{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:C.label}),r.jsx("small",{children:f(C.daemonId)?`${a.currentDevice}${I?` · ${a.active}`:""}`:I?a.active:C.displayName||C.daemonId})]})]}),r.jsx("button",{"aria-label":`${a.rename} ${C.label}`,title:`${a.rename} ${C.label}`,className:"device-rename-button",onClick:()=>N(C),type:"button",children:r.jsx(Mo,{"aria-hidden":"true"})}),h&&ee().canEditConnection?.(C.daemonId)&&r.jsx("button",{"aria-label":`${a.editConnection} ${C.label}`,title:`${a.editConnection} ${C.label}`,className:"device-rename-button",onClick:()=>{h(C),m(!1)},type:"button",children:r.jsx(Bo,{"aria-hidden":"true"})})]})},C.daemonId)}),o.length===0?r.jsx("p",{className:"empty-copy",children:a.noSavedDevices}):null]}):null]})}function Fs({label:e,value:t,options:n,onChange:s}){const i=c.useId();return r.jsxs("div",{className:"filter-section",children:[r.jsx("span",{className:"filter-section-label",id:i,children:e}),r.jsx("div",{className:"filter-choice-list",role:"radiogroup","aria-labelledby":i,children:n.map(a=>r.jsxs("label",{className:"filter-menu-row",children:[r.jsx("input",{type:"radio",name:i,value:a.value,checked:t===a.value,onChange:()=>s(a.value)}),r.jsx("span",{children:a.label}),r.jsx(_t,{className:"filter-menu-check","aria-hidden":"true","data-checked":t===a.value})]},a.value))})]})}function zu({folder:e,initialValue:t,t:n,onClose:s,onSave:i}){const[a,o]=c.useState(t),l=c.useRef(null),u=Dn(s,l),h=d=>{d.preventDefault(),i(a)};return dt.createPortal(r.jsxs("div",{"aria-labelledby":"folder-tag-dialog-title","aria-modal":"true",className:"folder-tag-dialog-layer",ref:u,role:"dialog",tabIndex:-1,children:[r.jsx("div",{"aria-hidden":"true",className:"folder-tag-dialog-backdrop",onClick:s}),r.jsxs("form",{className:"folder-tag-dialog",onSubmit:h,children:[r.jsxs("header",{children:[r.jsx("span",{className:"folder-tag-dialog-icon","aria-hidden":"true",children:r.jsx(ui,{})}),r.jsxs("div",{children:[r.jsx("strong",{id:"folder-tag-dialog-title",children:n.editDirectoryTags}),r.jsx("span",{title:e,children:e})]}),r.jsx("button",{"aria-label":n.cancel,className:"mini-button",onClick:s,type:"button",children:r.jsx($e,{"aria-hidden":"true"})})]}),r.jsxs("label",{className:"folder-tag-dialog-field",children:[r.jsx("span",{children:n.directoryTags}),r.jsx("textarea",{"aria-describedby":"folder-tag-dialog-help",placeholder:n.directoryTagsPlaceholder,ref:l,rows:3,value:a,onChange:d=>o(d.target.value)})]}),r.jsx("p",{id:"folder-tag-dialog-help",children:n.directoryTagsDescription}),r.jsxs("footer",{children:[r.jsx("button",{className:"icon-text-button",onClick:s,type:"button",children:n.cancel}),r.jsx("button",{className:"primary-button",type:"submit",children:n.saveDirectoryTags})]})]})]}),document.body)}function Bu({search:e,busy:t,connected:n,filtersOpen:s,filtersActive:i,t:a,onSearchChange:o,onSearchCommit:l,onToggleFilters:u,onCreate:h}){const[d,m]=c.useState(!!e),b=c.useRef(null);return c.useEffect(()=>{const p=()=>{m(!0),requestAnimationFrame(()=>b.current?.focus())};return window.addEventListener("vibelet.session-search",p),()=>window.removeEventListener("vibelet.session-search",p)},[]),r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"rail-list-heading",children:[r.jsx("span",{children:a.sessions}),r.jsxs("div",{className:"rail-heading-actions",children:[r.jsx("button",{"aria-label":a.searchSessions,"aria-expanded":d,className:"rail-create-button",title:$n(a.searchSessions,"searchSessions"),type:"button",onClick:()=>{m(!0),requestAnimationFrame(()=>b.current?.focus())},children:r.jsx(Rn,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":a.newSession,className:"rail-create-button",disabled:t||!n,onClick:h,title:a.newSession,type:"button",children:r.jsx(Ln,{"aria-hidden":"true"})}),r.jsx("button",{"aria-expanded":s,"aria-label":a.sessionFilters,className:`filter-toggle ${s||i?"selected":""}`,onClick:u,title:a.sessionFilters,type:"button",children:r.jsx(ao,{"aria-hidden":"true"})})]})]}),(d||e)&&r.jsxs("div",{className:"search-box",children:[r.jsx(Rn,{"aria-hidden":"true"}),r.jsx("input",{ref:b,"aria-label":a.searchSessions,value:e,onBlur:l,onChange:p=>o(p.target.value),placeholder:a.searchSessions,onKeyDown:p=>{p.key==="Enter"&&l(),p.key==="Escape"&&(o(""),l(),m(!1))}}),r.jsx("button",{className:"filter-toggle","aria-label":a.cancel,type:"button",onClick:()=>{o(""),m(!1),b.current?.blur()},children:r.jsx($e,{"aria-hidden":"true"})})]})]})}function Hu({menu:e,pending:t,t:n,onOpen:s,onDetails:i,onCopyResumeCommand:a,onResumeInTerminal:o,terminalBusy:l,onTogglePinned:u,onToggleArchived:h,onDelete:d}){return r.jsxs("div",{className:"session-context-menu",role:"menu",style:{left:e.x,top:e.y},onPointerDown:m=>m.stopPropagation(),children:[r.jsxs("button",{type:"button",role:"menuitem",onClick:s,children:[r.jsx(Qr,{"aria-hidden":"true"}),n.open]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:i,children:[r.jsx(si,{"aria-hidden":"true"}),n.details]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:a,children:[r.jsx(mn,{"aria-hidden":"true"}),n.copyResumeCommand]}),o&&r.jsxs("button",{type:"button",role:"menuitem",disabled:t||l,title:l?n.resumeTerminalBusy:n.resumeInTerminal,onClick:o,children:[r.jsx(Ks,{"aria-hidden":"true"}),n.resumeInTerminal]}),r.jsx("span",{className:"context-menu-separator"}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:u,children:[r.jsx(_n,{"aria-hidden":"true"}),e.session.pinned?n.unpin:n.pin]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:h,children:[r.jsx(ns,{"aria-hidden":"true"}),e.session.archived?n.unarchive:n.archive]}),r.jsxs("button",{className:"danger",type:"button",role:"menuitem",onClick:d,children:[r.jsx(hi,{"aria-hidden":"true"}),n.delete]})]})}function Lr({session:e,active:t,selected:n=!1,responding:s,pending:i=!1,tagLabels:a,showFolder:o=!0,t:l,onSelect:u,onContextMenu:h,onToggleArchived:d,onTogglePinned:m}){const b=It(e),p=as(e.lastActivityAt,Date.now(),l),S=e.cwd?.split(/[\\/]/).filter(Boolean).at(-1)||e.cwd||".",w=e.branchUrl||(e.branch&&e.pullRequest?.url.match(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/)?e.pullRequest.url.replace(/\/pull\/\d+$/,`/tree/${encodeURIComponent(e.branch)}`):void 0),y=!!(e.branch||e.pullRequest),[g,f]=c.useState(null);c.useEffect(()=>{if(!g)return;const v=()=>f(null);return document.addEventListener("scroll",v,!0),()=>document.removeEventListener("scroll",v,!0)},[g]);const x=v=>{const j=v.getBoundingClientRect(),N=Math.min(360,window.innerWidth-24);f({left:Math.max(12,Math.min(j.left,window.innerWidth-N-12)),top:j.bottom+5>window.innerHeight-88?j.top-5:j.bottom+5,above:j.bottom+5>window.innerHeight-88})};return r.jsxs("div",{className:"session-item","data-multi-selected":n||void 0,"data-statuses":+!!e.pinned+ +!!e.archived,onMouseEnter:v=>x(v.currentTarget),onMouseLeave:()=>f(null),onFocusCapture:v=>x(v.currentTarget),onBlurCapture:v=>{(!(v.relatedTarget instanceof Node)||!v.currentTarget.contains(v.relatedTarget))&&f(null)},children:[r.jsxs("button",{className:`session-row ${t?"active":""} ${e.archived?"archived":""} ${s?"responding":""}`,"data-session-id":e.sessionId,"aria-current":t?"true":void 0,"aria-pressed":n,onContextMenu:h,onClick:u,onMouseDown:v=>{v.shiftKey&&v.preventDefault()},type:"button",children:[r.jsxs("span",{className:"session-row-head",children:[r.jsx("strong",{children:b}),r.jsxs("span",{className:"session-row-metadata",children:[r.jsx("span",{className:"session-row-agent",children:e.agent==="codex"?"Codex":"Claude"}),r.jsx("span",{className:"session-row-time",title:p,children:p})]}),s?r.jsx("span",{className:"session-running-indicator",role:"img","aria-label":l.agentResponding,title:l.agentResponding}):r.jsx("span",{className:"session-running-placeholder","aria-hidden":"true"})]}),a?.length?r.jsx("span",{className:"directory-tag-row",title:l.directoryTags,children:a.map(v=>r.jsx("em",{children:v},v))}):null,r.jsxs("span",{className:"session-row-footer","data-has-git":y||void 0,children:[!y&&o?r.jsx("span",{className:"session-row-folder",title:e.cwd,children:S}):null,e.pinned?r.jsx("span",{children:l.pinned}):null,e.archived?r.jsx("span",{children:l.archived}):null]})]}),r.jsxs("div",{className:"session-quick-actions",children:[r.jsx("button",{"aria-label":e.archived?l.unarchive:l.archive,className:e.archived?"is-archived":void 0,disabled:i,onClick:d,title:e.archived?l.unarchive:l.archive,type:"button",children:r.jsx(ns,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":e.pinned?l.unpin:l.pin,className:e.pinned?"is-pinned":void 0,disabled:i,onClick:m,title:e.pinned?l.unpin:l.pin,type:"button",children:r.jsx(_n,{"aria-hidden":"true"})})]}),y&&r.jsxs("div",{className:"session-git-links",children:[o&&r.jsx("span",{className:"session-git-folder",title:e.cwd,children:S}),e.branch&&(w?r.jsx("a",{className:"session-branch-link",href:w,target:"_blank",rel:"noopener noreferrer",title:e.branch,children:e.branch}):r.jsx("span",{className:"session-branch-link",title:e.branch,children:e.branch})),e.pullRequest&&r.jsxs("a",{className:"session-pr-link",href:e.pullRequest.url,target:"_blank",rel:"noopener noreferrer",title:e.pullRequest.title,children:["PR #",e.pullRequest.number]})]}),g&&dt.createPortal(r.jsx("div",{"aria-hidden":"true",className:"session-title-tooltip",style:{left:g.left,top:g.top,transform:g.above?"translateY(-100%)":void 0},children:b}),document.body)]})}function Ku({activeSessionId:e,busy:t,collapsedFolders:n,folderCounts:s,getFolderTags:i,groupFolders:a,groupedSessions:o,phase:l,pendingSessionIds:u,respondingSessionIds:h,t:d,visibleSessions:m,onEditFolderTags:b,onOpenCreateMenu:p,onOpenSessionMenu:S,onSelectSession:w,onToggleSessionArchived:y,onToggleSessionPinned:g,onToggleFolder:f}){const x=c.useId(),[v,j]=c.useState(()=>new Set),N=c.useRef(null),k=c.useMemo(()=>{const I=a?o.flatMap(R=>n[R.folder]?[]:R.sessions):m;return[...new Set(I.map(R=>R.sessionId))]},[n,a,o,m]);c.useEffect(()=>{const I=new Set(k);j(R=>[...R].every(z=>I.has(z))?R:new Set([...R].filter(z=>I.has(z)))),N.current&&!I.has(N.current)&&(N.current=null)},[k]),c.useEffect(()=>{v.size===0&&(N.current=e)},[e,v]);const C=(I,R)=>{if(R.shiftKey){const z=N.current??e??I,A=k.indexOf(z),M=k.indexOf(I),F=k.slice(Math.min(A<0?M:A,M),Math.max(A,M)+1);j(G=>{const ne=R.metaKey||R.ctrlKey?new Set(G):new Set;for(const ve of F)ne.add(ve);return ne}),N.current=z;return}if(N.current=I,R.metaKey||R.ctrlKey){j(z=>{const A=z.size?new Set(z):new Set(e?[e]:[]);return A.has(I)?A.delete(I):A.add(I),A});return}j(new Set),w(I)};return a?r.jsxs(r.Fragment,{children:[o.map(I=>{const R=!!n[I.folder],z=`${x}-${encodeURIComponent(I.folder)}`,A=I.kind==="folder"?s[I.folder]??I.sessions.length:I.sessions.length,M=I.kind==="attention"?d.needsAttentionSessionsGroup:I.kind==="running"?d.runningSessionsGroup:I.kind==="pinned"?d.pinnedSessionsGroup:I.folder;return r.jsxs("div",{className:`folder-group ${I.kind!=="folder"?"virtual-session-group":""}`,children:[r.jsxs("div",{className:"folder-heading",children:[r.jsxs("div",{className:"folder-header",children:[r.jsxs("button",{"aria-expanded":!R,"aria-controls":z,title:M,onClick:()=>f(I.folder),type:"button",children:[r.jsx(Xr,{className:"folder-disclosure","aria-hidden":"true"}),I.kind==="attention"?r.jsx(si,{"aria-hidden":"true"}):I.kind==="running"?r.jsx(Zr,{"aria-hidden":"true"}):I.kind==="pinned"?r.jsx(_n,{"aria-hidden":"true"}):R?r.jsx(ro,{"aria-hidden":"true"}):r.jsx(Qn,{"aria-hidden":"true"}),r.jsx("span",{children:I.kind==="folder"?I.folder.split(/[\\/]/).filter(Boolean).at(-1)||I.folder:M})]}),I.kind==="folder"?r.jsxs(r.Fragment,{children:[r.jsx("button",{"aria-label":i(I.folder).length?d.editDirectoryTags:d.addDirectoryTags,className:"mini-button folder-hover-action",onClick:()=>b(I.folder),title:i(I.folder).length?d.editDirectoryTags:d.addDirectoryTags,type:"button",children:r.jsx(ui,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":d.newSession,className:"mini-button folder-hover-action",disabled:t||l!=="connected",onClick:F=>p(F,I.folder),title:d.newSession,type:"button",children:r.jsx(Ln,{"aria-hidden":"true"})})]}):null,r.jsx("small",{className:"folder-session-count",title:`${A} ${d.sessions}`,children:A})]}),I.kind==="folder"&&i(I.folder).length?r.jsx("div",{className:"folder-tag-row",children:i(I.folder).map(F=>r.jsx("span",{children:F},F))}):null]}),r.jsx("div",{className:"folder-session-list",id:z,hidden:R,children:R?null:I.sessions.map(F=>r.jsx(Lr,{active:F.sessionId===e,selected:v.has(F.sessionId),responding:h.has(F.sessionId),pending:u?.has(F.sessionId),session:F,showFolder:I.kind!=="folder",tagLabels:i(F.cwd),t:d,onContextMenu:G=>S(G,F),onSelect:G=>C(F.sessionId,G),onToggleArchived:()=>y(F),onTogglePinned:()=>g(F)},F.sessionId))})]},I.folder)}),m.length===0?r.jsx("p",{className:"empty-copy",children:d.noSessionsMatch}):null]}):r.jsxs(r.Fragment,{children:[m.map(I=>r.jsx(Lr,{active:I.sessionId===e,selected:v.has(I.sessionId),responding:h.has(I.sessionId),pending:u?.has(I.sessionId),session:I,tagLabels:i(I.cwd),t:d,onContextMenu:R=>S(R,I),onSelect:R=>C(I.sessionId,R),onToggleArchived:()=>y(I),onTogglePinned:()=>g(I)},I.sessionId)),m.length===0?r.jsx("p",{className:"empty-copy",children:d.noSessionsMatch}):null]})}function Uu({agentFilter:e,t,onAgentFilterChange:n}){return r.jsx(Fs,{label:t.agentFilterLabel,value:e,options:[{value:"all",label:t.agentFilterAll},{value:"claude",label:t.agentFilterClaude},{value:"codex",label:t.agentFilterCodex}],onChange:n})}function Gu({groupFolders:e,hideArchived:t,separatePinnedGroup:n,showNeedsAttentionGroup:s,showRunningGroup:i,t:a,onToggleGroupFolders:o,onToggleHideArchived:l,onToggleNeedsAttentionGroup:u,onToggleRunningGroup:h,onToggleSeparatePinnedGroup:d}){const m=[[a.showNeedsAttentionGroup,s,u],[a.showRunningGroup,i,h],[a.separatePinnedGroup,n,d]];return r.jsxs("div",{className:"filter-section",children:[r.jsx("span",{className:"filter-section-label",children:a.filterViewOptions}),r.jsxs("div",{className:"filter-view-list",children:[r.jsxs("button",{"aria-pressed":e,className:"filter-menu-row",onClick:o,type:"button",children:[r.jsx("span",{children:a.groupByFolder}),r.jsx(_t,{className:"filter-menu-check","aria-hidden":"true","data-checked":e})]}),m.map(([b,p,S])=>r.jsxs("button",{"aria-pressed":e&&p,className:"filter-menu-row nested-filter-option",disabled:!e,onClick:S,type:"button",children:[r.jsx("span",{children:b}),r.jsx(_t,{className:"filter-menu-check","aria-hidden":"true","data-checked":e&&p})]},b)),r.jsxs("button",{"aria-pressed":t,className:"filter-menu-row",onClick:l,type:"button",children:[r.jsx("span",{children:a.hideArchived}),r.jsx(_t,{className:"filter-menu-check","aria-hidden":"true","data-checked":t})]})]})]})}function Vu(e,t,n=!1){const s=c.useMemo(()=>e,[e?.lastActivityAt,e?.sessionId]),i=c.useRef(null),a=c.useRef(null),o=c.useRef(t),[l,u]=c.useState(null),h=!!(e?.lastActivityAt&&e.sessionId),d=h?`${e?.lastActivityAt}:${e?.sessionId}`:null;return c.useEffect(()=>{o.current=t},[t]),c.useEffect(()=>{const m=i.current;if(!m||!s||!d){a.current=null,u(null);return}const b=m.closest(".session-list");if(!(b instanceof HTMLElement))return;let p=!0,S;u(null);const w=()=>{a.current!==d&&(a.current=d,u(d),o.current(s).catch(()=>{p&&(S=window.setTimeout(()=>{p&&(a.current=null,n?w():(y?.unobserve(m),y?.observe(m)))},1500))}).finally(()=>{p&&u(g=>g===d?null:g)}))},y=n?null:new IntersectionObserver(g=>{g.some(f=>f.isIntersecting)&&w()},{root:b,rootMargin:"0px 0px 240px 0px",threshold:.01});return n?w():y?.observe(m),()=>{p=!1,a.current=null,S!==void 0&&window.clearTimeout(S),y?.disconnect()}},[d,s,n]),{canLoadMore:h,loading:h&&l===d,sentinelRef:i}}function Qu(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Zu({connectionIndicators:e,activeSessionId:t,busy:n,collapsedFolders:s,currentCwd:i,activeDaemonId:a,displayName:o,savedTargets:l,directoryTags:u,folderCounts:h,groupFolders:d,sessionSort:m,onSessionSortChange:b,groupedSessions:p,hideArchived:S,separatePinnedGroup:w,showNeedsAttentionGroup:y,showRunningGroup:g,inventoryVersion:f,nextCursor:x,phase:v,pendingSessionIds:j,respondingSessionIds:N,search:k,sessionAgentFilter:C,sessionsCount:I,sinceFilter:R,statusText:z,t:A,visibleSessions:M,onLoadMore:F,onCopyResumeCommand:G,onResumeInTerminal:ne,onConnectTarget:ve,onRequestNewSession:Se,onDeleteSession:ae,onEditFolderTags:ke,onOpenSessionDetails:fe,onResetFilters:oe,onRenameTarget:ce,onEditConnection:T,onSearchChange:D,onSearchCommit:W,onSelectSession:U,onToggleSessionArchived:O,onToggleSessionPinned:V,onSessionAgentFilterChange:B,onSinceFilterChange:X,onToggleFolder:Q,onToggleGroupFolders:He,onToggleHideArchived:me,onToggleNeedsAttentionGroup:Je,onToggleRunningGroup:je,onToggleSeparatePinnedGroup:Fe}){const[ue,he]=c.useState(!1),[Ie,Re]=c.useState(null);c.useEffect(()=>{if(!Ie)return;const Z=window.setTimeout(()=>Re(null),2400);return()=>window.clearTimeout(Z)},[Ie]);const[Ke,Ue]=c.useState(null),[ge,Oe]=c.useState(null),Ge=c.useRef(null),Ve=c.useRef(null),[et,qe]=c.useState(null),tt=m!=="updated"||C!=="all"||R!=="30d"||!d||d&&(y||g||w)||S,xe=Vu(x,F,m!=="updated"||!S),pe=ge?!!j?.has(ge.session.sessionId):!1,We=Z=>u[Qu(Z)??"/"]??[],rt=v==="connected"?`${M.length}/${I} sessions · v${f??"-"}`:A.sameOriginAccess,J=`${z} · ${rt}`,te=ee().toolbarTarget?.("left");c.useLayoutEffect(()=>{if(!ue)return;const Z=()=>{const Ce=Ge.current?.getBoundingClientRect();if(!Ce)return;const be=Math.min(820,window.innerWidth-24);qe({top:Ce.bottom+8,left:Math.max(12,Math.min(Ce.left,window.innerWidth-be-12))})};return Z(),window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[ue]),c.useEffect(()=>{if(!ue&&!ge)return;const Z=be=>{const re=be.target;re instanceof Node&&(Ge.current?.contains(re)||Ve.current?.contains(re))||(he(!1),Oe(null))},Ce=be=>{be.key==="Escape"&&(he(!1),Oe(null))};return document.addEventListener("pointerdown",Z),document.addEventListener("keydown",Ce),()=>{document.removeEventListener("pointerdown",Z),document.removeEventListener("keydown",Ce)}},[ge,ue]);const Ae=(Z,Ce)=>{Oe(null),he(!1),Se(Ce)},E=(Z,Ce)=>{Z.preventDefault(),Oe({session:Ce,x:Math.min(Z.clientX,window.innerWidth-224-10),y:Math.min(Z.clientY,window.innerHeight-306-10)})},ye=()=>Oe(null),Me=Z=>{he(!1),Oe(null),Ue({folder:Z,value:We(Z).join(", ")})},bt=Z=>{Ke&&(ke(Ke.folder,Z),Ue(null))},Te=Z=>{if(!ge)return;const{session:Ce}=ge;ye(),Z(Ce)},Pe=r.jsxs("div",{className:"brand-block",title:J,children:[r.jsx("div",{className:"brand-mark","aria-hidden":"true",children:r.jsx("img",{alt:"",className:"brand-logo",height:"40",src:Ou,width:"40"})}),r.jsx(Wu,{activeDaemonId:a,busy:n,fallbackName:o,phase:v,statusText:z,t:A,targets:l,onConnect:ve,onRename:ce,onEditConnection:T}),e]});return r.jsxs("aside",{className:"session-rail","aria-label":A.sessions,children:[te?dt.createPortal(Pe,te):Pe,r.jsxs("div",{className:"search-filter-wrap",ref:Ge,children:[r.jsx(Bu,{search:k,busy:n,connected:v==="connected",filtersOpen:ue,filtersActive:tt,t:A,onSearchChange:D,onSearchCommit:W,onToggleFilters:()=>he(Z=>!Z),onCreate:Ae}),ue&&et?dt.createPortal(r.jsxs("div",{className:"filter-popover session-filter-popover",role:"dialog","aria-label":A.sessionFilters,ref:Ve,style:{top:et.top,left:et.left},children:[r.jsx(Fs,{label:A.sessionSortLabel,value:m,options:[{value:"updated",label:A.sessionSortUpdated},{value:"created",label:A.sessionSortCreated},{value:"title",label:A.sessionSortTitle},{value:"folder",label:A.sessionSortFolder}],onChange:b}),r.jsx(Uu,{agentFilter:C,t:A,onAgentFilterChange:B}),r.jsx(Fs,{label:A.searchTimeRangeLabel,value:R,options:[{value:"all",label:A.searchTimeRangeAllTime},{value:"7d",label:A.searchTimeRangeLast7Days},{value:"30d",label:A.searchTimeRangeLast30Days},{value:"90d",label:A.searchTimeRangeLast90Days}],onChange:X}),r.jsx(Gu,{groupFolders:d,hideArchived:S,separatePinnedGroup:w,showNeedsAttentionGroup:y,showRunningGroup:g,t:A,onToggleGroupFolders:He,onToggleHideArchived:me,onToggleNeedsAttentionGroup:Je,onToggleRunningGroup:je,onToggleSeparatePinnedGroup:Fe}),tt?r.jsx("button",{className:"filter-reset-button",onClick:oe,type:"button",children:A.resetFilters}):null]}),document.body):null]}),r.jsxs("div",{className:"session-list",children:[r.jsx(Ku,{activeSessionId:t,busy:n,collapsedFolders:s,folderCounts:h,getFolderTags:We,groupFolders:d,groupedSessions:p,phase:v,pendingSessionIds:j,respondingSessionIds:N,t:A,visibleSessions:M,onEditFolderTags:Me,onOpenCreateMenu:Ae,onOpenSessionMenu:E,onSelectSession:U,onToggleSessionArchived:O,onToggleSessionPinned:V,onToggleFolder:Q},a??"unconnected"),xe.canLoadMore?r.jsx("div",{"aria-live":"polite",className:`session-load-sentinel ${xe.loading?"loading":""}`,ref:xe.sentinelRef,role:"status",children:xe.loading?r.jsxs(r.Fragment,{children:[r.jsx(rs,{className:"spin","aria-hidden":"true"}),r.jsx("span",{children:A.loadingMore})]}):null}):null]}),Ke?r.jsx(zu,{folder:Ke.folder,initialValue:Ke.value,t:A,onClose:()=>Ue(null),onSave:bt}):null,ge?r.jsx(Hu,{menu:ge,pending:pe,t:A,onOpen:()=>Te(Z=>U(Z.sessionId)),onDetails:()=>Te(fe),onCopyResumeCommand:()=>Te(Z=>{Promise.resolve(G(Z)).then(()=>Re({message:A.commandCopied,tone:"success"})).catch(()=>Re({message:A.copyResumeFailed,tone:"error"}))}),onResumeInTerminal:ne&&a&&ee().resumeInTerminal&&ee().isLocalDaemon?.(a)?()=>Te(ne):void 0,terminalBusy:N.has(ge.session.sessionId),onTogglePinned:()=>Te(V),onToggleArchived:()=>Te(O),onDelete:()=>Te(ae)}):null,r.jsx(er,{feedback:Ie})]})}function Ju({collapsed:e,children:t,onExpand:n,onResize:s,t:i}){const a=ee().toolbarTarget?.("left"),o=r.jsx("button",{"aria-label":e?i.expandSessionSidebar:i.collapseSessionSidebar,className:"sidebar-titlebar-toggle",onClick:n,title:$n(e?i.expandSessionSidebar:i.collapseSessionSidebar,"leftSidebar"),type:"button",children:r.jsx(Io,{"aria-hidden":"true"})});return r.jsxs(r.Fragment,{children:[a?dt.createPortal(o,a):o,r.jsx("div",{className:"session-sidebar-motion",inert:e,"aria-hidden":e,children:t}),r.jsx("button",{"aria-label":i.resizeSessionSidebar,"aria-hidden":e,className:"resize-handle",disabled:e,onPointerDown:s,title:i.resizeSessionSidebar,type:"button",children:r.jsx("span",{})})]})}const ur={version:"",latestVersion:"",loading:!1,error:null};function $r(e){const t=e.match(/^\d+/);return t?Number(t[0]):0}function Yu(e,t){const n=e.split(/[+-]/,1)[0].split(".").map($r),s=t.split(/[+-]/,1)[0].split(".").map($r),i=Math.max(n.length,s.length);for(let a=0;a<i;a+=1){const o=n[a]??0,l=s[a]??0;if(o<l)return-1;if(o>l)return 1}return 0}function ea(e,t){return Yu(e,t)<0}function Xu(e){const t=e.toLowerCase();if(t.includes("alpha"))return"alpha";if(t.includes("beta"))return"beta";if(e.trim())return"latest"}function eh(e,t,n){const s=e?.webSocketUrl?e.webSocketUrl:t.origin;try{const i=new URL(s);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 th(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 nh({busy:e,connected:t,dismissed:n,feedback:s,synced:i,t:a,onPull:o,onPushMerge:l,onPushReplace:u,onSkip:h}){const d=!t||e!==null;return r.jsxs("section",{className:"control-section compact-section archive-sync-panel",children:[r.jsx("h2",{children:a.archiveSyncTitle}),r.jsx("p",{className:"empty-copy",children:i?a.archiveSyncSynced:n?a.archiveSyncSkippedState:a.archiveSyncBody}),r.jsxs("div",{className:"action-grid archive-sync-actions",children:[r.jsxs("button",{className:"icon-text-button",disabled:d,onClick:l,type:"button",children:[r.jsx(uo,{"aria-hidden":"true"}),e==="pushMerge"?a.archiveSyncSyncing:a.archiveSyncPushMerge]}),r.jsxs("button",{className:"icon-text-button",disabled:d,onClick:o,type:"button",children:[r.jsx(ts,{"aria-hidden":"true"}),e==="pull"?a.archiveSyncSyncing:a.archiveSyncPull]}),r.jsxs("button",{className:"icon-text-button",disabled:d,onClick:u,type:"button",children:[r.jsx(nc,{"aria-hidden":"true"}),e==="pushReplace"?a.archiveSyncSyncing:a.archiveSyncPushReplace]}),r.jsxs("button",{className:"icon-text-button",disabled:d,onClick:h,type:"button",children:[r.jsx(ja,{"aria-hidden":"true"}),a.archiveSyncSkip]})]}),s?r.jsx("p",{className:`empty-copy ${s.tone==="error"?"error-copy":"success-copy"}`,children:s.message}):null]})}function sh({pairing:e,phase:t,t:n,onForgetPairing:s}){const i=t==="connected"?"connected":e?t:n.notPaired;return r.jsxs("section",{className:"control-section compact-section",children:[r.jsx("h2",{children:n.currentDevice}),r.jsxs("dl",{children:[r.jsxs("div",{children:[r.jsx("dt",{children:n.daemon}),r.jsx("dd",{children:e?.displayName??e?.daemonId??n.notPaired})]}),r.jsxs("div",{children:[r.jsx("dt",{children:n.status}),r.jsx("dd",{children:i})]})]}),r.jsx("div",{className:"action-grid",children:r.jsxs("button",{className:"danger-button",disabled:!e,onClick:s,type:"button",children:[r.jsx(vo,{"aria-hidden":"true"}),n.forget]})})]})}function rh({connected:e,metadata:t,showUpdate:n,updateBusy:s,restartBusy:i,t:a,updateStatus:o,onUpdate:l,onRestart:u}){const h=t.version&&t.latestVersion&&n?`${t.version} -> ${t.latestVersion}`:t.version||a.unknown;return r.jsxs("section",{className:"control-section compact-section",children:[r.jsx("h2",{children:a.desktopConnector}),r.jsx("dl",{children:r.jsxs("div",{children:[r.jsx("dt",{children:a.version}),r.jsx("dd",{children:t.loading?a.checking:h})]})}),r.jsxs("div",{className:"action-grid",children:[n?r.jsxs("button",{className:"primary-button",disabled:!e||s||i,onClick:l,type:"button",children:[r.jsx(ts,{"aria-hidden":"true"}),s?a.updating:a.update]}):null,r.jsxs("button",{className:"danger-button",disabled:!e||i,onClick:u,type:"button",children:[r.jsx(En,{"aria-hidden":"true"}),i?a.restarting:a.restart]})]}),t.error?r.jsx("p",{className:"empty-copy",children:t.error}):null,o?r.jsx("p",{className:"empty-copy",children:o}):null]})}function ih({activeDaemonId:e,busy:t,t:n,targets:s,onConnect:i,onForget:a}){return r.jsxs("section",{className:"control-section compact-section",children:[r.jsx("h2",{children:n.savedDevices}),r.jsxs("div",{className:"stack-list",children:[s.map(o=>r.jsxs("div",{className:"data-row target-row",children:[r.jsxs("div",{children:[r.jsxs("strong",{children:[o.label,o.daemonId===e?` · ${n.active}`:""]}),r.jsxs("span",{children:[o.displayName??o.daemonId," ·"," ",o.lastConnectedAt?as(o.lastConnectedAt,Date.now(),n):n.notConnectedRecently]})]}),r.jsxs("div",{className:"row-actions",children:[r.jsx("button",{"aria-label":`Connect to ${o.label}`,className:"icon-button",disabled:t,onClick:()=>i(o),type:"button",children:r.jsx(oi,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":`Forget ${o.label}`,className:"icon-button danger-icon",disabled:t,onClick:()=>a(o.daemonId),type:"button",children:r.jsx(hi,{"aria-hidden":"true"})})]})]},o.daemonId)),s.length===0?r.jsx("p",{className:"empty-copy",children:n.noSavedDevices}):null]})]})}function Fr({workspace:e,portalOnly:t=!1}){const[n,s]=c.useState(()=>ee().settingsTarget?.()??null);c.useEffect(()=>{const l=()=>s(ee().settingsTarget?.()??null);return window.addEventListener("vibelet.settings.target.changed",l),l(),()=>window.removeEventListener("vibelet.settings.target.changed",l)},[]);const i=e,a=r.jsxs(r.Fragment,{children:[r.jsx(sh,{pairing:i.pairing,phase:i.phase,t:i.t,onForgetPairing:i.clearPairing}),r.jsx(ih,{activeDaemonId:i.pairing?.daemonId,busy:i.busy,t:i.t,targets:i.savedTargets,onConnect:i.connectSavedTarget,onForget:i.forgetSavedTarget}),r.jsx(nh,{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}),r.jsx(rh,{connected:i.phase==="connected",metadata:i.daemonMetadata,restartBusy:i.admin.loading&&i.admin.action==="restart",showUpdate:!!(i.daemonMetadata.version&&i.daemonMetadata.latestVersion&&ea(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")}})]}),o=r.jsx("div",{className:"remote-workspace-settings",children:a});return t?n?dt.createPortal(o,n):null:o}function ah(){const e=ee().polishSettings,t=Ye(Xe().language)!=="en",[n,s]=c.useState(),[i,a]=c.useState({...gs}),[o,l]=c.useState(""),[u,h]=c.useState(!1),[d,m]=c.useState(""),[b,p]=c.useState(!1);if(c.useEffect(()=>{let w=!0;return e?.status().then(y=>{w&&(s(y),a(y.settings))}).catch(()=>{w&&(p(!0),m(t?"无法读取润色设置。":"Could not load polishing settings."))}),()=>{w=!1}},[e]),!e)return null;const S=async w=>{h(!0),m(""),p(!1);try{const y=await e.save(i,w);s(y),a(y.settings),l(""),m(t?"已保存":"Saved"),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch{p(!0),m(t?"保存失败,请检查 HTTPS API 地址、模型和提示词。":"Save failed. Check the HTTPS API URL, model and prompts.")}finally{h(!1)}};return r.jsxs("section",{className:"control-section compact-section speech-polish-settings",children:[r.jsx("h2",{children:t?"语音润色":"Voice polishing"}),r.jsxs("label",{className:"speech-enabled",children:[r.jsx("input",{type:"checkbox",role:"switch","aria-checked":i.enabled,className:"settings-switch",checked:i.enabled,disabled:!n||u,onChange:async w=>{const y={...i,enabled:w.target.checked};a(y),h(!0),m(""),p(!1);try{const g=await e.save({...n.settings,enabled:y.enabled});s(g),a(y),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch{a(i),p(!0),m(t?"无法保存开关设置":"Could not save setting")}finally{h(!1)}}}),t?"启用语音润色":"Enable voice polishing"]}),i.enabled&&r.jsxs("fieldset",{disabled:!n||u,className:"speech-polish-fields",children:[r.jsx("p",{className:"empty-copy",children:t?"识别后轻度整理口误、重复和标点,保留原意。转写文字会发送到你配置的模型;失败时保留原始文字,仅填入草稿。":"Lightly correct slips, repetition and punctuation while preserving meaning. Transcripts are sent to your configured model. Failures keep the original text; nothing is sent from your draft."}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"API 地址":"API URL"}),r.jsx("input",{type:"url",value:i.baseUrl,onChange:w=>a({...i,baseUrl:w.target.value}),autoComplete:"off"})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"模型":"Model"}),r.jsx("input",{value:i.model,onChange:w=>a({...i,model:w.target.value}),autoComplete:"off"})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"润色 API Key":"Polishing API Key"}),r.jsx("input",{type:"password",autoComplete:"off",value:o,onChange:w=>l(w.target.value),placeholder:n?.configured?t?"已保存 · 留空保留":"Saved · leave blank to keep":"API Key"})]}),r.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&&!o.trim()&&r.jsx("p",{className:"empty-copy",children:t?"请填写 API Key 并保存,润色才能生效。":"Enter and save an API key to use polishing."}),r.jsxs("details",{className:"speech-polish-advanced",children:[r.jsx("summary",{children:t?"自定义提示词":"Custom prompts"}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"中文提示词":"Chinese prompt"}),r.jsx("textarea",{rows:5,value:i.promptZh,onChange:w=>a({...i,promptZh:w.target.value})})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"英文提示词":"English prompt"}),r.jsx("textarea",{rows:5,value:i.promptEn,onChange:w=>a({...i,promptEn:w.target.value})})]}),r.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>a({...i,promptZh:gs.promptZh,promptEn:gs.promptEn}),children:t?"恢复默认提示词":"Reset prompts"})]}),r.jsxs("div",{className:"attention-actions",children:[r.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{S(o.trim()||void 0)},children:t?"保存润色设置":"Save polishing settings"}),n?.configured&&r.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{S("")},children:t?"移除润色密钥":"Remove polishing key"})]})]}),d&&r.jsx("p",{role:b?"alert":"status",className:b?"error-copy":"empty-copy",children:d})]})}const oh={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 ch(){const e=ee().speechSettings,t=oh[Ye(Xe().language)],[n,s]=c.useState(),[i,a]=c.useState(""),[o,l]=c.useState(!1),[u,h]=c.useState(""),[d,m]=c.useState(Ze().getItem("vibelet.web.voice.enabled")==="true"),b=!!(globalThis.isSecureContext&&typeof globalThis.navigator?.mediaDevices?.getUserMedia=="function"&&globalThis.MediaRecorder?.isTypeSupported("audio/webm"));c.useEffect(()=>{let g=!0;return e?.status().then(f=>{g&&s(f)}).catch(()=>{g&&h("Unable to load speech settings.")}),()=>{g=!1}},[e]);const p=g=>{m(g),Ze().setItem("vibelet.web.voice.enabled",String(g)),window.dispatchEvent(new Event("vibelet.speech.changed"))},S=async g=>{if(!(!e||o)){l(!0),h("");try{s(await e.saveKey(g)),a(""),g||p(!1),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch(f){h(f instanceof Error?f.message:String(f))}finally{l(!1)}}};if(!e)return null;const w=n?.engine==="volcengine",y=[...n?.systemAvailable?[{value:"system",label:"macOS · Apple"}]:[],{value:"deepgram",label:"Deepgram · Nova-3"},{value:"volcengine",label:Ye(Xe().language)==="en"?"Volcengine · ASR Flash":"火山引擎 · 录音识别"}];return r.jsxs(r.Fragment,{children:[r.jsxs("section",{className:"control-section compact-section speech-input-settings",children:[r.jsx("h2",{children:t.title}),r.jsxs("label",{className:"speech-enabled",children:[r.jsx("input",{type:"checkbox",role:"switch","aria-checked":d,className:"settings-switch",checked:d,disabled:!b,onChange:g=>p(g.target.checked)}),t.enabled]}),d&&r.jsxs(r.Fragment,{children:[e.setEngine&&r.jsxs("div",{className:"field speech-engine-field",children:[r.jsx("span",{children:Ye(Xe().language)==="en"?"Recognition engine":"识别引擎"}),r.jsx(Cn,{icon:ii,menuLabel:"Speech engine",label:y.find(g=>g.value===n?.engine)?.label??"Deepgram · Nova-3",options:y,value:n?.engine??"deepgram",disabled:o,onSelect:async g=>{l(!0),h(""),a("");try{s(await e.setEngine(g)),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch(f){h(f instanceof Error?f.message:String(f))}finally{l(!1)}}})]}),r.jsx("p",{className:"empty-copy",children:n?.engine==="system"?Ye(Xe().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。文字只填入草稿,不会自动发送。":w?Ye(Xe().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"&&r.jsxs(r.Fragment,{children:[r.jsx("p",{className:"empty-copy",children:n?.persistence==="encrypted"?t.secure:t.session}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:w?"火山引擎 API Key":"Deepgram API Key"}),r.jsx("input",{type:"password",autoComplete:"off",value:i,onChange:g=>a(g.target.value),placeholder:n?.configured?t.saved:"API Key"})]}),r.jsxs("div",{className:"attention-actions",children:[r.jsx("button",{type:"button",className:"icon-text-button",disabled:o||!i.trim(),onClick:()=>{S(i)},children:t.save}),n?.configured&&r.jsx("button",{type:"button",className:"icon-text-button",disabled:o,onClick:()=>{S("")},children:t.remove})]})]})]}),!b&&r.jsx("p",{className:"empty-copy",children:t.unsupported}),u&&r.jsx("p",{role:"alert",className:"error-copy",children:u})]}),d&&r.jsx(ah,{})]})}function Or(e){const t=e?.fiveHour??e?.weekly,n=Number(t?.usedPercent);return Number.isFinite(n)?{availablePercent:Math.round(Math.max(0,Math.min(100,100-n))),resetsAt:t?.resetsAt??""}:null}function lh(e,t=Date.now()){const n=new Date(e);if(!Number.isFinite(n.getTime())||n.getTime()<=t)return null;const s=i=>String(i).padStart(2,"0");return`${n.getFullYear()}-${s(n.getMonth()+1)}-${s(n.getDate())} ${s(n.getHours())}:${s(n.getMinutes())}`}function dh(e){const t=[],n=Or(e.codex),s=Or(e.claude);return n!==null&&t.push({agent:"codex",label:"Codex",...n}),s!==null&&t.push({agent:"claude",label:"Claude",...s}),t}function uh(e){return e?"success":"warning"}function hh(e,t){return!e||t===null?"warning":t<150?"success":t<500?"warning":"danger"}function fh({connected:e,latencyMs:t,limits:n,t:s}){const i=dh({codex:n.codex?.limits,claude:n.claude?.limits}),[a,o]=c.useState(0);c.useEffect(()=>{if(o(0),i.length<2)return;const m=setInterval(()=>o(b=>(b+1)%i.length),4e3);return()=>clearInterval(m)},[i.length]);const l=i[a%i.length],u=l?lh(l.resetsAt):null,h=l?`${l.label} ${l.availablePercent}%`:s.quotaUnavailable,d=e?t===null?s.latencyMeasuring:`${t} ms`:s.latencyDisconnected;return r.jsxs("div",{className:"connection-indicators",children:[r.jsxs("span",{role:"img",className:"connection-quota",title:`${s.remainingQuota}: ${h} · ${u?s.quotaResetsAt.replace("{time}",u):s.quotaResetUnavailable}${e?"":` · ${s.latencyDisconnected}`}`,"aria-label":`${s.remainingQuota}: ${h}${e?"":` · ${s.latencyDisconnected}`}`,children:[r.jsx("span",{className:"connection-quota-dot",style:{background:`var(--${uh(e)})`}}),h]}),r.jsxs("span",{role:"img",className:"connection-latency",style:{color:`var(--${hh(e,t)})`},"aria-label":`${s.connectionLatency}: ${d}`,children:[r.jsx(Zr,{size:11,"aria-hidden":"true"}),d]})]})}function mh({workspace:e}){const{phase:t,clientRef:n,pairing:s,t:i}=e,[a,o]=c.useState(null),[l,u]=c.useState({});return c.useEffect(()=>{u({})},[s?.daemonId]),c.useEffect(()=>{const h=n.current;if(o(null),t!=="connected"||!h)return;let d=!0;const m=h.onLatency(o),b=()=>{for(const S of["codex","claude"])h.request({action:"usage.limits.fetch",id:h.makeId("header-usage"),agent:S},{timeoutMs:15e3}).then(w=>{d&&n.current===h&&u(y=>({...y,[S]:w}))}).catch(()=>{})};b();const p=setInterval(b,6e4);return()=>{d=!1,m(),clearInterval(p)}},[t,n,s?.daemonId]),r.jsx(fh,{connected:t==="connected",latencyMs:a,limits:l,t:i})}function ph({value:e,t,showSession:n=!0,onChange:s}){const i=[...n?[{tab:"session",label:t.session,Icon:li}]:[],{tab:"files",label:t.files,Icon:Qn},{tab:"terminal",label:t.terminal,Icon:is},{tab:"browser",label:t.browser,Icon:ni}];return r.jsx("div",{className:"control-tabs",children:i.map(({tab:a,label:o,Icon:l})=>r.jsxs("button",{"aria-label":o,"aria-pressed":e===a,className:e===a?"selected":"",onClick:()=>s(a),title:o,type:"button",children:[r.jsx(l,{"aria-hidden":"true"}),r.jsx("span",{children:o})]},a))})}function gh({chinese:e}){const[t,n]=c.useState(Zn),[s,i]=c.useState(null),[a,o]=c.useState(""),l=u=>{dc(u),n(u),o("")};return r.jsxs("section",{className:"control-section compact-section workspace-shortcut-settings",children:[r.jsx("h2",{children:e?"应用内快捷键":"In-app shortcuts"}),r.jsx("p",{className:"empty-copy",children:e?"点击组合键后直接按键录制。Esc 取消,退格键清除。新建标签会沿用当前终端或浏览器;其他页面默认新建浏览器标签。":"Click a shortcut to record it. Escape cancels; Backspace clears. New tab follows the current terminal or browser; elsewhere it opens a browser tab."}),en.map(u=>r.jsxs("div",{className:"workspace-shortcut-row",children:[r.jsx("span",{children:e?u.zh:u.en}),r.jsx("button",{type:"button","data-shortcut-recording":s===u.id?"true":void 0,"aria-label":`${e?"设置快捷键:":"Set shortcut: "}${e?u.zh:u.en}`,onClick:()=>{i(u.id),o("")},onBlur:()=>i(null),onKeyDown:h=>{if(s!==u.id)return;if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){i(null),o("");return}if(h.key==="Backspace"||h.key==="Delete"){l({...t,[u.id]:""}),i(null);return}const d=mi(h.nativeEvent);if(!d)return;const m=lc(u.id,d,t);if(m){const b=en.find(p=>p.id===m);o(m==="reserved"?e?"此组合键用于系统菜单或编辑操作,请换一个组合。":"Reserved for a system menu or editing action. Choose another combination.":`${e?"已用于:":"Already assigned to: "}${e?b?.zh:b?.en}`);return}l({...t,[u.id]:d}),i(null)},children:s===u.id?e?"按下快捷键…":"Press shortcut…":pi(Us(u.id,t))||(e?"未设置":"Not set")})]},u.id)),a&&r.jsx("p",{role:"alert",children:a}),r.jsx("div",{className:"attention-actions",children:r.jsx("button",{type:"button",onClick:()=>{l({}),i(null)},children:e?"恢复默认快捷键":"Restore defaults"})}),r.jsx("p",{className:"empty-copy",children:e?"⌘N 新建会话,⌘, 打开设置;⌘W 保留为关闭窗口。关闭标签默认使用 ⌘⌥W。":"⌘N creates a session; ⌘, opens settings; ⌘W closes the window. Close tab defaults to ⌘⌥W."})]})}function yh({children:e,t,onClose:n}){const s=c.useRef(null);return c.useEffect(()=>{const i=document.getElementById("vibelet-workspace");return i&&(i.inert=!0),s.current?.focus(),()=>{i&&(i.inert=!1)}},[]),dt.createPortal(r.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),o=a[0],l=a.at(-1);i.shiftKey&&document.activeElement===o&&(i.preventDefault(),l?.focus()),!i.shiftKey&&document.activeElement===l&&(i.preventDefault(),o?.focus())},children:[r.jsxs("button",{ref:s,type:"button",className:"icon-text-button",onClick:n,children:["← ",t.chat]}),r.jsx("h1",{children:t.settings}),r.jsxs("div",{className:"browser-settings-body",children:[r.jsx(yi,{}),e,r.jsx(gh,{chinese:t.browser!=="Browser"})]})]}),document.body)}function bh({children:e,collapsed:t,t:n,value:s,showSession:i,onChange:a,onResize:o}){const l=lr("right",d=>{(d==="terminal"||d==="browser")&&a(d)}),u=ee().toolbarTarget?.("controls"),h=r.jsx(ph,{value:s,t:n,showSession:i,onChange:a});return s==="admin"&&ee().kind==="browser"?r.jsx(yh,{t:n,onClose:()=>a("files"),children:e}):r.jsxs(r.Fragment,{children:[u&&!t?dt.createPortal(h,u):null,r.jsx("button",{"aria-label":n.resizeControlsSidebar,"aria-hidden":t,className:"resize-handle right-resize-handle",disabled:t,onPointerDown:o,title:n.resizeControlsSidebar,type:"button",children:r.jsx("span",{})}),r.jsx("div",{className:"workspace-control-sidebar-motion",inert:t,"aria-hidden":t,children:r.jsxs("aside",{"aria-label":n.controls,className:"control-pane",...l,children:[!u&&r.jsx("div",{className:"control-pane-toolbar",children:h}),e]})})]})}function vh({path:e,label:t,zh:n}){const{copyText:s,feedback:i}=Xs(n?"已复制路径":"Path copied",n?"复制失败,请重试":"Copy failed. Please try again."),a=i?.message??t;return r.jsx("button",{type:"button",title:a,"aria-label":a,onClick:()=>{s(e)},children:i?i.tone==="success"?r.jsx(_t,{}):r.jsx($e,{}):r.jsx(mn,{})})}function tm(e){return/\.(md|mdx|markdown|mdown)$/i.test(e)}function es(e,t,n){const s=t.split(";")[0].trim().toLowerCase();return s.startsWith("image/")?"image":s==="text/html"||/\.html?$/i.test(e)?"html":s==="application/pdf"||/\.pdf$/i.test(e)?"pdf":s.startsWith("audio/")||/\.(mp3|wav|m4a|ogg|flac)$/i.test(e)?"audio":s.startsWith("video/")||/\.(mp4|webm|mov)$/i.test(e)?"video":n?"text":"unsupported"}function xh(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 wh({file:e}){const[t,n]=c.useState(!1),s=Dn(()=>n(!1),void 0,t),i=Mn(),a=Ye(Xe().language),o=a==="en"?"Close":a==="zh-TW"?"關閉":"关闭",l=ee().pdfPreviewUrl?.(e.path,e.cwd)??e.objectUrl;return r.jsxs(r.Fragment,{children:[r.jsxs("button",{className:"icon-text-button",type:"button",onClick:()=>n(!0),children:[r.jsx(ti,{"aria-hidden":"true"}),i.pdfPreview]}),t&&dt.createPortal(r.jsx("div",{className:"remote-document-layer",onPointerDown:u=>{u.target===u.currentTarget&&n(!1)},children:r.jsxs("div",{ref:s,className:"remote-document-dialog","aria-label":i.pdfPreview,role:"dialog","aria-modal":"true",tabIndex:-1,children:[r.jsxs("header",{children:[r.jsx("span",{children:e.path.split("/").pop()}),r.jsx("button",{className:"icon-button",type:"button","aria-label":o,onClick:()=>n(!1),children:r.jsx($e,{"aria-hidden":"true"})})]}),r.jsx("iframe",{title:i.pdfPreview,src:`${l}#toolbar=1&navpanes=0&view=Fit`})]})}),document.body)]})}function ta({file:e}){const[t,n]=c.useState(!1),s=Mn(),i=es(e.path,e.contentType,e.kind==="text");if(t)return r.jsx("p",{className:"empty-copy",role:"status",children:s.mediaError});if(i==="html"){const a=e.dirty?void 0:ee().htmlPreviewUrl?.(e.path,e.cwd);return r.jsx("iframe",{className:"remote-document-preview",sandbox:"allow-scripts",title:s.htmlPreview,src:a,srcDoc:a?void 0:xh(e.text)})}return e.objectUrl?i==="image"?r.jsx("div",{className:"remote-image-viewer",children:r.jsx("img",{className:"remote-image",src:e.objectUrl,alt:e.path,onError:()=>n(!0)})}):i==="audio"?r.jsx("audio",{"aria-label":s.audioPreview,controls:!0,preload:"metadata",src:e.objectUrl,onError:()=>n(!0)}):i==="video"?r.jsx("video",{"aria-label":s.videoPreview,controls:!0,playsInline:!0,preload:"metadata",src:e.objectUrl,onError:()=>n(!0)}):i==="pdf"?r.jsx(wh,{file:e}):r.jsx("p",{className:"empty-copy",children:s.mediaError}):null}const Sh=c.lazy(()=>at(()=>import("./file-editor-FileCodeEditor-ZAqN9Q2f.js").then(e=>e.Q),__vite__mapDeps([18,1,2,19])).then(e=>({default:e.FileCodeEditor})));function kh({file:e,onOpenRemoteFile:t,onTextChange:n}){const[s,i]=c.useState("preview"),a=es(e.path,e.contentType,!0)==="html",o=Ye(Xe().language)!=="en";return r.jsxs(r.Fragment,{children:[a&&r.jsxs("div",{className:"segmented editor-mode-tabs",children:[r.jsx("button",{type:"button",className:s==="edit"?"selected":"",onClick:()=>i("edit"),children:o?"编辑":"Edit"}),r.jsx("button",{type:"button",className:s==="preview"?"selected":"",onClick:()=>i("preview"),children:o?"预览":"Preview"})]}),a&&s==="preview"?r.jsx(ta,{file:e}):r.jsx(c.Suspense,{fallback:r.jsx("pre",{className:"remote-editor",children:e.text}),children:r.jsx(Sh,{path:e.path,cwd:e.cwd,text:e.text,onChange:n,onOpenFile:t})})]})}const Os="vibelet:file-operation-before",qs="vibelet:file-operation-done";function un(e,t=""){const n=e.replace(/\\/g,"/"),s=/^(\/|[a-z]:\/|~)/i.test(n)?n:`${t.replace(/\\/g,"/")}/${n}`,i=[];for(const a of s.split("/"))!a||a==="."||(a===".."?i.pop():i.push(a));return`${s.startsWith("/")?"/":""}${i.join("/")}`}function ws(e,t,n){const s=un(e,n),i=un(t,n);return s===i||s.startsWith(`${i}/`)}async function nm(e,t){const n=new CustomEvent(Os,{cancelable:!0,detail:{...e,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd}});if(!window.dispatchEvent(n))throw new Error("unsaved_changes");const s=await fetch("/file-operation",{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.pairToken}`},body:JSON.stringify(e)}),i=await s.text();let a;try{a=JSON.parse(i)}catch{throw new Error(s.status===404||/^Vibelet Daemon v/.test(i)?"daemon_update_required":"operation_failed")}if(s.status===404&&a.error!=="ENOENT")throw new Error("daemon_update_required");if(!s.ok)throw new Error(a.error??"operation_failed");return or()?.daemonId===t.daemonId&&window.dispatchEvent(new CustomEvent(qs,{detail:{...a,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd,source:e.path}})),a}function jh(e){const t=c.useRef(e);t.current=e,c.useEffect(()=>{const n=i=>{const{detail:a}=i,o=t.current;if(o.daemonId!==a.daemonId||a.action==="copy"||a.action==="restore")return;[...Object.values(o.files),o.remoteFile].filter(Boolean).some(u=>u.dirty&&ws(u.path,a.path,a.cwd))&&i.preventDefault()},s=i=>{const{detail:a}=i,o=t.current;if(o.daemonId!==a.daemonId||a.action==="copy"||a.action==="restore")return;const l=a.source??a.path,u=m=>{if(!ws(m.path,l,a.cwd))return m;if(a.action==="delete")return null;const b=`${a.target}${un(m.path,a.cwd).slice(un(l,a.cwd).length)}`;return{...m,path:b}};o.setFiles(m=>Object.fromEntries(Object.values(m).flatMap(b=>{const p=u(b);return p?[[p.path,p]]:[]}))),o.active&&o.files[o.active]&&o.setActive(u(o.files[o.active])?.path??null),o.setRemoteFile(m=>m&&u(m));const h=new URL(window.location.href),d=h.searchParams.get("file");d&&ws(d,l,a.cwd)&&(a.action==="delete"?h.searchParams.delete("file"):h.searchParams.set("file",`${a.target}${un(d,a.cwd).slice(un(l,a.cwd).length)}`),window.history.replaceState(null,"",h.href))};return window.addEventListener(Os,n),window.addEventListener(qs,s),()=>{window.removeEventListener(Os,n),window.removeEventListener(qs,s)}},[])}function Ch({workspace:e,children:t}){const n=an(),s=lr("center"),[i,a]=c.useState({}),[o,l]=c.useState(null),[u,h]=c.useState(null),d=c.useRef({files:i,remoteFile:e.remoteFile,daemonId:e.pairing?.daemonId});d.current={files:i,remoteFile:e.remoteFile,daemonId:e.pairing?.daemonId};const m=c.useRef(null),b=c.useRef(e.activeSessionId),p=Ye(Xe().language)!=="en";c.useEffect(()=>{d.current.files={},a({}),l(null),m.current=null},[e.pairing?.daemonId]),c.useEffect(()=>{if(!e.remoteFile){m.current=null;return}const v=e.remoteFile,j=d.current.files[v.path];if(j?.dirty&&!v.dirty&&j.cwd===v.cwd&&j.text!==v.text){e.setRemoteFile(j),l(j.path),n.setCenter(null);return}a(N=>({...N,[v.path]:v})),m.current!==v.path&&(l(v.path),n.setCenter(null)),m.current=v.path},[e.remoteFile]),c.useEffect(()=>{const v=b.current;b.current=e.activeSessionId,!(!v||v===e.activeSessionId)&&(l(null),m.current=null)},[e.activeSessionId]);const S=v=>{n.setCenter(null),e.setRemoteFile(i[v]),l(v)},w=async v=>{const j=i[v],N=e.pairing?.daemonId;if(!j)return;const k=hn();j.dirty&&!await Cs({title:k.discard,message:v,confirmLabel:k.discardAction,danger:!0})||d.current.daemonId!==N||d.current.files[v]?.text!==j.text||(a(C=>{const I={...C};return delete I[v],I}),v===o&&(l(null),m.current=null,e.setRemoteFile(null)))};jh({daemonId:e.pairing?.daemonId,files:i,active:o,remoteFile:e.remoteFile,setFiles:a,setActive:l,setRemoteFile:e.setRemoteFile}),c.useEffect(()=>{const v=j=>{const N=j.detail;if(N==="closeTab"){n.center?n.close(n.center):o&&w(o);return}const k=[null,...Object.keys(i),...n.items.filter(R=>R.location==="center").map(R=>R.id)],C=k.indexOf(n.center||o),I=k[(Math.max(C,0)+(N==="nextTab"?1:k.length-1))%k.length];I?i[I]?S(I):n.setCenter(I):(l(null),n.setCenter(null))};return window.addEventListener(Ns,v),()=>window.removeEventListener(Ns,v)},[i,o,n]);const y=o?i[o]:null,g=async()=>{const v=e.remoteFile;!v||!await Cs({message:e.t.confirmOverwrite(Dt(v.path)),danger:!0})||d.current.remoteFile===v&&await e.saveRemoteFile({force:!0})},f=ee().toolbarTarget?.("conversation"),x=y&&!n.center&&r.jsxs("header",{className:"document-file-header",role:"toolbar","aria-label":p?"文件操作":"File actions",children:[r.jsx("button",{type:"button",title:e.t.download,"aria-label":e.t.download,onClick:()=>{e.downloadRemoteFile()},children:r.jsx(ts,{})}),r.jsx(vh,{path:y.path,label:e.t.copyPath,zh:p},y.path),y.kind==="text"&&r.jsx("button",{type:"button",title:e.t.saveFile,"aria-label":e.t.saveFile,disabled:!y.dirty||e.busy,onClick:()=>{e.saveRemoteFile()},children:r.jsx(Fo,{})})]});return r.jsx(Mi.Provider,{value:u,children:r.jsxs("div",{className:"workspace-documents",...s,children:[!f&&r.jsx("div",{className:"chat-header document-conversation-header",ref:h}),(Object.keys(i).length>0||n.items.some(v=>v.location==="center"))&&r.jsxs("div",{className:"document-tabs",children:[r.jsxs("div",{className:"document-tab-items",role:"tablist","aria-label":p?"工作区标签页":"Workspace tabs",children:[r.jsx("button",{role:"tab","aria-selected":!o&&!n.center,onClick:()=>{l(null),n.setCenter(null),m.current=null},type:"button",children:e.t.chat}),Object.values(i).map(v=>r.jsxs("div",{className:"document-tab","data-active":!n.center&&o===v.path,children:[r.jsxs("button",{type:"button",role:"tab","aria-selected":!n.center&&o===v.path,title:v.path,onClick:()=>S(v.path),children:[r.jsx(ti,{}),r.jsxs("span",{className:"document-tab-label",children:[Dt(v.path),v.dirty?" ·":""]})]}),r.jsx("button",{type:"button",className:"document-tab-close",title:e.t.close,"aria-label":`${e.t.close} ${Dt(v.path)}`,onClick:()=>w(v.path),children:r.jsx($e,{})})]},v.path)),r.jsx($s,{location:"center",t:e.t})]}),x]}),r.jsx("div",{hidden:!!o||!!n.center,className:"document-chat",children:t}),r.jsx("div",{hidden:!n.center,className:"dock-center-content",children:r.jsx(Xn,{location:"center"})}),y&&!n.center&&r.jsxs("section",{className:"document-file",role:"tabpanel","aria-label":Dt(y.path),children:[y.kind==="text"?r.jsx(kh,{file:y,onOpenRemoteFile:(v,j)=>{e.openRemoteFile(v,j,{updateRoute:!0})},onTextChange:v=>e.setRemoteFile(j=>j&&{...j,text:v,dirty:!0})},y.path):r.jsx(ta,{file:y},y.path),e.remoteFileConflict&&r.jsxs("div",{role:"alert",className:"inline-notice warning",children:[r.jsx("span",{children:e.t.remoteFileConflict(y.path)}),r.jsx("button",{type:"button",onClick:()=>{g()},children:e.t.forceSave})]})]})]})})}function Ih(e){const t=an(),[n,s]=c.useState(Zn),i=c.useRef({workspace:e,dock:t,shortcuts:n});i.current={workspace:e,dock:t,shortcuts:n},c.useEffect(()=>{const a=()=>s(Zn()),o=l=>{if(l.defaultPrevented||l.isComposing||l.repeat||document.querySelector('[data-shortcut-recording="true"], [role="dialog"], .desktop-workspace-container[hidden], .browser-settings-page'))return;const u=mi(l);if(!u)return;const{workspace:h,dock:d,shortcuts:m}=i.current,b=en.find(g=>Us(g.id,m)===u)?.id;if(!b)return;l.preventDefault(),l.stopPropagation();const p=h.controlTab==="terminal"?"terminal":"browser",S=d.items.find(g=>g.id===d.center),w=l.target instanceof Element&&!!l.target.closest('.workspace-control-sidebar-motion, .dock-surface[data-location="right"]'),y=!w&&S?S:d.items.find(g=>g.id===d.right[p]);switch(b){case"leftSidebar":h.setLeftSidebarCollapsed(g=>!g);break;case"rightSidebar":h.setRightSidebarCollapsed(g=>!g);break;case"files":case"terminal":case"browser":h.setControlTabAndOpen(b);break;case"searchSessions":h.setLeftSidebarCollapsed(!1),window.dispatchEvent(new Event("vibelet.session-search"));break;case"newTab":{const g=S?.kind==="terminal"||S?.kind==="browser"?S.kind:p;d.add(g,h.t[g],h.cwd),h.setControlTabAndOpen(g);break}case"moveTab":y&&d.move(y.id,y.location==="center"?"right":"center");break;case"diff":h.activeSession&&h.setDiffSessionId(h.activeSession.sessionId);break;case"closeTab":case"nextTab":case"previousTab":if(w)if(b==="closeTab")y&&d.close(y.id);else{const g=d.items.filter(f=>f.location==="right"&&f.kind===p);g.length&&d.setRight(f=>({...f,[p]:g[(Math.max(0,g.findIndex(x=>x.id===y?.id))+(b==="nextTab"?1:g.length-1))%g.length].id}))}else window.dispatchEvent(new CustomEvent(Ns,{detail:b}));break}};return window.addEventListener(Is,a),window.addEventListener("keydown",o),()=>{window.removeEventListener(Is,a),window.removeEventListener("keydown",o)}},[])}const na="vibelet.web.savedTargets",sa=12;function Nh(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Eh(e){if(!Nh(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 ra(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const s of e){const i=Eh(s);if(!(!i||t.has(i.daemonId))&&(t.add(i.daemonId),n.push(i),n.length>=sa))break}return n}function Rh(e=Ze()){const t=e.getItem(na);if(!t)return[];try{return ra(JSON.parse(t))}catch{return[]}}function ia(e,t=Ze()){t.setItem(na,JSON.stringify(ra(e)))}function Ah(e,t,n=new Date().toISOString()){const s=e.find(a=>a.daemonId===t.daemonId);return[{...t,label:s?.label||t.displayName||t.daemonId.slice(0,10),lastConnectedAt:n},...e.filter(a=>a.daemonId!==t.daemonId)].slice(0,sa)}function Mh(e,t,n){const s=n.trim();return s?e.map(i=>i.daemonId===t?{...i,label:s}:i):e}function Th(e,t){return e.filter(n=>n.daemonId!==t)}function Ph(e){return e.filter(t=>t.archived===!0).map(t=>t.sessionId)}function Dh(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 _h(e,t,n){if(!e?.isConnected)return{ok:!1,error:"not_connected"};try{const s=await e.request({action:"sessions.archiveSync",id:e.makeId("archive_sync"),mode:t,...t==="pull"?{}:{archivedSessionIds:n??[]}});return{ok:!0,archivedSessionIds:Array.isArray(s.archivedSessionIds)?s.archivedSessionIds.filter(i=>typeof i=="string"&&i.length>0):[]}}catch(s){return{ok:!1,error:s instanceof Error?s.message:String(s)}}}function Lh(e){const t=c.useCallback((f,x)=>{e.updateSessionListPreferences(v=>({...v,archiveSyncedDaemonIds:x==="synced"?{...v.archiveSyncedDaemonIds,[f]:!0}:v.archiveSyncedDaemonIds,archiveSyncCardDismissedDaemonIds:{...v.archiveSyncCardDismissedDaemonIds,[f]:!0}}))},[e]),n=c.useCallback((f,x)=>{const v=f==="pull"?e.t.archiveSyncSuccessPull:f==="pushMerge"?e.t.archiveSyncSuccessMerge:e.t.archiveSyncSuccessPush;if(e.setArchiveSyncStatus(Dh(x,v,{timeout:e.t.archiveSyncFailedTimeout,disconnected:e.t.archiveSyncFailedDisconnected,generic:e.t.archiveSyncFailedGeneric})),!x.ok)return;const j=new Set(x.archivedSessionIds);e.setSessions(N=>N.map(k=>({...k,archived:j.has(k.sessionId)}))),e.pairingRef.current?.daemonId&&t(e.pairingRef.current.daemonId,"synced"),e.requestSessions({force:!0})},[t,e]),s=c.useCallback(async f=>{if(e.archiveSyncBusy)return;e.setArchiveSyncBusy(f),e.setArchiveSyncStatus(null);const x=await _h(e.clientRef.current,f,Ph(e.displaySessions));n(f,x),e.setArchiveSyncBusy(null)},[n,e]),i=c.useCallback(()=>{e.pairing?.daemonId&&(t(e.pairing.daemonId,"dismissed"),e.setArchiveSyncStatus({tone:"success",message:e.t.archiveSyncSkipped}))},[t,e]),a=c.useCallback(async f=>{const x=e.clientRef.current;if(x?.isConnected&&!(f==="update"&&!await In(hn().update))&&!(f==="restart"&&!await In(hn().restart))&&!(e.clientRef.current!==x||!x.isConnected)){e.setAdmin(v=>({...v,loading:!0,action:f,statusText:""})),e.setErrorText(null);try{if(f==="update"){const v=Xu(e.daemonMetadata.version),j=await x.request({action:"daemon.update",id:x.makeId("daemon_update"),...v?{channel:v}:{}});e.setAdmin(N=>({...N,loading:!1,action:null,statusText:j.alreadyRunning?"Connector update already running":"Connector update started"}));return}await x.request({action:"daemon.restart",id:x.makeId("daemon_restart")}),e.setAdmin(v=>({...v,loading:!1,action:null,statusText:"Connector restart requested"})),e.refreshDaemonMetadata()}catch(v){e.setAdmin(j=>({...j,loading:!1,action:null})),e.setErrorText(v instanceof Error?v.message:String(v))}}},[e]),o=c.useCallback(async()=>{if(!e.activeSession)return;const f=Vc(e.activeSession,e.messages);Qc(Gc(It(e.activeSession),e.activeSession.sessionId),f),await navigator.clipboard?.writeText(f).catch(()=>{})},[e.activeSession,e.messages]),l=c.useCallback(async()=>{if(!("Notification"in window)){e.setNotificationPermission("unsupported"),e.setErrorText("Browser notifications are not supported.");return}const f=await Notification.requestPermission();e.notificationPermissionRef.current=f,e.setNotificationPermission(f),f==="granted"&&e.updateNotificationSettings({enabled:!0}),e.setStatusText(f==="granted"?"Browser notifications enabled":"Browser notifications not enabled")},[e]),u=c.useCallback(async()=>{const f=e.pairingRef.current;!await In(hn().forget)||e.pairingRef.current!==f||(e.intentionalDisconnectRef.current=!0,e.connectionAttemptIdRef.current+=1,zi(),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(ur),e.setPhase("missing-pair"),e.setStatusText(e.t.missingPair))},[e]),h=c.useCallback(f=>{if(f&&e.notificationPermission==="default"){l();return}e.updateNotificationSettings({enabled:f})},[e,l]),d=c.useCallback(f=>{e.connectWithPairingRef.current(f,!0)},[e]),m=c.useCallback(f=>e.saveTargets(Th(e.savedTargets,f)),[e]),b=c.useCallback(f=>{e.setActiveSessionId(f.sessionId),e.setRenameTitle(f.customTitle??f.title??""),e.setDetailsOpen(!0)},[e]),p=c.useCallback((f,x)=>{const v=fa(x);e.updateSessionListPreferences(j=>({...j,directoryTags:ma(j.directoryTags,f,v)}))},[e]),S=c.useCallback(f=>{e.setControlTab("files"),e.listDirectory(f,{updateRoute:!0})},[e]),w=c.useCallback(async f=>{try{await Ys(wi(f)),e.setStatusText(e.t.commandCopied)}catch{throw e.setErrorText(e.t.copyResumeFailed),new Error(e.t.copyResumeFailed)}},[e]),y=c.useRef(!1),g=c.useCallback(async f=>{if(y.current)return;const x=ee(),v=e.pairingRef.current?.daemonId;if(!(!v||!x.resumeInTerminal||!x.isLocalDaemon?.(v))){y.current=!0;try{const j=e.clientRef.current;if(!j)throw new Error("Not connected");await j.request({action:"session.release",id:j.makeId("release"),sessionId:f.sessionId,agent:f.agent}),await x.resumeInTerminal({...f,daemonId:v,approvalMode:f.approvalMode??f.observedApprovalMode})}catch(j){e.setErrorText(String(j).includes("session_busy")?e.t.resumeTerminalBusy:e.t.resumeTerminalFailed)}finally{y.current=!1}}},[e]);return{runArchiveSync:s,skipArchiveSync:i,runAdminAction:a,exportActiveSession:o,clearPairing:u,setNotificationsEnabled:h,connectSavedTarget:d,forgetSavedTarget:m,openSessionDetails:b,editFolderTags:p,browseFolder:S,copyResumeCommand:w,resumeInTerminal:g}}class $h{timer=null;sentAt=null;listeners=new Set;value=null;subscribe(t){return this.listeners.add(t),t(this.value),()=>{this.listeners.delete(t)}}start(t,n){this.stop();const s=()=>{if(this.sentAt!==null){this.stop(),n();return}this.sentAt=performance.now(),t()};s(),this.timer=setInterval(s,3e4)}acknowledge(){if(this.sentAt===null)return;const t=Math.max(0,Math.round(performance.now()-this.sentAt));this.sentAt=null,this.publish(t)}stop(){this.timer!==null&&clearInterval(this.timer),this.timer=null,this.sentAt=null,this.publish(null)}publish(t){this.value=t,this.listeners.forEach(n=>n(t))}}function qr(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function Fh(e,t=window.location,n=!0){const i=`${t.protocol==="https:"?"wss:":"ws:"}//${t.host}`;return n&&Wi(t.hostname)?i:e?.webSocketUrl?e.webSocketUrl:i}class Oh{heartbeat=new $h;onLatency=t=>this.heartbeat.subscribe(t);capabilities={};socket=null;pending=new Map;messageListeners=new Set;closeListeners=new Set;async connect(t){this.disconnect();const n=new WebSocket(Fh(t));this.socket=n;let s;const i=new Promise((o,l)=>{s=l,n.onopen=()=>o(),n.onerror=()=>l(new Error("WebSocket connection failed."))});if(n.onmessage=o=>{this.socket===n&&this.handleSocketMessage(o.data)},n.onclose=()=>{s(new Error("WebSocket disconnected.")),this.socket===n&&(this.heartbeat.stop(),this.socket=null,this.rejectPending(new Error("WebSocket disconnected.")),this.closeListeners.forEach(o=>o()))},await i,this.socket!==n)throw new Error("WebSocket disconnected.");const a=await this.request({action:"auth.hello",id:qr("auth"),pairToken:t.pairToken,daemonId:t.daemonId,deviceId:t.deviceId,locale:navigator.language});if(this.socket!==n)throw new Error("WebSocket disconnected.");return this.capabilities=a.capabilities??{},this.heartbeat.start(()=>n.send(JSON.stringify({action:"ping"})),()=>n.close()),a}request(t,n={}){return!this.socket||this.socket.readyState!==WebSocket.OPEN?Promise.reject(new Error("WebSocket is not connected.")):new Promise((s,i)=>{const a={action:t.action,resolve:s,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.heartbeat.stop(),this.capabilities={},this.rejectPending(new Error("WebSocket disconnected."));const t=this.socket;this.socket=null,t?.close(1e3,"client disconnect")}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}makeId(t){return qr(t)}handleSocketMessage(t){if(typeof t!="string")return;let n;try{n=JSON.parse(t)}catch{return}if(n.type==="pong"){this.heartbeat.acknowledge();return}if(n.type==="error"&&!n.sessionId){const s=/unsupported action "([^"]+)"/.exec(n.message)?.[1];if(s){let i=!1;for(const[a,o]of this.pending)o.action===s&&(this.pending.delete(a),o.timeoutId&&clearTimeout(o.timeoutId),o.reject(new Error(n.message)),i=!0);if(i)return}}if(n.type==="response"){const s=this.pending.get(n.id);if(s){this.pending.delete(n.id),s.timeoutId&&clearTimeout(s.timeoutId),n.ok?s.resolve(n.data):s.reject(new Error(n.error||"Request failed."));return}}this.messageListeners.forEach(s=>s(n))}rejectPending(t){for(const n of this.pending.values())n.timeoutId&&clearTimeout(n.timeoutId),n.reject(t);this.pending.clear()}}const aa="vibelet.web.sessionListCache",oa=120;function qh(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Wh(e){if(!qh(e)||typeof e.daemonId!="string"||!e.daemonId)return null;const t=Ii(e.page);return{daemonId:e.daemonId,page:{...t,sessions:t.sessions.slice(0,oa)},cachedAt:typeof e.cachedAt=="string"?e.cachedAt:new Date(0).toISOString()}}function zh(e,t=Ze()){if(!e)return null;try{const n=t.getItem(aa);if(!n)return null;const s=Wh(JSON.parse(n));return s?.daemonId===e?s.page:null}catch{return null}}function Bh(e,t,n=Ze(),s=new Date().toISOString()){if(!e)return;const i={daemonId:e,page:{...t,sessions:t.sessions.slice(0,oa)},cachedAt:s};n.setItem(aa,JSON.stringify(i))}function Hh(e){return e instanceof Error&&e.message==="auth_failed"}function Kh(e,t){return e instanceof Pn&&e.code==="pair_window_expired"?t.pairingLinkExpired:e instanceof Error?e.message:String(e)}function Uh(e){const t=c.useRef(null),n=c.useRef(e);n.current=e;const s=c.useCallback(a=>{const o=n.current,l=a??o.pairingRef.current;!l||o.intentionalDisconnectRef.current||(o.reconnectTimerRef.current&&window.clearTimeout(o.reconnectTimerRef.current),o.reconnectTimerRef.current=window.setTimeout(()=>{o.reconnectTimerRef.current=null,o.connectWithPairingRef.current(l,!0)},_c))},[]),i=c.useCallback(async(a,o=!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(o?l.t.reconnectingToDaemon:l.t.connectingToDaemon),l.setErrorText(null);const u=new Oh,h=l.connectionAttemptIdRef.current+1;l.connectionAttemptIdRef.current=h;const d=l.clientRef.current;l.clientRef.current=u,d?.disconnect();const m=()=>l.connectionAttemptIdRef.current===h&&l.clientRef.current===u;u.onMessage(b=>{m()&&n.current.handleServerMessage(b)}),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),s(l.pairingRef.current??a)))});try{let b=a,p;try{p=await u.connect(a)}catch(g){if(!m()||!a.webSocketUrl)throw g;b={...a,webSocketUrl:void 0},l.setStatusText(l.t.reconnectingToDaemon),p=await u.connect(b)}if(!m())return;const S={...b,displayName:p.displayName??b.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,Rr(S);const w=zh(S.daemonId);if(w&&l.setSessionsFromPage(w,!1),l.setSavedTargets(g=>{const f=Ah(g,S);return ia(f),f}),l.setPhase("connected"),l.setStatusText(l.t.connectedTo(p.displayName??a.displayName??"Vibelet Daemon")),l.refreshDaemonMetadata(S),await l.requestReconnectSnapshot(),!m())return;const y=n.current;await y.fetchAgentResources(y.agent,y.cwd),l.reportLog("web.connected",{reconnecting:o})}catch(b){if(!m())return;Hh(b)&&zi(),l.setPhase("error"),l.setStatusText(l.t.connectionFailed),l.setErrorText(b instanceof Error?b.message:String(b)),s(a)}},[s]);c.useEffect(()=>{const a=n.current;a.connectWithPairingRef.current=i},[i]),c.useEffect(()=>{const a=n.current;let o=!1;async function l(){const u=pd(),d=or()??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:wd(u,d)});const m=u?await t.current?.promise:d;if(!m||o)return;u&&(Rr(m),t.current=null,gd()),await a.connectWithPairingRef.current(m)}catch(m){if(o)return;u&&(t.current=null),a.setPhase("error"),a.setStatusText(a.t.pairingFailed),a.setErrorText(Kh(m,a.t))}}return l(),()=>{o=!0,a.intentionalDisconnectRef.current=!0,a.connectionAttemptIdRef.current+=1,a.reconnectTimerRef.current&&window.clearTimeout(a.reconnectTimerRef.current),a.clientRef.current?.disconnect()}},[e.t]),c.useEffect(()=>{const a=n.current;if(a.phase!=="connected")return;const o=window.setTimeout(()=>{a.requestSessions({force:!0}).catch(l=>a.setErrorText(l instanceof Error?l.message:String(l)))},260);return()=>window.clearTimeout(o)},[e.phase,e.requestSessions,e.search,e.sinceFilter]),c.useEffect(()=>{const a=n.current;a.phase==="connected"&&a.fetchAgentResources(a.agent,a.cwd)},[e.agent,e.cwd,e.fetchAgentResources,e.phase])}const ca="vibelet.web.composerDrafts",Ws={draftsBySessionId:{},newSessionDraft:""};function Wr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function la(e){return Wr(e)?{draftsBySessionId:Wr(e.draftsBySessionId)?Object.fromEntries(Object.entries(e.draftsBySessionId).filter(n=>typeof n[1]=="string")):{},newSessionDraft:typeof e.newSessionDraft=="string"?e.newSessionDraft:""}:Ws}function Gh(e=Ze()){const t=e.getItem(ca);if(!t)return Ws;try{return la(JSON.parse(t))}catch{return Ws}}function nn(e,t=Ze()){t.setItem(ca,JSON.stringify(la(e)))}function sn(e,t,n){if(!t)return{...e,newSessionDraft:n};const s={...e.draftsBySessionId};return n.trim()?s[t]=n:delete s[t],{...e,draftsBySessionId:s}}function rn(e,t){return t?e.draftsBySessionId[t]??"":e.newSessionDraft}function Vh(e,t,n){if(!t||!n||t===n)return e;const s=e.draftsBySessionId[t];if(s===void 0)return e;const i={...e.draftsBySessionId};return delete i[t],s.trim()&&(i[n]=s),{...e,draftsBySessionId:i}}function Qh(e){const[t,n]=c.useState(!1),s=c.useRef(!1),i=e.clientRef.current,a=e.activeSessionId,o=!a||!!(e.pendingApprovals[a]||e.pendingQuestions[a]),l=!o&&i?.supportsSessionSteer===!0&&!!a&&e.respondingSessions.has(a)&&e.activeSession?.runtime.state!=="externalRunning",u=!o&&i?.supportsQueueSendNow===!0;return{busy:t,canGuide:l,canSendNow:u,onAction:async(m,b)=>{if(!a||!i?.isConnected||s.current||!(b==="guide"?l:u))return;const p=new Set(m.map(g=>g.clientMessageId).filter(Boolean)),S=e.activeQueue.filter(g=>g.clientMessageId&&p.has(g.clientMessageId));if(!S.length)return;s.current=!0,n(!0),e.setErrorText(null);const w=new Set;for(const g of S)e.setCachedMessageDelivery(a,g.clientMessageId,"sending",g);const y=g=>{w.add(g.clientMessageId),e.setCachedMessageDelivery(a,g.clientMessageId,"delivered")};try{if(b==="sendNow")await i.request({action:"session.queue.sendNow",id:i.makeId("queue_now"),sessionId:a,clientMessageIds:S.map(g=>g.clientMessageId)},{timeoutMs:15e3}),S.forEach(y);else for(const g of S)await i.request({action:"session.steer",id:i.makeId("queue_guide"),sessionId:a,clientMessageId:g.clientMessageId,message:g.content,images:g.images},{timeoutMs:15e3}),y(g),e.setPendingQueues(f=>({...f,[a]:(f[a]??[]).filter(x=>x.clientMessageId!==g.clientMessageId)}))}catch(g){let f=!1;for(const x of S)w.has(x.clientMessageId)||(f=e.setCachedMessageDelivery(a,x.clientMessageId,"failed")!=="delivered"||f);f&&e.setErrorText(g instanceof Error?g.message:String(g))}finally{s.current=!1,n(!1)}},onCollect:async m=>{if(!a||!i?.isConnected||s.current)return;const b=new Set(m.map(S=>S.clientMessageId).filter(S=>!!S)),p=e.activeQueue.filter(S=>S.clientMessageId&&b.has(S.clientMessageId));if(!(p.length<2)){s.current=!0,n(!0),e.setErrorText(null);try{const w=(await i.request({action:"session.queue.collect",id:i.makeId("queue_collect"),sessionId:a,clientMessageIds:p.map(f=>f.clientMessageId)},{timeoutMs:15e3})).entries;if(!Array.isArray(w))throw new Error("Invalid queue collection response");const y=w.map(f=>f.content).filter(f=>f.trim()).join(`
|
|
11
|
+
|
|
12
|
+
`),g=f=>[f,y].filter(x=>x.trim()).join(`
|
|
13
|
+
|
|
14
|
+
`);if(e.setComposerDrafts(f=>{const x=sn(f,a,g(rn(f,a)));return e.composerDraftsRef.current=x,nn(x),x}),e.activeSessionIdRef.current===a){e.setDraft(g);const f=[...new Set(w.flatMap(x=>x.images??[]))];e.setAttachments(x=>{const v=new Set(x.map(j=>j.path));return[...x,...f.filter(j=>!v.has(j)).map(j=>({path:j,name:Dt(j),type:"image/*",size:0}))]})}e.setPendingQueues(f=>({...f,[a]:(f[a]??[]).filter(x=>!x.clientMessageId||!b.has(x.clientMessageId))}))}catch(S){e.setErrorText(S instanceof Error?S.message:String(S))}finally{s.current=!1,n(!1)}}}}}function ds(e,t){return!!t&&Object.hasOwn(e,t)}function Zh(e,t){const n=e.map(s=>({...s}));return t?Vs(Zs(n,t)):n}function Jh(e,t,n){return t?{...e,[t]:nf(e[t]??[],n)}:e}function da(e,t,n){return!t||n.length===0?e:{...e,[t]:ki(e[t]??[],n)}}function Yh(e,t,n){return n.historyKey&&e[t]?.some(s=>s.historyKey===n.historyKey)?e:da(e,t,[n])}function Xh(e,t,n){return!t||!n?e:{...e,[t]:Vs(Zs(e[t]??[],n))}}function ef(e,t,n){if(!t||!n||t===n||!ds(e,t))return e;const s={...e};return s[n]=e[t],delete s[t],s}function tf(e,t){if(!ds(e,t))return e;const n={...e};return delete n[t],n}function nf(e,t){const n=ki(e,t),s=new Map;for(const o of n)o.historyKey&&o.localClientMessageId&&!s.has(o.historyKey)&&s.set(o.historyKey,o);const i=t.map(o=>{const l=o.historyKey&&s.get(o.historyKey);return l?{...o,localClientMessageId:l.localClientMessageId,localDelivery:l.localDelivery}:{...o}}),a=new Set(i.map(o=>o.localClientMessageId));return[...i,...n.filter(o=>o.localClientMessageId&&o.historyKey?.startsWith("client:")&&!a.has(o.localClientMessageId))]}function Jt(e,t,n){const s=new Set(e);return n?s.add(t):s.delete(t),s}function sf(e){const t=c.useCallback((n,s,i,a,o)=>{const l=e.notificationSettingsRef.current;if(!l[a]||e.notifiedEventsRef.current.has(n))return;Nc(s,i,{onClick:()=>{window.focus(),o&&e.setActiveSessionId(o)},permission:e.notificationPermissionRef.current,settings:l,tag:n,visibilityState:document.visibilityState})&&e.notifiedEventsRef.current.add(n)},[e]);return c.useCallback(n=>{switch(n.type){case"response":{Xt(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(s=>e.setErrorText(s instanceof Error?s.message:String(s)));break;case"session.history":e.setPendingQueues(s=>({...s,[n.sessionId]:n.pendingQueue??[]})),e.clearHistoryLoading(n.sessionId),e.mergeCachedHistoryPage(n.sessionId,Zh(n.messages,n.partialReplyText),n.historyPage),n.sessionId===e.activeSessionIdRef.current&&(e.setPendingApprovals(s=>{const i={...s};return n.pendingApproval?i[n.sessionId]={type:"approval.request",sessionId:n.sessionId,...n.pendingApproval}:delete i[n.sessionId],i}),e.setPendingQuestions(s=>{const i={...s};if(n.pendingQuestion){const a={type:"question.request",sessionId:n.sessionId,...n.pendingQuestion};i[n.sessionId]=a,e.setQuestionAnswers(Js(a))}else delete i[n.sessionId];return i})),e.setRespondingSessions(s=>{const i=Jt(s,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=Jt(e.respondingSessionsRef.current,n.sessionId,!0),e.setRespondingSessions(s=>Jt(s,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}
|
|
15
|
+
|
|
16
|
+
${qc(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(s=>({...s,[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(s=>({...s,[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(s=>{const i={...s};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(s=>s.map(i=>i.sessionId===n.sessionId?{...i,stallWarning:n.warning}:i));break;case"session.interrupted_notice":e.setSessions(s=>s.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 s=(e.turnNotificationCountsRef.current[n.sessionId]??0)+1;e.turnNotificationCountsRef.current[n.sessionId]=s,t(`done:${n.sessionId}:${s}`,e.t.notificationReplyTitle,e.t.notificationReplyBody,"replies",n.sessionId)}e.respondingSessionsRef.current=Jt(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(s=>Jt(s,n.sessionId,!1)),e.setPendingApprovals(s=>{const i={...s};return delete i[n.sessionId],i}),e.setPendingQuestions(s=>{const i={...s};return delete i[n.sessionId],i}),n.usage&&e.setSessions(s=>s.map(i=>i.sessionId===n.sessionId?{...i,lastUsage:n.usage}:i)),e.requestSessions({force:!0,preserveLoaded:!0}).catch(s=>e.setErrorText(s instanceof Error?s.message:String(s)));break;case"session.interrupted":e.respondingSessionsRef.current=Jt(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(s=>Jt(s,n.sessionId,!1)),e.requestSessions({force:!0,preserveLoaded:!0}).catch(s=>e.setErrorText(s instanceof Error?s.message:String(s)));break;case"session.renamed":e.setSessions(s=>s.map(i=>i.sessionId===n.sessionId?{...i,customTitle:n.title}:i));break;case"error":e.setErrorText(n.message);break}},[e,t])}function rf(e,t,n,s=!1){if(!s)return{...e,[t]:[n]};const i=e[t]??[],a=i.includes(n)?i.filter(o=>o!==n):[...i,n];return{...e,[t]:a}}function af(e){const t=c.useCallback(async y=>{const g=e.clientRef.current,f=e.activeApproval;if(!(!g?.isConnected||!f)){e.setBusy(!0),e.setErrorText(null);try{await g.request({action:"session.approve",id:g.makeId("approve"),sessionId:f.sessionId,requestId:f.requestId,approved:y}),e.setPendingApprovals(x=>{const v={...x};return v[f.sessionId]?.requestId===f.requestId&&delete v[f.sessionId],v})}catch(x){const v=x instanceof Error?x.message:String(x);/session not found|session .* inactive/i.test(v)&&e.setPendingApprovals(j=>{if(j[f.sessionId]?.requestId!==f.requestId)return j;const N={...j};return delete N[f.sessionId],N}),e.setErrorText(v)}finally{e.setBusy(!1)}}},[e]),n=c.useCallback(async()=>{const y=e.clientRef.current;if(!(!y?.isConnected||!e.activeQuestion)){e.setBusy(!0),e.setErrorText(null);try{await y.request({action:"session.respondQuestion",id:y.makeId("question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId,answers:e.questionAnswers}),e.setPendingQuestions(g=>{const f={...g};return f[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete f[e.activeQuestion.sessionId],f})}catch(g){e.setErrorText(g instanceof Error?g.message:String(g))}finally{e.setBusy(!1)}}},[e]),s=c.useCallback(async()=>{const y=e.clientRef.current;if(!(!y?.isConnected||!e.activeQuestion)){e.setBusy(!0),e.setErrorText(null);try{await y.request({action:"session.cancelQuestion",id:y.makeId("cancel_question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId}),e.setPendingQuestions(g=>{const f={...g};return f[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete f[e.activeQuestion.sessionId],f})}catch(g){e.setErrorText(g instanceof Error?g.message:String(g))}finally{e.setBusy(!1)}}},[e]),i=c.useCallback((y,g,f)=>{e.setQuestionAnswers(x=>rf(x,y,g,!!f))},[e]),a=c.useCallback(async y=>{const g=e.clientRef.current,f=e.activeSession,x=f?.sessionId??(y==="session.interrupt"?e.activeSessionIdRef.current:null);if(!g?.isConnected||!x||y!=="session.interrupt"&&!f||y==="session.delete"&&!await In(hn().deleteSession(It(f)))||e.clientRef.current!==g||!g.isConnected)return!1;e.setBusy(!0),e.setErrorText(null);try{return y==="session.resume"?await g.request({action:y,id:g.makeId("resume"),sessionId:x,agent:f.agent}):await g.request({action:y,id:g.makeId(y.split(".").at(-1)??"session"),sessionId:x}),y==="session.delete"&&(e.removeCachedHistory(f.sessionId),e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([])),y!=="session.interrupt"&&await e.requestSessions({force:!0,preserveLoaded:!0}),!0}catch(v){return e.setErrorText(v instanceof Error?v.message:String(v)),!1}finally{e.setBusy(!1)}},[e]),o=c.useCallback(async y=>{const g=e.clientRef.current;if(!e.activeSession){e.setApprovalMode(y);return}if(g?.isConnected){e.setErrorText(null);try{await g.request({action:"session.setApprovalMode",id:g.makeId("approval_mode"),sessionId:e.activeSession.sessionId,approvalMode:y}),e.activeSessionIdRef.current===e.activeSession.sessionId&&e.setApprovalMode(y),e.setSessions(f=>f.map(x=>x.sessionId===e.activeSession.sessionId?{...x,approvalMode:y}:x))}catch(f){e.setErrorText(f instanceof Error?f.message:String(f))}}},[e]),l=c.useCallback(async y=>{const g=e.clientRef.current;if(!g?.isConnected||!e.activeSessionId||!y.clientMessageId)return;const f=e.activeSessionId;let x=-1;e.setPendingQueues(j=>{const N=j[f]??[];return x=N.findIndex(k=>k.clientMessageId===y.clientMessageId),{...j,[f]:N.filter(k=>k.clientMessageId!==y.clientMessageId)}}),e.setBusy(!0),e.setErrorText(null);try{await g.request({action:"session.queue.cancel",id:g.makeId("queue_cancel"),sessionId:f,clientMessageId:y.clientMessageId})}catch(j){e.setPendingQueues(N=>{const k=N[f]??[];if(k.some(I=>I.clientMessageId===y.clientMessageId))return N;const C=Math.min(Math.max(x,0),k.length);return{...N,[f]:[...k.slice(0,C),y,...k.slice(C)]}}),e.setErrorText(j instanceof Error?j.message:String(j));return}finally{e.setBusy(!1)}const v=j=>[j,y.content].filter(Boolean).join(`
|
|
17
|
+
|
|
18
|
+
`);if(e.setComposerDrafts(j=>{const N=sn(j,f,v(rn(j,f)));return e.composerDraftsRef.current=N,nn(N),N}),e.activeSessionIdRef.current===f&&(e.setDraft(v),y.images?.length)){const j=[...new Set(y.images)];e.setAttachments(N=>{const k=new Set(N.map(C=>C.path));return[...N,...j.filter(C=>!k.has(C)).map(C=>({path:C,name:Dt(C),type:"image/*",size:0}))]})}},[e]),u=c.useCallback(async(y,g)=>{if(e.pendingSessions[y.sessionId])return;const f=e.clientRef.current;if(f?.isConnected){e.setBusy(!0),e.setErrorText(null);try{const x=g?Date.now():void 0;await f.request({action:"session.setPinned",id:f.makeId("pin"),sessionId:y.sessionId,pinned:g,...x?{pinnedAt:x}:{}}),e.setSessions(v=>v.map(j=>j.sessionId===y.sessionId?{...j,pinned:g,pinnedAt:x}:j)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(x){e.setErrorText(x instanceof Error?x.message:String(x))}finally{e.setBusy(!1)}}},[e]),h=c.useCallback(async(y,g)=>{if(e.pendingSessions[y.sessionId])return;const f=e.clientRef.current;if(f?.isConnected){e.setBusy(!0),e.setErrorText(null);try{await f.request({action:"session.setArchived",id:f.makeId("archive"),sessionId:y.sessionId,archived:g}),e.setSessions(x=>x.map(v=>v.sessionId===y.sessionId?{...v,archived:g}:v)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(x){e.setErrorText(x instanceof Error?x.message:String(x))}finally{e.setBusy(!1)}}},[e]),d=c.useCallback(async y=>{if(e.pendingSessions[y.sessionId]){e.removeCachedHistory(y.sessionId),e.setPendingSessions(f=>{const x={...f};return delete x[y.sessionId],x}),e.setComposerDrafts(f=>{const x=sn(f,y.sessionId,"");return e.composerDraftsRef.current=x,nn(x),x}),e.activeSessionIdRef.current===y.sessionId&&(e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([]),e.setDraft(rn(e.composerDraftsRef.current,null)),e.setDetailsOpen(!1));return}const g=e.clientRef.current;if(!(!g?.isConnected||!await In(hn().deleteSession(It(y))))&&!(e.clientRef.current!==g||!g.isConnected)){e.setBusy(!0),e.setErrorText(null);try{await g.request({action:"session.delete",id:g.makeId("delete"),sessionId:y.sessionId}),e.removeCachedHistory(y.sessionId),e.setOptimisticSessions(f=>{if(!f[y.sessionId])return f;const x={...f};return delete x[y.sessionId],x}),e.activeSessionIdRef.current===y.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(f){e.setErrorText(f instanceof Error?f.message:String(f))}finally{e.setBusy(!1)}}},[e]),m=c.useCallback(async()=>{e.activeSession&&await u(e.activeSession,!e.activeSession.pinned)},[e.activeSession,u]),b=c.useCallback(async()=>{e.activeSession&&await h(e.activeSession,!e.activeSession.archived)},[e.activeSession,h]),p=c.useCallback(()=>{const y=e.activeSessionId;y&&a("session.interrupt").then(g=>{g&&(e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current),e.respondingSessionsRef.current.delete(y),e.setRespondingSessions(f=>{const x=new Set(f);return x.delete(y),x}))})},[e,a]),S=c.useCallback(()=>{e.setErrorText(null),e.phase==="connected"?e.requestSessions({force:!0,preserveLoaded:!0}):window.location.reload()},[e]),w=c.useCallback(async()=>{const y=e.renameTitle.trim();if(e.activeSession&&e.pendingSessions[e.activeSession.sessionId]){e.setPendingSessions(f=>{const x=f[e.activeSession.sessionId];return x?{...f,[e.activeSession.sessionId]:{...x,title:y||x.title,customTitle:y||void 0}}:f});return}const g=e.clientRef.current;if(!(!g?.isConnected||!e.activeSession)){e.setBusy(!0),e.setErrorText(null);try{await g.request({action:"session.rename",id:g.makeId("rename"),sessionId:e.activeSession.sessionId,title:y||void 0}),e.setSessions(f=>f.map(x=>x.sessionId===e.activeSession.sessionId?{...x,customTitle:y||void 0}:x))}catch(f){e.setErrorText(f instanceof Error?f.message:String(f))}finally{e.setBusy(!1)}}},[e]);return{respondApproval:t,respondQuestion:n,cancelQuestion:s,setQuestionChoice:i,requestActiveAction:a,interruptActiveSession:p,retrySessions:S,updateApprovalMode:o,cancelQueuedTurn:l,setSessionPinned:u,setSessionArchived:h,deleteSession:d,updatePinned:m,updateArchived:b,renameSession:w}}async function zs(e){return{[e]:"desktop-free"}}function of(){let e=null,t=null;const n=new Set,s=()=>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,s(),{remap(o){t===a&&(e={sessionId:o},s())},finish(){t===a&&(t=null,e=null,s())}}}}}function zr(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 Br=15e3,Hr="Session send timed out.";function jn(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function cf(e){const[t]=c.useState(of),[n,s]=c.useState(null),[i,a]=c.useState(null),o=c.useCallback(m=>{e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current),e.respondingSessionsRef.current.delete(m),e.setRespondingSessions(b=>{const p=new Set(b);return p.delete(m),p})},[e]),l=c.useCallback((m,b,p)=>{const S=jn(m)??jn(e.cwd)??it,w=b??e.agent,y=Wc(),g=zc({sessionId:y,agent:w,cwd:S,approvalMode:p?.approvalMode??e.approvalMode,model:Kn(p?.model??e.model),effort:e.effort||void 0,fastMode:e.fastMode,title:w==="codex"?e.t.newCodexSession:e.t.newClaudeSession}),f=p?.draft??(e.activeSessionIdRef.current?"":rn(e.composerDraftsRef.current,null));return e.setPendingSessions(x=>({...x,[y]:g})),e.setComposerDrafts(x=>{let v=sn(x,y,f);return e.activeSessionIdRef.current||(v=sn(v,null,"")),e.composerDraftsRef.current=v,nn(v),v}),e.setCwd(S),e.setAgent(w),e.activeSessionIdRef.current=y,e.setActiveSessionId(y),e.lastHistorySessionIdRef.current=y,e.messagesSessionIdRef.current=y,e.clearHistoryLoading(),e.setMessages([]),e.setDraft(f),p?.draft?.trim()&&a(y),e.setErrorText(null),e.reportLog("web.session.pending_create",{sessionId:y,agent:w,cwd:S}),y},[e]),u=c.useCallback(async(m,b,p)=>{const S=e.clientRef.current;if(!S?.isConnected)return e.setErrorText(e.t.webSocketNotConnected),null;const w=p?e.pendingSessions[p]:void 0,y=jn(m)??jn(w?.cwd)??jn(e.cwd)??it,g=b??w?.agent??e.agent,f=w?.approvalMode??e.approvalMode,x=w?w.model:Kn(e.model),v=w?.effort??(e.effort||void 0),j=w?.fastMode??e.fastMode;e.setErrorText(null);try{const N=await S.request({action:"session.create",id:S.makeId("create"),agent:g,cwd:y,approvalMode:f,continueSession:e.continueSession,model:x,effort:v,fastMode:j,...p?{clientSessionId:p}:{}}),k=Fc(N);if(!k)throw new Error(e.t.sessionIdMissing);const C=Xt(N)&&typeof N.oldSessionId=="string"?N.oldSessionId:p;return e.setCwd(y),e.setAgent(g),e.activeSessionIdRef.current=k,e.setActiveSessionId(k),e.lastHistorySessionIdRef.current=k,e.messagesSessionIdRef.current=k,e.clearHistoryLoading(),p&&w?(e.setPendingSessions(I=>{const R={...I};return delete R[p],C&&C!==p&&delete R[C],R}),e.setOptimisticSessions(I=>({...I,[k]:Bc(w,k)})),C&&C!==k&&e.remapLocalSessionState(C,k),p!==k&&e.remapLocalSessionState(p,k)):await e.requestSessions({force:!0}),e.reportLog("web.session.create",{sessionId:k,clientSessionId:p,agent:g,cwd:y}),k}catch(N){return e.setErrorText(N instanceof Error?N.message:String(N)),null}},[e]),h=c.useCallback(async m=>{m?.preventDefault();const b=e.draft.trim();if(!b||e.busy)return;const p=e.clientRef.current;if(!p?.isConnected){e.setErrorText(e.t.webSocketNotConnected);return}const S=t.start(e.activeSessionId);try{const w=xr(b)?"agentSkills":e.attachments.length===0&&pr(b,e.activeSession?.agent??e.agent)?"agentCommands":void 0;let y;if(w){e.setBusy(!0);try{y=await zs(w)}catch(M){e.setErrorText(M instanceof Error?M.message:String(M));return}finally{e.setBusy(!1)}}e.setBusy(!0),e.setErrorText(null),e.updateDraft("");const g=e.attachments;e.setAttachments([]);let f=e.activeSessionId,x=e.activeSession?.agent??e.agent;const v=f?e.pendingSessions[f]:void 0,j=v?v.model:Kn(e.model);if(f&&e.pendingSessions[f]){const M=await u(e.pendingSessions[f].cwd,e.pendingSessions[f].agent,f);if(!M){e.setBusy(!1),e.updateDraft(b),e.setAttachments(g);return}f=M,x=e.pendingSessions[e.activeSessionId??""]?.agent??x}else f||(f=await u());if(!f){e.setBusy(!1),e.updateDraft(b),e.setAttachments(g);return}S.remap(f);const N=g.length===0?pr(b,x):null;if(N){const M=wc(N.command),F=M?p.makeId("cmd_msg"):void 0;M&&(e.messagesSessionIdRef.current=f,e.appendCachedHistory(f,[{role:"user",content:M,timestamp:new Date().toISOString()}]),e.renderCachedHistory(f));try{const G=await p.request({action:"session.command",id:p.makeId("command"),sessionId:f,agent:x,command:N.command,...F?{clientMessageId:F}:{},featureEntitlements:y});await e.handleSessionCommandResponse(f,N.command,G)}catch(G){const ne=G instanceof Error?G.message:String(G);e.appendInfoMessage(f,gr(ne)),e.setErrorText(gr(ne))}finally{e.setBusy(!1)}return}const k=xc(b),C=g.map(M=>M.path),I=p.makeId("msg"),R=`client:${I}`;e.messagesSessionIdRef.current=f,e.setCachedMessageDelivery(f,I,"sending",{content:k,...C.length?{images:C}:{}}),e.renderCachedHistory(f),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(f),e.setRespondingSessions(M=>new Set(M).add(f));const z=xr(k)??void 0,A=z?y:void 0;try{const M=await p.request({action:"session.send",id:p.makeId("send"),sessionId:f,agent:x,message:k,clientMessageId:I,images:C.length?C:void 0,model:j,effort:e.effort||void 0,fastMode:e.fastMode,skillInvocation:z,featureEntitlements:A},{timeoutMs:Br,timeoutMessage:Hr});Xt(M)&&typeof M.oldSessionId=="string"&&typeof M.sessionId=="string"&&(S.remap(M.sessionId),e.remapLocalSessionState(M.oldSessionId,M.sessionId)),e.setCachedMessageDelivery(Xt(M)&&typeof M.sessionId=="string"?M.sessionId:f,I,"delivered"),e.reportLog("web.telemetry.send_accepted",{attachmentCount:C.length}),s(F=>F?.historyKey===R?null:F)}catch(M){f=e.resolveCachedMessageSession(f,I);const F=M instanceof Error?M.message:String(M),G=zr(vr(F,!!z));if(e.setCachedMessageDelivery(f,I,"failed")==="delivered")return;e.setErrorText(null),s({sessionId:f,agent:x,message:k,clientMessageId:I,historyKey:R,kind:G,retrying:!1,...C.length?{images:C}:{},model:j,effort:e.effort||void 0,fastMode:e.fastMode,skillInvocation:z,featureEntitlements:A}),e.reportLog("web.telemetry.send_failed",{attachmentCount:C.length,failureKind:G},"warn"),o(f)}finally{e.setBusy(!1)}}finally{S.finish()}},[o,u,e,t]),d=c.useCallback(async()=>{if(!n||n.retrying||e.busy)return;const m=e.clientRef.current;if(!m?.isConnected){s(S=>S?{...S,kind:"network"}:null);return}let b=e.resolveCachedMessageSession(n.sessionId,n.clientMessageId);const p=t.start(b);s(S=>S?{...S,retrying:!0}:null),e.ensureCachedHistoryEntry(b,{role:"user",content:n.message,historyKey:n.historyKey,...n.images?.length?{images:n.images}:{}}),e.setCachedMessageDelivery(b,n.clientMessageId,"sending"),e.setBusy(!0),e.setErrorText(null),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(b),e.setRespondingSessions(S=>new Set(S).add(b));try{const S=await m.request({action:"session.send",id:m.makeId("retry_send"),sessionId:b,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 zs("agentSkills"):void 0},{timeoutMs:Br,timeoutMessage:Hr});Xt(S)&&typeof S.oldSessionId=="string"&&typeof S.sessionId=="string"&&(p.remap(S.sessionId),e.remapLocalSessionState(S.oldSessionId,S.sessionId)),e.setCachedMessageDelivery(Xt(S)&&typeof S.sessionId=="string"?S.sessionId:b,n.clientMessageId,"delivered"),e.reportLog("web.telemetry.retry_accepted",{attachmentCount:n.images?.length??0}),s(null)}catch(S){b=e.resolveCachedMessageSession(b,n.clientMessageId);const w=S instanceof Error?S.message:String(S),y=zr(vr(w,!!n.skillInvocation));if(e.setCachedMessageDelivery(b,n.clientMessageId,"failed")==="delivered"){s(null);return}s(g=>g?{...g,sessionId:b,kind:y,retrying:!1}:null),e.reportLog("web.telemetry.retry_failed",{attachmentCount:n.images?.length??0,failureKind:y},"warn"),o(b)}finally{e.setBusy(!1),p.finish()}},[o,n,e,t]);return c.useEffect(()=>{if(!(!i||e.busy)){if(e.activeSessionId!==i||!e.pendingSessions[i]){a(null);return}a(null),h()}},[i,e.activeSessionId,e.busy,e.pendingSessions,h]),{failedSend:n,dismissFailedSend:()=>s(null),retryFailedSend:d,stagePendingSession:l,sendDraft:Object.assign(h,{submission:t})}}function lf({daemonId:e,session:t,setModel:n,setPendingSessions:s}){const i=t?.sessionId,a=t?.model??"";return c.useEffect(()=>{i&&n(a)},[e,i,a,n]),c.useCallback(o=>{n(o),i&&s(l=>{const u=l[i];return u?{...l,[i]:{...u,model:Kn(o)}}:l})},[i,n,s])}function df(e,t){const n=e.indexOf(t);if(n>=0)return n;const s=t.historyKey;if(s)return e.findIndex(o=>o.historyKey===s);const i=t.rewindPoint;if(i)return e.findIndex(o=>JSON.stringify(o.rewindPoint)===JSON.stringify(i));const a=e.flatMap((o,l)=>o.role===t.role&&o.type===t.type&&o.content===t.content&&o.timestamp===t.timestamp&&JSON.stringify(o.images)===JSON.stringify(t.images)?[l]:[]);return a.length===1?a[0]:-1}function uf(e){const t=c.useRef(!1);return async n=>{const s=e.activeSession,i=e.clientRef.current;if(!s||!i?.isConnected||t.current||e.busy)return;const a=Mn(),o=e.historyCacheRef.current[s.sessionId]??[],l=df(o,n);if(l<0||n.role!=="user"||n.type==="info"){e.setErrorText(a.unavailable);return}if((e.historyPageStartRef.current[s.sessionId]??0)>0){e.setErrorText(a.incompleteHistory);return}t.current=!0;let u=!1;try{u=await Cs({message:a.confirmRewind})}finally{t.current=!1}if(!(!u||e.clientRef.current!==i||!i.isConnected||e.activeSessionIdRef.current!==s.sessionId)){t.current=!0,e.setBusy(!0),e.setErrorText(null);try{const h=await i.request({action:"session.rewind",id:i.makeId("rewind"),sessionId:s.sessionId,agent:s.agent,targetUserMessageIndex:o.slice(0,l+1).filter(m=>m.role==="user"&&m.type!=="info").length-1,featureEntitlements:await zs("sessionRewind")},{timeoutMs:15e4,timeoutMessage:a.rewindFailed});if(!h||typeof h.sessionId!="string"||!h.sessionId||h.sessionId===s.sessionId||h.sourceSessionId!==s.sessionId||h.archivedSource!==!0||!Array.isArray(h.messages)||h.messages.some(m=>!m||typeof m.content!="string"||!["user","assistant","tool"].includes(m.role)))throw new Error(a.invalidResponse);const d={...s,sessionId:h.sessionId,archived:!1};e.setOptimisticSessions(m=>{const b={...m};return delete b[s.sessionId],b[h.sessionId]=d,b}),e.setSessions(m=>[...m.filter(b=>b.sessionId!==h.sessionId).map(b=>b.sessionId===s.sessionId?{...b,archived:!0,pinned:!1}:b),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(m=>({path:m,name:m.split("/").pop()??m,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 hf(e,t,n,s,i){if(t===n)return e;const a=!t&&i?i:s||it;return a===e.path?e:{path:a,entries:[],loading:!1,loaded:!1}}function Ss(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Yt(e=window.location.search){const t=new URLSearchParams(e),n=Ss(t.get("folder")),s=Ss(t.get("file")),i=Ss(t.get("cwd"));return{...n?{folder:n}:{},...s?{file:s}:{},...i?{cwd:i}:{}}}function ff(e,t,n=[]){const s=new URLSearchParams(e);for(const a of n)s.delete(a);for(const[a,o]of Object.entries(t))o?s.set(a,o):s.delete(a);const i=s.toString();return i?`?${i}`:""}function Kr(e,t={}){const n=t.history??window.history,s=t.location??window.location,i=[];e.folder&&i.push("file","cwd"),e.file&&i.push("folder");const a=ff(s.search,e,i),o=`${s.pathname}${a}${s.hash}`;if(t.replace){n.replaceState(null,"",o);return}n.pushState(null,"",o)}function ln(e,t){c.useEffect(()=>{e.current=t},[e,t])}function mf({activeSessionIdRef:e,composerDraftsRef:t,setComposerDrafts:n,setDraft:s}){const i=c.useCallback(o=>{s(o),n(l=>{const u=sn(l,e.current,o);return t.current=u,nn(u),u})},[e,t,n,s]),a=c.useCallback(o=>{n(l=>{const u=sn(l,null,o);return t.current=u,nn(u),u}),e.current||s(o)},[e,t,n,s]);return{updateDraft:i,updateNewSessionDraft:a}}function pf(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 gf(e){const{clientRef:t,pairing:n,cwd:s,phase:i,controlTab:a,setControlTab:o,setBusy:l,setErrorText:u,t:h}=e,d=c.useRef(!1),[m,b]=c.useState([]),[p,S]=c.useState(!1),w=c.useRef(new Set),[y,g]=c.useState({path:Yt().folder||Yt().cwd||it,entries:[],loading:!1,loaded:!1}),[f,x]=c.useState(""),[v,j]=c.useState(null),[N,k]=c.useState(()=>new Set),C=T=>JSON.stringify([T.cwd,T.path,T.etag]),I=!!v&&N.has(C(v)),R=c.useRef(null),z=c.useRef(null),A=c.useRef(0),M=c.useRef(y.path);c.useEffect(()=>{M.current!==y.path&&(A.current++,M.current=y.path)},[y.path]),c.useEffect(()=>(A.current++,g({path:Yt().folder||Yt().cwd||s||it,entries:[],loading:!1,loaded:!1}),b([]),S(!1),j(null),k(new Set),()=>{A.current++;for(const T of w.current)T.abort();w.current.clear(),z.current?.abort(),R.current&&(R.current.abort(),R.current=null,l(!1))}),[n?.pairToken]),c.useEffect(()=>{y.path!==it||Yt().folder||(A.current++,g(T=>({...T,entries:[],loaded:!1,loading:!1})))},[s]);const F=c.useRef(new Set);c.useEffect(()=>{v?.objectUrl&&F.current.add(v.objectUrl)},[v?.objectUrl]),c.useEffect(()=>()=>{for(const T of F.current)URL.revokeObjectURL(T);F.current.clear()},[n?.pairToken]);const G=c.useCallback(async T=>{if(!T?.length||!n)return;const D=new AbortController;w.current.add(D),S(!0),u(null);try{for(const W of Array.from(T)){const U=await fetch(`/upload?name=${encodeURIComponent(W.name)}`,{method:"POST",signal:D.signal,headers:{authorization:`Bearer ${n.pairToken}`,"content-type":W.type||"application/octet-stream"},body:W});if(D.signal.aborted)return;if(!U.ok)throw new Error(await U.text().catch(()=>h.uploadFailed)||h.uploadFailed);const O=Oc(await U.json());if(D.signal.aborted)return;if(!O)throw new Error(h.uploadPathMissing);const V={path:O,name:W.name,type:W.type||"application/octet-stream",size:W.size};b(B=>[...B,V])}}catch(W){D.signal.aborted||u(W instanceof Error?W.message:String(W))}finally{w.current.delete(D)&&S(w.current.size>0)}},[n,u,h.uploadFailed,h.uploadPathMissing]),ne=c.useCallback(async(T,D,W)=>{if(!n)return;z.current?.abort();const U=new AbortController;z.current=U,u(null);try{const O=/^(?:https?:\/\/|data:image\/|blob:)/i.test(T),V=await fetch(O?T:Un(T,D),{headers:O?{}:{authorization:`Bearer ${n.pairToken}`},signal:U.signal});if(!V.ok)throw new Error(await V.text().catch(()=>h.fileOpenFailed)||h.fileOpenFailed);const B=V.headers.get("content-type")??"application/octet-stream";if(O&&!B.startsWith("image/"))throw new Error(h.fileOpenFailed);const X=es(T,B,!1);if(X==="html"||X==="unsupported"&&Kc(T,B)){const Q=await V.text();if(U.signal.aborted)return;j({path:T,cwd:D,kind:"text",contentType:B,text:Q,etag:zn(V.headers,"etag"),lastModified:zn(V.headers,"last-modified"),size:Number(V.headers.get("content-length"))||void 0,dirty:!1})}else{const Q=await V.blob();if(U.signal.aborted)return;const He=es(T,B,!1)==="pdf"?new Blob([Q],{type:"application/pdf"}):Q;j({path:T,cwd:D,kind:Uc(T,B)?"image":"binary",contentType:B,text:"",objectUrl:URL.createObjectURL(He),etag:zn(V.headers,"etag"),lastModified:zn(V.headers,"last-modified"),size:Q.size,dirty:!1})}o("files"),W?.updateRoute&&Kr({file:T,...D?{cwd:D}:{}},{replace:W.replaceRoute})}catch(O){if(U.signal.aborted)return;u(O instanceof Error?O.message:String(O))}},[n,o,u]),ve=c.useCallback(async T=>{if(!n||!v||v.kind!=="text"||R.current)return;const D=new AbortController;R.current=D,l(!0),u(null);try{const W=await fetch(Un(v.path,v.cwd),{method:"PUT",signal:D.signal,headers:{authorization:`Bearer ${n.pairToken}`,"content-type":"text/markdown; charset=utf-8",...v.etag&&!T?.force?{"if-match":v.etag}:{}},body:v.text});if(D.signal.aborted)return;if(!W.ok)throw W.status===409?(k(O=>new Set(O).add(C(v))),new Error(h.remoteFileConflict(v.path))):new Error(await W.text().catch(()=>h.fileSaveFailed)||h.fileSaveFailed);const U=await W.json().catch(()=>({}));if(D.signal.aborted)return;k(O=>{const V=new Set(O);return V.delete(C(v)),V}),j(O=>pf(O,v,U))}catch(W){D.signal.aborted||u(W instanceof Error?W.message:String(W))}finally{R.current===D&&(R.current=null,l(!1))}},[n,v,l,u]),Se=c.useCallback(async()=>{if(!(!n||!v))try{const T=/^(?:https?:\/\/|data:image\/|blob:)/i.test(v.path),D=await fetch(T?v.path:Un(v.path,v.cwd),{headers:T?{}:{authorization:`Bearer ${n.pairToken}`}});if(!D.ok)throw new Error(h.downloadFailed);const W=URL.createObjectURL(await D.blob()),U=document.createElement("a");U.href=W,U.download=Dt(v.path),U.click(),URL.revokeObjectURL(W)}catch(T){u(T instanceof Error?T.message:String(T))}},[n,v,u]),ae=c.useCallback(async(T=y.path,D)=>{const W=t.current;if(!W?.isConnected)return;M.current=T;const U=++A.current;g(O=>({...O,path:T,entries:T===O.path?O.entries:[],loading:!0,loaded:!1,error:void 0}));try{const O=await W.request({action:"dirs.list",id:W.makeId("dirs"),path:T,cwd:s||void 0});if(U!==A.current)return;g({path:T,entries:O.entries??[],loading:!1,loaded:!0}),D?.updateRoute&&Kr({folder:T},{replace:D.replaceRoute})}catch(O){if(U!==A.current)return;g(V=>({...V,loading:!1,loaded:!0,error:O instanceof Error?O.message:String(O)}))}},[t,s,y.path]),ke=c.useCallback(async T=>{const D=t.current;if(!D?.isConnected)throw new Error(h.webSocketNotConnected);return(await D.request({action:"dirs.list",id:D.makeId("dirs"),path:T,cwd:s||void 0},{timeoutMs:1e4,timeoutMessage:h.directoryListTimedOut})).entries??[]},[t,s]),fe=c.useCallback(async T=>(await ke(T)).filter(D=>D.isDirectory),[ke]);c.useEffect(()=>{!d.current||a!=="files"||i!=="connected"||y.loading||y.loaded||ae(y.path||s||it)},[a,s,y.loaded,y.loading,y.path,ae,i]),c.useEffect(()=>{if(i!=="connected"||d.current)return;const T=Yt();if(!T.folder&&!T.file){d.current=!0;return}if(d.current=!0,o("files"),T.folder){ae(T.folder,{updateRoute:!1});return}T.file&&(T.cwd&&g(D=>({...D,path:T.cwd,loaded:!1})),ne(T.file,T.cwd,{updateRoute:!1}))},[ae,ne,i,o]);const oe=c.useCallback(async()=>{const T=t.current;if(!(!T?.isConnected||f.trim().length===0)){l(!0),u(null);try{await T.request({action:"dirs.create",id:T.makeId("mkdir"),path:Hc(y.path,f),cwd:s||void 0}),x(""),await ae(y.path)}catch(D){u(D instanceof Error?D.message:String(D))}finally{l(!1)}}},[t,s,y.path,ae,f,l,u]),ce=c.useCallback(async T=>{const D=t.current;if(!D?.isConnected)throw new Error(h.webSocketNotConnected);await D.request({action:"dirs.create",id:D.makeId("mkdir"),path:T,cwd:s||void 0},{timeoutMs:1e4,timeoutMessage:h.directoryCreationTimedOut})},[t,s]);return{attachments:m,setAttachments:b,uploadBusy:p,directory:y,setDirectory:g,newDirName:f,setNewDirName:x,remoteFile:v,setRemoteFile:j,remoteFileConflict:I,uploadFiles:G,openRemoteFile:ne,saveRemoteFile:ve,downloadRemoteFile:Se,listDirectory:ae,listSessionDirectories:fe,listFileTreeDirectory:ke,createDirectory:oe,createSessionDirectory:ce}}function yf({clientRef:e,setSessions:t}){const n=c.useRef(new Map);return c.useEffect(()=>()=>n.current.clear(),[]),c.useCallback(async s=>{const i=e.current;if(!i?.isConnected)return;const a=[...new Set(s.map(l=>l.cwd).filter(Boolean))];if(a.length===0)return;const o={};for(const l of a)n.current.set(l,o);try{const l=await i.request({action:"sessions.gitMetadata",id:i.makeId("git"),cwds:a});if(e.current!==i||!i.isConnected)return;t(u=>u.map(h=>e.current===i&&i.isConnected&&n.current.get(h.cwd)===o?{...h,pullRequest:l.pullRequests?.[h.cwd],branchUrl:l.branchUrls?.[h.cwd],branch:l.branches[h.cwd]??h.branch,diffStat:l.diffStats[h.cwd]??h.diffStat}:h))}catch{}},[])}const Bs=15e3,Ur=500,ks=1e3;function bf(e){const t=c.useRef({}),n=c.useRef(null),s=c.useRef({}),i=c.useRef(null),[a,o]=c.useState(!1),[l,u]=c.useState([]),h=c.useCallback(k=>k&&n.current&&n.current!==k?!1:(n.current=null,o(!1),!0),[]),d=c.useCallback(k=>ds(t.current,k)?(i.current=k,u(t.current[k]??[]),!0):!1,[]),m=c.useCallback((k,C,I)=>{t.current=Jh(t.current,k,C);const R=t.current[k]??[];return I?.renderActive!==!1&&k===e.activeSessionIdRef.current&&(i.current=k,u(R)),R},[e.activeSessionIdRef]),b=c.useCallback((k,C,I)=>{if(!I)return s.current[k]=void 0,m(k,C);const R=s.current[k],z=t.current[k]??[],A=I.start+C.length;if(R===void 0||A<R||I.start>R+z.length)return s.current[k]=I.start,m(k,C);s.current[k]=Math.min(R,I.start);const M=z.slice(0,Math.max(0,I.start-R)),F=z.slice(Math.max(0,A-R),Math.max(0,I.total-R));return m(k,[...M,...C,...F])},[m]),p=c.useCallback((k,C)=>{s.current[k]=0;const I=m(k,C,{renderActive:!1});i.current=k,u(I)},[m]),S=c.useCallback((k,C)=>{t.current=da(t.current,k,C),k===e.activeSessionIdRef.current&&(i.current=k,u(t.current[k]??[]))},[e.activeSessionIdRef]),w=c.useCallback((k,C)=>{t.current=Yh(t.current,k,C),k===e.activeSessionIdRef.current&&(i.current=k,u(t.current[k]??[]))},[e.activeSessionIdRef]),y=c.useCallback((k,C)=>Al(t.current,k,C),[]),g=c.useCallback((k,C,I,R)=>{k=y(k,C);const z=Ml(t.current[k]??[],C,I,R);return t.current={...t.current,[k]:z},(k===e.activeSessionIdRef.current||k===i.current)&&(i.current=k,u(t.current[k]??[])),z.find(A=>A.localClientMessageId===C)?.localDelivery},[e.activeSessionIdRef]),f=c.useCallback((k,C)=>{t.current=Xh(t.current,k,C),k===e.activeSessionIdRef.current&&(i.current=k,u(t.current[k]??[]))},[e.activeSessionIdRef]),x=c.useCallback((k,C)=>{S(k,[{role:"assistant",type:"info",content:C,timestamp:new Date().toISOString()}])},[S]),v=c.useCallback(k=>{t.current=tf(t.current,k),delete s.current[k]},[]),j=c.useCallback((k,C)=>{t.current=ef(t.current,k,C),s.current[C]=s.current[k],delete s.current[k]},[]),N=c.useCallback(async k=>{const C=e.clientRef.current;if(!C?.isConnected)return;const I=d(k.sessionId);I?h(k.sessionId):(n.current=k.sessionId,delete s.current[k.sessionId],o(!0),e.setErrorText(null));try{const R=s.current[k.sessionId]??0,z=t.current[k.sessionId]?.length??0;if(I&&(R===0||z>=ks)){const F=(await C.request({action:"reconnect.snapshot",id:C.makeId("snapshot"),activeSessionId:k.sessionId,activeAgent:k.agent,skipActiveSessionHistory:!0,skipGitMetadata:!0})).snapshot.activeSession;F?.sessionId===k.sessionId&&e.setPendingQueues(G=>({...G,[k.sessionId]:F.pendingQueue??[]}));return}await C.request({action:"session.history",id:C.makeId("history"),sessionId:k.sessionId,agent:k.agent,limit:Ur},{timeoutMessage:e.historyTimeoutMessage,timeoutMs:Bs});let A=s.current[k.sessionId];for(;typeof A=="number"&&A>0&&(t.current[k.sessionId]?.length??0)<ks;){const M=t.current[k.sessionId]?.length??0;await C.request({action:"session.history",id:C.makeId("history_older"),sessionId:k.sessionId,agent:k.agent,before:A,limit:Math.min(Ur,ks-M)},{timeoutMessage:e.historyTimeoutMessage,timeoutMs:Bs});const F=s.current[k.sessionId];if(typeof F!="number"||F>=A)break;A=F}}catch(R){e.activeSessionIdRef.current===k.sessionId&&e.setErrorText(R instanceof Error?R.message:String(R))}finally{h(k.sessionId)}},[h,e.activeSessionIdRef,e.clientRef,e.historyTimeoutMessage,e.setErrorText,e.setPendingQueues,d]);return{resolveCachedMessageSession:y,setCachedMessageDelivery:g,appendCachedDelta:f,appendCachedHistory:S,appendInfoMessage:x,clearHistoryLoading:h,ensureCachedHistoryEntry:w,historyCacheRef:t,historyLoading:a,historyPageStartRef:s,hydrateVisibleHistory:p,messages:l,messagesSessionIdRef:i,mergeCachedHistoryPage:b,remapCachedHistory:j,removeCachedHistory:v,renderCachedHistory:d,replaceCachedHistory:m,requestHistory:N,setMessages:u}}function vf(e){const{clientRef:t,activeSessionIdRef:n,search:s,sinceFilter:i,hideArchived:a,sessionAgentFilter:o}=e,l=c.useMemo(()=>({}),[s,i,a,o,n.current]),u=c.useRef({scope:l,options:e,request:0});return u.current.scope=l,u.current.options=e,c.useEffect(()=>()=>{u.current.request++},[]),c.useCallback(async()=>{const h=t.current;if(!h?.isConnected)return;const d=++u.current.request,m=()=>t.current===h&&h.isConnected&&u.current.request===d;for(;m();){const b=u.current,p=b.scope,S=b.options,w=n.current,y=()=>u.current.scope===p&&n.current===w;try{const g=await h.request({action:"reconnect.snapshot",id:h.makeId("snapshot"),activeSessionId:w??void 0,activeAgent:S.activeAgent,agent:S.sessionAgentFilter==="all"?void 0:S.sessionAgentFilter,search:S.search.trim()||void 0,sinceMs:Ni(S.sinceFilter),hideArchived:S.hideArchived,skipGitMetadata:!0});if(!m())return;if(!y())continue;u.current.options.apply(g.snapshot);return}catch(g){if(!m())return;if(y())throw g}}},[t,n])}function xf(e){const{clientRef:t,search:n,sinceFilter:s,hideArchived:i,sessionAgentFilter:a,viewKey:o}=e,l=c.useMemo(()=>({refresh:0}),[n,s,i,a,o]),u=c.useRef({options:e,scope:l});u.current={options:e,scope:l};const h=c.useRef(l);c.useLayoutEffect(()=>{h.current!==l&&(h.current=l,e.setNextCursor(void 0))},[e.setNextCursor,l]);const d=c.useRef(!0);return c.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]),c.useCallback(async m=>{const b=t.current;if(!d.current||!b?.isConnected||u.current.scope!==l)return;const p=m?.append?l.refresh:++l.refresh,S=()=>d.current&&t.current===b&&b.isConnected&&u.current.scope===l&&(m?.append||p===l.refresh);try{const w=await b.request({action:"sessions.list",id:b.makeId(m?.append?"sessions_more":"sessions"),limit:m?.preserveLoaded?Math.max(yr,u.current.options.loadedCount):yr,cursor:m?.cursor,agent:a==="all"?void 0:a,search:n.trim()||void 0,sinceMs:Ni(s),hideArchived:i,skipGitMetadata:!0,force:m?.force});if(!S())return;const y=Ii(w),g=u.current.options;g.setSessionsFromPage(y,m?.append),g.setActiveSessionId(f=>f??y.sessions[0]?.sessionId??null),g.hydrateGitMetadata(y.sessions),g.prefetchActiveHistories(y.sessions)}catch(w){if(S())throw w}},[t,l,n,s,i,a])}function wf(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 Sf(e,t){const n=t.trim().toLowerCase();return n?[It(e),e.cwd,e.agent,e.branch??"",...e.titleAliases??[]].some(s=>s.toLowerCase().includes(n)):!0}function kf(e,t){return e.filter(n=>t.hideArchived&&n.archived||t.agentFilter!=="all"&&n.agent!==t.agentFilter?!1:Sf(n,t.search))}function jf(e){const t=c.useRef([]),n=c.useMemo(()=>As(As(e.sessions,Object.values(e.optimisticSessions)),Object.values(e.pendingSessions)),[e.optimisticSessions,e.pendingSessions,e.sessions]),s=c.useMemo(()=>new Set(Object.keys(e.pendingSessions)),[e.pendingSessions]),i=c.useMemo(()=>n.find(p=>p.sessionId===e.activeSessionId)??null,[e.activeSessionId,n]),a=Object.values(e.pendingApprovals)[0]??null,o=Object.values(e.pendingQuestions)[0]??null,l=c.useMemo(()=>pa(kf(n,{search:e.search,hideArchived:e.hideArchived,agentFilter:e.sessionAgentFilter}),e.sessionSort??"updated"),[n,e.hideArchived,e.search,e.sessionAgentFilter,e.sessionSort]),u=c.useMemo(()=>new Set([...Object.keys(e.pendingApprovals),...Object.keys(e.pendingQuestions)]),[e.pendingApprovals,e.pendingQuestions]),h=l.filter(p=>e.respondingSessionIds.has(p.sessionId)).map(p=>p.sessionId),d=new Set(h),m=t.current.filter(p=>d.has(p));for(const p of h)m.includes(p)||m.push(p);t.current=m;const b=c.useMemo(()=>ga(Dc(l,{needsAttentionSessionIds:u,respondingSessionIds:e.respondingSessionIds,runningSessionOrder:m,separatePinnedGroup:e.separatePinnedGroup,showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup}),e.sessionSort??"updated"),[u,e.respondingSessionIds,e.separatePinnedGroup,e.showNeedsAttentionGroup,e.showRunningGroup,e.sessionSort,l,m]);return{activeApproval:a,activeQuestion:o,activeSession:i,displaySessions:n,groupedSessions:b,pendingSessionIds:s,visibleSessions:l}}const Cf=new Set(["attachmentCount","domNodes","durationMs","errorKind","failureKind","longTaskCount","maxLongTaskMs","online","phase","visibilityState"]);function If(e){const t={};for(const[n,s]of Object.entries(e))Cf.has(n)&&(typeof s=="string"?t[n]=s.slice(0,48):typeof s=="number"&&Number.isFinite(s)?t[n]=Math.round(s):typeof s=="boolean"&&(t[n]=s));return t}function Gr(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 Nf(e){c.useEffect(()=>{const t=performance.now(),n=(h,d,m="info")=>e(h,If(d),m),s=h=>{n("web.telemetry.runtime_error",{errorKind:Gr(h.error)},"error")},i=h=>{n("web.telemetry.unhandled_rejection",{errorKind:Gr(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 o=0,l=0,u=null;return typeof PerformanceObserver<"u"&&PerformanceObserver.supportedEntryTypes.includes("longtask")&&(u=new PerformanceObserver(h=>{for(const d of h.getEntries())o+=1,l=Math.max(l,d.duration)}),u.observe({entryTypes:["longtask"]})),window.addEventListener("error",s),window.addEventListener("unhandledrejection",i),()=>{window.clearTimeout(a),window.removeEventListener("error",s),window.removeEventListener("unhandledrejection",i),u?.disconnect(),o>0&&n("web.telemetry.long_tasks",{longTaskCount:o,maxLongTaskMs:l},"warn")}},[e])}const Ef=6;function Rf(e,t){return t.has(e.sessionId)||e.runtime?.isResponding===!0||e.runtime?.state==="daemonActive"||e.runtime?.state==="externalRunning"}function Af(e,t,n,s,i=Ef){if(i<=0)return[];const a=[];for(const o of e){if(a.length>=i)break;!o.sessionId||!Rf(o,n)||ds(t,o.sessionId)||s.has(o.sessionId)||a.push(o)}return a}function Mf(e,t,n=!1){const s=new Set(t.map(i=>i.sessionId));return As(n?e:e.filter(i=>s.has(i.sessionId)),t)}class Tf{cleared=new Map;live(t,n,s){const i=new Set(s.map(o=>o.clientMessageId)),a=this.cleared.get(n)??new Set;for(const o of t[n]??[])o.clientMessageId&&!i.has(o.clientMessageId)&&a.add(o.clientMessageId);for(const o of i)o&&a.delete(o);return this.cleared.set(n,a),{...t,[n]:s}}snapshot(t){return Object.fromEntries(Object.entries(t).map(([n,s])=>[n,s.filter(i=>!i.clientMessageId||!this.cleared.get(n)?.has(i.clientMessageId))]))}remap(t,n){const s=this.cleared.get(t);s&&(this.cleared.set(n,new Set([...this.cleared.get(n)??[],...s])),this.cleared.delete(t))}}function Pf(){const e=c.useRef(new Tf),[t,n]=c.useState({}),s=c.useCallback(o=>{n(l=>e.current.snapshot(typeof o=="function"?o(l):o))},[]),i=c.useCallback((o,l)=>{n(u=>e.current.live(u,o,l))},[]),a=c.useCallback((o,l)=>{e.current.remap(o,l)},[]);return{pendingQueues:t,setPendingQueues:s,setLivePendingQueue:i,remapPendingQueue:a}}function Df(e,t,n=1/0){return Math.min(Math.max(Math.round(e),t),n)}function _f(e,t){const n=e.leftCollapsed?0:e.leftPaneWidth,s=e.rightCollapsed?0:e.rightPaneWidth,i=n+s,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(s*a)}}function Lf(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 Vr=96,$f=64,Ff=252,Of=234;function qf(e,t){const[n,s]=c.useState(288),[i,a]=c.useState(297),[o,l]=c.useState(()=>window.innerWidth);c.useEffect(()=>{const d=()=>l(window.innerWidth);return window.addEventListener("resize",d),()=>window.removeEventListener("resize",d)},[]);const u=_f({leftCollapsed:e,rightCollapsed:t,leftPaneWidth:n,rightPaneWidth:i},o-Vr-$f),h=c.useCallback(d=>m=>{m.preventDefault();const b=m.clientX,p=d==="left"?u.leftPaneWidth:u.rightPaneWidth,S=m.currentTarget.closest(".workspace")?.querySelector(".chat-pane"),w=p+Math.max(0,(S?.getBoundingClientRect().width??0)-Vr),y=f=>{const x=(f.clientX-b)*(d==="left"?1:-1),v=Df(p+x,d==="left"?Ff:Of,w);d==="left"?s(v):a(v)},g=()=>{document.body.classList.remove("pane-resizing"),window.removeEventListener("pointermove",y),window.removeEventListener("pointerup",g),window.removeEventListener("pointercancel",g),window.removeEventListener("blur",g)};document.body.classList.add("pane-resizing"),window.addEventListener("pointermove",y),window.addEventListener("pointerup",g,{once:!0}),window.addEventListener("pointercancel",g,{once:!0}),window.addEventListener("blur",g,{once:!0})},[u.leftPaneWidth,u.rightPaneWidth]);return{...u,beginPaneResize:h}}function Wf(e,t){const[n,s]=c.useState(e);c.useEffect(()=>{const B=()=>{const X=Xe();s(Q=>({...Q,theme:X.theme,language:X.language,composer:X.composer}))};return window.addEventListener("vibelet.preferences.changed",B),()=>window.removeEventListener("vibelet.preferences.changed",B)},[]);const[i,a]=c.useState(e.sessionList.sortOrder),[o,l]=c.useState(""),[u,h]=c.useState(e.sessionList.searchHistory),[d,m]=c.useState(e.sessionList.sinceFilter),[b,p]=c.useState(e.sessionList.hideArchived),[S,w]=c.useState(e.sessionList.groupFolders),[y,g]=c.useState(e.sessionList.showNeedsAttentionGroup),[f,x]=c.useState(e.sessionList.showRunningGroup),[v,j]=c.useState(e.sessionList.separatePinnedGroup),[N,k]=c.useState(e.sessionList.collapsedFolders),[C,I]=c.useState(e.sessionList.agentFilter),[R,z]=c.useState(t),[A,M]=c.useState(e.layout.leftSidebarCollapsed),[F,G]=c.useState(e.layout.rightSidebarCollapsed),{leftPaneWidth:ne,rightPaneWidth:ve,beginPaneResize:Se}=qf(A,F),ae=n.sessionList.directoryTags,ke=n.sessionList.archiveSyncedDaemonIds,fe=n.sessionList.archiveSyncCardDismissedDaemonIds,oe=n.composer,ce=Lf({leftCollapsed:A,rightCollapsed:F,leftPaneWidth:ne,rightPaneWidth:ve});c.useEffect(()=>{s(B=>{const X={...B,sessionList:{...B.sessionList,searchHistory:u,sortOrder:i,sinceFilter:d,hideArchived:b,groupFolders:S,showNeedsAttentionGroup:y,showRunningGroup:f,separatePinnedGroup:v,collapsedFolders:N,agentFilter:C},layout:{...B.layout,leftSidebarCollapsed:A,rightSidebarCollapsed:F}};return wn(X),X})},[N,S,b,A,F,u,v,C,y,f,d,i]);const T=c.useCallback(()=>{h(B=>ya(B,o))},[o]),D=c.useCallback(B=>{z(B),ia(B)},[]),W=c.useCallback(B=>{s(X=>{const Q={...X,language:B};return wn(Q),Q})},[]),U=c.useCallback(B=>{s(X=>{const Q={...X,theme:B};return wn(Q),Q})},[]),O=c.useCallback(B=>{s(X=>{const Q={...X,sessionList:B(X.sessionList)};return wn(Q),Q})},[]),V=c.useCallback(B=>{s(X=>{const Q={...X,composer:B(X.composer)};return wn(Q),Q})},[]);return{webPreferences:n,sessionSort:i,setSessionSort:a,search:o,setSearch:l,sinceFilter:d,setSinceFilter:m,hideArchived:b,setHideArchived:p,groupFolders:S,setGroupFolders:w,showNeedsAttentionGroup:y,setShowNeedsAttentionGroup:g,showRunningGroup:f,setShowRunningGroup:x,separatePinnedGroup:v,setSeparatePinnedGroup:j,collapsedFolders:N,setCollapsedFolders:k,sessionAgentFilter:C,setSessionAgentFilter:I,directoryTags:ae,archiveSyncedDaemonIds:ke,archiveSyncCardDismissedDaemonIds:fe,composerPreferences:oe,savedTargets:R,setSavedTargets:z,leftSidebarCollapsed:A,setLeftSidebarCollapsed:M,rightSidebarCollapsed:F,setRightSidebarCollapsed:G,workspaceClassName:ce.workspaceClassName,wideMainClassName:ce.wideMainClassName,workspaceStyle:ce.style,beginPaneResize:Se,commitSearch:T,saveTargets:D,setLanguagePreference:W,setThemePreference:U,updateSessionListPreferences:O,updateComposerPreferences:V}}function zf(e){c.useEffect(()=>{const t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>ba(e,document.documentElement,t.matches);if(n(),e==="system")return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[e])}function Bf(){const e=c.useRef(null),t=c.useRef(async()=>{}),n=c.useRef(null),s=c.useRef(Nn()),i=c.useRef(Es()),a=c.useRef(Xe()),o=c.useRef(Gh()),l=c.useRef(Rh()),u=c.useRef(s.current),h=c.useRef(i.current),d=c.useRef(o.current),m=c.useRef(null),b=c.useRef(null),p=c.useRef(new Set),S=c.useRef(null),w=c.useRef(new Set),y=c.useRef(null),g=c.useRef(0),f=c.useRef(new Set),x=c.useRef({}),v=c.useRef(!1),[j,N]=c.useState("connecting"),[k,C]=c.useState(()=>js[Ye(a.current.language)].preparingVibeletWeb),[I,R]=c.useState(null),[z,A]=c.useState(null),[M,F]=c.useState([]),[G,ne]=c.useState({}),[ve,Se]=c.useState({}),[ae,ke]=c.useState(),[fe,oe]=c.useState({}),[ce,T]=c.useState(),[D,W]=c.useState(null),[U,O]=c.useState(null),[V,B]=c.useState(()=>new Set),[X,Q]=c.useState({}),[He,me]=c.useState({}),[Je,je]=c.useState({}),{pendingQueues:Fe,setPendingQueues:ue,setLivePendingQueue:he,remapPendingQueue:Ie}=Pf(),[Re,Ke]=c.useState("claude"),[Ue,ge]=c.useState(it),[Oe,Ge]=c.useState(Qs),[Ve]=c.useState(!1),[et,qe]=c.useState(""),[tt,xe]=c.useState(""),[pe,We]=c.useState(!1),[rt,J]=c.useState(""),[te,Ae]=c.useState(o.current),[E,ye]=c.useState(()=>rn(o.current,null)),{webPreferences:Me,sessionSort:bt,setSessionSort:Te,setRightSidebarCollapsed:Pe,search:Z,setSearch:Ce,sinceFilter:be,setSinceFilter:re,hideArchived:Wt,setHideArchived:Nt,groupFolders:vt,setGroupFolders:Lt,showNeedsAttentionGroup:ut,setShowNeedsAttentionGroup:Et,showRunningGroup:ht,setShowRunningGroup:Rt,separatePinnedGroup:At,setSeparatePinnedGroup:Qe,collapsedFolders:xt,setCollapsedFolders:ft,sessionAgentFilter:nt,setSessionAgentFilter:mt,directoryTags:wt,archiveSyncedDaemonIds:$t,archiveSyncCardDismissedDaemonIds:st,composerPreferences:Mt,savedTargets:St,setSavedTargets:_,leftSidebarCollapsed:K,setLeftSidebarCollapsed:ie,rightSidebarCollapsed:we,workspaceClassName:ot,wideMainClassName:ze,workspaceStyle:ct,beginPaneResize:Ne,commitSearch:pt,saveTargets:lt,setLanguagePreference:De,setThemePreference:gt,updateSessionListPreferences:Tt,updateComposerPreferences:kt}=Wf(a.current,l.current),jt=Ye(Me.language),zt=js[jt],[Ht,Kt]=c.useState(!1),[Ut,Ft]=c.useState("session"),[Ot,Gt]=c.useState(!1);zf(Me.theme);const Vt=c.useCallback(xn=>{Ft(xn),Pe(!1)},[Pe]),[q,$]=c.useState({}),[H,de]=c.useState({}),[Be,yt]=c.useState([]),[qt,pn]=c.useState({statusText:"",loading:!1,action:null}),[gn,yn]=c.useState(ur),[on,cn]=c.useState(i.current),[bn,Fn]=c.useState(s.current),[On,qn]=c.useState(null),[vn,Wn]=c.useState(null);return{clientRef:e,connectWithPairingRef:t,activeSessionIdRef:n,initialNotificationPermissionRef:s,initialNotificationSettingsRef:i,initialPreferencesRef:a,initialComposerDraftsRef:o,initialSavedTargetsRef:l,notificationPermissionRef:u,notificationSettingsRef:h,composerDraftsRef:d,lastHistorySessionIdRef:m,historyCacheDaemonIdRef:b,historyPrefetchingSessionIdsRef:p,pairingRef:S,notifiedEventsRef:w,reconnectTimerRef:y,connectionAttemptIdRef:g,respondingSessionsRef:f,turnNotificationCountsRef:x,intentionalDisconnectRef:v,phase:j,setPhase:N,statusText:k,setStatusText:C,errorText:I,setErrorText:R,pairing:z,setPairing:A,sessions:M,setSessions:F,pendingSessions:G,setPendingSessions:ne,optimisticSessions:ve,setOptimisticSessions:Se,nextCursor:ae,setNextCursor:ke,folderCounts:fe,setFolderCounts:oe,inventoryVersion:ce,setInventoryVersion:T,activeSessionId:D,setActiveSessionId:W,diffSessionId:U,setDiffSessionId:O,respondingSessions:V,setRespondingSessions:B,pendingApprovals:X,setPendingApprovals:Q,pendingQuestions:He,setPendingQuestions:me,questionAnswers:Je,setQuestionAnswers:je,pendingQueues:Fe,setPendingQueues:ue,setLivePendingQueue:he,remapPendingQueue:Ie,agent:Re,setAgent:Ke,cwd:Ue,setCwd:ge,approvalMode:Oe,setApprovalMode:Ge,continueSession:Ve,model:et,setModel:qe,effort:tt,setEffort:xe,fastMode:pe,setFastMode:We,renameTitle:rt,setRenameTitle:J,composerDrafts:te,setComposerDrafts:Ae,draft:E,setDraft:ye,webPreferences:Me,sessionSort:bt,setSessionSort:Te,search:Z,setSearch:Ce,sinceFilter:be,setSinceFilter:re,hideArchived:Wt,setHideArchived:Nt,groupFolders:vt,setGroupFolders:Lt,showNeedsAttentionGroup:ut,setShowNeedsAttentionGroup:Et,showRunningGroup:ht,setShowRunningGroup:Rt,separatePinnedGroup:At,setSeparatePinnedGroup:Qe,collapsedFolders:xt,setCollapsedFolders:ft,sessionAgentFilter:nt,setSessionAgentFilter:mt,directoryTags:wt,archiveSyncedDaemonIds:$t,archiveSyncCardDismissedDaemonIds:st,composerPreferences:Mt,savedTargets:St,setSavedTargets:_,leftSidebarCollapsed:K,setLeftSidebarCollapsed:ie,rightSidebarCollapsed:we,setRightSidebarCollapsed:Pe,workspaceClassName:ot,wideMainClassName:ze,workspaceStyle:ct,beginPaneResize:Ne,commitSearch:pt,saveTargets:lt,setLanguagePreference:De,setThemePreference:gt,updateSessionListPreferences:Tt,updateComposerPreferences:kt,language:jt,t:zt,busy:Ht,setBusy:Kt,controlTab:Ut,setControlTab:Ft,detailsOpen:Ot,setDetailsOpen:Gt,setControlTabAndOpen:Vt,modelOptions:q,setModelOptions:$,usageLimits:H,setUsageLimits:de,skills:Be,setSkills:yt,admin:qt,setAdmin:pn,daemonMetadata:gn,setDaemonMetadata:yn,notificationSettings:on,setNotificationSettings:cn,notificationPermission:bn,setNotificationPermission:Fn,archiveSyncBusy:On,setArchiveSyncBusy:qn,archiveSyncStatus:vn,setArchiveSyncStatus:Wn}}function Hf(){const e=Bf(),t=wf(e),{clientRef:n,activeSessionIdRef:s,notificationPermissionRef:i,notificationSettingsRef:a,composerDraftsRef:o,lastHistorySessionIdRef:l,historyPrefetchingSessionIdsRef:u,pairingRef:h,reconnectTimerRef:d,respondingSessionsRef:m,phase:b,setStatusText:p,setErrorText:S,pairing:w,setSessions:y,setOptimisticSessions:g,setNextCursor:f,setFolderCounts:x,setInventoryVersion:v,activeSessionId:j,setActiveSessionId:N,respondingSessions:k,setRespondingSessions:C,pendingApprovals:I,setPendingApprovals:R,pendingQuestions:z,setPendingQuestions:A,setQuestionAnswers:M,pendingQueues:F,setPendingQueues:G,agent:ne,setAgent:ve,cwd:Se,setCwd:ae,setApprovalMode:ke,composerDrafts:fe,setComposerDrafts:oe,search:ce,sinceFilter:T,hideArchived:D,sessionAgentFilter:W,setRightSidebarCollapsed:U,t:O,controlTab:V,setControlTab:B,setControlTabAndOpen:X,modelOptions:Q,setModelOptions:He,usageLimits:me,setUsageLimits:Je,setSkills:je,setDaemonMetadata:Fe,notificationSettings:ue,setNotificationSettings:he,notificationPermission:Ie,setNotificationPermission:Re,sessions:Ke,pendingSessions:Ue,optimisticSessions:ge,setDraft:Oe,setBusy:Ge}=e,{remoteFile:Ve,attachments:et,setAttachments:qe,uploadBusy:tt,directory:xe,setDirectory:pe,newDirName:We,setNewDirName:rt,setRemoteFile:J,remoteFileConflict:te,uploadFiles:Ae,openRemoteFile:E,saveRemoteFile:ye,downloadRemoteFile:Me,listDirectory:bt,listSessionDirectories:Te,listFileTreeDirectory:Pe,createDirectory:Z,createSessionDirectory:Ce}=gf({clientRef:n,pairing:w,cwd:Se,phase:b,controlTab:V,setControlTab:X,setBusy:Ge,setErrorText:S,t:O}),be=Object.keys(I).length+Object.keys(z).length,re=j?F[j]??[]:[],Wt=Q[ne]??[],Nt=me[ne],{activeSession:vt,activeApproval:Lt,activeQuestion:ut,displaySessions:Et,groupedSessions:ht,pendingSessionIds:Rt,visibleSessions:At}=jf({activeSessionId:j,hideArchived:D,optimisticSessions:ge,pendingApprovals:I,pendingQuestions:z,pendingSessions:Ue,respondingSessionIds:k,search:ce,separatePinnedGroup:t.separatePinnedGroup,sessionAgentFilter:W,sessionSort:e.sessionSort,sessions:Ke,showNeedsAttentionGroup:t.showNeedsAttentionGroup,showRunningGroup:t.showRunningGroup}),{historyCacheRef:Qe,historyPageStartRef:xt,hydrateVisibleHistory:ft,messagesSessionIdRef:nt,remapCachedHistory:mt,appendCachedDelta:wt,appendCachedHistory:$t,appendInfoMessage:st,clearHistoryLoading:Mt,ensureCachedHistoryEntry:St,setCachedMessageDelivery:_,resolveCachedMessageSession:K,historyLoading:ie,messages:we,mergeCachedHistoryPage:ot,removeCachedHistory:ze,renderCachedHistory:ct,replaceCachedHistory:Ne,requestHistory:pt,setMessages:lt}=bf({activeSessionIdRef:s,clientRef:n,historyTimeoutMessage:O.historyRequestTimedOut,setPendingQueues:G,setErrorText:S});ln(s,j),ln(h,w),ln(m,k),ln(a,ue),ln(i,Ie),ln(o,fe);const{updateNewSessionDraft:De,updateDraft:gt}=mf({activeSessionIdRef:s,composerDraftsRef:o,setComposerDrafts:oe,setDraft:Oe});c.useEffect(()=>{va();const q=xa();q&&(De(q),B("session"),wa())},[De]),c.useEffect(()=>{const q=()=>{he(Es()),Re(Nn())};return window.addEventListener("vibelet.notifications.changed",q),()=>window.removeEventListener("vibelet.notifications.changed",q)},[]),c.useEffect(()=>{V==="admin"&&Re(Nn())},[V]),c.useEffect(()=>()=>{d.current&&window.clearTimeout(d.current)},[]);const Tt=c.useCallback((q,$=!1)=>{y(H=>Mf(H,q.sessions,$)),g(H=>{const de=new Set(q.sessions.map(yt=>yt.sessionId)),Be=Object.fromEntries(Object.entries(H).filter(([yt])=>!de.has(yt)));return Object.keys(Be).length===Object.keys(H).length?H:Be}),f(q.nextCursor),v(q.inventoryVersion),q.folderCounts&&x(q.folderCounts),$||Bh(h.current?.daemonId,q),p(q.inventoryBackfillInFlight?O.connectedIndexing:O.connected)},[O.connected,O.connectedIndexing]),kt=yf({clientRef:n,setSessions:y}),jt=c.useCallback((q,$=m.current)=>{const H=n.current;if(!H?.isConnected||q.length===0)return;const de=Af(q,Qe.current,$,u.current);for(const Be of de)u.current.add(Be.sessionId),H.request({action:"session.history",id:H.makeId("history_prefetch"),sessionId:Be.sessionId,agent:Be.agent},{timeoutMessage:O.historyPrefetchTimedOut,timeoutMs:Bs}).catch(()=>{}).finally(()=>{u.current.delete(Be.sessionId)})},[O.historyPrefetchTimedOut]),zt=c.useCallback(q=>{const $=Zc(q,{currentActiveSessionId:s.current,currentCwd:Se});Tt($.page,!1),f($.page.nextCursor),v($.page.inventoryVersion),$.messages&&$.activeSessionId&&ft($.activeSessionId,$.messages),N($.activeSessionId),$.activeAgent&&ve($.activeAgent),$.activeCwd&&ae($.activeCwd),$.activeApprovalMode&&ke($.activeApprovalMode),$.questionAnswers&&M($.questionAnswers),m.current=new Set($.respondingSessionIds),C(m.current),R($.pendingApprovals),A($.pendingQuestions),G($.pendingQueues),kt(q.sessions),jt(q.sessions,new Set($.respondingSessionIds))},[Se,kt,ft,jt,Tt]),Ht=vf({clientRef:n,activeSessionIdRef:s,activeAgent:vt?.agent??ne,sessionAgentFilter:W,search:ce,sinceFilter:T,hideArchived:D,apply:zt}),Kt=xf({clientRef:n,search:ce,sinceFilter:T,hideArchived:D,sessionAgentFilter:W,viewKey:[e.sessionSort,e.groupFolders,t.showNeedsAttentionGroup,t.showRunningGroup,t.separatePinnedGroup].join(":"),loadedCount:Ke.length,setNextCursor:f,setSessionsFromPage:Tt,setActiveSessionId:N,hydrateGitMetadata:kt,prefetchActiveHistories:jt}),Ut=c.useCallback(async(q,$)=>{const H=n.current;if(H?.isConnected)try{const[de,Be,yt]=await Promise.all([H.request({action:"models.list",id:H.makeId("models"),agent:q}),H.request({action:"usage.limits.fetch",id:H.makeId("usage"),agent:q}),H.request({action:"skills.list",id:H.makeId("skills"),cwd:$||void 0})]);He(qt=>({...qt,[q]:de.options??[]})),Je(qt=>({...qt,[q]:Be})),je(Array.isArray(yt.skills)?yt.skills:[])}catch(de){S(de instanceof Error?de.message:String(de))}},[]),Ft=c.useCallback((q,$,H="info")=>{const de=n.current;de?.isConnected&&de.request({action:"log.report",id:de.makeId("log"),entries:[{level:H,event:q,data:$,ts:new Date().toISOString()}]}).catch(()=>{})},[]);Nf(Ft);const Ot=c.useCallback(async(q=h.current)=>{if(!q){Fe(ur);return}Fe($=>({...$,loading:!0,error:null}));try{const $=await fetch(eh(q,window.location,{sameOrigin:!1}),{cache:"no-store"});if(!$.ok)throw new Error(`HTTP ${$.status}`);const H=th(await $.json().catch(()=>null));Fe({...H,loading:!1,error:null})}catch{Fe($=>({...$,loading:!1,error:O.connectorVersionFailed}))}},[O.connectorVersionFailed]);c.useEffect(()=>{const q=()=>{he(Es()),Re(Nn())};return window.addEventListener("vibelet.notifications.changed",q),()=>window.removeEventListener("vibelet.notifications.changed",q)},[]),c.useEffect(()=>{V==="admin"&&b==="connected"&&Ot()},[V,b,Ot]);const Gt=c.useCallback(q=>{he($=>{const H={...$,...q};return a.current=H,Cc(H),H})},[]),Vt=c.useCallback((q,$)=>{!q||!$||q===$||(N(H=>H===q?$:H),l.current===q&&(l.current=$),nt.current===q&&(nt.current=$),mt(q,$),m.current=br(m.current,q,$),C(H=>br(H,q,$)),R(H=>vs(H,q,$)),A(H=>vs(H,q,$)),e.remapPendingQueue(q,$),G(H=>vs(H,q,$)),g(H=>{const de=H[q];if(!de)return H;const Be={...H};return delete Be[q],Be[$]={...de,sessionId:$},Be}),oe(H=>{const de=Vh(H,q,$);return de!==H&&(o.current=de,nn(de)),de}))},[]);return{...e,...t,attachments:et,setAttachments:qe,uploadBusy:tt,directory:xe,setDirectory:pe,newDirName:We,setNewDirName:rt,remoteFile:Ve,setRemoteFile:J,remoteFileConflict:te,uploadFiles:Ae,openRemoteFile:E,saveRemoteFile:ye,downloadRemoteFile:Me,listDirectory:bt,listSessionDirectories:Te,listFileTreeDirectory:Pe,createDirectory:Z,createSessionDirectory:Ce,pendingActionsCount:be,activeQueue:re,activeModelOptions:Wt,activeUsage:Nt,activeApproval:Lt,activeQuestion:ut,activeSession:vt,displaySessions:Et,groupedSessions:ht,pendingSessionIds:Rt,visibleSessions:At,appendCachedDelta:wt,appendCachedHistory:$t,appendInfoMessage:st,clearHistoryLoading:Mt,ensureCachedHistoryEntry:St,setCachedMessageDelivery:_,resolveCachedMessageSession:K,historyCacheRef:Qe,historyLoading:ie,historyPageStartRef:xt,hydrateVisibleHistory:ft,messages:we,messagesSessionIdRef:nt,mergeCachedHistoryPage:ot,remapCachedHistory:mt,removeCachedHistory:ze,renderCachedHistory:ct,replaceCachedHistory:Ne,requestHistory:pt,setMessages:lt,updateDraft:gt,updateNewSessionDraft:De,setSessionsFromPage:Tt,hydrateGitMetadata:kt,prefetchActiveHistories:jt,applyReconnectSnapshot:zt,requestReconnectSnapshot:Ht,requestSessions:Kt,fetchAgentResources:Ut,reportLog:Ft,refreshDaemonMetadata:Ot,updateNotificationSettings:Gt,remapLocalSessionState:Vt}}function Kf(){const e=Hf(),t=c.useRef(void 0),n=uf(e),{initialSavedTargetsRef:s,composerDraftsRef:i,lastHistorySessionIdRef:a,respondingSessionsRef:o,phase:l,setErrorText:u,pairing:h,setSessions:d,pendingSessions:m,activeSessionId:b,setActiveSessionId:p,setRespondingSessions:S,setPendingApprovals:w,setPendingQuestions:y,setPendingQueues:g,setLivePendingQueue:f,agent:x,setAgent:v,cwd:j,setCwd:N,setApprovalMode:k,setModel:C,setEffort:I,setFastMode:R,setRenameTitle:z,setDraft:A,archiveSyncedDaemonIds:M,archiveSyncCardDismissedDaemonIds:F,setControlTabAndOpen:G,daemonMetadata:ne,notificationPermission:ve,setDirectory:Se,displaySessions:ae,appendInfoMessage:ke,clearHistoryLoading:fe,messagesSessionIdRef:oe,renderCachedHistory:ce,replaceCachedHistory:T,requestHistory:D,setMessages:W,requestSessions:U,remapLocalSessionState:O,attachments:V,setAttachments:B,listDirectory:X,activeApproval:Q,activeQuestion:He,activeSession:me,appendCachedDelta:Je,appendCachedHistory:je,ensureCachedHistoryEntry:Fe,setCachedMessageDelivery:ue,resolveCachedMessageSession:he,historyCacheRef:Ie,messages:Re,mergeCachedHistoryPage:Ke,removeCachedHistory:Ue,updateDraft:ge,setSessionsFromPage:Oe,requestReconnectSnapshot:Ge,fetchAgentResources:Ve,reportLog:et,refreshDaemonMetadata:qe,updateNotificationSettings:tt,clientRef:xe,connectWithPairingRef:pe,activeSessionIdRef:We,notificationPermissionRef:rt,notificationSettingsRef:J,historyCacheDaemonIdRef:te,pairingRef:Ae,notifiedEventsRef:E,reconnectTimerRef:ye,connectionAttemptIdRef:Me,turnNotificationCountsRef:bt,intentionalDisconnectRef:Te,setPhase:Pe,setStatusText:Z,setPairing:Ce,setPendingSessions:be,setOptimisticSessions:re,questionAnswers:Wt,setQuestionAnswers:Nt,approvalMode:vt,continueSession:Lt,model:ut,effort:Et,fastMode:ht,renameTitle:Rt,setComposerDrafts:At,draft:Qe,search:xt,sinceFilter:ft,savedTargets:nt,setSavedTargets:mt,saveTargets:wt,updateSessionListPreferences:$t,t:st,busy:Mt,setBusy:St,setDetailsOpen:_,setAdmin:K,setDaemonMetadata:ie,setNotificationPermission:we,archiveSyncBusy:ot,setArchiveSyncBusy:ze,setArchiveSyncStatus:ct}=e,Ne=c.useCallback(async(se,Ct,P)=>{const Y=typeof P.sessionId=="string"?P.sessionId:se,_e=typeof P.oldSessionId=="string"?P.oldSessionId:se;_e&&Y&&_e!==Y&&O(_e,Y),Ct.name==="clear"?(T(Y,[]),g(le=>{const Ee={...le};return delete Ee[Y],delete Ee[_e],Ee}),w(le=>{const Ee={...le};return delete Ee[Y],delete Ee[_e],Ee}),y(le=>{const Ee={...le};return delete Ee[Y],delete Ee[_e],Ee}),p(Y)):Ct.name==="new"?(p(Y),oe.current=Y,ce(Y)):Ct.name==="exit"?(d(le=>le.map(Ee=>Ee.sessionId===Y?{...Ee,archived:!0}:Ee)),p(null),oe.current=null,a.current=null,W([])):Ct.name==="goal"&&"goal"in P&&ke(Y,Sc(P.goal)),P.turnStarted&&!P.queued&&(o.current=new Set(o.current).add(Y),S(le=>new Set(le).add(Y))),await U({force:!0})},[ke,O,ce,T,U]),pt=sf({notificationSettingsRef:J,notifiedEventsRef:E,notificationPermissionRef:rt,activeSessionIdRef:We,respondingSessionsRef:o,turnNotificationCountsRef:bt,t:st,setActiveSessionId:p,setErrorText:u,setPendingQueues:g,setLivePendingQueue:f,setPendingApprovals:w,setPendingQuestions:y,setQuestionAnswers:Nt,setRespondingSessions:S,setSessions:d,remapLocalSessionState:O,requestSessions:U,clearHistoryLoading:fe,replaceCachedHistory:T,mergeCachedHistoryPage:Ke,appendCachedHistory:je,appendCachedDelta:Je});Uh({clientRef:xe,connectWithPairingRef:pe,pairingRef:Ae,reconnectTimerRef:ye,connectionAttemptIdRef:Me,intentionalDisconnectRef:Te,historyCacheRef:Ie,historyCacheDaemonIdRef:te,messagesSessionIdRef:oe,lastHistorySessionIdRef:a,rememberedTarget:s.current[0]??null,agent:x,cwd:j,phase:l,search:xt,sinceFilter:ft,t:st,handleServerMessage:pt,setPhase:Pe,setStatusText:Z,setErrorText:u,setMessages:W,setPairing:Ce,setSavedTargets:mt,setSessionsFromPage:Oe,refreshDaemonMetadata:qe,requestReconnectSnapshot:Ge,fetchAgentResources:Ve,reportLog:et,requestSessions:U}),c.useEffect(()=>{const se=ae.find(_e=>_e.sessionId===b);if(!se){a.current=null,oe.current=null,fe(),W([]),A(rn(i.current,null));return}v(se.agent),N(se.cwd||it),I(se.effort??""),R(se.fastMode??!1),k(se.approvalMode??Qs),z(se.customTitle??se.title??""),A(rn(i.current,se.sessionId));const Ct=t.current,P=`${h?.daemonId}:${se.sessionId}`;t.current=P;const Y=Yt();if(Se(_e=>hf(_e,Ct,P,se.cwd||it,Y.folder||Y.cwd)),m[se.sessionId]){a.current=se.sessionId,fe(),oe.current!==se.sessionId&&(oe.current=se.sessionId,W([]));return}if(ce(se.sessionId)){const _e=a.current!==se.sessionId;a.current=se.sessionId,fe(se.sessionId),_e&&D(se);return}a.current!==se.sessionId&&(a.current=se.sessionId,oe.current!==se.sessionId&&(oe.current=se.sessionId,W([])),D(se))},[b,fe,ae,m,ce,D]);const lt=lf({daemonId:h?.daemonId,session:me,setModel:C,setPendingSessions:be}),{stagePendingSession:De,failedSend:gt,dismissFailedSend:Tt,retryFailedSend:kt,sendDraft:jt}=cf({clientRef:xe,activeSessionIdRef:We,composerDraftsRef:i,lastHistorySessionIdRef:a,messagesSessionIdRef:oe,respondingSessionsRef:o,agent:x,cwd:j,approvalMode:vt,continueSession:Lt,model:ut,effort:Et,fastMode:ht,activeSessionId:b,activeSession:me,pendingSessions:m,draft:Qe,busy:Mt,attachments:V,t:st,setPendingSessions:be,setOptimisticSessions:re,setComposerDrafts:At,setCwd:N,setAgent:v,setActiveSessionId:p,setMessages:W,setDraft:A,setErrorText:u,setBusy:St,setAttachments:B,setRespondingSessions:S,clearHistoryLoading:fe,reportLog:et,remapLocalSessionState:O,requestSessions:U,updateDraft:ge,appendCachedHistory:je,ensureCachedHistoryEntry:Fe,setCachedMessageDelivery:ue,resolveCachedMessageSession:he,renderCachedHistory:ce,handleSessionCommandResponse:Ne,appendInfoMessage:ke}),{respondApproval:zt,respondQuestion:Ht,cancelQuestion:Kt,setQuestionChoice:Ut,requestActiveAction:Ft,interruptActiveSession:Ot,retrySessions:Gt,updateApprovalMode:Vt,cancelQueuedTurn:q,setSessionPinned:$,setSessionArchived:H,deleteSession:de,updatePinned:Be,updateArchived:yt,renameSession:qt}=af({clientRef:xe,activeSessionIdRef:We,composerDraftsRef:i,lastHistorySessionIdRef:a,messagesSessionIdRef:oe,respondingSessionsRef:o,activeApproval:Q,activeQuestion:He,activeSession:me,activeSessionId:b,questionAnswers:Wt,pendingSessions:m,phase:l,renameTitle:Rt,setBusy:St,setErrorText:u,setPendingApprovals:w,setPendingQuestions:y,setQuestionAnswers:Nt,setPendingQueues:g,setActiveSessionId:p,setMessages:W,setApprovalMode:k,setSessions:d,setPendingSessions:be,setComposerDrafts:At,setDraft:A,setAttachments:B,setDetailsOpen:_,setRespondingSessions:S,setOptimisticSessions:re,removeCachedHistory:Ue,requestSessions:U}),{runArchiveSync:pn,skipArchiveSync:gn,runAdminAction:yn,exportActiveSession:on,clearPairing:cn,setNotificationsEnabled:bn,connectSavedTarget:Fn,forgetSavedTarget:On,openSessionDetails:qn,editFolderTags:vn,browseFolder:Wn,copyResumeCommand:xn,resumeInTerminal:us}=Lh({clientRef:xe,pairingRef:Ae,connectWithPairingRef:pe,notificationPermissionRef:rt,intentionalDisconnectRef:Te,connectionAttemptIdRef:Me,historyCacheRef:Ie,historyCacheDaemonIdRef:te,messagesSessionIdRef:oe,lastHistorySessionIdRef:a,displaySessions:ae,pairing:h,t:st,archiveSyncBusy:ot,daemonMetadata:ne,activeSession:me,messages:Re,notificationPermission:ve,savedTargets:nt,setArchiveSyncBusy:ze,setArchiveSyncStatus:ct,setSessions:d,setAdmin:K,setErrorText:u,setNotificationPermission:we,setStatusText:Z,setMessages:W,setPairing:Ce,setDaemonMetadata:ie,setPhase:Pe,setActiveSessionId:p,setRenameTitle:z,setDetailsOpen:_,setControlTab:G,updateSessionListPreferences:$t,requestSessions:U,refreshDaemonMetadata:qe,updateNotificationSettings:tt,saveTargets:wt,listDirectory:X}),hr=c.useCallback(async se=>{const Ct=xe.current;return Ct?.isConnected?(await Ct.request({action:"models.list",id:Ct.makeId("models"),agent:se})).options??[]:[]},[]),hs=ve==="denied"||ve==="unsupported",fs=!!(ne.version&&ne.latestVersion&&ea(ne.version,ne.latestVersion)),Qt=h?.daemonId,ms=!!(Qt&&M[Qt]),ps=!!(Qt&&F[Qt]),fr=Qh(e);return{...e,setModel:lt,queueControls:fr,listSessionModels:hr,rewindMessage:n,handleSessionCommandResponse:Ne,handleServerMessage:pt,failedSend:gt,dismissFailedSend:Tt,retryFailedSend:kt,stagePendingSession:De,sendDraft:jt,respondApproval:zt,respondQuestion:Ht,cancelQuestion:Kt,setQuestionChoice:Ut,requestActiveAction:Ft,interruptActiveSession:Ot,retrySessions:Gt,updateApprovalMode:Vt,cancelQueuedTurn:q,setSessionPinned:$,setSessionArchived:H,deleteSession:de,updatePinned:Be,updateArchived:yt,renameSession:qt,runArchiveSync:pn,skipArchiveSync:gn,runAdminAction:yn,exportActiveSession:on,clearPairing:cn,setNotificationsEnabled:bn,connectSavedTarget:Fn,forgetSavedTarget:On,openSessionDetails:qn,editFolderTags:vn,browseFolder:Wn,copyResumeCommand:xn,resumeInTerminal:us,notificationsBlocked:hs,hasDaemonUpdate:fs,activeDaemonId:Qt,archiveSynced:ms,archiveSyncDismissed:ps}}const Uf=c.lazy(()=>at(()=>import("./NewSessionDialog-LttGZHY7.js"),__vite__mapDeps([20,1,2,12,21]))),Gf=c.lazy(()=>at(()=>import("./GlobalPendingDialog-BCLMQc_r.js"),__vite__mapDeps([22,1,2])));function Vf(){return r.jsx(wu,{children:r.jsx(Qf,{})})}function Qf(){const[e,t]=c.useState(!0),[n,s]=c.useState(!1),i=Kf();Ih(i);const[a,o]=c.useState(null);c.useEffect(()=>{const P=()=>o(le=>le??{cwd:i.cwd}),Y=ee().subscribeCommand?.(le=>{le==="new-session"&&P()}),_e=le=>{ee().kind==="browser"&&(le.metaKey||le.ctrlKey)&&!le.altKey&&!le.shiftKey&&le.key.toLowerCase()==="n"&&(le.preventDefault(),P())};return window.addEventListener("keydown",_e),()=>{Y?.(),window.removeEventListener("keydown",_e)}},[i.cwd]),c.useEffect(()=>{i.controlTab==="browser"&&t(!0)},[i.controlTab]),c.useEffect(()=>{i.controlTab==="terminal"&&s(!0)},[i.controlTab]),c.useEffect(()=>{(i.controlTab==="session"||ee().kind==="desktop"&&i.controlTab==="admin")&&i.setControlTab("files");const P=()=>i.setControlTabAndOpen("admin");return window.addEventListener("vibelet.browser.settings",P),()=>window.removeEventListener("vibelet.browser.settings",P)},[i.controlTab,i.setControlTab,i.setControlTabAndOpen]),c.useEffect(()=>{i.activeQuestion&&i.setQuestionAnswers(Js(i.activeQuestion))},[i.activeQuestion,i.setQuestionAnswers]);const{clientRef:l,phase:u,statusText:h,errorText:d,pairing:m,sessions:b,nextCursor:p,folderCounts:S,inventoryVersion:w,activeSessionId:y,setActiveSessionId:g,diffSessionId:f,setDiffSessionId:x,respondingSessions:v,questionAnswers:j,agent:N,cwd:k,approvalMode:C,model:I,setModel:R,effort:z,setEffort:A,fastMode:M,setFastMode:F,renameTitle:G,setRenameTitle:ne,draft:ve,webPreferences:Se,sessionSort:ae,setSessionSort:ke,search:fe,setSearch:oe,sinceFilter:ce,setSinceFilter:T,hideArchived:D,setHideArchived:W,groupFolders:U,setGroupFolders:O,showNeedsAttentionGroup:V,setShowNeedsAttentionGroup:B,showRunningGroup:X,setShowRunningGroup:Q,separatePinnedGroup:He,setSeparatePinnedGroup:me,collapsedFolders:Je,setCollapsedFolders:je,sessionAgentFilter:Fe,setSessionAgentFilter:ue,directoryTags:he,composerPreferences:Ie,savedTargets:Re,leftSidebarCollapsed:Ke,setLeftSidebarCollapsed:Ue,rightSidebarCollapsed:ge,setRightSidebarCollapsed:Oe,workspaceClassName:Ge,wideMainClassName:Ve,workspaceStyle:et,beginPaneResize:qe,commitSearch:tt,saveTargets:xe,setLanguagePreference:pe,setThemePreference:We,updateComposerPreferences:rt,t:J,busy:te,rewindMessage:Ae,controlTab:E,setControlTab:ye,detailsOpen:Me,setDetailsOpen:bt,setControlTabAndOpen:Te,skills:Pe,admin:Z,daemonMetadata:Ce,notificationSettings:be,notificationPermission:re,archiveSyncBusy:Wt,archiveSyncStatus:Nt,attachments:vt,setAttachments:Lt,uploadBusy:ut,directory:Et,newDirName:ht,setNewDirName:Rt,remoteFile:At,uploadFiles:Qe,openRemoteFile:xt,listDirectory:ft,listSessionDirectories:nt,listFileTreeDirectory:mt,createDirectory:wt,createSessionDirectory:$t,pendingActionsCount:st,activeQueue:Mt,activeModelOptions:St,activeUsage:_,activeApproval:K,activeQuestion:ie,activeSession:we,displaySessions:ot,groupedSessions:ze,pendingSessionIds:ct,visibleSessions:Ne,historyLoading:pt,messages:lt,messagesSessionIdRef:De,updateDraft:gt,requestReconnectSnapshot:Tt,requestSessions:kt,fetchAgentResources:jt,failedSend:zt,dismissFailedSend:Ht,retryFailedSend:Kt,stagePendingSession:Ut,listSessionModels:Ft,sendDraft:Ot,respondApproval:Gt,respondQuestion:Vt,cancelQuestion:q,setQuestionChoice:$,requestActiveAction:H,interruptActiveSession:de,retrySessions:Be,updateApprovalMode:yt,cancelQueuedTurn:qt,setSessionPinned:pn,setSessionArchived:gn,deleteSession:yn,updatePinned:on,updateArchived:cn,renameSession:bn,runArchiveSync:Fn,skipArchiveSync:On,runAdminAction:qn,exportActiveSession:vn,clearPairing:Wn,setNotificationsEnabled:xn,connectSavedTarget:us,forgetSavedTarget:hr,openSessionDetails:hs,editFolderTags:fs,copyResumeCommand:Qt,resumeInTerminal:ms,notificationsBlocked:ps,hasDaemonUpdate:fr,archiveSynced:se,archiveSyncDismissed:Ct}=i;return u==="missing-pair"?r.jsxs(r.Fragment,{children:[r.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:J.skipToConversation}),r.jsx(yu,{errorText:d,t:J})]}):r.jsxs("main",{className:Ge,id:"vibelet-workspace",style:et,children:[a&&r.jsx(c.Suspense,{fallback:null,children:r.jsx(Uf,{cwd:a.cwd,agent:N,device:m?.daemonId??"disconnected",connected:u==="connected",approvalMode:C,model:I,t:J,onClose:()=>o(null),onCreate:Ut,onListModels:Ft,onListDirectories:nt,onCreateDirectory:$t})}),r.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:J.skipToConversation}),r.jsx(Ju,{collapsed:Ke,onExpand:()=>Ue(P=>!P),onResize:qe("left"),t:J,children:r.jsx(Zu,{connectionIndicators:r.jsx(mh,{workspace:i}),activeDaemonId:m?.daemonId,activeSessionId:y,busy:te,collapsedFolders:Je,currentCwd:k,directoryTags:he,displayName:m?.displayName,savedTargets:Re,folderCounts:S,groupFolders:U,sessionSort:ae,onSessionSortChange:ke,groupedSessions:ze,hideArchived:D,separatePinnedGroup:He,showNeedsAttentionGroup:V,showRunningGroup:X,inventoryVersion:w,nextCursor:p,phase:u,respondingSessionIds:v,search:fe,sessionAgentFilter:Fe,sessionsCount:ot.length,sinceFilter:ce,statusText:h,t:J,visibleSessions:Ne,onLoadMore:P=>kt({append:!0,cursor:P}),onCopyResumeCommand:Qt,onResumeInTerminal:ms,onConnectTarget:us,pendingSessionIds:ct,onRequestNewSession:P=>o({cwd:P??k}),onDeleteSession:P=>{yn(P)},onEditFolderTags:fs,onOpenSessionDetails:hs,onResetFilters:()=>{ke("updated"),ue("all"),T("30d"),W(!1),O(!0),B(!1),Q(!1),me(!1)},onRenameTarget:(P,Y)=>xe(Mh(Re,P,Y)),onEditConnection:ee().settingsTarget?P=>window.dispatchEvent(new CustomEvent("vibelet.desktop.edit-connection",{detail:P.pairToken})):void 0,onSearchChange:oe,onSearchCommit:tt,onSelectSession:g,onToggleSessionArchived:P=>{gn(P,!P.archived)},onToggleSessionPinned:P=>{pn(P,!P.pinned)},onSessionAgentFilterChange:ue,onSinceFilterChange:T,onToggleFolder:P=>je(Y=>({...Y,[P]:!Y[P]})),onToggleGroupFolders:()=>O(P=>!P),onToggleHideArchived:()=>W(P=>!P),onToggleNeedsAttentionGroup:()=>{i.toggleSessionViewGroup("needsAttention")},onToggleRunningGroup:()=>{i.toggleSessionViewGroup("running")},onToggleSeparatePinnedGroup:()=>{i.toggleSessionViewGroup("pinned")},onToggleCollapse:()=>Ue(!0)})}),r.jsxs("section",{className:Ve,"aria-label":J.vibeletWorkspace,id:"vibelet-main-content",tabIndex:-1,children:[r.jsx(Ch,{workspace:i,children:r.jsx(Od,{activeSession:we,activeSessionId:y,activeModelOptions:St,activeQueue:Mt,activeUsage:_,agent:N,approvalMode:C,attachments:vt,busy:te,cwd:k,draft:ve,effort:z,errorText:d,failedSend:zt,onDismissFailedSend:Ht,fastMode:M,historyLoading:pt,messages:lt,messagesSessionId:De.current,model:I,phase:u,quickReplies:Ie.quickReplies,renameTitle:G,respondingSessionIds:v,sendShortcut:Ie.sendShortcut,skills:Pe,uploadBusy:ut,detailsOpen:Me,t:J,onApprovalModeChange:P=>{yt(P)},onBrowseFiles:()=>{const P=we?.cwd||k||it;Te("files"),ft(P,{updateRoute:!0})},queueControls:i.queueControls,onCancelQueuedTurn:P=>{qt(P)},onClearInterrupt:()=>{H("session.clearInterrupt")},onDraftChange:gt,onDetailsOpenChange:bt,onEffortChange:A,onExportActiveSession:()=>{vn()},onRewindMessage:P=>{Ae(P)},onFastModeChange:F,onRetryFailedSend:Kt,onModelChange:R,onOpenRemoteFile:(P,Y)=>{xt(P,Y,{updateRoute:!0})},onInterrupt:de,onDismissError:()=>i.setErrorText(null),onRetry:Be,onRenameSession:()=>{bn()},onRenameTitleChange:ne,onRemoveAttachment:P=>Lt(Y=>Y.filter(_e=>_e.path!==P)),onRefreshSkills:()=>{jt(we?.agent??N,k)},onSubmit:Ot,onToggleArchived:()=>{cn()},onTogglePinned:()=>{on()},onUploadFiles:Qe,onViewChanges:x})}),r.jsxs(bh,{collapsed:ge,t:J,value:E,showSession:!1,onChange:ye,onResize:qe("right"),children:[E==="files"?r.jsx(c.Suspense,{fallback:r.jsx(_r,{t:J}),children:r.jsx(Pu,{busy:te,cwd:k,directory:Et,onLoadChildren:mt,newDirName:ht,remoteFile:At,t:J,onCreateDirectory:()=>{wt()},onListDirectory:P=>{ft(P,{updateRoute:!0})},onNewDirNameChange:Rt,onOpenRemoteFile:(P,Y)=>{xt(P,Y,{updateRoute:!0})}},`${m?.daemonId}:${k}`)}):null,n?r.jsxs("div",{hidden:E!=="terminal",className:"terminal-tab-content",children:[r.jsx($s,{location:"right",kind:"terminal",t:J,cwd:k===it?Et.path:k}),r.jsx(Xn,{location:"right",kind:"terminal"})]}):null,e?r.jsxs("div",{hidden:E!=="browser",className:"browser-tab-content",children:[r.jsx($s,{location:"right",kind:"browser",t:J}),r.jsx(Xn,{location:"right",kind:"browser"})]}):null,E==="admin"?r.jsxs(c.Suspense,{fallback:r.jsx(_r,{t:J}),children:[r.jsx(Du,{language:Se.language,t:J,onLanguageChange:pe}),!ee().settingsTarget&&r.jsx(ch,{}),r.jsx(_u,{t:J,theme:Se.theme,onThemeChange:We}),r.jsx(Lu,{notificationsBlocked:ps,permission:re,settings:be,t:J,onToggleEnabled:xn}),!ee().settingsTarget&&r.jsx(Fr,{workspace:i})]}):null]})]}),ee().settingsTarget&&r.jsx(Fr,{workspace:i,portalOnly:!0}),r.jsx("div",{className:"workspace-header-actions",children:r.jsx(mc,{activeSession:we,busy:te,controlsOpen:!ge,t:J,onOpenControls:()=>{ge&&st===0&&E==="session"&&ye("files"),Oe(P=>!P)},onRefreshSessions:()=>{kt({force:!0})},onRestoreSnapshot:()=>{Tt()},onToggleArchived:()=>{cn()},onTogglePinned:()=>{on()},onViewChanges:x})}),st>0&&r.jsx(c.Suspense,{fallback:null,children:r.jsx(Gf,{activeApproval:K,activeQuestion:ie,pendingCount:st,requestKey:JSON.stringify([...Object.values(i.pendingApprovals),...Object.values(i.pendingQuestions)].map(P=>JSON.stringify([P.sessionId,P.requestId])).sort()),sessions:b,busy:te,errorText:d,questionAnswers:j,t:J,onCancelQuestion:()=>{q()},onQuestionChoice:$,onRespondApproval:P=>{Gt(P)},onRespondQuestion:()=>{Vt()},onDismissRequest:(P,Y,_e)=>{P==="approval"?i.setPendingApprovals(le=>{if(le[Y]?.requestId!==_e)return le;const Ee={...le};return delete Ee[Y],Ee}):i.setPendingQuestions(le=>{if(le[Y]?.requestId!==_e)return le;const Ee={...le};return delete Ee[Y],Ee})},onClearRequests:()=>{i.setPendingApprovals({}),i.setPendingQuestions({})}})}),r.jsx(vu,{}),r.jsx(Eu,{onOpenRight:Te,client:u==="connected"?l.current:null,daemonId:m?.daemonId,deviceName:m?.displayName??"",controlTab:E,rightVisible:!ge,t:J}),r.jsx(Fu,{activeSession:we,client:l.current,close:()=>x(null),id:f,sessions:b,t:J})]})}const sm=Object.freeze(Object.defineProperty({__proto__:null,App:Vf},Symbol.toStringTag,{value:"Module"}));export{Jr as A,is as B,_t as C,sm as D,gu as F,ni as G,go as I,vo as K,rs as L,Id as M,Mo as P,En as R,Hs as S,hi as T,$e as X,mn as a,Au as b,ti as c,qc as d,Qn as e,Dt as f,Cn as g,ys as h,or as i,Hc as j,Jf as k,Ru as l,nm as m,un as n,Ta as o,em as p,ro as q,Tn as r,Yr as s,Xr as t,Cd as u,tm as v,Ys as w,Yf as x,Xf as y,Ln as z};
|