vibelet 1.2.229 → 1.2.231
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/vibelet.mjs +123 -98
- package/dist/web/assets/App-BbkHX6Hv.css +1 -0
- package/dist/web/assets/App-TtlYNy7O.js +20 -0
- package/dist/web/assets/{BrowserControlPanel-Cxs5WG6_.js → BrowserControlPanel-DzDyeCam.js} +1 -1
- package/dist/web/assets/{ChipGroup-BVP2S5VF.js → ChipGroup-Do4YgaVh.js} +1 -1
- package/dist/web/assets/FilesControlPanel-Dy08iN_7.js +1 -0
- package/dist/web/assets/GlobalPendingDialog-BokEX_Go.js +1 -0
- package/dist/web/assets/{ImageViewer-Cu953aPv.js → ImageViewer-BAycGfGo.js} +1 -1
- package/dist/web/assets/{LanguageSettingsPanel-BQcBduA3.js → LanguageSettingsPanel-db264JO3.js} +1 -1
- package/dist/web/assets/NewSessionDialog-BTZlw3Gl.js +1 -0
- package/dist/web/assets/{NotificationSettingsPanel-CAR-3hg5.js → NotificationSettingsPanel-BYr3-NRw.js} +1 -1
- package/dist/web/assets/{TerminalControlPanel-BeAaO_xN.js → TerminalControlPanel-16KT-TCS.js} +1 -1
- package/dist/web/assets/{ThemeSettingsPanel-CehjZMem.js → ThemeSettingsPanel-D3-WUp4t.js} +1 -1
- package/dist/web/assets/{arrow-right-DfOPiOAm.js → arrow-right-mMC7Zi8G.js} +1 -1
- package/dist/web/assets/{collectMessageImages-D5nmo9r7.js → collectMessageImages-F_MsAk3D.js} +2 -2
- package/dist/web/assets/{file-editor-FileCodeEditor-DnxVv451.js → file-editor-FileCodeEditor-CInvSSQe.js} +3 -3
- package/dist/web/assets/{file-editor-MarkdownLivePreview-DUOOwTFo.js → file-editor-MarkdownLivePreview-CRJo_RMu.js} +1 -1
- package/dist/web/assets/{file-editor-index-sNXn6Dlj.js → file-editor-index-Cbe_0mr3.js} +1 -1
- package/dist/web/assets/{file-editor-index-hO37u8iH.js → file-editor-index-DXLgqR7Z.js} +1 -1
- package/dist/web/assets/{file-editor-index-6CjSO29S.js → file-editor-index-Gu3GlV9m.js} +1 -1
- package/dist/web/assets/{file-editor-index-ByUvpdPB.js → file-editor-index-R2lTkg6K.js} +1 -1
- package/dist/web/assets/{file-editor-index-PzETHMIH.js → file-editor-index-VN_2L1I4.js} +1 -1
- package/dist/web/assets/{file-editor-index-BWFONDrO.js → file-editor-index-awBV_67q.js} +1 -1
- package/dist/web/assets/{file-editor-index-CSZztQo5.js → file-editor-index-hdpS6VVW.js} +1 -1
- package/dist/web/assets/{file-editor-index-B9HLkvhU.js → file-editor-index-ixbyM_m4.js} +1 -1
- package/dist/web/assets/{folder-plus-ByEha8BZ.js → folder-plus-DbDHVXck.js} +1 -1
- package/dist/web/assets/{highlighted-body-TPN3WLV5-DBlbFIPA.js → highlighted-body-TPN3WLV5-F1GioA6X.js} +1 -1
- package/dist/web/assets/index-DJLpIsPI.js +71 -0
- package/dist/web/assets/{index-CTHbgfqq.css → index-XET9GutV.css} +1 -1
- package/dist/web/assets/{mermaid-O7DHMXV3-DkoqfAOM.js → mermaid-O7DHMXV3-H7_sz6Xo.js} +3 -3
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/web/assets/App-BPS30HWl.css +0 -1
- package/dist/web/assets/App-DcLmCQZc.js +0 -12
- package/dist/web/assets/DiffDrawer-BWx4QFFg.js +0 -2
- package/dist/web/assets/FilesControlPanel-CmG4pm47.js +0 -1
- package/dist/web/assets/GlobalPendingDialog-DpTYtgOQ.js +0 -1
- package/dist/web/assets/NewSessionDialog-tL5HWBLl.js +0 -1
- package/dist/web/assets/index-BH_ibxBN.js +0 -71
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mermaid-O7DHMXV3-DkoqfAOM.js","assets/index-BH_ibxBN.js","assets/index-CTHbgfqq.css","assets/collectMessageImages-D5nmo9r7.js","assets/mermaid-O7DHMXV3-tkqeC_Xz.css","assets/ImageViewer-Cu953aPv.js","assets/arrow-right-DfOPiOAm.js","assets/ImageViewer-L8SQkFy1.css","assets/BrowserControlPanel-Cxs5WG6_.js","assets/TerminalControlPanel-BeAaO_xN.js","assets/DiffDrawer-BWx4QFFg.js","assets/FilesControlPanel-CmG4pm47.js","assets/folder-plus-ByEha8BZ.js","assets/FilesControlPanel-DsKJrFYk.css","assets/LanguageSettingsPanel-BQcBduA3.js","assets/ChipGroup-BVP2S5VF.js","assets/ThemeSettingsPanel-CehjZMem.js","assets/NotificationSettingsPanel-CAR-3hg5.js","assets/file-editor-FileCodeEditor-DnxVv451.js","assets/FileCodeEditor-yqSvo7VZ.css","assets/NewSessionDialog-tL5HWBLl.js","assets/NewSessionDialog-cuN6a01X.css","assets/GlobalPendingDialog-DpTYtgOQ.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{c as F,m as Fe,e as qe,l as ze,j as r,r as c,i as Et,k as ne,S as ca,n as la,u as Mn,E as Gr,o as Ss,_ as nt,D as Yn,p as fs,q as dn,t as ks,v as wn,w as da,x as ua,s as gn,y as ha,z as fa,A as ma,B as pa,C as ga}from"./index-BH_ibxBN.js";const ya=[["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"}]],ba=F("activity",ya);const va=[["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"}]],xa=F("archive-restore",va);const wa=[["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"}]],qs=F("archive",wa);const Sa=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],ka=F("arrow-down",Sa);const ja=[["path",{d:"M3 19V5",key:"rwsyhb"}],["path",{d:"m13 6-6 6 6 6",key:"1yhaz7"}],["path",{d:"M7 12h14",key:"uoisry"}]],Vr=F("arrow-left-to-line",ja);const Ca=[["path",{d:"M17 12H3",key:"8awo09"}],["path",{d:"m11 18 6-6-6-6",key:"8c2y43"}],["path",{d:"M21 5v14",key:"nzette"}]],Ia=F("arrow-right-to-line",Ca);const Na=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Ea=F("arrow-up",Na);const Ra=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],$t=F("check",Ra);const Ta=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],Qr=F("chevron-down",Ta);const Aa=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Zr=F("chevron-right",Aa);const Ma=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Pa=F("chevron-up",Ma);const Da=[["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"}]],Jr=F("circle-alert",Da);const _a=[["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"}]],La=F("clipboard",_a);const Fa=[["path",{d:"M12 6v6h4",key:"135r8i"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],$a=F("clock-3",Fa);const Oa=[["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"}]],Wa=F("code-xml",Oa);const qa=[["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"}]],hn=F("copy",qa);const za=[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M4 20v-7a4 4 0 0 1 4-4h12",key:"1lu4f8"}]],Ba=F("corner-up-right",za);const Ha=[["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"}]],ms=F("cpu",Ha);const Ka=[["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"}]],Ua=F("ellipsis",Ka);const Ga=[["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"}]],Va=F("eye",Ga);const Qa=[["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"}]],Za=F("file-pen-line",Qa);const Ja=[["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"}]],Yr=F("file-text",Ja);const Ya=[["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"}]],Un=F("folder-open",Ya);const Xa=[["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"}]],eo=F("folder",Xa);const to=[["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"}]],no=F("funnel",to);const so=[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]],Nt=F("gauge",so);const ro=[["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"}]],Xn=F("git-compare",ro);const io=[["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"}]],ao=F("git-merge",io);const oo=[["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"}]],Xr=F("globe",oo);const co=[["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"}]],lo=F("hash",co);const uo=[["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"}]],ho=F("image-off",uo);const fo=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]],ei=F("info",fo);const mo=[["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"}]],po=F("key-round",mo);const go=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],es=F("loader-circle",go);const yo=[["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"}]],ti=F("message-circle",yo);const bo=[["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"}]],ni=F("mic",bo);const vo=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]],xo=F("panel-left",vo);const wo=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],So=F("panel-right",wo);const ko=[["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"}]],si=F("paperclip",ko);const jo=[["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"}]],Co=F("pencil",jo);const Io=[["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"}]],ts=F("pin",Io);const No=[["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"}]],ri=F("plug-zap",No);const Eo=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Pn=F("plus",Eo);const Ro=[["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"}]],kn=F("refresh-cw",Ro);const To=[["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"}]],ii=F("rotate-ccw",To);const Ao=[["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"}]],Mo=F("save",Ao);const Po=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],jn=F("search",Po);const Do=[["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"}]],_o=F("send",Do);const Lo=[["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"}]],Fo=F("settings",Lo);const $o=[["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"}]],zs=F("shield-check",$o);const Oo=[["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"}]],ai=F("sliders-horizontal",Oo);const Wo=[["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=F("sparkles",Wo);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"}]],ns=F("square-terminal",zo);const Bo=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],oi=F("square",Bo);const Ho=[["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"}]],ci=F("tag",Ho);const Ko=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Bs=F("terminal",Ko);const Uo=[["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"}]],li=F("trash-2",Uo);const Go=[["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"}]],Vo=F("upload",Go);const Qo=[["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"}]],Zo=F("wrench",Qo);const Jo=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],_e=F("x",Jo);const Yo=[["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"}]],cn=F("zap",Yo),js="vibelet.shortcuts.changed",Cs="vibelet.workspace.command",nn=[{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 di(){return/Mac|iPhone|iPad/.test(navigator.platform)}const Xo={BracketLeft:"[",BracketRight:"]",Comma:",",Period:".",Slash:"/",Backslash:"\\",Minus:"-",Equal:"=",Space:"space"};function ui(e,t=di()){const n=Xo[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 hi(e,t=di()){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 ec(e,t={}){return t[e]??nn.find(n=>n.id===e).default}function tc(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":nn.find(s=>s.id!==e&&ec(s.id,n)===t)?.id??null:null}const fi="vibelet.web.shortcuts";function Gn(){try{const e=JSON.parse(Fe().getItem(fi)||"{}");return Object.fromEntries(nn.filter(t=>typeof e?.[t.id]=="string").map(t=>[t.id,e[t.id]]))}catch{return{}}}function Hs(e,t=Gn()){return t[e]??nn.find(n=>n.id===e).default}function nc(e){Fe().setItem(fi,JSON.stringify(e)),window.dispatchEvent(new Event(js))}function Dn(e,t){const n=Hs(t);return n?`${e} (${hi(n)})`:e}const sc="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",rc="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 Vn(){const e=qe(ze().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 mi(){const e=Vn();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:rc,url:"https://apps.apple.com/app/id6761245790"},{label:e.android,qr:sc,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 ic({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=Vn().title;return Et.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":Vn().close,onClick:e,children:r.jsx(_e,{"aria-hidden":"true"})}),r.jsx(mi,{})]})}),document.body)}function ac({activeSession:e,busy:t,controlsOpen:n,t:s,onOpenControls:i,onRefreshSessions:a,onRestoreSnapshot:o,onToggleArchived:l,onTogglePinned:d,onViewChanges:h}){const[u,m]=c.useState(!1),[g,y]=c.useState(!1),k=c.useRef(null);c.useEffect(()=>{if(!g)return;const v=j=>{j.target instanceof Node&&!k.current?.contains(j.target)&&y(!1)},S=j=>{j.key==="Escape"&&y(!1)};return document.addEventListener("pointerdown",v),document.addEventListener("keydown",S),()=>{document.removeEventListener("pointerdown",v),document.removeEventListener("keydown",S)}},[g]);const x=v=>{y(!1),v()},b=ne(),p=r.jsxs("div",{className:"header-actions",children:[u&&r.jsx(ic,{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(kn,{"aria-hidden":"true"})}),r.jsx("button",{"aria-expanded":n,"aria-label":n?s.collapseControlsSidebar:s.workspaceTools,title:Dn(n?s.collapseControlsSidebar:s.workspaceTools,"rightSidebar"),className:"header-tool-button",onClick:i,type:"button",children:r.jsx(So,{"aria-hidden":"true"})}),e||b.openSettings?r.jsxs("div",{className:"header-more-wrap",ref:k,children:[r.jsx("button",{"aria-expanded":g,"aria-haspopup":"menu","aria-label":s.moreActions,className:"icon-button",onClick:()=>y(v=>!v),title:s.moreActions,type:"button",children:r.jsx(Ua,{"aria-hidden":"true"})}),g?r.jsxs("div",{className:"header-action-menu",role:"menu",children:[e&&r.jsxs(r.Fragment,{children:[r.jsxs("button",{onClick:()=>x(()=>h(e.sessionId)),role:"menuitem",type:"button",children:[r.jsx(Xn,{"aria-hidden":"true"}),r.jsx("span",{children:s.viewChanges})]}),r.jsxs("button",{disabled:t,onClick:()=>x(d),role:"menuitem",type:"button",children:[r.jsx(ts,{"aria-hidden":"true"}),r.jsx("span",{children:e.pinned?s.unpin:s.pin})]}),r.jsxs("button",{disabled:t,onClick:()=>x(l),role:"menuitem",type:"button",children:[r.jsx(qs,{"aria-hidden":"true"}),r.jsx("span",{children:e.archived?s.unarchive:s.archive})]}),r.jsxs("button",{onClick:()=>x(o),role:"menuitem",type:"button",children:[r.jsx(ii,{"aria-hidden":"true"}),r.jsx("span",{children:s.restoreSnapshot})]})]}),r.jsxs("button",{role:"menuitem",type:"button",onClick:()=>x(()=>m(!0)),children:[r.jsx(ca,{"aria-hidden":"true"}),r.jsx("span",{children:Vn().title})]}),b.openSettings&&r.jsxs("button",{role:"menuitem",type:"button",onClick:()=>x(b.openSettings),children:[r.jsx(Fo,{"aria-hidden":"true"}),r.jsx("span",{children:s.settings})]}),r.jsxs("button",{onClick:()=>x(a),role:"menuitem",type:"button",children:[r.jsx(kn,{"aria-hidden":"true"}),r.jsx("span",{children:s.refreshSessions})]})]}):null]}):null]}),f=b.toolbarTarget?.("right");return f?Et.createPortal(p,f):p}const oc=/^[A-Za-z][A-Za-z0-9_-]*$/,cc=[{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 pi(e){return cc.filter(t=>!e||t.agents.includes(e))}function Ks(e){return e.trim().toLowerCase()}function qn(e){if(!e.startsWith("/")||e.startsWith("//"))return null;const t=/^\/([A-Za-z0-9_-]*)$/.exec(e);if(!t)return null;const n=t[1]??"";return n&&!oc.test(n)?null:{start:0,end:e.length,keyword:Ks(n)}}function lc(e,t,n=8){const s=Ks(t);return(s?e.filter(a=>a.name.includes(s)||a.title.toLowerCase().includes(s)).sort((a,o)=>hr(a,s)-hr(o,s)):[...e]).slice(0,n)}function hr(e,t){return e.name===t?0:e.name.startsWith(t)?1:e.name.includes(t)?2:3}function dc(e,t,n){return`${e.slice(0,t.start)}${gi(n,"")}${e.slice(t.end)}`}function uc(e,t,n){return t?dc(e,t,n):`${gi(n,e)}${e}`}function gi(e,t){const n=t.length>0,s=n&&!/^\s/.test(t),i=!!(e.argsHint&&!n);return`/${e.name}${i||s?" ":""}`}function fr(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=Ks(s[1]??""),a=pi(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 hc(e){return e.startsWith("//")?e.slice(1):e}function fc(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 mc(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 mr(e){return e==="subscriptionRequired"?"Error: Agent commands require an active Pro subscription.":`Error: ${e||"Command failed."}`}function pc(e,t){return!t||!qn(e)?e:t.draftBeforeInsertion}function yi(e){return/^[a-zA-Z0-9._/~-]+$/.test(e)?e:`'${e.replace(/'/g,"'\\''")}'`}function gc(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(yi).join(" ")}function bi(e){return`cd ${yi(e.cwd||".")} && ${gc(e)}`}const vi="vibelet.web.notificationSettings",zt={enabled:!1,approvals:!0,questions:!0,replies:!0,hiddenOnly:!0};function Is(e=Fe()){try{const t=e.getItem(vi);if(!t)return{...zt};const n=JSON.parse(t);return tn(n)?{enabled:typeof n.enabled=="boolean"?n.enabled:zt.enabled,approvals:typeof n.approvals=="boolean"?n.approvals:zt.approvals,questions:typeof n.questions=="boolean"?n.questions:zt.questions,replies:typeof n.replies=="boolean"?n.replies:zt.replies,hiddenOnly:typeof n.hiddenOnly=="boolean"?n.hiddenOnly:zt.hiddenOnly}:{...zt}}catch{return{...zt}}}function yc(e,t=Fe()){t.setItem(vi,JSON.stringify(e))}function Sn(e=typeof Notification>"u"?void 0:Notification){return ne().notifications?ne().notifications.permission():e?.permission??"unsupported"}function bc(e,t,n=typeof document>"u"?"visible":document.visibilityState){return!(!e.enabled||t!=="granted"||e.hiddenOnly&&n==="visible")}function vc(e,t,n={}){const s=n.notificationFactory??(typeof Notification>"u"?void 0:Notification);if(!s&&!ne().notifications)return!1;const i=n.settings??{enabled:!0,hiddenOnly:!1},a=n.permission??Sn(),o=n.visibilityState??(typeof document>"u"?"visible":document.visibilityState);if(!bc(i,a,o))return!1;if(ne().notifications)return ne().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 Ns(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 xc(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??"")&&Ns(e,t)}function wc(e){for(let t=e.length-1;t>=0;t-=1)if(e[t]?.role==="user")return t;return-1}function xi(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((u,m)=>m)).find(u=>{const m=n[u];if(a.has(u))return!1;if(xc(m,o))return!0;if(m.historyKey&&!m.historyKey.startsWith("client:"))return!1;if(m.liveReply&&(u===n.length-1||n.slice(u+1).every(g=>g.localClientMessageId&&g.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:")&&Ns(m,o)){const g=Date.parse(m.timestamp??""),y=Date.parse(o.timestamp??"");if(Number.isFinite(g)&&Number.isFinite(y))return y>=g-1e3}return!!(o.historyKey&&!o.historyKey.startsWith("client:")&&m.historyKey?.startsWith("client:")&&m.role==="user"&&u===wc(n)&&n.slice(u+1).every(g=>g.role!=="assistant"||g.type==="info"||g.liveReply)&&Ns(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 u=n[h].historyKey;u&&u!==o.historyKey&&s.delete(u),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 Us(e){const t=e.at(-1);return t?.role==="assistant"&&t.type!=="info"?[...e.slice(0,-1),{...t,liveReply:!0}]:e.slice()}const Sc=".",kc="@vibelet/needs-attention",jc="@vibelet/running",Cc="@vibelet/pinned";function Ic(e,t={}){const n=new Map,s=[],i=[],a=[];for(const l of e){const d=l.archived!==!0;if(!!(t.showNeedsAttentionGroup&&d&&(t.needsAttentionSessionIds?.has(l.sessionId)||l.runtime.needsAttention||l.interruptReason||l.stallWarning))?s.push(l):t.showRunningGroup&&d&&t.respondingSessionIds?.has(l.sessionId)&&i.push(l),t.separatePinnedGroup&&d&&l.pinned){a.push(l);continue}const u=l.cwd||Sc;n.set(u,[...n.get(u)??[],l])}const o=[];if(s.length>0&&o.push({folder:kc,kind:"attention",sessions:s}),i.length>0){const l=new Map(t.runningSessionOrder?.map((d,h)=>[d,h]));o.push({folder:jc,kind:"running",sessions:l.size?[...i].sort((d,h)=>(l.get(d.sessionId)??Number.MAX_SAFE_INTEGER)-(l.get(h.sessionId)??Number.MAX_SAFE_INTEGER)):i})}return a.length>0&&o.push({folder:Cc,kind:"pinned",sessions:[...a].sort((l,d)=>Date.parse(d.lastActivityAt)-Date.parse(l.lastActivityAt))}),[...o,...Array.from(n.entries()).map(([l,d])=>({folder:l,kind:"folder",sessions:d}))]}function ss(e,t=Date.now(),n=la){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 wi(e,t){return e.type==="info"?t.messageInfoRole:{user:t.messageUserRole,assistant:t.messageAssistantRole,tool:t.messageToolRole}[e.role]}function Si(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 tt=".",Gs="normal",pr=80,Nc=1600,Ec="pending_local_";function tn(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Rc(e){if(!Number.isFinite(e))return"unknown";const t=e??0;return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function St(e){return e.customTitle||e.title||e.sessionId.slice(0,10)}function Vs(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 ki(e){const t=e;return{sessions:Array.isArray(t.sessions)?t.sessions:[],nextCursor:Si(t.nextCursor),inventoryVersion:t.inventoryVersion,inventoryBackfillInFlight:t.inventoryBackfillInFlight,folderCounts:t.folderCounts}}function Tc(e){const t=e;return typeof t.sessionId=="string"?t.sessionId:null}function Ac(e){const t=e;return typeof t.path=="string"?t.path:null}function Bt(e){return e.split("/").filter(Boolean).at(-1)??e}function Mc(e){return Object.entries(e).length===0?"No structured input.":JSON.stringify(e,null,2)}function Qs(e){return Object.fromEntries(e.questions.map(t=>[t.id,t.options[0]?[t.options[0].label]:[]]))}function zn(e){return e.trim()||void 0}function gr(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 Es(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 ps=0;function Pc(e=Date.now()){return ps=(ps+1)%1e4,`${Ec}${e}_${ps}`}function Dc(e){const t=e.now??new Date().toISOString();return{sessionId:e.sessionId,agent:e.agent,cwd:e.cwd||tt,...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 _c(e,t,n=new Date().toISOString()){return{...e,sessionId:t,lastActivityAt:n}}function gs(e,t,n){if(!t||!n||t===n||!Object.hasOwn(e,t))return e;const{[t]:s,...i}=e;return{...i,[n]:s}}function yr(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 Lc(e,t){const n=e.replace(/\\/g,"/").replace(/\/+$/,"");return!n||n==="."?t:`${n}/${t}`}function Ef(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 Fc(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 $c(e,t){return t.startsWith("image/")||/\.(png|jpe?g|gif|webp|heic|heif|svg)$/i.test(e)}function Bn(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 On(e,t){return e.get(t)||void 0}function Oc(e,t){return`${e.replace(/[<>:"/\\|?*\u0000-\u001F]/g," ").replace(/\s+/g," ").trim().slice(0,80)||t.slice(0,12)||"session"}.txt`}function Wc(e,t){const n=[`# ${St(e)}`,"",`- Agent: ${e.agent}`,`- Session: \`${e.sessionId}\``,`- Working directory: \`${e.cwd}\``,`- Created: ${e.createdAt}`,`- Exported: ${new Date().toISOString()}`,""];for(const 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 y of e.sessions)(y.runtime.isResponding||y.runtime.state==="daemonActive")&&n.add(y.sessionId);for(const y of e.pendingApprovals??[])s[y.sessionId]={type:"approval.request",...y};for(const y of e.pendingQuestions??[])i[y.sessionId]={type:"question.request",...y};let o=null,l,d,h,u,m,g;if(e.activeSession){const y=e.activeSession,k=e.sessions.find(b=>b.sessionId===y.sessionId);o=y.sessionId,l=y.agent,d=k?.cwd||t.currentCwd||tt,h=y.approvalMode??k?.approvalMode??Gs,u=y.approvalMode??null;const x=y.messages??[];if(m=y.partialReplyText?Us(Vs(x,y.partialReplyText)):x,(y.isResponding||y.externallyResponding)&&n.add(y.sessionId),y.pendingApproval&&(s[y.sessionId]={type:"approval.request",sessionId:y.sessionId,...y.pendingApproval}),y.pendingQuestion){const b={type:"question.request",sessionId:y.sessionId,...y.pendingQuestion};i[y.sessionId]=b,g=Qs(b)}y.pendingQueue?.length&&(a[y.sessionId]=y.pendingQueue)}else{const y=t.currentActiveSessionId??null;if(y){const k=e.sessionAliases?.[y];k?o=k:e.sessions.some(x=>x.sessionId===y)&&(o=y)}o=o??e.sessions[0]?.sessionId??null}return{page:{sessions:e.sessions,nextCursor:Si(e.nextCursor),inventoryVersion:e.inventoryVersion,inventoryBackfillInFlight:e.inventoryBackfillInFlight},activeSessionId:o,activeAgent:l,activeCwd:d,activeApprovalMode:h,activeApprovalOverride:u,messages:m,respondingSessionIds:Array.from(n),pendingApprovals:s,pendingQuestions:i,pendingQueues:a,questionAnswers:g}}function br(e,t){if(e==="subscriptionRequired"){const n=typeof window>"u"?"en":qe(ze().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 Bc=/^[A-Za-z_][A-Za-z0-9._:-]*$/,Hc=/(?:^|\s)\$([A-Za-z_][A-Za-z0-9._:-]*|)$/;function Cn(e){return e.trim().toLowerCase()}function vr(e){const t=e.trim(),n=/^\$([A-Za-z_][A-Za-z0-9._:-]*)(?:\s+([\s\S]*))?$/.exec(t);return n?{name:Cn(n[1]??""),...n[2]?.trim()?{args:n[2].trim()}:{}}:null}function Hn(e){const t=Hc.exec(e);if(!t||t.index+t[0].length!==e.length)return null;const n=t[1]??"";if(n&&!Bc.test(n))return null;const s=t[0].lastIndexOf("$");return{start:t.index+s,end:e.length,keyword:Cn(n)}}function Kc(e,t,n){return`${e.slice(0,t.start)}$${Cn(n)} ${e.slice(t.end)}`}function Uc(e,t){if(!t)return e;const n=Hn(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 Gc(e,t,n=8){const s=Cn(t);return(s?e.filter(a=>Cn(a.name).includes(s)):e).slice(0,n)}function xn({icon:e,label:t,menuLabel:n,options:s,value:i,onSelect:a,align:o="left",disabled:l,selected:d,wide:h}){const[u,m]=c.useState(!1),g=c.useRef(null),y=c.useRef(null),k=s.some(x=>x.icon);return c.useEffect(()=>{if(!u)return;const x=g.current?.querySelectorAll('[role="menuitemradio"]:not(:disabled)');([...x??[]].find(f=>f.getAttribute("aria-checked")==="true")??x?.[0])?.focus();const p=f=>{f.target instanceof Node&&!g.current?.contains(f.target)&&m(!1)};return document.addEventListener("pointerdown",p),()=>document.removeEventListener("pointerdown",p)},[u]),r.jsxs("div",{className:"composer-menu",ref:g,onBlur:x=>{const b=x.relatedTarget;(!b||!x.currentTarget.contains(b))&&m(!1)},onKeyDown:x=>{if(x.key==="Escape"&&u&&(x.stopPropagation(),x.preventDefault(),m(!1),y.current?.focus()),!["ArrowDown","ArrowUp","Home","End"].includes(x.key))return;if(x.preventDefault(),!u){m(!0);return}const b=[...x.currentTarget.querySelectorAll('[role="menuitemradio"]:not(:disabled)')];if(!b.length)return;const p=b.indexOf(document.activeElement),f=x.key==="Home"?0:x.key==="End"?b.length-1:(p+(x.key==="ArrowDown"?1:-1)+b.length)%b.length;b[f]?.focus()},children:[r.jsxs("button",{ref:y,"aria-expanded":u,"aria-haspopup":"menu",className:`composer-option-button ${u||d?"selected":""}`,disabled:l,onClick:()=>m(x=>!x),title:n,type:"button",children:[r.jsx(e,{"aria-hidden":"true"}),r.jsx("span",{children:t}),u?r.jsx(Pa,{"aria-hidden":"true"}):r.jsx(Qr,{"aria-hidden":"true"})]}),u?r.jsx("div",{"aria-label":n,className:`composer-option-popover ${k?"":"without-icons"} ${h?"wide":""} ${o==="right"?"align-right":""}`,role:"menu",children:s.map(x=>{const b=x.icon,p=x.value===i;return r.jsxs("button",{"aria-checked":p,className:p?"selected":"",disabled:x.disabled,onClick:()=>{a(x.value),m(!1),y.current?.focus()},role:"menuitemradio",title:x.description??x.label,type:"button",children:[k&&r.jsx("span",{className:"composer-menu-icon",children:b?r.jsx(b,{"aria-hidden":"true"}):null}),r.jsxs("span",{className:"composer-menu-copy",children:[r.jsx("strong",{children:x.label}),x.description?r.jsx("small",{children:x.description}):null]}),r.jsx("span",{className:"composer-menu-indicator","aria-hidden":"true",children:p?r.jsx($t,{className:"composer-menu-check"}):null})]},x.value)})}):null]})}function ji(e,t,n){const s=c.useRef(null);return c.useEffect(()=>{n&&document.getElementById(`${e}-${t}`)?.scrollIntoView({block:"nearest"})},[e,t,n]),s}function Vc({visible:e,listId:t,selectedIndex:n,onHighlight:s,skills:i,onClose:a,onSelect:o,t:l}){const d=ji(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:d,children:i.map((h,u)=>r.jsxs("button",{id:`${t}-${u}`,role:"option","aria-selected":n===u,onMouseEnter:()=>s(u),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 Qc({visible:e,listId:t,selectedIndex:n,onHighlight:s,commands:i,onClose:a,onSelect:o,t:l}){const d=ji(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:d,children:i.map((h,u)=>r.jsxs("button",{id:`${t}-${u}`,role:"option","aria-selected":n===u,onMouseEnter:()=>s(u),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 Zc({queue:e,controls:t,busy:n,t:s,onCancel:i}){const[a,o]=c.useState(new Set),l=e.filter(m=>m.clientMessageId),d=l.filter(m=>a.has(m.clientMessageId)),h=n||t.busy,u=d.length?d: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&&d.length===l.length?new Set:new Set(l.map(m=>m.clientMessageId))),children:l.length>0&&d.length===l.length?s.queueClearSelection:s.queueSelectAll})]}),r.jsx("div",{className:"composer-queue-list",children:e.map((m,g)=>r.jsxs("div",{className:"composer-queue-item",children:[r.jsx("input",{type:"checkbox","aria-label":s.selectQueuedTurn(g+1),checked:!!m.clientMessageId&&a.has(m.clientMessageId),disabled:h||!m.clientMessageId,onChange:()=>o(y=>{const k=new Set(y),x=m.clientMessageId;return k.has(x)?k.delete(x):k.add(x),k})}),r.jsx("span",{title:m.content,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(g+1),disabled:h||!m.clientMessageId||!t.canGuide,onClick:()=>{t.onAction([m],"guide")},children:r.jsx(Ba,{"aria-hidden":"true"})}),r.jsx("button",{type:"button",title:s.queueSendNow,"aria-label":s.sendQueuedTurnNow(g+1),disabled:h||!m.clientMessageId||!t.canSendNow,onClick:()=>{t.onAction([m],"sendNow")},children:r.jsx(_o,{"aria-hidden":"true"})}),r.jsx("button",{type:"button",className:"queue-withdraw-button",title:s.withdraw,"aria-label":s.withdrawQueuedTurn(g+1),disabled:h||!m.clientMessageId,onClick:()=>i(m),children:r.jsx(_e,{"aria-hidden":"true"})})]})]},m.clientMessageId||`${m.enqueuedAt}:${g}`))}),r.jsxs("footer",{className:"queue-batch-actions",children:[d.length>0&&r.jsx("span",{children:s.queueSelectedCount(d.length)}),r.jsx("button",{type:"button",disabled:h||!u.length||!t.canGuide,onClick:()=>{t.onAction(u,"guide")},children:d.length?s.queueGuideSelected:s.queueGuideAll}),r.jsx("button",{type:"button",disabled:h||!u.length||!t.canSendNow,onClick:()=>{t.onAction(u,"sendNow")},children:d.length?s.queueSendSelected:s.queueSendAll})]})]}):null}function Jc({connected:e,busy:t,sending:n,responding:s,hasDraft:i,shortcut:a,onStop:o,t:l}){const d=n?"sending":s?"replying":"ready",h=s&&!n&&!i,u=n?l.sendingMessage:h?l.stopGenerating:l.send,m=n?l.sendingMessage:s?l.replyingMessage:l.send,g=n?es:h?oi:Ea;return r.jsxs("button",{type:h?"button":"submit",className:"send-button","data-state":d,"data-action":h?"stop":"send",disabled:!e||t||n||!h&&!i,"aria-label":u,"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(g,{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 Yc({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,d=u=>o({context:e,index:u});return{listId:i,selectedIndex:l,selectIndex:d,handleKeyDown:u=>!e||u.nativeEvent.isComposing||u.nativeEvent.keyCode===229||u.metaKey||u.ctrlKey||u.altKey||u.shiftKey?!1:u.key==="Escape"?(u.preventDefault(),u.stopPropagation(),s(),!0):t?u.key==="ArrowDown"||u.key==="ArrowUp"?(u.preventDefault(),u.stopPropagation(),d((l+(u.key==="ArrowDown"?1:-1)+t)%t),!0):u.key==="Enter"||u.key==="Tab"?(u.preventDefault(),u.stopPropagation(),n(l),!0):!1:!1}}async function Xc(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,d)=>[...d].forEach((h,u)=>i.setUint8(l+u,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,d)=>n.getChannelData(d));for(let l=0;l<n.length;l++){const d=Math.max(-1,Math.min(1,o.reduce((h,u)=>h+u[l],0)/o.length));i.setInt16(44+l*2,d*(d<0?32768:32767),!0)}return s}finally{await t.close()}}function el({onTranscript:e}){const t=ne(),[n,s]=c.useState("idle"),[i,a]=c.useState("");c.useEffect(()=>{if(!i||n!=="idle")return;const p=setTimeout(()=>a(""),5e3);return()=>clearTimeout(p)},[i,n]);const[o,l]=c.useState(0),d=c.useRef(!1);c.useEffect(()=>{if(n!=="recording")return;const p=Date.now();l(0);const f=setInterval(()=>l(Math.floor((Date.now()-p)/1e3)),1e3);return()=>clearInterval(f)},[n]);const[h,u]=c.useState(!1);c.useEffect(()=>{let p=!0;const f=()=>{t.speechSettings?.status().then(v=>{p&&u(v.configured)}).catch(()=>{p&&u(!1)})};return f(),window.addEventListener("vibelet.speech.changed",f),()=>{p=!1,window.removeEventListener("vibelet.speech.changed",f)}},[]);const m=c.useRef(null),g=c.useRef(!0),y=c.useRef(e);y.current=e;const k=qe(ze().language),x=k!=="en";if(c.useEffect(()=>(g.current=!0,()=>{g.current=!1,m.current?.stream.getTracks().forEach(p=>p.stop()),m.current?.state==="recording"&&m.current.stop()}),[]),!h||!t.transcribeAudio||Fe().getItem("vibelet.web.voice.enabled")!=="true")return null;const b=async()=>{if(!d.current){d.current=!0,a(""),s("starting");try{const p=await navigator.mediaDevices.getUserMedia({audio:!0});if(!g.current){p.getTracks().forEach(C=>C.stop());return}let f;try{f=new MediaRecorder(p,{mimeType:"audio/webm"})}catch(C){throw p.getTracks().forEach(w=>w.stop()),C}m.current=f;const v=[];let S=0;f.ondataavailable=C=>{v.push(C.data),S+=C.data.size,S>9*1024*1024&&f.state==="recording"&&f.stop()};const j=setTimeout(()=>{f.state==="recording"&&f.stop()},6e4);f.onstop=async()=>{if(clearTimeout(j),p.getTracks().forEach(C=>C.stop()),m.current=null,!!g.current){s("transcribing");try{const C=new Blob(v,{type:"audio/webm"}),w=await t.speechSettings?.status(),I=w?.engine==="system"||w?.engine==="volcengine"?await Xc(C):new Uint8Array(await C.arrayBuffer()),E=await t.transcribeAudio(I,k==="zh-TW"?"zh-TW":x?"zh":"en");if(g.current)if(E.trim()){a("");let L=E;const Y=await t.polishSettings?.status().catch(()=>{});if(!g.current)return;if(Y?.settings.enabled&&t.polishTranscript){s("polishing");try{const B=await t.polishTranscript(E);L=B.text,g.current&&B.status==="fallback"&&a(x?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}catch{g.current&&a(x?"润色暂不可用,已保留原始识别文字。":"Polishing unavailable; the original transcript was kept.")}}g.current&&y.current(L)}else a(x?"没有识别到语音,请靠近麦克风重试。":"No speech detected. Try speaking closer to the microphone.")}catch{g.current&&a(x?"语音识别失败,请检查麦克风权限、语音设置和网络。":"Speech failed. Check microphone access, speech settings and connection.")}finally{d.current=!1,g.current&&s("idle")}}};try{f.start(1e3)}catch(C){throw clearTimeout(j),p.getTracks().forEach(w=>w.stop()),m.current=null,C}s("recording")}catch{d.current=!1,g.current&&(s("idle"),a(x?"无法开启麦克风,请检查系统权限。":"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":x?n==="recording"?"停止录音":"语音输入":n==="recording"?"Stop recording":"Voice input",title:n==="recording"?x?"停止录音":"Stop recording":x?"语音输入(最长 60 秒)":"Voice input (up to 60 seconds)",onClick:()=>{n==="recording"?m.current?.state==="recording"&&m.current.stop():b()},children:n==="recording"?r.jsx(oi,{"aria-hidden":"true"}):n==="idle"?r.jsx(ni,{"aria-hidden":"true"}):r.jsx(es,{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"?x?"录音中":"Recording":n==="polishing"?x?"润色中":"Polishing":n==="transcribing"?x?"识别中":"Transcribing":x?"开启麦克风":"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 tl(e){return[{value:"normal",label:e.approvalNormal,description:e.approvalNormalDescription,icon:zs},{value:"plan",label:e.approvalPlan,description:e.approvalPlanDescription,icon:ai},{value:"acceptEdits",label:e.approvalEdits,description:e.approvalEditsDescription,icon:Za},{value:"autoApprove",label:e.approvalAuto,description:e.approvalAutoDescription,icon:cn}]}function nl(e){return[{value:"",label:e.effort,description:e.useDaemonDefault,icon:Nt},{value:"minimal",label:e.effortMinimal,icon:Nt},{value:"low",label:e.effortLow,icon:Nt},{value:"medium",label:e.effortMedium,icon:Nt},{value:"high",label:e.effortHigh,icon:Nt},{value:"xhigh",label:e.effortXHigh,icon:Nt},{value:"max",label:e.effortMax,icon:Nt},{value:"ultra",label:e.effortUltra,icon:Nt}]}function sl({activeQueue:e,queueControls:t,agent:n,attachments:s,approvalMode:i,activeModelOptions:a,busy:o,sending:l,responding:d,onStop:h,draft:u,effort:m,fastMode:g,model:y,phase:k,quickReplies:x,sendShortcut:b,skills:p,uploadBusy:f,t:v,onApprovalModeChange:S,onCancelQueuedTurn:j,onDraftChange:C,onEffortChange:w,onFastModeChange:I,onModelChange:E,onRefreshSkills:L,onRemoveAttachment:Y,onSubmit:B,onUploadFiles:T}){const X=c.useRef(null),H=c.useRef(null),[se,Se]=c.useState(!1),[ve,xe]=c.useState(!1),[A,M]=c.useState(!1),[W,z]=c.useState(!1),[K,J]=c.useState(""),[Q,oe]=c.useState(""),$=c.useRef(null),V=c.useRef(null),ee=k==="connected",Ge=c.useMemo(()=>pi(n),[n]),we=c.useMemo(()=>qn(u),[u]),Be=we?`${we.start}:${we.end}:${we.keyword}`:"",ae=!!(W||we&&Q!==Be),ke=c.useMemo(()=>lc(Ge,we?.keyword??"",8),[Ge,we?.keyword]),le=c.useMemo(()=>Hn(u),[u]),je=le?`${le.start}:${le.end}:${le.keyword}`:"",de=!!(!ae&&(A||le&&K!==je)),ue=c.useMemo(()=>Gc(p,le?.keyword??"",8),[le?.keyword,p]),ce=c.useMemo(()=>tl(v),[v]),me=c.useMemo(()=>nl(v),[v]),He=a.find(N=>N.value===y)?.label??(y||v.defaultOption),Ke=ce.find(N=>N.value===i)?.label??i,Ze=me.find(N=>N.value===m)?.label??m,$e=a.map(N=>({value:N.value,label:N.label,description:N.desc,icon:ms}));$e.some(N=>N.value==="")||$e.unshift({value:"",label:v.defaultOption,description:v.useDaemonDefaultModel,icon:ms}),c.useEffect(()=>{le||($.current=null,J(""),M(!1))},[le]),c.useEffect(()=>{we||(V.current=null,oe(""),z(!1))},[we]);const Ce=async(N,Ie)=>{await T(N),Ie.value=""},Je=async N=>{N.preventDefault(),Se(!1),ee&&await T(N.dataTransfer.files)},Pe=async N=>{!ee||!N.clipboardData.files.length||await T(N.clipboardData.files)},Ve=()=>{const N=Uc(u,$.current);$.current=null,N!==u&&C(N),je&&J(je),M(!1),H.current?.focus()},Ee=()=>{const N=pc(u,V.current);V.current=null,N!==u&&C(N),Be&&oe(Be),z(!1),H.current?.focus()},fe=()=>{if(ae){Ee();return}oe(""),!qn(u)&&u.length===0&&(V.current={draftBeforeInsertion:u},C("/")),z(!0),H.current?.focus()},Z=N=>{const Ie=qn(u),De=uc(u,Ie,N);C(De),V.current=null,z(!1),oe(""),H.current?.focus()},he=()=>{if(de){Ve();return}if(L(),J(""),!Hn(u)){const N=u.length===0||/\s$/.test(u)?"":" ";$.current={draftBeforeInsertion:u,triggerStart:u.length+N.length},C(`${u}${N}$`)}M(!0),H.current?.focus()},U=N=>{const Ie=Hn(u),De=Ie?Kc(u,Ie,N.name):u.trim().length?`${u}${/\s$/.test(u)?"":" "}$${N.name} `:`$${N.name} `;C(De),$.current=null,M(!1),J(""),H.current?.focus()},G=Yc({context:ae?`command:${Be}:${ke.map(N=>N.name).join(",")}`:de?`skill:${je}:${ue.map(N=>`${N.source}:${N.name}`).join(",")}`:"",count:ae?ke.length:de?ue.length:0,onSelect:N=>ae?Z(ke[N]):U(ue[N]),onClose:ae?Ee:Ve}),pe=N=>{G.handleKeyDown(N)||N.key!=="Enter"||N.nativeEvent.isComposing||N.nativeEvent.keyCode===229||!(b==="enter"?!N.shiftKey:N.metaKey||N.ctrlKey)||(N.preventDefault(),B())};return r.jsxs("form",{className:`composer ${se?"dragging":""}`,onDragEnter:N=>{N.preventDefault(),Se(!0)},onDragLeave:()=>Se(!1),onDragOver:N=>N.preventDefault(),onDrop:N=>{Je(N)},onSubmit:N=>{B(N)},children:[r.jsx(Zc,{queue:e,controls:t,busy:o,t:v,onCancel:j}),ve&&x.length?r.jsx("div",{className:"quick-reply-row",children:x.slice(0,6).map(N=>r.jsx("button",{onClick:()=>C(u?`${u}
|
|
4
|
-
${N}`:N),type:"button",children:N},N))}):null,r.jsx(Vc,{visible:de,skills:ue,listId:G.listId,selectedIndex:G.selectedIndex,onHighlight:G.selectIndex,onClose:Ve,onSelect:U,t:v}),r.jsx(Qc,{visible:ae,commands:ke,listId:G.listId,selectedIndex:G.selectedIndex,onHighlight:G.selectIndex,onClose:Ee,onSelect:Z,t:v}),r.jsx("textarea",{ref:H,"aria-controls":ae||de?G.listId:void 0,"aria-activedescendant":ae&&ke.length||de&&ue.length?`${G.listId}-${G.selectedIndex}`:void 0,"aria-autocomplete":"list",value:u,onChange:N=>C(N.target.value),onPaste:N=>{Pe(N)},onKeyDown:pe,placeholder:v.messagePlaceholder,rows:3,disabled:!ee}),r.jsxs("div",{className:"composer-toolbar",children:[r.jsxs("div",{className:"composer-leading-controls",children:[r.jsx(el,{onTranscript:N=>C(u?`${u} ${N}`:N)}),r.jsx("button",{type:"button",className:"icon-button",onClick:()=>X.current?.click(),title:v.uploadFiles,disabled:!ee||f,children:r.jsx(Pn,{"aria-hidden":"true"})}),x.length?r.jsx("button",{className:`icon-button ${ve?"selected":""}`,type:"button",title:ve?v.hideQuickReplies:v.showQuickReplies,onClick:()=>xe(N=>!N),children:r.jsx(qo,{"aria-hidden":"true"})}):null,r.jsx("button",{className:`icon-button ${de?"selected":""}`,type:"button",title:v.skills,onClick:he,disabled:!ee||f,children:r.jsx(cn,{"aria-hidden":"true"})}),r.jsx("button",{className:`icon-button ${ae?"selected":""}`,type:"button",title:v.commands,onClick:fe,disabled:!ee||f,children:r.jsx(ns,{"aria-hidden":"true"})})]}),r.jsx("input",{ref:X,type:"file",multiple:!0,hidden:!0,onChange:N=>{Ce(N.currentTarget.files,N.currentTarget)}}),r.jsxs("div",{className:"composer-control-strip",children:[r.jsx(xn,{icon:i==="autoApprove"?cn:zs,label:Ke,menuLabel:v.approvalMode,options:ce,value:i,onSelect:S,wide:!0}),r.jsx(xn,{icon:ms,label:He,menuLabel:v.model,options:$e,value:y,onSelect:E,align:"right",wide:!0}),r.jsx(xn,{icon:Nt,label:Ze||v.effort,menuLabel:v.effort,options:me,value:m,onSelect:w,align:"right"}),r.jsx(xn,{icon:cn,label:g?v.fast:v.normal,menuLabel:v.fastMode,options:[{value:"off",label:v.normal,description:v.standardExecution,icon:Nt},{value:"on",label:v.fast,description:v.preferFasterResponses,icon:cn}],value:g?"on":"off",onSelect:N=>I(N==="on"),align:"right",selected:g,wide:!0})]}),r.jsx(Jc,{connected:ee,busy:o,sending:l,responding:d,hasDraft:!!u.trim(),shortcut:b,onStop:h,t:v})]}),s.length||f?r.jsx("div",{className:"attachment-row",children:s.length?r.jsx("div",{className:"attachment-list",children:s.map(N=>r.jsxs("span",{children:[r.jsx(si,{"aria-hidden":"true"}),N.name||Bt(N.path),r.jsx("small",{children:Rc(N.size)}),r.jsx("button",{type:"button",onClick:()=>Y(N.path),title:v.removeAttachment,children:r.jsx(_e,{"aria-hidden":"true"})})]},N.path))}):r.jsxs("span",{className:"attachment-empty",children:[r.jsx("span",{className:"loading-spinner small","aria-hidden":"true"}),v.uploading]})}):null]})}function rl({cwd:e,paths:t,t:n,onClose:s,onOpenRemoteFile:i}){const a=c.useRef(null),o=Mn(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(si,{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:Bt(l)}),r.jsx("small",{children:l})]}),r.jsx(Gr,{"aria-hidden":"true"})]},l))})]})]}):null}function Ci({title:e,draft:t,label:n,disabled:s,onDraftChange:i,onCommit:a}){const[o,l]=c.useState(!1),d=c.useRef(null),h=c.useRef(null),u=c.useRef(!1);c.useLayoutEffect(()=>{o?(d.current?.focus(),d.current?.select()):u.current&&(u.current=!1,h.current?.focus())},[o]);const m=()=>{u.current=!0,l(!1)};return o?r.jsx("input",{ref:d,className:"inline-session-title-input","aria-label":n,value:t,onChange:g=>i(g.target.value),onBlur:()=>l(!1),onKeyDown:g=>{g.nativeEvent.isComposing||g.keyCode===229||(g.key==="Enter"?(g.preventDefault(),t.trim()&&t.trim()!==e&&a(),m()):g.key==="Escape"&&(g.preventDefault(),g.stopPropagation(),m()))}}):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 Ii=c.createContext(null);function il({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(jn,{"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 al({activeSession:e,agent:t,cwd:n,t:s,onOpenDetails:i,renameTitle:a,busy:o,onRename:l,onRenameTitleChange:d,onViewChanges:h,search:u}){const[m,g]=c.useState(!1),y=c.useRef(null);c.useEffect(()=>{u.query&&g(!0)},[u.query]);const k=()=>{u.onChange(""),g(!1),y.current?.focus()},x=e?St(e):s.newSession,b=e?.cwd??(n.trim().length>0&&n!=="."?n:""),p=e?.agent??t,f=c.useContext(Ii),v=ne().toolbarTarget?.("conversation")??f,S=r.jsxs("div",{className:"chat-header-title-row",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 ${p}`,type:"button",onClick:i,"aria-label":s.details,title:s.details,disabled:!e,children:p==="codex"?"Codex":"Claude"}),r.jsx("h1",{children:e?r.jsx(Ci,{title:x,draft:a,label:s.rename,disabled:o,onDraftChange:d,onCommit:l},e.sessionId):x})]}),b?r.jsx("p",{title:b,children:b}):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:e.runtime.state}):null,e.terminal?.mode?r.jsx("span",{children:e.terminal.mode}):null]}):null]}),e?r.jsxs("button",{className:"chat-changes-button",type:"button","aria-label":s.viewChanges,title:s.viewChanges,onClick:()=>h(e.sessionId),children:[r.jsx(Xn,{"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:y,className:"icon-button chat-search-toggle",type:"button","aria-label":s.searchThisSession,title:s.searchThisSession,"aria-expanded":m,"aria-controls":"conversation-message-search",onClick:()=>m?k():g(!0),children:r.jsx(jn,{"aria-hidden":"true"})})]});return r.jsxs("header",{className:`chat-header chat-search-header ${v?"chat-header-in-titlebar":""}`,children:[v?Et.createPortal(S,v):S,m&&r.jsx(il,{...u,t:s,onClose:k})]})}async function Ni(e){const t=ne().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,d)=>s.getRangeAt(d).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 Ei(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 Ni(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 Zs({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 ol({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(Jr,{"aria-hidden":"true"}),r.jsx("span",{children:e}),r.jsxs("button",{className:"chat-notice-retry",onClick:n,type:"button",children:[r.jsx(kn,{"aria-hidden":"true"}),t]})]})}function cl({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 xr({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(Jr,{"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(kn,{"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 ll({label:e,onClick:t}){return r.jsxs("button",{className:"scroll-latest-button",type:"button","aria-label":e,title:e,onClick:t,children:[r.jsx(ka,{"aria-hidden":"true"}),r.jsx("span",{role:"status",children:e})]})}const dl=/\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g,ul=/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F\u00AD\u061C\u180E\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g,hl=new Set(["","{}","[]","null","undefined",'""']);function Wn(e){return e.replace(/\s+/g," ").trim()}function Ae(e,t){return typeof e[t]=="string"?e[t]:""}function wr(e,t){return typeof e[t]=="number"?e[t]:void 0}function yn(e,t){return e.length<=t?e:`${e.slice(0,t)}...`}function ys(e){const t=[],n=Ae(e,"file_path")||Ae(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 fl(e){return typeof e!="string"?"":e.replace(/\r\n?/g,`
|
|
5
|
-
`).replace(dl,"").replace(ul,"").trim()}function Js(e){const t=fl(e);return hl.has(t)?"":t}function ml(e){return Js(e).length>0}function Ys(e){const t=Js(e);if(!t)return"";try{const n=JSON.parse(t);if(n&&typeof n=="object"&&!Array.isArray(n)){const s=typeof n.query=="string"?Wn(n.query):"";if(s)return s;const i=typeof n.command=="string"?Wn(n.command):"";if(i)return i;const a=typeof n.description=="string"?Wn(n.description):"";if(a)return a}}catch{}return Wn(t)}function pl(e,t){if(!t)return[];switch((e??"").toLowerCase()){case"read":return ys(t);case"write":{const s=ys(t),i=Ae(t,"content");return i&&s.push({label:"Content",isDiff:!0,value:"",diffNew:yn(i,500)}),s}case"edit":{const s=ys(t),i=Ae(t,"old_string")||Ae(t,"oldString"),a=Ae(t,"new_string")||Ae(t,"newString");return(i||a)&&s.push({label:"Change",isDiff:!0,value:"",diffOld:yn(i,300),diffNew:yn(a,300)}),s}case"bash":{const s=Ae(t,"command");return s?[{label:"Command",value:s,isCode:!0}]:[]}case"websearch":{const s=Ae(t,"query");return s?[{label:"Query",value:s}]:[]}case"webfetch":{const s=[],i=Ae(t,"url");i&&s.push({label:"URL",value:i});const a=Ae(t,"prompt");return a&&s.push({label:"Prompt",value:yn(a,200)}),s}case"glob":{const s=Ae(t,"pattern");return s?[{label:"Pattern",value:s}]:[]}case"grep":{const s=[],i=Ae(t,"pattern");i&&s.push({label:"Pattern",value:i,isCode:!0});const a=Ae(t,"path");return a&&s.push({label:"In",value:a,isFilePath:!0}),s}default:{const s=[],i=Ae(t,"command");if(i)return[{label:"Command",value:i,isCode:!0}];const a=Ae(t,"file_path")||Ae(t,"filePath");a&&s.push({label:"Path",value:a,isFilePath:!0});const o=Ae(t,"description");o&&s.push({label:"Description",value:yn(o,200)});const l=Ae(t,"query");l&&s.push({label:"Query",value:l});const d=Ae(t,"url");return d&&s.push({label:"URL",value:d}),s}}}function Sr(e){return e.role==="tool"?!0:e.type!=="info"?!1:!/^Error:/i.test(e.content.trim())}function Ri(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=>Ys(s.content)).find(Boolean)??""}function Ti(e,t){return`${e.historyKey??e.timestamp??e.toolName??e.content.slice(0,24)??"message"}:${t}`}function gl(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})=>Ti(l,o)).join("|")}`}),n=a-1}return t}function yl(e,t){return e.type==="message"?e.index===t:e.entries.some(n=>n.index===t)}function bl(e){const t=e.at(-1);return t?`${e.length}:${t.historyKey??""}:${t.timestamp??""}:${t.content.length}`:"0"}function vl(e,t,n,s,i,a){const o=()=>{const l=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,l&&d?.scrollTo({top:d.scrollTop,behavior:"auto"})};return{onWheel:l=>{if(!l.deltaY)return;const d=e.current;(l.deltaY<0||d&&d.scrollHeight-d.scrollTop-d.clientHeight>2)&&o()},onPointerDown:l=>{const d=l.currentTarget.getBoundingClientRect();(l.button===1||l.clientX>=d.right-16)&&o()},onTouchStart:o,onKeyDown:l=>{l.target instanceof Element&&l.target.closest('input,textarea,[contenteditable="true"]')||["ArrowUp","ArrowDown","PageUp","PageDown","Home","End"," "].includes(l.key)&&o()}}}function xl(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 wl(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 Sl(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 kl={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 In(){return kl[qe(ze().language)]}const Rs="vibelet:image-gallery";function jl(e){window.dispatchEvent(new CustomEvent(Rs,{detail:e}))}const Cl="(?:png|jpg|jpeg|gif|webp|svg|heic|heif)",Il="(?:~/|/|\\.{1,2}/|[A-Za-z0-9._-]+/)",Nl="[^\\n`<>\"')\\]},。!?;:、]*?",El="(?::\\d+(?::\\d+)?|#[^\\s`<>\"')\\]},。!?;:、]+)?",Rl=`${Il}${Nl}\\.${Cl}${El}`,kr=new RegExp(`(${Rl})`,"gi"),Tl=[".png",".jpg",".jpeg",".gif",".webp",".svg",".heic",".heif"],Ts="\\s`<>\"')\\]},。!?;:、",jr="`<>\"')\\]},。!?;:、\\n\\r\\t",Al=new RegExp(`(^|[\\s([{>])((?:~\\/|\\/|\\.{1,2}\\/)[^${Ts}]+|[A-Za-z0-9._-]+(?:\\/[A-Za-z0-9._-]+)+(?:\\.[A-Za-z0-9._-]+)?\\/?)`,"g"),Ml=new RegExp(`(^|[\\s([{>])((?=[^${jr}]*\\/)[^${jr}]+?\\.[A-Za-z0-9._-]+(?::\\d+(?::\\d+)?|#[^${Ts}]+)?)(?=$|[${Ts}])`,"g");function As(e){let t=e;for(;/[.,!?;:,。!?;:、]+$/.test(t);)t=t.slice(0,-1);return t}function Ms(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 rs(e){let t=As(e.trim());if(!t)return"";const n=t.indexOf("#");if(n>0){const i=t.slice(0,n);Ms(i,{allowBareFilename:!0})&&(t=i)}const s=t.match(/^(.*?)(:\d+(?::\d+)?)$/);if(s){const i=s[1]??"";Ms(i,{allowBareFilename:!0})&&(t=i)}return As(t)}function Pl(e,t){return e.start<t.end&&t.start<e.end}function Ps(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 Dl(e){if(Ps(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(Ps(a))return{start:e.start+i,end:e.end,rawCandidate:a}}return e}function _l(e){const t=[];for(const n of e.matchAll(Al)){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(Ml)){const s=n[1]??"",i=n[2]??"",o=(n.index??0)+s.length,l=Dl({start:o,end:o+i.length,rawCandidate:i}),d=t.filter(h=>Pl(h,l));if(d.length===0){t.push(l);continue}if(Ps(l.rawCandidate)){for(const h of d){const u=t.indexOf(h);u>=0&&t.splice(u,1)}t.push(l)}}return t.sort((n,s)=>n.start-s.start||n.end-s.end)}function Xs(e,t){const n=rs(e);return Ms(n,t)}function er(e){const t=rs(e).toLowerCase();return Xs(t,{allowBareFilename:!0})&&Tl.some(n=>t.endsWith(n))}function Ll(e){if(!e)return[];const t=[];let n=0;for(const s of _l(e)){s.start>n&&t.push({type:"text",value:e.slice(n,s.start)});const i=As(s.rawCandidate),a=rs(i),o=s.rawCandidate.slice(i.length);Xs(i)&&!er(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 Fl=/^[a-z][a-z0-9+.-]*:/i,$l=/^[a-z]:[\\/]/i,Ai=/\.(?:md|markdown)$/i,Mi="https://vibelet.local",Pi="/__vibelet_markdown__",Ol=`${Mi}${Pi}`;function Wl(e){try{return decodeURIComponent(e)}catch{return e}}function Di(e){const t=e?.trim()??"";if(!t||t.startsWith("#")||t.startsWith("//"))return null;const n=ql(t);if(n)return n;if(Fl.test(t)&&!$l.test(t))return null;const s=t.split(/[?#]/,1)[0]??"";return Ai.test(s)?Wl(s):null}function Rf(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:zl(s)}).join(`
|
|
7
|
-
`)}function ql(e){let t;try{t=new URL(e)}catch{return null}if(t.origin!==Mi||t.pathname!==Pi)return null;const n=t.searchParams.get("path");return!n||!Ai.test(n)?null:n}function zl(e){let t="",n=0;for(;n<e.length;){if(e[n]==="`"){const s=Bl(e,n);t+=e.slice(n,s),n=s;continue}if(e[n]==="["&&e[n-1]!=="!"){const s=Hl(e,n);if(s){t+=s.text,n=s.end;continue}}t+=e[n],n+=1}return t}function Bl(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 Hl(e,t){const n=Kl(e,t);if(n<0||e[n+1]!=="(")return null;const s=n+2,i=Ul(e,s);if(i<0)return null;const a=e.slice(s,i),o=Gl(a);return o?{text:`${e.slice(t,s)}${o})`,end:i+1}:null}function Kl(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 Ul(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 Gl(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),d=Cr(l);return d?`${t}<${d}>${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=Di(e);return t?`${Ol}?path=${encodeURIComponent(t)}`:null}const _i="https://vibelet.local/__vibelet_file__";function Nn(e){if(!e)return null;const t=Di(e);if(t)return t;let n=e.trim();if(n.startsWith(_i))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=rs(n),Xs(n,{allowBareFilename:!0})?n:null}const Ds=e=>`${_i}?path=${encodeURIComponent(e)}`;function Li(e){return e.value??e.children?.map(Li).join("")??""}function Vl(e){const t=[],n=new RegExp(`(?:file://(?:localhost)?(?=/))?${kr.source}`,kr.flags);let s=0;const i=a=>{for(const o of Ll(a))t.push(o.type==="path"?{type:"link",url:Ds(o.target??o.value),children:[{type:"text",value:o.value}]}:{type:"text",value:o.value})};for(const a of e.matchAll(n)){const o=Nn(a[0]);!o||!er(o)||(i(e.slice(s,a.index)),t.push({type:"image",url:Ds(o),alt:o.split(/[\\/]/).at(-1)}),s=a.index+a[0].length)}return i(e.slice(s)),t}function Tf(){return e=>{const t=n=>{if(n.type==="link"||n.type==="image"){const s=Nn(n.url);s&&(n.url=Ds(s),er(s)&&(n.alt=n.alt||Li(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"?Vl(s.value??""):(t(s),[s])))};t(e)}}const Fi="pair",sn="vibelet.web.pairing",Ir="vibelet.web.deviceId";class En extends Error{constructor(t,n){super(n),this.code=t,this.name="PairingCreateError"}}function tr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ql(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 Zl(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 Jl(e){if(!tr(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 Yl(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 $i(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 Xl(e){const t=e.trim();return t.includes(":")&&!t.startsWith("[")?`[${t}]`:t}function ed(e,t){return t.protocol==="https:"&&e.secure!==!0?null:`${e.secure===!0?"wss":"ws"}://${Xl(e.host)}:${e.port}`}function Nr(e){return Yl(e.host)?0:e.source==="local_network"?1:e.source==="configured_host"?2:3}function td(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 nd(e,t,n=window.location,s=!0){if(s&&$i(n.hostname))return;const i=[...t?.connections??[],...e.connections??[],...td(e,t)].map(Jl).filter(a=>!!a).filter(a=>a.kind==="direct").sort((a,o)=>Nr(a)-Nr(o));for(const a of i){const o=ed(a,n);if(o)return o}}function sd(e){if(!e.d||!e.c)return null;const t=Array.isArray(e.o)?e.o.map(Zl).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 rd(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 id(e=window.location.hash){const t=e.startsWith("#")?e.slice(1):e,n=new URLSearchParams(t).get(Fi);if(!n)return null;try{const s=JSON.parse(Ql(n));if(!tr(s))return null;if(s.t==="vp")return sd(s);if(s.type==="vibelet-pair")return rd(s)}catch{return null}return null}function ad(){if(!window.location.hash.includes(`${Fi}=`))return;const e=`${window.location.pathname}${window.location.search}`;window.history.replaceState(null,"",e)}function od(e=Fe()){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(sn);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 nr(e){if(typeof window>"u")return null;try{return e===Fe()?window.sessionStorage:null}catch{return null}}function sr(e=Fe(),t=nr(e)){const n=Er(e);if(n)return n;const s=t?Er(t):null;return s?(e.setItem(sn,JSON.stringify(s)),t?.removeItem(sn),s):null}function Rr(e,t=Fe(),n=nr(t)){t.setItem(sn,JSON.stringify(e)),n?.removeItem(sn)}function Oi(e=Fe(),t=nr(e)){e.removeItem(sn),t?.removeItem(sn)}function cd(e,t=Date.now()){if(!e.expiresAt)return!1;const n=new Date(e.expiresAt).getTime();return Number.isFinite(n)&&n<t}async function ld(e){const t=await e.text().catch(()=>"");try{const n=JSON.parse(t);if(tr(n)&&n.error==="pair_window_expired")return new En("pair_window_expired","Pairing link expired.")}catch{}return new En("pairing_failed",t||"Pairing failed.")}async function dd(e,t=od()){if(cd(e))throw new En("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 ld(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:nd(e,s,window.location,!0)}}async function ud(e,t){try{return await dd(e,t?.deviceId)}catch(n){if(n instanceof En&&n.code==="pair_window_expired"&&t?.daemonId===e.daemonId)return t;throw n}}const Tr=20*1024*1024;function hd(e,t,n=1600){const s=Nn(e),i=sr(),[a,o]=c.useState(null),[l,d]=c.useState(null);return c.useEffect(()=>{if(!s)return;const m=new AbortController;let g;return o(null),d(null),(async()=>{try{if(!i)throw new Error("No pairing");const k=new URL(Bn(s,t));n!==null&&k.searchParams.set("w",String(n));const x=await fetch(k,{headers:{authorization:`Bearer ${i.pairToken}`},signal:m.signal});if(!x.ok||Number(x.headers.get("content-length"))>Tr)throw new Error("Image unavailable");const b=await x.blob();if(!b.type.startsWith("image/")||b.size>Tr)throw new Error("Unsupported image");if(m.signal.aborted)return;g=URL.createObjectURL(b),o({src:e,url:g})}catch{m.signal.aborted||d(e)}})(),()=>{m.abort(),g&&URL.revokeObjectURL(g)}},[e,s,t,n,i?.pairToken,i?.webSocketUrl]),{url:s?a?.src===e?a.url:void 0:e,error:l===e,fail:()=>d(e)}}function fd({src:e,alt:t,cwd:n,onOpen:s,gallery:i}){const a=Nn(e),{url:o,error:l,fail:d}=hd(e,n),h=Ss[qe(ze().language)],u=t||Bt(a??e);return r.jsx("button",{className:"message-image-preview",type:"button",title:a??e,"aria-label":`${h.preview}: ${u}`,onClick:async m=>{m.preventDefault(),m.stopPropagation();const g=await i?.()??[{src:e,alt:u,cwd:n}],y=g.findIndex(k=>k.src===e||a&&Nn(k.src)===a);jl({images:y<0?[{src:e,alt:u,cwd:n}]:g,index:Math.max(0,y),onOpen:s})},children:l?r.jsxs("span",{className:"message-image-placeholder",children:[r.jsx(ho,{"aria-hidden":"true"}),u," · ",h.fileOpenFailed]}):o?r.jsx("img",{src:o,alt:u,loading:"lazy",onError:d}):r.jsxs("span",{className:"message-image-placeholder",children:[r.jsx(es,{className:"session-running-icon","aria-hidden":"true"}),u]})})}function md({message:e,t}){return r.jsx("pre",{className:"message-markdown-source",role:"region","aria-label":t.markdownSource,children:e.content})}function pd({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 gd({message:e,onCopy:t,t:n}){const s=pl(e.toolName,e.toolInput),i=Ys(e.content),a=Js(e.content),o=ml(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(Bs,{"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(hn,{"aria-hidden":"true"})})]}),s.length?r.jsx("div",{className:"tool-fields",children:s.map((d,h)=>r.jsx(pd,{field:d},`${d.label}:${h}`))}):null,o?r.jsx("pre",{className:"json-box compact",children:a}):null]})}function Wi({messages:e,showHeader:t=!0,onClose:n,onCopy:s,t:i}){if(!e.length)return null;const o=e.filter(u=>u.role==="tool").length||e.length,l=i.toolCallCount(o),d=Ri(e),h=e.map(u=>u.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:d,children:d||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(hn,{"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((u,m)=>r.jsx(gd,{message:u,onCopy:s,t:i},`${u.historyKey??u.timestamp??u.toolName??"tool"}:${m}`))})]})}const yd=c.lazy(async()=>nt(()=>import("./mermaid-O7DHMXV3-DkoqfAOM.js").then(e=>e.b),__vite__mapDeps([0,1,2,3,4])).then(e=>({default:e.MessageMarkdown})));function bd({activeMatch:e,baseCwd:t,message:n,onCopy:s,onRewind:i,onCloseTool:a,onOpenAttachment:o,onOpenRemoteFile:l,onToggleSource:d,onToggleTool:h,sourceOpen:u,toolOpen:m,t:g}){const y=Sl(n,g),k=n.role==="tool"?Ys(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:wi(n,g)}),r.jsxs("div",{className:"message-meta-side",children:[y&&r.jsx("span",{className:"message-delivery","data-state":y.state,role:"status",title:y.title,children:y.label}),r.jsx("time",{children:ss(n.timestamp,Date.now(),g)})]})]}),u?r.jsx(md,{message:n,t:g}):n.role==="tool"?r.jsxs("button",{className:"tool-inline-summary","aria-expanded":m,onClick:h,type:"button",children:[r.jsxs("span",{children:[r.jsx(Zo,{"aria-hidden":"true"}),n.toolName??g.tool]}),k?r.jsx("small",{children:k}):null]}):n.role==="assistant"||n.role==="user"?r.jsx(c.Suspense,{fallback:r.jsx("pre",{children:n.content}),children:r.jsx(yd,{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(x=>r.jsx(fd,{src:x,cwd:t,onOpen:l,gallery:async()=>[...(await nt(async()=>{const{collectMessageImages:b}=await import("./collectMessageImages-D5nmo9r7.js").then(p=>p.q);return{collectMessageImages:b}},[])).collectMessageImages(n.content,t),...(n.images??[]).map(b=>({src:b,cwd:t}))]},x)),r.jsxs("button",{className:"file-pill",onClick:()=>o(n.images??[]),type:"button",children:[r.jsx(Va,{"aria-hidden":"true"}),g.preview]})]}):null,n.role==="tool"&&m?r.jsx(Wi,{messages:[n],onClose:a,onCopy:s,t:g}):null,r.jsxs("div",{className:"message-actions","aria-label":g.messageActions,role:"group",children:[i&&n.role==="user"&&n.type!=="info"&&r.jsx("button",{type:"button",onClick:i,title:In().rewind,"aria-label":In().rewind,children:r.jsx(ii,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":g.copyMessage,onClick:()=>s(n.content),title:g.copyMessage,type:"button",children:r.jsx(hn,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":g.viewMarkdownSource,"aria-expanded":u,onClick:d,title:u?g.hideMarkdownSource:g.viewMarkdownSource,type:"button",children:r.jsx(Wa,{"aria-hidden":"true"})})]})]})}function vd({activeMatch:e,expanded:t,messages:n,onToggle:s}){const i=n.filter(l=>l.role==="tool").length||n.length,a=Ri(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(Zr,{className:"tool-group-chevron","aria-hidden":"true"}),r.jsx("strong",{children:o})]}),a?r.jsx("span",{className:"tool-group-summary",children:a}):null]})})}function xd(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=u=>{u.type==="focusin"&&u.target instanceof Element&&u.target.contains(e.current)||(i.current=u.target instanceof Element&&!!e.current?.contains(u.target)&&!u.target.closest("input,textarea,select")&&!u.target.isContentEditable)},h=[["pointerdown",l],["focusin",l],["keydown",u=>{!i.current||u.isComposing||(u.metaKey||u.ctrlKey)&&!u.altKey&&!u.shiftKey&&u.key.toLowerCase()==="a"&&(u.preventDefault(),s.current(),o(m=>m+1))}]];return h.forEach(([u,m])=>document.addEventListener(u,m,!0)),()=>h.forEach(([u,m])=>document.removeEventListener(u,m,!0))},[e,t]),c.useLayoutEffect(()=>{if(!i.current)return;const l=e.current?.querySelectorAll(".message-frame"),d=l?.[l.length-1];d&&window.getSelection()?.setBaseAndExtent(l[0],0,d,d.childNodes.length)},[a,e,t])}const Kn=160,wd=120,bn=-1;function Jt(e){return Math.max(0,e-Kn)}function Sd(e,t){const n=t.length,[s,i]=c.useState(()=>({sessionId:e,start:Jt(n),total:n})),a=s.sessionId!==e?Jt(n):s.start===bn?bn:n>s.total&&s.start+Kn>=s.total?Jt(n):Math.min(s.start,Jt(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(g=>({sessionId:e,start:Math.max(0,(g.sessionId===e?g.start:Jt(n))-wd),total:n}))},[e,n]),l=c.useCallback(g=>{const y=t.findIndex(x=>yl(x,g));if(a===bn||y<0||y>=a&&y<a+Kn)return!1;const k=Math.min(Jt(n),Math.max(0,y-40));return i({sessionId:e,start:k,total:n}),!0},[t,e,a,n]),d=c.useCallback(()=>{i({sessionId:e,start:Jt(n),total:n})},[e,n]),h=()=>i({sessionId:e,start:bn,total:n}),u=Math.max(0,a),m=a===bn?n:Math.min(n,a+Kn);return{ensureMessageVisible:l,hiddenItemCount:u,hiddenLaterItemCount:Math.max(0,n-m),revealEarlier:o,revealLatest:d,revealAll:h,visibleItems:t.slice(u,m)}}const Ar=()=>null,kd=()=>()=>{};function jd(e,t,n,s){const i=c.useSyncExternalStore(e.submission?.subscribe??kd,e.submission?.getSnapshot??Ar,Ar),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 Cd({activeSession:e,activeUsage:t,messages:n,renameTitle:s,busy:i,t:a,onBrowseFiles:o,onClose:l,onExport:d,onJumpToMessage:h,onRename:u,onRenameTitleChange:m,onToggleArchived:g,onTogglePinned:y,onViewChanges:k}){const[x,b]=c.useState(""),{copyText:p,feedback:f}=Ei(a.commandCopied,a.copyResumeFailed),v=c.useRef(null),S=Mn(l,v),j=c.useMemo(()=>bi(e),[e]),C=c.useMemo(()=>{const w=x.trim().toLowerCase();return w?n.map((I,E)=>({message:I,index:E})).filter(({message:I})=>I.role!=="user"&&I.role!=="assistant"?!1:I.content.toLowerCase().includes(w)).slice(0,20):[]},[n,x]);return r.jsxs("div",{"aria-labelledby":"session-detail-title","aria-modal":"true",className:"session-detail-drawer",ref:S,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:St(e),children:r.jsx(Ci,{title:St(e),draft:s,label:a.rename,disabled:i,onDraftChange:m,onCommit:u},e.sessionId)})]}),r.jsx("button",{"aria-label":a.closeSessionDetails,className:"icon-button",onClick:l,ref:v,type:"button",children:r.jsx(_e,{"aria-hidden":"true"})})]}),r.jsxs("div",{className:"detail-info-grid",children:[r.jsxs("div",{children:[r.jsx(Un,{"aria-hidden":"true"}),r.jsx("span",{children:a.workingDirectory}),r.jsx("strong",{title:e.cwd,children:e.cwd})]}),r.jsxs("div",{children:[r.jsx(ti,{"aria-hidden":"true"}),r.jsx("span",{children:a.messages}),r.jsx("strong",{children:n.filter(w=>w.role==="user"||w.role==="assistant").length})]}),r.jsxs("div",{children:[r.jsx(lo,{"aria-hidden":"true"}),r.jsx("span",{children:a.session}),r.jsx("strong",{title:e.sessionId,children:e.sessionId})]}),r.jsxs("div",{children:[r.jsx(Bs,{"aria-hidden":"true"}),r.jsx("span",{children:a.runtime}),r.jsx("strong",{children:e.runtime.state})]})]}),e.branch||e.diffStat?r.jsxs("button",{className:"detail-command-card detail-changes-card",type:"button",onClick:k,children:[r.jsx(Xn,{"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(jn,{"aria-hidden":"true"}),r.jsx("input",{value:x,onChange:w=>b(w.target.value),placeholder:a.searchMessages}),x.trim()?r.jsx("small",{children:a.searchResultCount(C.length)}):null]}),x.trim()&&C.length?r.jsx("div",{className:"detail-search-results",children:C.map(({message:w,index:I})=>r.jsxs("button",{type:"button",onClick:()=>{h(I,x),l()},children:[r.jsx("span",{children:wi(w,a)}),r.jsx("strong",{children:w.content})]},`${w.historyKey??w.timestamp??I}:${I}`))}):null,x.trim()?null:r.jsxs(r.Fragment,{children:[r.jsxs("button",{className:"detail-command-card",type:"button",onClick:o,children:[r.jsx(Un,{"aria-hidden":"true"}),r.jsx("span",{children:a.browseFiles})]}),r.jsxs("button",{className:"detail-command-card",type:"button",onClick:()=>{p(j)},children:[r.jsx(La,{"aria-hidden":"true"}),r.jsx("span",{title:j,children:j})]}),r.jsx(Zs,{feedback:f}),r.jsxs("div",{className:"detail-action-grid",children:[r.jsxs("button",{className:"icon-text-button",disabled:i,type:"button",onClick:y,children:[r.jsx(ts,{"aria-hidden":"true"}),e.pinned?a.unpin:a.pin]}),r.jsxs("button",{className:"icon-text-button",disabled:i,type:"button",onClick:g,children:[r.jsx(qs,{"aria-hidden":"true"}),e.archived?a.unarchive:a.archive]}),r.jsxs("button",{className:"icon-text-button",type:"button",onClick:d,children:[r.jsx(Yn,{"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," ",ss(e.createdAt,Date.now(),a)]})]})]})]})}function Id({activeSession:e,activeSessionId:t,activeModelOptions:n,activeQueue:s,queueControls:i,activeUsage:a,agent:o,approvalMode:l,attachments:d,busy:h,cwd:u,draft:m,effort:g,errorText:y,failedSend:k,onDismissFailedSend:x,fastMode:b,historyLoading:p,messages:f,messagesSessionId:v,model:S,phase:j,quickReplies:C,renameTitle:w,respondingSessionIds:I,sendShortcut:E,skills:L,uploadBusy:Y,detailsOpen:B,t:T,onApprovalModeChange:X,onBrowseFiles:H,onCancelQueuedTurn:se,onClearInterrupt:Se,onDraftChange:ve,onDetailsOpenChange:xe,onEffortChange:A,onExportActiveSession:M,onRewindMessage:W,onFastModeChange:z,onRetryFailedSend:K,onModelChange:J,onOpenRemoteFile:Q,onInterrupt:oe,onRetry:$,onDismissError:V,onRefreshSkills:ee,onRenameSession:Ge,onRenameTitleChange:we,onRemoveAttachment:Be,onSubmit:ae,onToggleArchived:ke,onTogglePinned:le,onUploadFiles:je,onViewChanges:de}){const ue=jd(ae,K,j==="connected"&&!h&&!!m.trim(),t),[ce,me]=c.useState(""),[Me,He]=c.useState(0),[Ke,Ze]=c.useState(null),[$e,Ce]=c.useState(null),[Je,Pe]=c.useState(!1),[Ve,Ee]=c.useState([]),fe=c.useRef(null),Z=c.useRef([]),he=c.useRef(null),U=c.useRef(null),G=c.useRef(!1),pe=c.useRef(!1),N=c.useRef(!0),Ie=c.useRef(0),De=c.useRef(0),ht=c.useMemo(()=>gl(f),[f]),{ensureMessageVisible:Rt,hiddenItemCount:Ye,hiddenLaterItemCount:ge,revealAll:kt,revealEarlier:ft,revealLatest:jt,visibleItems:ot}=Sd(t,ht),Ct=c.useMemo(()=>!!(k&&ot.some(_=>_.type==="message"&&_.message.historyKey===k.historyKey)),[k,ot]),Xe=c.useRef(null),{copyText:mt,feedback:Tt}=Ei(T.messageCopied,T.copyFailed),Oe=c.useMemo(()=>{const _=ce.trim().toLowerCase();return _?f.map((q,re)=>({index:re,message:q})).filter(({message:q})=>q.content.toLowerCase().includes(_)):[]},[ce,f]),It=_=>{N.current=!1,Ie.current=0;const q=Rt(_),re=()=>Z.current[_]?.scrollIntoView({behavior:"smooth",block:"center"});q?requestAnimationFrame(()=>requestAnimationFrame(re)):re()},At=()=>{if(!Oe.length)return;const _=Me%Oe.length,q=Oe[_]?.index;typeof q=="number"&&It(q),He(re=>(re+1)%Oe.length)},Ue=c.useCallback(()=>{const _=fe.current;_&&(N.current=!0,Ie.current=0,_.scrollTop=_.scrollHeight,Pe(!1))},[]),st=c.useCallback(_=>{N.current=!0,Ie.current=0,pe.current=!0,G.current=!1,Xe.current=null;const q=fe.current,re=q?q.scrollHeight-q.scrollTop-q.clientHeight:0,Re=_??(ge===0&&q&&re<=q.clientHeight?"smooth":"auto"),et=()=>{const ye=fe.current;!ye||!pe.current||(ye.scrollTo({top:ye.scrollHeight,behavior:Re}),Pe(!1),requestAnimationFrame(()=>{pe.current=!1}))};ge>0?(jt(),requestAnimationFrame(()=>requestAnimationFrame(et))):et()},[ge,jt]),pt=()=>{const _=fe.current;if(!_)return;const q=_.querySelector(".message-frame");Xe.current={element:q,top:q?q.getBoundingClientRect().top-_.getBoundingClientRect().top:_.scrollTop,height:_.scrollHeight}},gt=()=>{const _=fe.current;if(!_)return;_.scrollTop<160&&Ye>0&&!G.current&&!pe.current&&(G.current=!0,pt(),ft());const q=_.scrollTop>De.current;De.current=_.scrollTop;const re=_.scrollHeight-_.scrollTop-_.clientHeight;Ie.current>0&&!pe.current&&!G.current&&(N.current=q&&re<=2&&ge===0),Pe(re>180||ge>0)};c.useLayoutEffect(()=>{ge>0&&Pe(!0)},[ge]);const yt=vl(fe,N,U,pe,Ie,De),bt=bl(f);c.useLayoutEffect(()=>{const _=Xe.current,q=fe.current;if(_&&q){if(_.element?.isConnected){const ye=_.element.getBoundingClientRect().top-q.getBoundingClientRect().top;q.scrollTop+=ye-_.top}else q.scrollTop+=q.scrollHeight-_.height;Xe.current=null,G.current=!1;return}if(he.current!==t&&(he.current=t,U.current=t,Ze(null),Ce(null)),!fe.current)return;const Re=v===t;if(t!==null&&U.current===t&&Re&&(!p||f.length>0)){Ue();let ye=0,rt=-1,Te=0;const vt=performance.now(),it=()=>{if(U.current!==t)return;Ue();const Le=fe.current?.scrollHeight??0;Te=Le===rt?Te+1:0,rt=Le;const at=performance.now()-vt>=1400;if(!p&&Te>=4||!p&&at){U.current=null;return}at||(ye=requestAnimationFrame(it))};return ye=requestAnimationFrame(it),Pe(!1),()=>cancelAnimationFrame(ye)}N.current&&ge===0&&Ue()},[t,Ye,ge,p,bt,f.length,v,j,Ue]),c.useLayoutEffect(()=>{const _=fe.current;if(!_)return;const q=new ResizeObserver(()=>{N.current&&ge===0&&Ue()});q.observe(_);for(const re of _.children)q.observe(re);return()=>q.disconnect()},[t,bt,Ye,ge,Ue]);const ct=Oe.length&&ce.trim()?Oe[(Me+Oe.length-1)%Oe.length]?.index:void 0;return xd(fe,t,()=>{pt(),kt()}),r.jsxs("section",{className:"chat-pane","aria-label":T.chat,children:[r.jsx(al,{activeSession:e,agent:o,cwd:u,t:T,onOpenDetails:()=>e&&xe(!0),renameTitle:w,busy:h,onRename:Ge,onRenameTitleChange:we,onViewChanges:de,search:{query:ce,matchCount:Oe.length,onChange:_=>{me(_),He(0)},onNext:At}}),r.jsxs("div",{className:"chat-notices","aria-live":"polite",children:[y?r.jsx(ol,{message:y,retryLabel:T.retry,onRetry:$,closeLabel:T.close,onDismiss:V}):null,k&&!Ct?r.jsx(xr,{failedSend:k,onRetry:()=>{ue.retry()},onDismiss:x,t:T}):null,e?.interruptReason?r.jsxs("div",{className:"notice warning",children:[r.jsx(cn,{"aria-hidden":"true"}),r.jsx("span",{children:e.interruptReason.humanText||e.interruptReason.kind}),r.jsx("button",{className:"icon-text-button",disabled:h,onClick:Se,type:"button",children:T.clear})]}):null,e?.stallWarning?r.jsxs("div",{className:"notice warning",children:[r.jsx($a,{"aria-hidden":"true"}),r.jsx("span",{children:e.stallWarning.humanText||T.agentMayBeStalled})]}):null]}),r.jsxs("div",{className:"message-scroll","aria-busy":p,"data-history-loading":p?"true":"false","data-rendered-items":ot.length,"data-hidden-items":Ye,"data-hidden-later-items":ge,"data-total-messages":f.length,ref:fe,onScroll:gt,...yt,children:[p&&f.length===0?r.jsx(cl,{label:T.loadingHistory}):null,!p&&f.length===0?r.jsxs("div",{className:"empty-state compact",children:[r.jsx(zs,{"aria-hidden":"true"}),r.jsx("h2",{children:e?T.noVisibleMessages:T.startDaemonSession}),r.jsx("p",{children:T.emptyChatHint})]}):null,Ye>0?r.jsx("div",{className:"conversation-window-gate",children:r.jsx("button",{type:"button",onClick:()=>{G.current=!0,pt(),ft()},children:T.showEarlierMessages(Ye)})}):null,ot.map(_=>{if(_.type==="toolGroup"){const Te=_.entries.map(Le=>Le.message),vt=_.entries.some(Le=>ct===Le.index),it=$e===_.id;return r.jsx("div",{className:"message-frame tool info",ref:Le=>{for(const at of _.entries)Z.current[at.index]=Le},children:r.jsxs("div",{className:"inline-message-stack",children:[r.jsx(vd,{activeMatch:vt,expanded:it,messages:Te,onToggle:()=>Ce(Le=>Le===_.id?null:_.id)}),it?r.jsx(Wi,{messages:Te,showHeader:!1,onClose:()=>Ce(null),onCopy:mt,t:T}):null]})},_.id)}const{index:q,message:re}=_,Re=Ti(re,q),et=Ke===Re,ye=$e===Re,rt=k?.historyKey===re.historyKey?k:null;return r.jsxs("div",{className:`message-frame ${re.role} ${re.type==="info"?"info":""}`,ref:Te=>{Z.current[q]=Te},children:[r.jsx(bd,{activeMatch:ct===q,baseCwd:e?.cwd,message:re,onCopy:mt,onRewind:h||I.has(t??"")?void 0:()=>W(re),onCloseTool:()=>Ce(null),onOpenAttachment:Ee,onOpenRemoteFile:Q,onToggleSource:()=>Ze(Te=>Te===Re?null:Re),onToggleTool:()=>Ce(Te=>Te===Re?null:Re),sourceOpen:et,toolOpen:ye,t:T}),rt?r.jsx(xr,{failedSend:rt,onRetry:()=>{ue.retry()},onDismiss:x,t:T}):null]},Re)}),ge>0?r.jsx("div",{className:"conversation-window-gate",children:r.jsx("button",{type:"button",onClick:()=>st("auto"),children:T.showLatestMessages(ge)})}):null,r.jsx("div",{"aria-hidden":"true",className:"message-latest-anchor"}),Je?r.jsx(ll,{label:T.newMessages,onClick:()=>st()}):null]}),r.jsx(Zs,{feedback:Tt}),r.jsx(sl,{activeModelOptions:n,activeQueue:s,queueControls:i,agent:o,approvalMode:l,attachments:d,busy:h,sending:ue.sending,responding:I.has(t??""),onStop:oe,draft:m,effort:g,fastMode:b,model:S,phase:j,quickReplies:C,sendShortcut:E,skills:L,uploadBusy:Y,onApprovalModeChange:X,onCancelQueuedTurn:se,onDraftChange:ve,onEffortChange:A,onFastModeChange:z,onModelChange:J,onRemoveAttachment:Be,onRefreshSkills:ee,onSubmit:_=>(st("auto"),ue.submit(_)),onUploadFiles:je,t:T},t),B&&e?r.jsx(Cd,{activeSession:e,activeUsage:a,busy:h,messages:f,renameTitle:w,t:T,onBrowseFiles:()=>{xe(!1),H()},onClose:()=>xe(!1),onExport:M,onJumpToMessage:(_,q)=>{me(q),He(0),It(_)},onRename:Ge,onRenameTitleChange:we,onToggleArchived:ke,onTogglePinned:le,onViewChanges:()=>{xe(!1),de(e.sessionId)}}):null,r.jsx(rl,{cwd:e?.cwd,paths:Ve,t:T,onClose:()=>Ee([]),onOpenRemoteFile:Q})]})}const Nd="https://service.lifeos.vip/feedback",qi=8e3,Ed=6e4,Mr=4,Rd=20*1024*1024,zi=["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"],Bi=["authorization","proxy-authorization"],Hi=["cookie","set-cookie"],Td=[...Bi,...Hi],is=(e,t)=>t.length-e.length,Ki=[...zi].sort(is).join("|"),Ad=zi.filter(e=>!Td.includes(e)).sort(is).join("|"),Md=[...Bi].sort(is).join("|"),Pd=[...Hi].sort(is).join("|"),Dd=new RegExp(`(?:${Ki}|credential|private[-_ ]?key|session[-_ ]?id|e-?mail|phone|mobile|address)`,"i"),_d=new RegExp(`(["']?(?:${Md})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|(?:Basic|Bearer)\\s+[^\\s,;}]+|AWS4-HMAC-SHA256[^\\r\\n]*(?=\\r?$)|[^\\s,;}]+)`,"gim"),Ld=new RegExp(`(["']?(?:${Pd})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\r\\n]+)`,"gi"),Fd=new RegExp(`(["']?(?:${Ad})["']?\\s*[:=]\\s*)("[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\s,;}&]+)`,"gi"),$d=new RegExp(`([?&](?:${Ki})=)[^&\\s]+`,"gi");function Od(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(),d=/^(Basic|Bearer)\b/i.exec(l)?.[1];return`${i}${o}${d?`${d} `:""}${t}${o}`};return e.replace(/-----BEGIN(?: [A-Z0-9]+)? PRIVATE KEY-----[\s\S]*?-----END(?: [A-Z0-9]+)? PRIVATE KEY-----/gi,t).replace(_d,n).replace(Ld,n).replace(Fd,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($d,`$1${t}`)}function Wd(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 un(e){return Wd(Od(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 qd(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},d=new WeakSet,h=(u,m)=>{if(l.remaining<=0)return"[TRUNCATED]";if(u===null||typeof u=="boolean"||typeof u=="number")return u;if(typeof u=="bigint")return u.toString();if(typeof u=="string"){const k=un(u).slice(0,Math.min(o,l.remaining));return l.remaining-=k.length,k}if(m>=i)return"[MAX_DEPTH]";if(typeof u!="object")return un(String(u)).slice(0,Math.min(200,l.remaining));if(d.has(u))return"[Circular]";if(d.add(u),Array.isArray(u))return u.slice(0,s).map(y=>h(y,m+1));const g={};for(const[y,k]of Object.entries(u).slice(0,a)){if(l.remaining<=0)break;const x=un(y).slice(0,Math.min(120,l.remaining));l.remaining-=x.length,g[x]=Dd.test(y)?"[REDACTED]":h(k,m+1)}return g};return h(e,0)}function zd(e,t=Ed){const n=un(e);return n.length<=t?n:`[truncated ${n.length-t} chars]
|
|
10
|
-
${n.slice(-t)}`}function Bd(e){return un(e.trim()).slice(0,qi)}function Hd(e){try{const t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}}async function Kd(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 Ud(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??Kd)({url:t.endpoint??Nd,method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify(e),signal:n.signal}),o=new Promise((h,u)=>{i=setTimeout(()=>{n.abort(),u(new Error("Feedback request timed out"))},s)}),l=await Promise.race([a,o]),d=Hd(l.body);if(l.status<200||l.status>=300||d.code!==0)throw new Error(d.message||l.statusText||"Feedback request failed");if(typeof d.data?.id!="string"||!d.data.id||typeof d.data.createdAt!="string")throw new Error("Feedback response is invalid");return{id:d.data.id,createdAt:d.data.createdAt,issueFingerprint:typeof d.data?.issueFingerprint=="string"?d.data.issueFingerprint:void 0,issueOccurrence:typeof d.data?.issueOccurrence=="number"?d.data.issueOccurrence:void 0}}finally{i&&clearTimeout(i)}}const Gd=["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"],Vd=new Set(Gd);function Qd(e){const t={contextSchemaVersion:1};if(e)for(const[n,s]of Object.entries(e))Vd.has(n)&&s!==void 0&&(t[n]=s);return qd(t)}const Zd={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"},Jd={title:"意见反馈",subtitle:"报告问题,或告诉我们希望改进的地方。",bug:"问题",feature:"建议",description:"详细说明",descriptionPlaceholder:"发生了什么,或者你希望我们怎样改进?",email:"邮箱(选填)",emailPlaceholder:"便于我们回复你",includeDiagnostics:"附带经过隐私处理的诊断信息",privacyNotice:"仅在需要时附带诊断信息;发送前会移除已识别的凭据、个人标识和本地路径。",submit:"发送反馈",sending:"正在发送…",success:"感谢反馈,已经发送成功。",error:"发送失败,请稍后重试。",close:"关闭"},Yd={title:"意見回饋",subtitle:"回報問題,或告訴我們希望改善的地方。",bug:"問題",feature:"建議",description:"詳細說明",descriptionPlaceholder:"發生了什麼,或你希望我們如何改善?",email:"電子郵件(選填)",emailPlaceholder:"方便我們回覆你",includeDiagnostics:"附上經過隱私處理的診斷資訊",privacyNotice:"僅在需要時附上診斷資訊;傳送前會移除已識別的憑證、個人識別資訊和本機路徑。",submit:"傳送回饋",sending:"正在傳送…",success:"感謝回饋,已成功傳送。",error:"傳送失敗,請稍後再試。",close:"關閉"};function Ui(e){const t=e?.trim().toLowerCase().replace(/_/g,"-")??"";return/^zh(?:-(?:tw|hk|mo|hant))(?:-|$)/u.test(t)?Yd:t.startsWith("zh")?Jd:Zd}const Xd=new Set(["image/jpeg","image/png","image/webp","image/gif"]);function eu(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 tu(e){if(!e?.length)return;if(e.length>Mr)throw new Error(`Feedback supports at most ${Mr} images`);const t=e.map(s=>{if(!Xd.has(s.mimeType))throw new Error("Feedback image type is not supported");const i=eu(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:un(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)>Rd)throw new Error("Feedback images are too large");return t}function nu(e){const t=Bd(e.description);if(!t)throw new Error("Feedback description is required");const n=e.includeLogs===!1||!e.logs?"":zd(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:Qd(e.metadata),images:tu(e.images)}}function su({language:e,entry:t="web-settings"}){const n=qe(e),s=c.useMemo(()=>Ui(n),[n]),[i,a]=c.useState("bug"),[o,l]=c.useState(""),[d,h]=c.useState(""),[u,m]=c.useState("idle"),g=async()=>{if(!(!o.trim()||u==="sending")){m("sending");try{await Ud(nu({product:"vibelet",source:ne().kind==="desktop"?"desktop":"web",type:i,description:o,email:d,appVersion:ne().appVersion||"web",locale:n,platform:navigator.platform||"web",metadata:{app:ne().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:qi,value:o,placeholder:s.descriptionPlaceholder,onChange:y=>l(y.target.value)})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:s.email}),r.jsx("input",{type:"email",maxLength:320,value:d,placeholder:s.emailPlaceholder,onChange:y=>h(y.target.value)})]}),r.jsx("button",{className:"primary-button",type:"button",disabled:!o.trim()||u==="sending",onClick:()=>{g()},children:u==="sending"?s.sending:s.submit}),u==="success"?r.jsx("p",{className:"empty-copy success-copy",children:s.success}):null,u==="error"?r.jsx("p",{className:"empty-copy error-copy",children:s.error}):null]})}const bs="vibelet --access=quick";function ru({errorText:e,t}){const[n,s]=c.useState("idle"),[i,a]=c.useState(!1),o=ze().language,l=Ui(o),d=async()=>{try{if(navigator.clipboard?.writeText)await navigator.clipboard.writeText(bs);else{const h=document.createElement("textarea");h.value=bs,h.style.position="fixed",h.style.opacity="0",document.body.append(h),h.select();const u=document.execCommand("copy");if(h.remove(),!u)throw new Error("copy failed")}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(ns,{})}),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:bs}),r.jsxs("button",{className:"primary-button",onClick:()=>{d()},type:"button",children:[n==="success"?r.jsx($t,{"aria-hidden":"true"}):r.jsx(hn,{"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(ti,{"aria-hidden":"true"}),l.title]}),i?r.jsx("div",{className:"connection-feedback-panel",children:r.jsx(su,{language:o,entry:"connection-guide"})}):null]})})}const iu=c.lazy(()=>nt(()=>import("./ImageViewer-Cu953aPv.js"),__vite__mapDeps([5,1,2,6,7])));function au(){const[e,t]=c.useState(null);return c.useEffect(()=>{const n=s=>t(s.detail);return window.addEventListener(Rs,n),()=>window.removeEventListener(Rs,n)},[]),e?r.jsx(c.Suspense,{fallback:null,children:r.jsx(iu,{request:e,onClose:()=>t(null)},e.images[e.index].src)}):null}function ou(){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),[d,h]=c.useState({}),[u,m]=c.useState({}),g=c.useCallback((f,v,S,j,C,w)=>{const I=crypto.randomUUID(),E=f==="diff"?"center":"right";return f!=="diff"&&(v=`${v} ${++t.current[f]}`),a(L=>[...L,{id:I,kind:f,title:v,cwd:S,session:j,scope:C,path:w,location:E}]),E==="center"?l(I):h(L=>({...L,[f]:I})),I},[]),y=c.useCallback((f,v)=>{const S=i.find(j=>j.id===f);S&&(a(j=>j.map(C=>C.id===f?{...C,location:v}:C)),v==="center"?(l(f),h(j=>({...j,[S.kind]:i.find(C=>C.id!==f&&C.kind===S.kind&&C.location==="right")?.id}))):(h(j=>({...j,[S.kind]:f})),e.current?.(S.kind),o===f&&l(null)))},[i,o]),k=c.useCallback(f=>{const v=i.find(S=>S.id===f);a(S=>S.filter(j=>j.id!==f)),o===f&&l(null),v&&d[v.kind]===f&&h(S=>({...S,[v.kind]:i.find(j=>j.id!==f&&j.kind===v.kind&&j.location==="right")?.id}))},[i,o,d]),x=c.useCallback((f,v)=>a(S=>S.map(j=>j.id===f&&j.title!==v?{...j,title:v}:j)),[]),b=c.useCallback((f,v)=>m(S=>{if(S[f]===v||!S[f]&&!v)return S;const j={...S};return v?j[f]=v:delete j[f],j}),[]),p=c.useCallback(()=>{a([]),l(null),h({}),s(f=>f+1)},[]);return c.useMemo(()=>({openRight:e,epoch:n,items:i,center:o,right:d,hosts:u,add:g,move:y,close:k,rename:x,register:b,reset:p,setCenter:l,setRight:h}),[n,i,o,d,u,g,y,k,x,b,p])}const rr=c.createContext(null);function cu({children:e}){const t=ou();return r.jsx(rr.Provider,{value:t,children:e})}function rn(){const e=c.useContext(rr);if(!e)throw new Error("Dock workspace provider missing");return e}function Gi(){return c.useContext(rr)}const Qn="application/x-vibelet-workspace-tab",lu={browser:Xr,terminal:ns,diff:Xn};function as(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=rn(),a=as(n),o=c.useRef(null),l=i.items.filter(d=>d.location===e&&(!t||d.kind===t));return c.useEffect(()=>{e==="right"&&t&&!i.items.some(d=>d.kind===t)&&i.add(t,n[t==="browser"?"browser":"terminal"],s)},[e,t,i.epoch]),c.useEffect(()=>{if(e!=="right"||!o.current)return;const d=o.current.querySelector('.dock-tab[data-active="true"]');d&&(o.current.scrollLeft=Math.max(0,d.offsetLeft-o.current.offsetLeft))},[e,t,i.right,l.map(d=>d.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(Vr,{})}),r.jsx("div",{className:"dock-tab-items",ref:o,children:l.map(d=>{const h=e==="center"?i.center===d.id:i.right[d.kind]===d.id,u=lu[d.kind];return r.jsxs("div",{className:"document-tab dock-tab","data-active":h,"data-dock-id":d.id,draggable:!0,onDragStart:m=>{m.dataTransfer.setData(Qn,d.id),m.dataTransfer.effectAllowed="move"},children:[r.jsxs("button",{type:"button",role:"tab","aria-selected":h,title:d.title,onClick:()=>e==="center"?i.setCenter(d.id):i.setRight(m=>({...m,[d.kind]:d.id})),children:[r.jsx(u,{}),r.jsx("span",{children:d.title})]}),h&&e==="center"&&r.jsx("button",{type:"button",className:"dock-move","aria-label":a.right,title:a.right,onClick:()=>i.move(d.id,"right"),children:r.jsx(Ia,{})}),r.jsx("button",{type:"button",className:"document-tab-close","aria-label":`${n.close} ${d.title}`,title:n.close,onClick:()=>i.close(d.id),children:r.jsx(_e,{})})]},d.id)})}),e==="right"&&t&&r.jsx("button",{type:"button",className:"dock-new","aria-label":a.create,title:Dn(a.create,"newTab"),onClick:()=>i.add(t,n[t==="browser"?"browser":"terminal"],s),children:r.jsx(Pn,{})})]})}function du({item:e,t}){const n=rn(),s=as(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(Qn,e.id),i.dataTransfer.effectAllowed="move"},onClick:()=>n.move(e.id,"center"),children:r.jsx(Vr,{})}),r.jsx("button",{type:"button","aria-label":s.create,title:Dn(s.create,"newTab"),onClick:()=>n.add(e.kind,t[e.kind==="browser"?"browser":"terminal"],e.cwd),children:r.jsx(Pn,{})})]})}function Zn({location:e,kind:t}){const n=rn(),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 ir(e,t){const n=Gi();return n?{onDragOver:s=>{s.dataTransfer.types.includes(Qn)&&(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(Qn),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 uu=c.lazy(()=>nt(()=>import("./BrowserControlPanel-Cxs5WG6_.js"),__vite__mapDeps([8,1,2,6]))),hu=c.lazy(()=>nt(()=>import("./TerminalControlPanel-BeAaO_xN.js"),__vite__mapDeps([9,1,2]))),fu=c.lazy(()=>nt(()=>import("./DiffDrawer-BWx4QFFg.js"),__vite__mapDeps([10,1,2])).then(e=>({default:e.DiffDrawer})));function mu({item:e,...t}){const n=rn(),s=ir(e.location),[i]=c.useState(()=>document.createElement("div")),a=e.location==="right",l=a&&n.items.filter(g=>g.location==="right"&&g.kind===e.kind).length===1?r.jsx(du,{item:e,t:t.t}):void 0,d=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,u=n.hosts.parking;c.useLayoutEffect(()=>{u&&i.parentElement!==u&&u.appendChild(i)},[i,u]),c.useLayoutEffect(()=>{i.className="dock-surface",i.dataset.dockId=e.id,i.dataset.location=e.location,i.dataset.kind=e.kind,i.hidden=!d;const g=a&&e.kind==="diff",y=()=>{const x=h?.getBoundingClientRect();Object.assign(i.style,g?{left:"0px",top:"0px",width:"100vw",height:"100vh"}:{left:`${x?.left??0}px`,top:`${x?.top??0}px`,width:`${x?.width??0}px`,height:`${x?.height??0}px`})};y();const k=new ResizeObserver(y);return h&&k.observe(h),window.addEventListener("resize",y),window.addEventListener("scroll",y,!0),()=>{k.disconnect(),window.removeEventListener("resize",y),window.removeEventListener("scroll",y,!0)}},[i,h,d,e.id,e.location,e.kind,a]),c.useLayoutEffect(()=>()=>i.remove(),[i]);const m=()=>n.move(e.id,a?"center":"right");return Et.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(uu,{t:t.t,dockActions:l,onTitleChange:g=>n.rename(e.id,g)}):e.kind==="terminal"?r.jsx(hu,{client:t.client,cwd:e.cwd??"",deviceName:t.deviceName,visible:d,t:t.t,dockActions:l}):e.session&&t.client?r.jsx(fu,{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:as(t.t).center,presentation:a?"drawer":"workspace",initialScope:e.scope,initialPath:e.path}):null})}),i)}function pu(e){const t=rn();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(Zn,{location:"right",kind:"diff"})}),t.items.map(s=>r.jsx(mu,{item:s,...e},s.id))]})}const Pr=new WeakMap,Vi=5e3;function ar(e,t,n){let s=Pr.get(e);s||Pr.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 Af(e,t,n){return ar(e,t,n)}function gu(e,t,n){const s=ar(e,t,n);return s.pending?s.pending:s.data&&Date.now()-s.updated<Vi?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 yu(e,t,n,s){const i=ar(e,t,n),a=i.patches.get(s);if(a?.pending)return a.pending;if(a?.data&&Date.now()-i.updated<Vi)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 bu(e,t){const n=await gu(e,t,"unstaged");n.files[0]&&await yu(e,t,"unstaged",n.files[0].path)}function vu({t:e,onClose:t}){const n=c.useRef(null),s=Mn(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 xu=c.lazy(async()=>nt(()=>import("./FilesControlPanel-CmG4pm47.js"),__vite__mapDeps([11,1,2,12,13])).then(e=>({default:e.FilesControlPanel}))),wu=c.lazy(async()=>nt(()=>import("./LanguageSettingsPanel-BQcBduA3.js"),__vite__mapDeps([14,1,2,15])).then(e=>({default:e.LanguageSettingsPanel}))),Su=c.lazy(async()=>nt(()=>import("./ThemeSettingsPanel-CehjZMem.js"),__vite__mapDeps([16,1,2,15])).then(e=>({default:e.ThemeSettingsPanel}))),ku=c.lazy(async()=>nt(()=>import("./NotificationSettingsPanel-CAR-3hg5.js"),__vite__mapDeps([17,1,2])).then(e=>({default:e.NotificationSettingsPanel}))),Qi=()=>nt(()=>import("./DiffDrawer-BWx4QFFg.js"),__vite__mapDeps([10,1,2])).then(e=>({default:e.DiffDrawer})),ju=c.lazy(Qi);function Dr({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 Cu({client:e,id:t,activeSession:n,sessions:s,t:i,close:a}){const o=Gi(),l=n?.sessionId,d=n?.cwd,h=n?.runtime.isResponding;c.useEffect(()=>{if(!e||!l)return;const m=window.setTimeout(()=>{document.visibilityState!=="hidden"&&(Qi().catch(()=>{}),bu(e,{sessionId:l,cwd:d}).catch(()=>{}))},350);return()=>window.clearTimeout(m)},[e,l,d,h]);const u=s.find(m=>m.sessionId===t);return!u||!e?null:r.jsx(c.Suspense,{fallback:r.jsx(vu,{t:i,onClose:a}),children:r.jsx(ju,{client:e,sessionId:u.sessionId,cwd:u.cwd,sessionTitle:St(u),t:i,onClose:a,dockLabel:as(i).center,onDock:o?({scope:m,path:g})=>{o.add("diff",St(u),u.cwd,u,m,g),a()}:void 0},u.sessionId)})}const Iu="/web/assets/logo-SQcOtj-8.png";function Nu(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 Eu({activeDaemonId:e,busy:t,fallbackName:n,phase:s,statusText:i,t:a,targets:o,onConnect:l,onRename:d}){const[h,u]=c.useState(!1),[m,g]=c.useState(null),[y,k]=c.useState(""),x=c.useRef(null),b=c.useRef(null),p=ne().isLocalDaemon??(()=>!1),f=Nu(o,e,p),S=o.find(w=>w.daemonId===e)?.label||n||e?.slice(0,10)||"Vibelet Web";c.useEffect(()=>{h||g(null),m&&b.current?.select()},[h,m]),c.useEffect(()=>{if(!h)return;const w=E=>{E.target instanceof Node&&!x.current?.contains(E.target)&&u(!1)},I=E=>{E.key==="Escape"&&u(!1)};return document.addEventListener("pointerdown",w),document.addEventListener("keydown",I),()=>{document.removeEventListener("pointerdown",w),document.removeEventListener("keydown",I)}},[h]);const j=w=>{g(w.daemonId),k(w.label)},C=()=>{!m||!y.trim()||(d(m,y),g(null))};return r.jsxs("div",{className:"device-switcher",ref:x,children:[r.jsxs("button",{"aria-expanded":h,"aria-haspopup":"menu",className:"device-switcher-trigger",onClick:()=>u(w=>!w),title:S,type:"button",children:[r.jsx("strong",{children:S}),r.jsx(Qr,{"aria-hidden":"true"})]}),r.jsxs("span",{className:`brand-connection ${s}`,children:[r.jsx("i",{"aria-hidden":"true"}),s==="connected"?a.connected:i]}),h?r.jsxs("div",{"aria-label":a.savedDevices,className:"device-switcher-menu",role:"menu",children:[f.map(w=>{const I=w.daemonId===e;return r.jsx("div",{className:"device-switcher-row",children:m===w.daemonId?r.jsxs("form",{className:"device-rename-form",onSubmit:E=>{E.preventDefault(),C()},children:[r.jsx("input",{ref:b,"aria-label":a.rename,autoFocus:!0,onChange:E=>k(E.target.value),onKeyDown:E=>{E.key==="Escape"&&(E.stopPropagation(),g(null))},value:y}),r.jsx("button",{"aria-label":a.rename,title:a.rename,disabled:!y.trim(),type:"submit",children:r.jsx($t,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":a.cancel,title:a.cancel,type:"button",onClick:()=>g(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(w),u(!1)},role:"menuitem",type:"button",children:[I?r.jsx($t,{"aria-hidden":"true"}):r.jsx(ri,{"aria-hidden":"true"}),r.jsxs("span",{children:[r.jsx("strong",{children:w.label}),r.jsx("small",{children:p(w.daemonId)?`${a.currentDevice}${I?` · ${a.active}`:""}`:I?a.active:w.displayName||w.daemonId})]})]}),r.jsx("button",{"aria-label":`${a.rename} ${w.label}`,title:`${a.rename} ${w.label}`,className:"device-rename-button",onClick:()=>j(w),type:"button",children:r.jsx(Co,{"aria-hidden":"true"})})]})},w.daemonId)}),o.length===0?r.jsx("p",{className:"empty-copy",children:a.noSavedDevices}):null]}):null]})}function Zi({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 Ru({folder:e,initialValue:t,t:n,onClose:s,onSave:i}){const[a,o]=c.useState(t),l=c.useRef(null),d=Mn(s,l),h=u=>{u.preventDefault(),i(a)};return Et.createPortal(r.jsxs("div",{"aria-labelledby":"folder-tag-dialog-title","aria-modal":"true",className:"folder-tag-dialog-layer",ref:d,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(ci,{})}),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:u=>o(u.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 Tu({search:e,busy:t,connected:n,filtersOpen:s,filtersActive:i,t:a,onSearchChange:o,onSearchCommit:l,onToggleFilters:d,onCreate:h}){const[u,m]=c.useState(!!e),g=c.useRef(null);return c.useEffect(()=>{const y=()=>{m(!0),requestAnimationFrame(()=>g.current?.focus())};return window.addEventListener("vibelet.session-search",y),()=>window.removeEventListener("vibelet.session-search",y)},[]),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":u,className:"rail-create-button",title:Dn(a.searchSessions,"searchSessions"),type:"button",onClick:()=>{m(!0),requestAnimationFrame(()=>g.current?.focus())},children:r.jsx(jn,{"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(Pn,{"aria-hidden":"true"})}),r.jsx("button",{"aria-expanded":s,"aria-label":a.sessionFilters,className:`filter-toggle ${s||i?"selected":""}`,onClick:d,title:a.sessionFilters,type:"button",children:r.jsx(no,{"aria-hidden":"true"})})]})]}),(u||e)&&r.jsxs("div",{className:"search-box",children:[r.jsx(jn,{"aria-hidden":"true"}),r.jsx("input",{ref:g,"aria-label":a.searchSessions,value:e,onBlur:l,onChange:y=>o(y.target.value),placeholder:a.searchSessions,onKeyDown:y=>{y.key==="Enter"&&l(),y.key==="Escape"&&(o(""),l(),m(!1))}}),r.jsx("button",{className:"filter-toggle","aria-label":a.cancel,type:"button",onClick:()=>{o(""),m(!1),g.current?.blur()},children:r.jsx(_e,{"aria-hidden":"true"})})]})]})}function Au({menu:e,pending:t,t:n,onOpen:s,onDetails:i,onCopyResumeCommand:a,onResumeInTerminal:o,terminalBusy:l,onTogglePinned:d,onToggleArchived:h,onDelete:u}){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(Gr,{"aria-hidden":"true"}),n.open]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:i,children:[r.jsx(ei,{"aria-hidden":"true"}),n.details]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:a,children:[r.jsx(hn,{"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(Bs,{"aria-hidden":"true"}),n.resumeInTerminal]}),r.jsx("span",{className:"context-menu-separator"}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:d,children:[r.jsx(ts,{"aria-hidden":"true"}),e.session.pinned?n.unpin:n.pin]}),r.jsxs("button",{type:"button",role:"menuitem",disabled:t,onClick:h,children:[r.jsx(qs,{"aria-hidden":"true"}),e.session.archived?n.unarchive:n.archive]}),r.jsxs("button",{className:"danger",type:"button",role:"menuitem",onClick:u,children:[r.jsx(li,{"aria-hidden":"true"}),n.delete]})]})}function _r({session:e,active:t,responding:n,tagLabels:s,showFolder:i=!0,t:a,onSelect:o,onContextMenu:l}){const d=St(e),h=ss(e.lastActivityAt,Date.now(),a),u=e.cwd?.split(/[\\/]/).filter(Boolean).at(-1)||e.cwd||".",m=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),g=!!(e.branch||e.pullRequest);return r.jsxs("div",{className:"session-item","data-statuses":+!!e.pinned+ +!!e.archived,children:[r.jsxs("button",{className:`session-row ${t?"active":""} ${e.archived?"archived":""} ${n?"responding":""}`,"data-session-id":e.sessionId,"aria-current":t?"true":void 0,onContextMenu:l,onClick:o,title:d,type:"button",children:[r.jsxs("span",{className:"session-row-head",children:[r.jsx("strong",{children:d}),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:h,children:h})]}),n?r.jsx("span",{className:"session-running-indicator",role:"img","aria-label":a.agentResponding,title:a.agentResponding}):r.jsx("span",{className:"session-running-placeholder","aria-hidden":"true"})]}),s?.length?r.jsx("span",{className:"directory-tag-row",title:a.directoryTags,children:s.map(y=>r.jsx("em",{children:y},y))}):null,r.jsxs("span",{className:"session-row-footer","data-has-git":g||void 0,children:[!g&&i?r.jsx("span",{className:"session-row-folder",title:e.cwd,children:u}):null,e.pinned?r.jsx("span",{children:a.pinned}):null,e.archived?r.jsx("span",{children:a.archived}):null]})]}),g&&r.jsxs("div",{className:"session-git-links",children:[i&&r.jsx("span",{className:"session-git-folder",title:e.cwd,children:u}),e.branch&&(m?r.jsx("a",{className:"session-branch-link",href:m,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]})]})]})}function Mu({activeSessionId:e,busy:t,collapsedFolders:n,folderCounts:s,getFolderTags:i,groupFolders:a,groupedSessions:o,phase:l,respondingSessionIds:d,t:h,visibleSessions:u,onEditFolderTags:m,onOpenCreateMenu:g,onOpenSessionMenu:y,onSelectSession:k,onToggleFolder:x}){const b=c.useId();return a?r.jsxs(r.Fragment,{children:[o.map(p=>{const f=!!n[p.folder],v=`${b}-${encodeURIComponent(p.folder)}`,S=p.kind==="folder"?s[p.folder]??p.sessions.length:p.sessions.length,j=p.kind==="attention"?h.needsAttentionSessionsGroup:p.kind==="running"?h.runningSessionsGroup:p.kind==="pinned"?h.pinnedSessionsGroup:p.folder;return r.jsxs("div",{className:`folder-group ${p.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":!f,"aria-controls":v,title:j,onClick:()=>x(p.folder),type:"button",children:[r.jsx(Zr,{className:"folder-disclosure","aria-hidden":"true"}),p.kind==="attention"?r.jsx(ei,{"aria-hidden":"true"}):p.kind==="running"?r.jsx(ba,{"aria-hidden":"true"}):p.kind==="pinned"?r.jsx(ts,{"aria-hidden":"true"}):f?r.jsx(eo,{"aria-hidden":"true"}):r.jsx(Un,{"aria-hidden":"true"}),r.jsx("span",{children:p.kind==="folder"?p.folder.split(/[\\/]/).filter(Boolean).at(-1)||p.folder:j})]}),p.kind==="folder"?r.jsxs(r.Fragment,{children:[r.jsx("button",{"aria-label":i(p.folder).length?h.editDirectoryTags:h.addDirectoryTags,className:"mini-button folder-hover-action",onClick:()=>m(p.folder),title:i(p.folder).length?h.editDirectoryTags:h.addDirectoryTags,type:"button",children:r.jsx(ci,{"aria-hidden":"true"})}),r.jsx("button",{"aria-label":h.newSession,className:"mini-button folder-hover-action",disabled:t||l!=="connected",onClick:C=>g(C,p.folder),title:h.newSession,type:"button",children:r.jsx(Pn,{"aria-hidden":"true"})})]}):null,r.jsx("small",{className:"folder-session-count",title:`${S} ${h.sessions}`,children:S})]}),p.kind==="folder"&&i(p.folder).length?r.jsx("div",{className:"folder-tag-row",children:i(p.folder).map(C=>r.jsx("span",{children:C},C))}):null]}),r.jsx("div",{className:"folder-session-list",id:v,hidden:f,children:f?null:p.sessions.map(C=>r.jsx(_r,{active:C.sessionId===e,responding:d.has(C.sessionId),session:C,showFolder:p.kind!=="folder",tagLabels:i(C.cwd),t:h,onContextMenu:w=>y(w,C),onSelect:()=>k(C.sessionId)},C.sessionId))})]},p.folder)}),u.length===0?r.jsx("p",{className:"empty-copy",children:h.noSessionsMatch}):null]}):r.jsxs(r.Fragment,{children:[u.map(p=>r.jsx(_r,{active:p.sessionId===e,responding:d.has(p.sessionId),session:p,tagLabels:i(p.cwd),t:h,onContextMenu:f=>y(f,p),onSelect:()=>k(p.sessionId)},p.sessionId)),u.length===0?r.jsx("p",{className:"empty-copy",children:h.noSessionsMatch}):null]})}function Pu({agentFilter:e,t,onAgentFilterChange:n}){return r.jsx(Zi,{label:t.agentFilterLabel,value:e,options:[{value:"all",label:t.agentFilterAll},{value:"claude",label:t.agentFilterClaude},{value:"codex",label:t.agentFilterCodex}],onChange:n})}function Du({groupFolders:e,hideArchived:t,separatePinnedGroup:n,showNeedsAttentionGroup:s,showRunningGroup:i,t:a,onToggleGroupFolders:o,onToggleHideArchived:l,onToggleNeedsAttentionGroup:d,onToggleRunningGroup:h,onToggleSeparatePinnedGroup:u}){const m=[[a.showNeedsAttentionGroup,s,d],[a.showRunningGroup,i,h],[a.separatePinnedGroup,n,u]];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(([g,y,k])=>r.jsxs("button",{"aria-pressed":e&&y,className:"filter-menu-row nested-filter-option",disabled:!e,onClick:k,type:"button",children:[r.jsx("span",{children:g}),r.jsx($t,{className:"filter-menu-check","aria-hidden":"true","data-checked":e&&y})]},g)),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 _u(e,t){const n=c.useRef(null),s=c.useRef(null),i=c.useRef(t),[a,o]=c.useState(null),l=!!(e?.lastActivityAt&&e.sessionId),d=l?`${e?.lastActivityAt}:${e?.sessionId}`:null;return c.useEffect(()=>{i.current=t},[t]),c.useEffect(()=>{const h=n.current;if(!h||!e||!d){s.current=null,o(null);return}const u=h.closest(".session-list");if(!(u instanceof HTMLElement))return;let m=!0,g;o(null);const y=new IntersectionObserver(k=>{!k.some(x=>x.isIntersecting)||s.current===d||(s.current=d,o(d),i.current(e).catch(()=>{m&&(g=window.setTimeout(()=>{m&&(s.current=null,y.unobserve(h),y.observe(h))},1500))}).finally(()=>{m&&o(x=>x===d?null:x)}))},{root:u,rootMargin:"0px 0px 240px 0px",threshold:.01});return y.observe(h),()=>{m=!1,g!==void 0&&window.clearTimeout(g),y.disconnect()}},[d,e]),{canLoadMore:l,loading:a===d,sentinelRef:n}}function Lu(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Fu({activeSessionId:e,busy:t,collapsedFolders:n,currentCwd:s,activeDaemonId:i,displayName:a,savedTargets:o,directoryTags:l,folderCounts:d,groupFolders:h,groupedSessions:u,hideArchived:m,separatePinnedGroup:g,showNeedsAttentionGroup:y,showRunningGroup:k,inventoryVersion:x,nextCursor:b,phase:p,pendingSessionIds:f,respondingSessionIds:v,search:S,sessionAgentFilter:j,sessionsCount:C,sinceFilter:w,statusText:I,t:E,visibleSessions:L,onLoadMore:Y,onCopyResumeCommand:B,onResumeInTerminal:T,onConnectTarget:X,onRequestNewSession:H,onDeleteSession:se,onEditFolderTags:Se,onOpenSessionDetails:ve,onResetFilters:xe,onRenameTarget:A,onSearchChange:M,onSearchCommit:W,onSelectSession:z,onToggleSessionArchived:K,onToggleSessionPinned:J,onSessionAgentFilterChange:Q,onSinceFilterChange:oe,onToggleFolder:$,onToggleGroupFolders:V,onToggleHideArchived:ee,onToggleNeedsAttentionGroup:Ge,onToggleRunningGroup:we,onToggleSeparatePinnedGroup:Be}){const[ae,ke]=c.useState(!1),[le,je]=c.useState(null);c.useEffect(()=>{if(!le)return;const U=window.setTimeout(()=>je(null),2400);return()=>window.clearTimeout(U)},[le]);const[de,ue]=c.useState(null),[ce,me]=c.useState(null),Me=c.useRef(null),He=j!=="all"||w!=="30d"||!h||h&&(y||k||g)||m,Ke=_u(b,Y),Ze=ce?!!f?.has(ce.session.sessionId):!1,$e=U=>l[Lu(U)??"/"]??[],Ce=p==="connected"?`${L.length}/${C} sessions · v${x??"-"}`:E.sameOriginAccess,Je=`${I} · ${Ce}`;c.useEffect(()=>{if(!ae&&!ce)return;const U=pe=>{const N=pe.target;N instanceof Node&&Me.current?.contains(N)||(ke(!1),me(null))},G=pe=>{pe.key==="Escape"&&(ke(!1),me(null))};return document.addEventListener("pointerdown",U),document.addEventListener("keydown",G),()=>{document.removeEventListener("pointerdown",U),document.removeEventListener("keydown",G)}},[ce,ae]);const Pe=(U,G)=>{me(null),ke(!1),H(G)},Ve=(U,G)=>{U.preventDefault(),me({session:G,x:Math.min(U.clientX,window.innerWidth-224-10),y:Math.min(U.clientY,window.innerHeight-306-10)})},Ee=()=>me(null),fe=U=>{ke(!1),me(null),ue({folder:U,value:$e(U).join(", ")})},Z=U=>{de&&(Se(de.folder,U),ue(null))},he=U=>{if(!ce)return;const{session:G}=ce;Ee(),U(G)};return r.jsxs("aside",{className:"session-rail","aria-label":E.sessions,children:[r.jsxs("div",{className:"brand-block",title:Je,children:[r.jsx("div",{className:"brand-mark","aria-hidden":"true",children:r.jsx("img",{alt:"",className:"brand-logo",height:"40",src:Iu,width:"40"})}),r.jsx(Eu,{activeDaemonId:i,busy:t,fallbackName:a,phase:p,statusText:I,t:E,targets:o,onConnect:X,onRename:A})]}),r.jsxs("div",{className:"search-filter-wrap",ref:Me,children:[r.jsx(Tu,{search:S,busy:t,connected:p==="connected",filtersOpen:ae,filtersActive:He,t:E,onSearchChange:M,onSearchCommit:W,onToggleFilters:()=>ke(U=>!U),onCreate:Pe}),ae?r.jsxs("div",{className:"filter-popover",role:"dialog","aria-label":E.sessionFilters,children:[r.jsx(Pu,{agentFilter:j,t:E,onAgentFilterChange:Q}),r.jsx(Zi,{label:E.searchTimeRangeLabel,value:w,options:[{value:"all",label:E.searchTimeRangeAllTime},{value:"7d",label:E.searchTimeRangeLast7Days},{value:"30d",label:E.searchTimeRangeLast30Days},{value:"90d",label:E.searchTimeRangeLast90Days}],onChange:oe}),r.jsx(Du,{groupFolders:h,hideArchived:m,separatePinnedGroup:g,showNeedsAttentionGroup:y,showRunningGroup:k,t:E,onToggleGroupFolders:V,onToggleHideArchived:ee,onToggleNeedsAttentionGroup:Ge,onToggleRunningGroup:we,onToggleSeparatePinnedGroup:Be}),He?r.jsx("button",{className:"filter-reset-button",onClick:xe,type:"button",children:E.resetFilters}):null]}):null]}),r.jsxs("div",{className:"session-list",children:[r.jsx(Mu,{activeSessionId:e,busy:t,collapsedFolders:n,folderCounts:d,getFolderTags:$e,groupFolders:h,groupedSessions:u,phase:p,respondingSessionIds:v,t:E,visibleSessions:L,onEditFolderTags:fe,onOpenCreateMenu:Pe,onOpenSessionMenu:Ve,onSelectSession:z,onToggleFolder:$}),Ke.canLoadMore?r.jsx("div",{"aria-live":"polite",className:`session-load-sentinel ${Ke.loading?"loading":""}`,ref:Ke.sentinelRef,role:"status",children:Ke.loading?r.jsxs(r.Fragment,{children:[r.jsx(es,{className:"spin","aria-hidden":"true"}),r.jsx("span",{children:E.loadingMore})]}):null}):null]}),de?r.jsx(Ru,{folder:de.folder,initialValue:de.value,t:E,onClose:()=>ue(null),onSave:Z}):null,ce?r.jsx(Au,{menu:ce,pending:Ze,t:E,onOpen:()=>he(U=>z(U.sessionId)),onDetails:()=>he(ve),onCopyResumeCommand:()=>he(U=>{Promise.resolve(B(U)).then(()=>je({message:E.commandCopied,tone:"success"})).catch(()=>je({message:E.copyResumeFailed,tone:"error"}))}),onResumeInTerminal:T&&i&&ne().resumeInTerminal&&ne().isLocalDaemon?.(i)?()=>he(T):void 0,terminalBusy:v.has(ce.session.sessionId),onTogglePinned:()=>he(J),onToggleArchived:()=>he(K),onDelete:()=>he(se)}):null,r.jsx(Zs,{feedback:le})]})}function $u({collapsed:e,children:t,onExpand:n,onResize:s,t:i}){const a=ne().toolbarTarget?.("left"),o=r.jsx("button",{"aria-label":e?i.expandSessionSidebar:i.collapseSessionSidebar,className:"sidebar-titlebar-toggle",onClick:n,title:Dn(e?i.expandSessionSidebar:i.collapseSessionSidebar,"leftSidebar"),type:"button",children:r.jsx(xo,{"aria-hidden":"true"})});return r.jsxs(r.Fragment,{children:[a?Et.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 or={version:"",latestVersion:"",loading:!1,error:null};function Lr(e){const t=e.match(/^\d+/);return t?Number(t[0]):0}function Ou(e,t){const n=e.split(/[+-]/,1)[0].split(".").map(Lr),s=t.split(/[+-]/,1)[0].split(".").map(Lr),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 Ji(e,t){return Ou(e,t)<0}function Wu(e){const t=e.toLowerCase();if(t.includes("alpha"))return"alpha";if(t.includes("beta"))return"beta";if(e.trim())return"latest"}function qu(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 zu(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 Bu({busy:e,connected:t,dismissed:n,feedback:s,synced:i,t:a,onPull:o,onPushMerge:l,onPushReplace:d,onSkip:h}){const u=!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:u,onClick:l,type:"button",children:[r.jsx(ao,{"aria-hidden":"true"}),e==="pushMerge"?a.archiveSyncSyncing:a.archiveSyncPushMerge]}),r.jsxs("button",{className:"icon-text-button",disabled:u,onClick:o,type:"button",children:[r.jsx(Yn,{"aria-hidden":"true"}),e==="pull"?a.archiveSyncSyncing:a.archiveSyncPull]}),r.jsxs("button",{className:"icon-text-button",disabled:u,onClick:d,type:"button",children:[r.jsx(Vo,{"aria-hidden":"true"}),e==="pushReplace"?a.archiveSyncSyncing:a.archiveSyncPushReplace]}),r.jsxs("button",{className:"icon-text-button",disabled:u,onClick:h,type:"button",children:[r.jsx(xa,{"aria-hidden":"true"}),a.archiveSyncSkip]})]}),s?r.jsx("p",{className:`empty-copy ${s.tone==="error"?"error-copy":"success-copy"}`,children:s.message}):null]})}function Hu({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(po,{"aria-hidden":"true"}),n.forget]})})]})}function Ku({connected:e,metadata:t,showUpdate:n,updateBusy:s,restartBusy:i,t:a,updateStatus:o,onUpdate:l,onRestart:d}){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(Yn,{"aria-hidden":"true"}),s?a.updating:a.update]}):null,r.jsxs("button",{className:"danger-button",disabled:!e||i,onClick:d,type:"button",children:[r.jsx(kn,{"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 Uu({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?ss(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(ri,{"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(li,{"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(()=>ne().settingsTarget?.()??null);c.useEffect(()=>{const l=()=>s(ne().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(Hu,{pairing:i.pairing,phase:i.phase,t:i.t,onForgetPairing:i.clearPairing}),r.jsx(Uu,{activeDaemonId:i.pairing?.daemonId,busy:i.busy,t:i.t,targets:i.savedTargets,onConnect:i.connectSavedTarget,onForget:i.forgetSavedTarget}),r.jsx(Bu,{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(Ku,{connected:i.phase==="connected",metadata:i.daemonMetadata,restartBusy:i.admin.loading&&i.admin.action==="restart",showUpdate:!!(i.daemonMetadata.version&&i.daemonMetadata.latestVersion&&Ji(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?Et.createPortal(o,n):null:o}function Gu(){const e=ne().polishSettings,t=qe(ze().language)!=="en",[n,s]=c.useState(),[i,a]=c.useState({...fs}),[o,l]=c.useState(""),[d,h]=c.useState(!1),[u,m]=c.useState(""),[g,y]=c.useState(!1);if(c.useEffect(()=>{let x=!0;return e?.status().then(b=>{x&&(s(b),a(b.settings))}).catch(()=>{x&&(y(!0),m(t?"无法读取润色设置。":"Could not load polishing settings."))}),()=>{x=!1}},[e]),!e)return null;const k=async x=>{h(!0),m(""),y(!1);try{const b=await e.save(i,x);s(b),a(b.settings),l(""),m(t?"已保存":"Saved"),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch{y(!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||d,onChange:async x=>{const b={...i,enabled:x.target.checked};a(b),h(!0),m(""),y(!1);try{const p=await e.save({...n.settings,enabled:b.enabled});s(p),a(b),window.dispatchEvent(new Event("vibelet.speech.changed"))}catch{a(i),y(!0),m(t?"无法保存开关设置":"Could not save setting")}finally{h(!1)}}}),t?"启用语音润色":"Enable voice polishing"]}),i.enabled&&r.jsxs("fieldset",{disabled:!n||d,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:x=>a({...i,baseUrl:x.target.value}),autoComplete:"off"})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"模型":"Model"}),r.jsx("input",{value:i.model,onChange:x=>a({...i,model:x.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:x=>l(x.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:x=>a({...i,promptZh:x.target.value})})]}),r.jsxs("label",{className:"field",children:[r.jsx("span",{children:t?"英文提示词":"English prompt"}),r.jsx("textarea",{rows:5,value:i.promptEn,onChange:x=>a({...i,promptEn:x.target.value})})]}),r.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>a({...i,promptZh:fs.promptZh,promptEn:fs.promptEn}),children:t?"恢复默认提示词":"Reset prompts"})]}),r.jsxs("div",{className:"attention-actions",children:[r.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{k(o.trim()||void 0)},children:t?"保存润色设置":"Save polishing settings"}),n?.configured&&r.jsx("button",{type:"button",className:"icon-text-button",onClick:()=>{k("")},children:t?"移除润色密钥":"Remove polishing key"})]})]}),u&&r.jsx("p",{role:g?"alert":"status",className:g?"error-copy":"empty-copy",children:u})]})}const Vu={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 Qu(){const e=ne().speechSettings,t=Vu[qe(ze().language)],[n,s]=c.useState(),[i,a]=c.useState(""),[o,l]=c.useState(!1),[d,h]=c.useState(""),[u,m]=c.useState(Fe().getItem("vibelet.web.voice.enabled")==="true"),g=!!(globalThis.isSecureContext&&typeof globalThis.navigator?.mediaDevices?.getUserMedia=="function"&&globalThis.MediaRecorder?.isTypeSupported("audio/webm"));c.useEffect(()=>{let p=!0;return e?.status().then(f=>{p&&s(f)}).catch(()=>{p&&h("Unable to load speech settings.")}),()=>{p=!1}},[e]);const y=p=>{m(p),Fe().setItem("vibelet.web.voice.enabled",String(p)),window.dispatchEvent(new Event("vibelet.speech.changed"))},k=async p=>{if(!(!e||o)){l(!0),h("");try{s(await e.saveKey(p)),a(""),p||y(!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 x=n?.engine==="volcengine",b=[...n?.systemAvailable?[{value:"system",label:"macOS · Apple"}]:[],{value:"deepgram",label:"Deepgram · Nova-3"},{value:"volcengine",label:qe(ze().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":u,className:"settings-switch",checked:u,disabled:!g,onChange:p=>y(p.target.checked)}),t.enabled]}),u&&r.jsxs(r.Fragment,{children:[e.setEngine&&r.jsxs("div",{className:"field speech-engine-field",children:[r.jsx("span",{children:qe(ze().language)==="en"?"Recognition engine":"识别引擎"}),r.jsx(xn,{icon:ni,menuLabel:"Speech engine",label:b.find(p=>p.value===n?.engine)?.label??"Deepgram · Nova-3",options:b,value:n?.engine??"deepgram",disabled:o,onSelect:async p=>{l(!0),h(""),a("");try{s(await e.setEngine(p)),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"?qe(ze().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。文字只填入草稿,不会自动发送。":x?qe(ze().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:x?"火山引擎 API Key":"Deepgram API Key"}),r.jsx("input",{type:"password",autoComplete:"off",value:i,onChange:p=>a(p.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:()=>{k(i)},children:t.save}),n?.configured&&r.jsx("button",{type:"button",className:"icon-text-button",disabled:o,onClick:()=>{k("")},children:t.remove})]})]})]}),!g&&r.jsx("p",{className:"empty-copy",children:t.unsupported}),d&&r.jsx("p",{role:"alert",className:"error-copy",children:d})]}),u&&r.jsx(Gu,{})]})}function Zu({value:e,t,showSession:n=!0,onChange:s}){const i=[...n?[{tab:"session",label:t.session,Icon:ai}]:[],{tab:"files",label:t.files,Icon:Un},{tab:"terminal",label:t.terminal,Icon:ns},{tab:"browser",label:t.browser,Icon:Xr}];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 Ju({chinese:e}){const[t,n]=c.useState(Gn),[s,i]=c.useState(null),[a,o]=c.useState(""),l=d=>{nc(d),n(d),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."}),nn.map(d=>r.jsxs("div",{className:"workspace-shortcut-row",children:[r.jsx("span",{children:e?d.zh:d.en}),r.jsx("button",{type:"button","data-shortcut-recording":s===d.id?"true":void 0,"aria-label":`${e?"设置快捷键:":"Set shortcut: "}${e?d.zh:d.en}`,onClick:()=>{i(d.id),o("")},onBlur:()=>i(null),onKeyDown:h=>{if(s!==d.id)return;if(h.preventDefault(),h.stopPropagation(),h.key==="Escape"){i(null),o("");return}if(h.key==="Backspace"||h.key==="Delete"){l({...t,[d.id]:""}),i(null);return}const u=ui(h.nativeEvent);if(!u)return;const m=tc(d.id,u,t);if(m){const g=nn.find(y=>y.id===m);o(m==="reserved"?e?"此组合键用于系统菜单或编辑操作,请换一个组合。":"Reserved for a system menu or editing action. Choose another combination.":`${e?"已用于:":"Already assigned to: "}${e?g?.zh:g?.en}`);return}l({...t,[d.id]:u}),i(null)},children:s===d.id?e?"按下快捷键…":"Press shortcut…":hi(Hs(d.id,t))||(e?"未设置":"Not set")})]},d.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 Yu({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)}},[]),Et.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(d=>d.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(mi,{}),e,r.jsx(Ju,{chinese:t.browser!=="Browser"})]})]}),document.body)}function Xu({children:e,collapsed:t,t:n,value:s,showSession:i,onChange:a,onResize:o}){const l=ir("right",u=>{(u==="terminal"||u==="browser")&&a(u)}),d=ne().toolbarTarget?.("controls"),h=r.jsx(Zu,{value:s,t:n,showSession:i,onChange:a});return s==="admin"&&ne().kind==="browser"?r.jsx(Yu,{t:n,onClose:()=>a("files"),children:e}):r.jsxs(r.Fragment,{children:[d&&!t?Et.createPortal(h,d):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:[!d&&r.jsx("div",{className:"control-pane-toolbar",children:h}),e]})})]})}function Mf(e){return/\.(md|mdx|markdown|mdown)$/i.test(e)}function Jn(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 eh(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 th({file:e}){const[t,n]=c.useState(!1),s=Mn(()=>n(!1),void 0,t),i=In(),a=qe(ze().language),o=a==="en"?"Close":a==="zh-TW"?"關閉":"关闭",l=ne().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(Yr,{"aria-hidden":"true"}),i.pdfPreview]}),t&&Et.createPortal(r.jsx("div",{className:"remote-document-layer",onPointerDown:d=>{d.target===d.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 Yi({file:e}){const[t,n]=c.useState(!1),s=In(),i=Jn(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:ne().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:eh(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(th,{file:e}):r.jsx("p",{className:"empty-copy",children:s.mediaError}):null}const nh=c.lazy(()=>nt(()=>import("./file-editor-FileCodeEditor-DnxVv451.js").then(e=>e.Q),__vite__mapDeps([18,1,2,19])).then(e=>({default:e.FileCodeEditor})));function sh({file:e,onOpenRemoteFile:t,onTextChange:n}){const[s,i]=c.useState("preview"),a=Jn(e.path,e.contentType,!0)==="html",o=qe(ze().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(Yi,{file:e}):r.jsx(c.Suspense,{fallback:r.jsx("pre",{className:"remote-editor",children:e.text}),children:r.jsx(nh,{path:e.path,cwd:e.cwd,text:e.text,onChange:n,onOpenFile:t})})]})}const Ls="vibelet:file-operation-before",Fs="vibelet:file-operation-done";function ln(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 vs(e,t,n){const s=ln(e,n),i=ln(t,n);return s===i||s.startsWith(`${i}/`)}async function Pf(e,t){const n=new CustomEvent(Ls,{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 sr()?.daemonId===t.daemonId&&window.dispatchEvent(new CustomEvent(Fs,{detail:{...a,daemonId:t.daemonId,cwd:e.sourceCwd??e.cwd,source:e.path}})),a}function rh(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(d=>d.dirty&&vs(d.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,d=m=>{if(!vs(m.path,l,a.cwd))return m;if(a.action==="delete")return null;const g=`${a.target}${ln(m.path,a.cwd).slice(ln(l,a.cwd).length)}`;return{...m,path:g}};o.setFiles(m=>Object.fromEntries(Object.values(m).flatMap(g=>{const y=d(g);return y?[[y.path,y]]:[]}))),o.active&&o.files[o.active]&&o.setActive(d(o.files[o.active])?.path??null),o.setRemoteFile(m=>m&&d(m));const h=new URL(window.location.href),u=h.searchParams.get("file");u&&vs(u,l,a.cwd)&&(a.action==="delete"?h.searchParams.delete("file"):h.searchParams.set("file",`${a.target}${ln(u,a.cwd).slice(ln(l,a.cwd).length)}`),window.history.replaceState(null,"",h.href))};return window.addEventListener(Ls,n),window.addEventListener(Fs,s),()=>{window.removeEventListener(Ls,n),window.removeEventListener(Fs,s)}},[])}function ih({workspace:e,children:t}){const n=rn(),s=ir("center"),[i,a]=c.useState({}),[o,l]=c.useState(null),[d,h]=c.useState(null),u=c.useRef({files:i,remoteFile:e.remoteFile,daemonId:e.pairing?.daemonId});u.current={files:i,remoteFile:e.remoteFile,daemonId:e.pairing?.daemonId};const m=c.useRef(null),g=c.useRef(e.activeSessionId),y=qe(ze().language)!=="en";c.useEffect(()=>{a({}),l(null),m.current=null},[e.pairing?.daemonId]),c.useEffect(()=>{if(!e.remoteFile){m.current=null;return}const S=e.remoteFile;a(j=>({...j,[S.path]:S})),m.current!==S.path&&(l(S.path),n.setCenter(null)),m.current=S.path},[e.remoteFile]),c.useEffect(()=>{const S=g.current;g.current=e.activeSessionId,!(!S||S===e.activeSessionId)&&(l(null),m.current=null)},[e.activeSessionId]);const k=S=>{n.setCenter(null),e.setRemoteFile(i[S]),l(S)},x=async S=>{const j=i[S],C=e.pairing?.daemonId;if(!j)return;const w=dn();j.dirty&&!await ks({title:w.discard,message:S,confirmLabel:w.discardAction,danger:!0})||u.current.daemonId!==C||u.current.files[S]?.text!==j.text||(a(I=>{const E={...I};return delete E[S],E}),S===o&&(l(null),m.current=null,e.setRemoteFile(null)))};rh({daemonId:e.pairing?.daemonId,files:i,active:o,remoteFile:e.remoteFile,setFiles:a,setActive:l,setRemoteFile:e.setRemoteFile}),c.useEffect(()=>{const S=j=>{const C=j.detail;if(C==="closeTab"){n.center?n.close(n.center):o&&x(o);return}const w=[null,...Object.keys(i),...n.items.filter(L=>L.location==="center").map(L=>L.id)],I=w.indexOf(n.center||o),E=w[(Math.max(I,0)+(C==="nextTab"?1:w.length-1))%w.length];E?i[E]?k(E):n.setCenter(E):(l(null),n.setCenter(null))};return window.addEventListener(Cs,S),()=>window.removeEventListener(Cs,S)},[i,o,n]);const b=o?i[o]:null,p=async()=>{const S=e.remoteFile;!S||!await ks({message:e.t.confirmOverwrite(Bt(S.path)),danger:!0})||u.current.remoteFile===S&&await e.saveRemoteFile({force:!0})},f=ne().toolbarTarget?.("conversation"),v=b&&!n.center&&r.jsxs("header",{className:"document-file-header",role:"toolbar","aria-label":y?"文件操作":"File actions",children:[r.jsx("button",{type:"button",title:e.t.download,"aria-label":e.t.download,onClick:()=>{e.downloadRemoteFile()},children:r.jsx(Yn,{})}),r.jsx("button",{type:"button",title:e.t.copyPath,"aria-label":e.t.copyPath,onClick:()=>{navigator.clipboard.writeText(b.path)},children:r.jsx(hn,{})}),b.kind==="text"&&r.jsx("button",{type:"button",title:e.t.saveFile,"aria-label":e.t.saveFile,disabled:!b.dirty||e.busy,onClick:()=>{e.saveRemoteFile()},children:r.jsx(Mo,{})})]});return r.jsx(Ii.Provider,{value:d,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(S=>S.location==="center"))&&r.jsxs("div",{className:"document-tabs",children:[r.jsxs("div",{className:"document-tab-items",role:"tablist","aria-label":y?"工作区标签页":"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(S=>r.jsxs("div",{className:"document-tab","data-active":!n.center&&o===S.path,children:[r.jsxs("button",{type:"button",role:"tab","aria-selected":!n.center&&o===S.path,title:S.path,onClick:()=>k(S.path),children:[r.jsx(Yr,{}),r.jsxs("span",{className:"document-tab-label",children:[Bt(S.path),S.dirty?" ·":""]})]}),r.jsx("button",{type:"button",className:"document-tab-close",title:e.t.close,"aria-label":`${e.t.close} ${Bt(S.path)}`,onClick:()=>x(S.path),children:r.jsx(_e,{})})]},S.path)),r.jsx(_s,{location:"center",t:e.t})]}),v]}),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(Zn,{location:"center"})}),b&&!n.center&&r.jsxs("section",{className:"document-file",role:"tabpanel","aria-label":Bt(b.path),children:[b.kind==="text"?r.jsx(sh,{file:b,onOpenRemoteFile:(S,j)=>{e.openRemoteFile(S,j,{updateRoute:!0})},onTextChange:S=>e.setRemoteFile(j=>j&&{...j,text:S,dirty:!0})},b.path):r.jsx(Yi,{file:b},b.path),e.remoteFileConflict&&r.jsxs("div",{role:"alert",className:"inline-notice warning",children:[r.jsx("span",{children:e.t.remoteFileConflict(b.path)}),r.jsx("button",{type:"button",onClick:()=>{p()},children:e.t.forceSave})]})]})]})})}function ah(e){const t=rn(),[n,s]=c.useState(Gn),i=c.useRef({workspace:e,dock:t,shortcuts:n});i.current={workspace:e,dock:t,shortcuts:n},c.useEffect(()=>{const a=()=>s(Gn()),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 d=ui(l);if(!d)return;const{workspace:h,dock:u,shortcuts:m}=i.current,g=nn.find(p=>Hs(p.id,m)===d)?.id;if(!g)return;l.preventDefault(),l.stopPropagation();const y=h.controlTab==="terminal"?"terminal":"browser",k=u.items.find(p=>p.id===u.center),x=l.target instanceof Element&&!!l.target.closest('.workspace-control-sidebar-motion, .dock-surface[data-location="right"]'),b=!x&&k?k:u.items.find(p=>p.id===u.right[y]);switch(g){case"leftSidebar":h.setLeftSidebarCollapsed(p=>!p);break;case"rightSidebar":h.setRightSidebarCollapsed(p=>!p);break;case"files":case"terminal":case"browser":h.setControlTabAndOpen(g);break;case"searchSessions":h.setLeftSidebarCollapsed(!1),window.dispatchEvent(new Event("vibelet.session-search"));break;case"newTab":{const p=k?.kind==="terminal"||k?.kind==="browser"?k.kind:y;u.add(p,h.t[p],h.cwd),h.setControlTabAndOpen(p);break}case"moveTab":b&&u.move(b.id,b.location==="center"?"right":"center");break;case"diff":h.activeSession&&h.setDiffSessionId(h.activeSession.sessionId);break;case"closeTab":case"nextTab":case"previousTab":if(x)if(g==="closeTab")b&&u.close(b.id);else{const p=u.items.filter(f=>f.location==="right"&&f.kind===y);p.length&&u.setRight(f=>({...f,[y]:p[(Math.max(0,p.findIndex(v=>v.id===b?.id))+(g==="nextTab"?1:p.length-1))%p.length].id}))}else window.dispatchEvent(new CustomEvent(Cs,{detail:g}));break}};return window.addEventListener(js,a),window.addEventListener("keydown",o),()=>{window.removeEventListener(js,a),window.removeEventListener("keydown",o)}},[])}const Xi="vibelet.web.savedTargets",ea=12;function oh(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function ch(e){if(!oh(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 ta(e){if(!Array.isArray(e))return[];const t=new Set,n=[];for(const s of e){const i=ch(s);if(!(!i||t.has(i.daemonId))&&(t.add(i.daemonId),n.push(i),n.length>=ea))break}return n}function lh(e=Fe()){const t=e.getItem(Xi);if(!t)return[];try{return ta(JSON.parse(t))}catch{return[]}}function na(e,t=Fe()){t.setItem(Xi,JSON.stringify(ta(e)))}function dh(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,ea)}function uh(e,t,n){const s=n.trim();return s?e.map(i=>i.daemonId===t?{...i,label:s}:i):e}function hh(e,t){return e.filter(n=>n.daemonId!==t)}function fh(e){return e.filter(t=>t.archived===!0).map(t=>t.sessionId)}function mh(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 ph(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 gh(e){const t=c.useCallback((f,v)=>{e.updateSessionListPreferences(S=>({...S,archiveSyncedDaemonIds:v==="synced"?{...S.archiveSyncedDaemonIds,[f]:!0}:S.archiveSyncedDaemonIds,archiveSyncCardDismissedDaemonIds:{...S.archiveSyncCardDismissedDaemonIds,[f]:!0}}))},[e]),n=c.useCallback((f,v)=>{const S=f==="pull"?e.t.archiveSyncSuccessPull:f==="pushMerge"?e.t.archiveSyncSuccessMerge:e.t.archiveSyncSuccessPush;if(e.setArchiveSyncStatus(mh(v,S,{timeout:e.t.archiveSyncFailedTimeout,disconnected:e.t.archiveSyncFailedDisconnected,generic:e.t.archiveSyncFailedGeneric})),!v.ok)return;const j=new Set(v.archivedSessionIds);e.setSessions(C=>C.map(w=>({...w,archived:j.has(w.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 v=await ph(e.clientRef.current,f,fh(e.displaySessions));n(f,v),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 v=e.clientRef.current;if(v?.isConnected&&!(f==="update"&&!await wn(dn().update))&&!(f==="restart"&&!await wn(dn().restart))&&!(e.clientRef.current!==v||!v.isConnected)){e.setAdmin(S=>({...S,loading:!0,action:f,statusText:""})),e.setErrorText(null);try{if(f==="update"){const S=Wu(e.daemonMetadata.version),j=await v.request({action:"daemon.update",id:v.makeId("daemon_update"),...S?{channel:S}:{}});e.setAdmin(C=>({...C,loading:!1,action:null,statusText:j.alreadyRunning?"Connector update already running":"Connector update started"}));return}await v.request({action:"daemon.restart",id:v.makeId("daemon_restart")}),e.setAdmin(S=>({...S,loading:!1,action:null,statusText:"Connector restart requested"})),e.refreshDaemonMetadata()}catch(S){e.setAdmin(j=>({...j,loading:!1,action:null})),e.setErrorText(S instanceof Error?S.message:String(S))}}},[e]),o=c.useCallback(async()=>{if(!e.activeSession)return;const f=Wc(e.activeSession,e.messages);qc(Oc(St(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]),d=c.useCallback(async()=>{const f=e.pairingRef.current;!await wn(dn().forget)||e.pairingRef.current!==f||(e.intentionalDisconnectRef.current=!0,e.connectionAttemptIdRef.current+=1,Oi(),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(or),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]),u=c.useCallback(f=>{e.connectWithPairingRef.current(f,!0)},[e]),m=c.useCallback(f=>e.saveTargets(hh(e.savedTargets,f)),[e]),g=c.useCallback(f=>{e.setActiveSessionId(f.sessionId),e.setRenameTitle(f.customTitle??f.title??""),e.setDetailsOpen(!0)},[e]),y=c.useCallback((f,v)=>{const S=da(v);e.updateSessionListPreferences(j=>({...j,directoryTags:ua(j.directoryTags,f,S)}))},[e]),k=c.useCallback(f=>{e.setControlTab("files"),e.listDirectory(f,{updateRoute:!0})},[e]),x=c.useCallback(async f=>{try{await Ni(bi(f)),e.setStatusText(e.t.commandCopied)}catch{throw e.setErrorText(e.t.copyResumeFailed),new Error(e.t.copyResumeFailed)}},[e]),b=c.useRef(!1),p=c.useCallback(async f=>{if(b.current)return;const v=ne(),S=e.pairingRef.current?.daemonId;if(!(!S||!v.resumeInTerminal||!v.isLocalDaemon?.(S))){b.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 v.resumeInTerminal({...f,daemonId:S,approvalMode:f.approvalMode??f.observedApprovalMode})}catch(j){e.setErrorText(String(j).includes("session_busy")?e.t.resumeTerminalBusy:e.t.resumeTerminalFailed)}finally{b.current=!1}}},[e]);return{runArchiveSync:s,skipArchiveSync:i,runAdminAction:a,exportActiveSession:o,clearPairing:d,setNotificationsEnabled:h,connectSavedTarget:u,forgetSavedTarget:m,openSessionDetails:g,editFolderTags:y,browseFolder:k,copyResumeCommand:x,resumeInTerminal:p}}function $r(e){return`${e}_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`}function yh(e,t=window.location,n=!0){const i=`${t.protocol==="https:"?"wss:":"ws:"}//${t.host}`;return n&&$i(t.hostname)?i:e?.webSocketUrl?e.webSocketUrl:i}class bh{capabilities={};socket=null;pending=new Map;messageListeners=new Set;closeListeners=new Set;async connect(t){this.disconnect();const n=new WebSocket(yh(t));this.socket=n;const s=new Promise((a,o)=>{n.onopen=()=>a(),n.onerror=()=>o(new Error("WebSocket connection failed."))});n.onmessage=a=>this.handleSocketMessage(a.data),n.onclose=()=>{this.socket===n&&(this.socket=null),this.rejectPending(new Error("WebSocket disconnected.")),this.closeListeners.forEach(a=>a())},await s;const i=await this.request({action:"auth.hello",id:$r("auth"),pairToken:t.pairToken,daemonId:t.daemonId,deviceId:t.deviceId,locale:navigator.language});return this.capabilities=i.capabilities??{},i}request(t,n={}){return!this.socket||this.socket.readyState!==WebSocket.OPEN?Promise.reject(new Error("WebSocket is not connected.")):new Promise((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.capabilities={},this.rejectPending(new Error("WebSocket disconnected.")),this.socket?.close(1e3,"client disconnect"),this.socket=null}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}makeId(t){return $r(t)}handleSocketMessage(t){if(typeof t!="string")return;let n;try{n=JSON.parse(t)}catch{return}if(n.type!=="pong"){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 sa="vibelet.web.sessionListCache",ra=120;function vh(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function xh(e){if(!vh(e)||typeof e.daemonId!="string"||!e.daemonId)return null;const t=ki(e.page);return{daemonId:e.daemonId,page:{...t,sessions:t.sessions.slice(0,ra)},cachedAt:typeof e.cachedAt=="string"?e.cachedAt:new Date(0).toISOString()}}function wh(e,t=Fe()){if(!e)return null;try{const n=t.getItem(sa);if(!n)return null;const s=xh(JSON.parse(n));return s?.daemonId===e?s.page:null}catch{return null}}function Sh(e,t,n=Fe(),s=new Date().toISOString()){if(!e)return;const i={daemonId:e,page:{...t,sessions:t.sessions.slice(0,ra)},cachedAt:s};n.setItem(sa,JSON.stringify(i))}function kh(e){return e instanceof Error&&e.message==="auth_failed"}function jh(e,t){return e instanceof En&&e.code==="pair_window_expired"?t.pairingLinkExpired:e instanceof Error?e.message:String(e)}function Ch(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)},Nc))},[]),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 d=new bh,h=l.connectionAttemptIdRef.current+1;l.connectionAttemptIdRef.current=h;const u=l.clientRef.current;l.clientRef.current=d,u?.disconnect();const m=()=>l.connectionAttemptIdRef.current===h&&l.clientRef.current===d;d.onMessage(l.handleServerMessage),d.onClose(()=>{l.clientRef.current===d&&(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 g=a,y;try{y=await d.connect(a)}catch(b){if(!a.webSocketUrl)throw b;g={...a,webSocketUrl:void 0},l.setStatusText(l.t.reconnectingToDaemon),y=await d.connect(g)}if(!m())return;const k={...g,displayName:y.displayName??g.displayName};l.historyCacheDaemonIdRef.current&&l.historyCacheDaemonIdRef.current!==k.daemonId&&(l.historyCacheRef.current={},l.messagesSessionIdRef.current=null,l.lastHistorySessionIdRef.current=null,l.setMessages([])),l.historyCacheDaemonIdRef.current=k.daemonId,l.setPairing(k),l.pairingRef.current=k,Rr(k);const x=wh(k.daemonId);x&&l.setSessionsFromPage(x,!1),l.setSavedTargets(b=>{const p=dh(b,k);return na(p),p}),l.setPhase("connected"),l.setStatusText(l.t.connectedTo(y.displayName??a.displayName??"Vibelet Daemon")),l.refreshDaemonMetadata(k),await l.requestReconnectSnapshot(),await l.fetchAgentResources(l.agent,l.cwd),l.reportLog("web.connected",{reconnecting:o})}catch(g){if(!m())return;kh(g)&&Oi(),l.setPhase("error"),l.setStatusText(l.t.connectionFailed),l.setErrorText(g instanceof Error?g.message:String(g)),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 d=id(),u=sr()??a.rememberedTarget;if(!d&&!u){a.setPhase("missing-pair"),a.setStatusText(a.t.missingPair);return}try{a.setPhase("pairing"),d&&t.current?.pairNonce!==d.pairNonce&&(t.current={pairNonce:d.pairNonce,promise:ud(d,u)});const m=d?await t.current?.promise:u;if(!m||o)return;d&&(Rr(m),t.current=null,ad()),await a.connectWithPairingRef.current(m)}catch(m){if(o)return;d&&(t.current=null),a.setPhase("error"),a.setStatusText(a.t.pairingFailed),a.setErrorText(jh(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])}function Ih(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",d=!o&&i?.supportsQueueSendNow===!0;return{busy:t,canGuide:l,canSendNow:d,onAction:async(u,m)=>{if(!a||!i?.isConnected||s.current||!(m==="guide"?l:d))return;const g=new Set(u.map(b=>b.clientMessageId).filter(Boolean)),y=e.activeQueue.filter(b=>b.clientMessageId&&g.has(b.clientMessageId));if(!y.length)return;s.current=!0,n(!0),e.setErrorText(null);const k=new Set;for(const b of y)e.setCachedMessageDelivery(a,b.clientMessageId,"sending",b);const x=b=>{k.add(b.clientMessageId),e.setCachedMessageDelivery(a,b.clientMessageId,"delivered")};try{if(m==="sendNow")await i.request({action:"session.queue.sendNow",id:i.makeId("queue_now"),sessionId:a,clientMessageIds:y.map(b=>b.clientMessageId)},{timeoutMs:15e3}),y.forEach(x);else for(const b of y)await i.request({action:"session.steer",id:i.makeId("queue_guide"),sessionId:a,clientMessageId:b.clientMessageId,message:b.content,images:b.images},{timeoutMs:15e3}),x(b),e.setPendingQueues(p=>({...p,[a]:(p[a]??[]).filter(f=>f.clientMessageId!==b.clientMessageId)}))}catch(b){let p=!1;for(const f of y)k.has(f.clientMessageId)||(p=e.setCachedMessageDelivery(a,f.clientMessageId,"failed")!=="delivered"||p);p&&e.setErrorText(b instanceof Error?b.message:String(b))}finally{s.current=!1,n(!1)}}}}function os(e,t){return!!t&&Object.hasOwn(e,t)}function Nh(e,t){const n=e.map(s=>({...s}));return t?Us(Vs(n,t)):n}function Eh(e,t,n){return t?{...e,[t]:Ph(e[t]??[],n)}:e}function ia(e,t,n){return!t||n.length===0?e:{...e,[t]:xi(e[t]??[],n)}}function Rh(e,t,n){return n.historyKey&&e[t]?.some(s=>s.historyKey===n.historyKey)?e:ia(e,t,[n])}function Th(e,t,n){return!t||!n?e:{...e,[t]:Us(Vs(e[t]??[],n))}}function Ah(e,t,n){if(!t||!n||t===n||!os(e,t))return e;const s={...e};return s[n]=e[t],delete s[t],s}function Mh(e,t){if(!os(e,t))return e;const n={...e};return delete n[t],n}function Ph(e,t){const n=xi(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 Yt(e,t,n){const s=new Set(e);return n?s.add(t):s.delete(t),s}function Dh(e){const t=c.useCallback((n,s,i,a,o)=>{const l=e.notificationSettingsRef.current;if(!l[a]||e.notifiedEventsRef.current.has(n))return;vc(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":{tn(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,Nh(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(Qs(a))}else delete i[n.sessionId];return i})),e.setRespondingSessions(s=>{const i=Yt(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=Yt(e.respondingSessionsRef.current,n.sessionId,!0),e.setRespondingSessions(s=>Yt(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}
|
|
11
|
-
|
|
12
|
-
${Mc(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=Yt(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(s=>Yt(s,n.sessionId,!1)),n.sessionId===e.activeSessionIdRef.current&&(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=Yt(e.respondingSessionsRef.current,n.sessionId,!1),e.setRespondingSessions(s=>Yt(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])}const aa="vibelet.web.composerDrafts",$s={draftsBySessionId:{},newSessionDraft:""};function Or(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function oa(e){return Or(e)?{draftsBySessionId:Or(e.draftsBySessionId)?Object.fromEntries(Object.entries(e.draftsBySessionId).filter(n=>typeof n[1]=="string")):{},newSessionDraft:typeof e.newSessionDraft=="string"?e.newSessionDraft:""}:$s}function _h(e=Fe()){const t=e.getItem(aa);if(!t)return $s;try{return oa(JSON.parse(t))}catch{return $s}}function Rn(e,t=Fe()){t.setItem(aa,JSON.stringify(oa(e)))}function Tn(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 An(e,t){return t?e.draftsBySessionId[t]??"":e.newSessionDraft}function Lh(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 Fh(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 $h(e){const t=c.useCallback(async b=>{const p=e.clientRef.current;if(!(!p?.isConnected||!e.activeApproval)){e.setBusy(!0),e.setErrorText(null);try{await p.request({action:"session.approve",id:p.makeId("approve"),sessionId:e.activeApproval.sessionId,requestId:e.activeApproval.requestId,approved:b}),e.setPendingApprovals(f=>{const v={...f};return v[e.activeApproval.sessionId]?.requestId===e.activeApproval.requestId&&delete v[e.activeApproval.sessionId],v})}catch(f){e.setErrorText(f instanceof Error?f.message:String(f))}finally{e.setBusy(!1)}}},[e]),n=c.useCallback(async()=>{const b=e.clientRef.current;if(!(!b?.isConnected||!e.activeQuestion)){e.setBusy(!0),e.setErrorText(null);try{await b.request({action:"session.respondQuestion",id:b.makeId("question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId,answers:e.questionAnswers}),e.setPendingQuestions(p=>{const f={...p};return f[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete f[e.activeQuestion.sessionId],f})}catch(p){e.setErrorText(p instanceof Error?p.message:String(p))}finally{e.setBusy(!1)}}},[e]),s=c.useCallback(async()=>{const b=e.clientRef.current;if(!(!b?.isConnected||!e.activeQuestion)){e.setBusy(!0),e.setErrorText(null);try{await b.request({action:"session.cancelQuestion",id:b.makeId("cancel_question"),sessionId:e.activeQuestion.sessionId,requestId:e.activeQuestion.requestId}),e.setPendingQuestions(p=>{const f={...p};return f[e.activeQuestion.sessionId]?.requestId===e.activeQuestion.requestId&&delete f[e.activeQuestion.sessionId],f})}catch(p){e.setErrorText(p instanceof Error?p.message:String(p))}finally{e.setBusy(!1)}}},[e]),i=c.useCallback((b,p,f)=>{e.setQuestionAnswers(v=>Fh(v,b,p,!!f))},[e]),a=c.useCallback(async b=>{const p=e.clientRef.current,f=e.activeSession,v=f?.sessionId??(b==="session.interrupt"?e.activeSessionIdRef.current:null);if(!p?.isConnected||!v||b!=="session.interrupt"&&!f||b==="session.delete"&&!await wn(dn().deleteSession(St(f)))||e.clientRef.current!==p||!p.isConnected)return!1;e.setBusy(!0),e.setErrorText(null);try{return b==="session.resume"?await p.request({action:b,id:p.makeId("resume"),sessionId:v,agent:f.agent}):await p.request({action:b,id:p.makeId(b.split(".").at(-1)??"session"),sessionId:v}),b==="session.delete"&&(e.removeCachedHistory(f.sessionId),e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([])),b!=="session.interrupt"&&await e.requestSessions({force:!0,preserveLoaded:!0}),!0}catch(S){return e.setErrorText(S instanceof Error?S.message:String(S)),!1}finally{e.setBusy(!1)}},[e]),o=c.useCallback(async b=>{const p=e.clientRef.current;if(!e.activeSession){e.setApprovalMode(b);return}if(p?.isConnected){e.setErrorText(null);try{await p.request({action:"session.setApprovalMode",id:p.makeId("approval_mode"),sessionId:e.activeSession.sessionId,approvalMode:b}),e.activeSessionIdRef.current===e.activeSession.sessionId&&e.setApprovalMode(b),e.setSessions(f=>f.map(v=>v.sessionId===e.activeSession.sessionId?{...v,approvalMode:b}:v))}catch(f){e.setErrorText(f instanceof Error?f.message:String(f))}}},[e]),l=c.useCallback(async b=>{const p=e.clientRef.current;if(!p?.isConnected||!e.activeSessionId||!b.clientMessageId)return;const f=e.activeSessionId;let v=-1;e.setPendingQueues(S=>{const j=S[f]??[];return v=j.findIndex(C=>C.clientMessageId===b.clientMessageId),{...S,[f]:j.filter(C=>C.clientMessageId!==b.clientMessageId)}}),e.setBusy(!0),e.setErrorText(null);try{await p.request({action:"session.queue.cancel",id:p.makeId("queue_cancel"),sessionId:f,clientMessageId:b.clientMessageId})}catch(S){e.setPendingQueues(j=>{const C=j[f]??[];if(C.some(I=>I.clientMessageId===b.clientMessageId))return j;const w=Math.min(Math.max(v,0),C.length);return{...j,[f]:[...C.slice(0,w),b,...C.slice(w)]}}),e.setErrorText(S instanceof Error?S.message:String(S))}finally{e.setBusy(!1)}},[e]),d=c.useCallback(async(b,p)=>{if(e.pendingSessions[b.sessionId])return;const f=e.clientRef.current;if(f?.isConnected){e.setBusy(!0),e.setErrorText(null);try{const v=p?Date.now():void 0;await f.request({action:"session.setPinned",id:f.makeId("pin"),sessionId:b.sessionId,pinned:p,...v?{pinnedAt:v}:{}}),e.setSessions(S=>S.map(j=>j.sessionId===b.sessionId?{...j,pinned:p,pinnedAt:v}:j)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(v){e.setErrorText(v instanceof Error?v.message:String(v))}finally{e.setBusy(!1)}}},[e]),h=c.useCallback(async(b,p)=>{if(e.pendingSessions[b.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:b.sessionId,archived:p}),e.setSessions(v=>v.map(S=>S.sessionId===b.sessionId?{...S,archived:p}:S)),await e.requestSessions({force:!0,preserveLoaded:!0})}catch(v){e.setErrorText(v instanceof Error?v.message:String(v))}finally{e.setBusy(!1)}}},[e]),u=c.useCallback(async b=>{if(e.pendingSessions[b.sessionId]){e.removeCachedHistory(b.sessionId),e.setPendingSessions(f=>{const v={...f};return delete v[b.sessionId],v}),e.setComposerDrafts(f=>{const v=Tn(f,b.sessionId,"");return e.composerDraftsRef.current=v,Rn(v),v}),e.activeSessionIdRef.current===b.sessionId&&(e.setActiveSessionId(null),e.messagesSessionIdRef.current=null,e.lastHistorySessionIdRef.current=null,e.setMessages([]),e.setDraft(An(e.composerDraftsRef.current,null)),e.setDetailsOpen(!1));return}const p=e.clientRef.current;if(!(!p?.isConnected||!await wn(dn().deleteSession(St(b))))&&!(e.clientRef.current!==p||!p.isConnected)){e.setBusy(!0),e.setErrorText(null);try{await p.request({action:"session.delete",id:p.makeId("delete"),sessionId:b.sessionId}),e.removeCachedHistory(b.sessionId),e.setOptimisticSessions(f=>{if(!f[b.sessionId])return f;const v={...f};return delete v[b.sessionId],v}),e.activeSessionIdRef.current===b.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 d(e.activeSession,!e.activeSession.pinned)},[e.activeSession,d]),g=c.useCallback(async()=>{e.activeSession&&await h(e.activeSession,!e.activeSession.archived)},[e.activeSession,h]),y=c.useCallback(()=>{const b=e.activeSessionId;b&&a("session.interrupt").then(p=>{p&&(e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current),e.respondingSessionsRef.current.delete(b),e.setRespondingSessions(f=>{const v=new Set(f);return v.delete(b),v}))})},[e,a]),k=c.useCallback(()=>{e.setErrorText(null),e.phase==="connected"?e.requestSessions({force:!0,preserveLoaded:!0}):window.location.reload()},[e]),x=c.useCallback(async()=>{const b=e.renameTitle.trim();if(e.activeSession&&e.pendingSessions[e.activeSession.sessionId]){e.setPendingSessions(f=>{const v=f[e.activeSession.sessionId];return v?{...f,[e.activeSession.sessionId]:{...v,title:b||v.title,customTitle:b||void 0}}:f});return}const p=e.clientRef.current;if(!(!p?.isConnected||!e.activeSession)){e.setBusy(!0),e.setErrorText(null);try{await p.request({action:"session.rename",id:p.makeId("rename"),sessionId:e.activeSession.sessionId,title:b||void 0}),e.setSessions(f=>f.map(v=>v.sessionId===e.activeSession.sessionId?{...v,customTitle:b||void 0}:v))}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:y,retrySessions:k,updateApprovalMode:o,cancelQueuedTurn:l,setSessionPinned:d,setSessionArchived:h,deleteSession:u,updatePinned:m,updateArchived:g,renameSession:x}}async function Os(e){return{[e]:"desktop-free"}}function Oh(){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 Wr(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 qr=15e3,zr="Session send timed out.";function vn(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function Wh(e){const[t]=c.useState(Oh),[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(g=>{const y=new Set(g);return y.delete(m),y})},[e]),l=c.useCallback((m,g,y)=>{const k=vn(m)??vn(e.cwd)??tt,x=g??e.agent,b=Pc(),p=Dc({sessionId:b,agent:x,cwd:k,approvalMode:y?.approvalMode??e.approvalMode,model:zn(y?.model??e.model),effort:e.effort||void 0,fastMode:e.fastMode,title:x==="codex"?e.t.newCodexSession:e.t.newClaudeSession}),f=y?.draft??(e.activeSessionIdRef.current?"":An(e.composerDraftsRef.current,null));return e.setPendingSessions(v=>({...v,[b]:p})),e.setComposerDrafts(v=>{let S=Tn(v,b,f);return e.activeSessionIdRef.current||(S=Tn(S,null,"")),e.composerDraftsRef.current=S,Rn(S),S}),e.setCwd(k),e.setAgent(x),e.activeSessionIdRef.current=b,e.setActiveSessionId(b),e.lastHistorySessionIdRef.current=b,e.messagesSessionIdRef.current=b,e.clearHistoryLoading(),e.setMessages([]),e.setDraft(f),y?.draft?.trim()&&a(b),e.setErrorText(null),e.reportLog("web.session.pending_create",{sessionId:b,agent:x,cwd:k}),b},[e]),d=c.useCallback(async(m,g,y)=>{const k=e.clientRef.current;if(!k?.isConnected)return e.setErrorText(e.t.webSocketNotConnected),null;const x=y?e.pendingSessions[y]:void 0,b=vn(m)??vn(x?.cwd)??vn(e.cwd)??tt,p=g??x?.agent??e.agent,f=x?.approvalMode??e.approvalMode,v=x?x.model:zn(e.model),S=x?.effort??(e.effort||void 0),j=x?.fastMode??e.fastMode;e.setErrorText(null);try{const C=await k.request({action:"session.create",id:k.makeId("create"),agent:p,cwd:b,approvalMode:f,continueSession:e.continueSession,model:v,effort:S,fastMode:j,...y?{clientSessionId:y}:{}}),w=Tc(C);if(!w)throw new Error(e.t.sessionIdMissing);const I=tn(C)&&typeof C.oldSessionId=="string"?C.oldSessionId:y;return e.setCwd(b),e.setAgent(p),e.activeSessionIdRef.current=w,e.setActiveSessionId(w),e.lastHistorySessionIdRef.current=w,e.messagesSessionIdRef.current=w,e.clearHistoryLoading(),y&&x?(e.setPendingSessions(E=>{const L={...E};return delete L[y],I&&I!==y&&delete L[I],L}),e.setOptimisticSessions(E=>({...E,[w]:_c(x,w)})),I&&I!==w&&e.remapLocalSessionState(I,w),y!==w&&e.remapLocalSessionState(y,w)):await e.requestSessions({force:!0}),e.reportLog("web.session.create",{sessionId:w,clientSessionId:y,agent:p,cwd:b}),w}catch(C){return e.setErrorText(C instanceof Error?C.message:String(C)),null}},[e]),h=c.useCallback(async m=>{m?.preventDefault();const g=e.draft.trim();if(!g||e.busy)return;const y=e.clientRef.current;if(!y?.isConnected){e.setErrorText(e.t.webSocketNotConnected);return}const k=t.start(e.activeSessionId);try{const x=vr(g)?"agentSkills":e.attachments.length===0&&fr(g,e.activeSession?.agent??e.agent)?"agentCommands":void 0;let b;if(x){e.setBusy(!0);try{b=await Os(x)}catch(T){e.setErrorText(T instanceof Error?T.message:String(T));return}finally{e.setBusy(!1)}}e.setBusy(!0),e.setErrorText(null),e.updateDraft("");const p=e.attachments;e.setAttachments([]);let f=e.activeSessionId,v=e.activeSession?.agent??e.agent;const S=f?e.pendingSessions[f]:void 0,j=S?S.model:zn(e.model);if(f&&e.pendingSessions[f]){const T=await d(e.pendingSessions[f].cwd,e.pendingSessions[f].agent,f);if(!T){e.setBusy(!1),e.updateDraft(g),e.setAttachments(p);return}f=T,v=e.pendingSessions[e.activeSessionId??""]?.agent??v}else f||(f=await d());if(!f){e.setBusy(!1),e.updateDraft(g),e.setAttachments(p);return}k.remap(f);const C=p.length===0?fr(g,v):null;if(C){const T=fc(C.command),X=T?y.makeId("cmd_msg"):void 0;T&&(e.messagesSessionIdRef.current=f,e.appendCachedHistory(f,[{role:"user",content:T,timestamp:new Date().toISOString()}]),e.renderCachedHistory(f));try{const H=await y.request({action:"session.command",id:y.makeId("command"),sessionId:f,agent:v,command:C.command,...X?{clientMessageId:X}:{},featureEntitlements:b});await e.handleSessionCommandResponse(f,C.command,H)}catch(H){const se=H instanceof Error?H.message:String(H);e.appendInfoMessage(f,mr(se)),e.setErrorText(mr(se))}finally{e.setBusy(!1)}return}const w=hc(g),I=p.map(T=>T.path),E=y.makeId("msg"),L=`client:${E}`;e.messagesSessionIdRef.current=f,e.setCachedMessageDelivery(f,E,"sending",{content:w,...I.length?{images:I}:{}}),e.renderCachedHistory(f),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(f),e.setRespondingSessions(T=>new Set(T).add(f));const Y=vr(w)??void 0,B=Y?b:void 0;try{const T=await y.request({action:"session.send",id:y.makeId("send"),sessionId:f,agent:v,message:w,clientMessageId:E,images:I.length?I:void 0,model:j,effort:e.effort||void 0,fastMode:e.fastMode,skillInvocation:Y,featureEntitlements:B},{timeoutMs:qr,timeoutMessage:zr});tn(T)&&typeof T.oldSessionId=="string"&&typeof T.sessionId=="string"&&(k.remap(T.sessionId),e.remapLocalSessionState(T.oldSessionId,T.sessionId)),e.setCachedMessageDelivery(tn(T)&&typeof T.sessionId=="string"?T.sessionId:f,E,"delivered"),e.reportLog("web.telemetry.send_accepted",{attachmentCount:I.length}),s(X=>X?.historyKey===L?null:X)}catch(T){f=e.resolveCachedMessageSession(f,E);const X=T instanceof Error?T.message:String(T),H=Wr(br(X,!!Y));if(e.setCachedMessageDelivery(f,E,"failed")==="delivered")return;e.setErrorText(null),s({sessionId:f,agent:v,message:w,clientMessageId:E,historyKey:L,kind:H,retrying:!1,...I.length?{images:I}:{},model:j,effort:e.effort||void 0,fastMode:e.fastMode,skillInvocation:Y,featureEntitlements:B}),e.reportLog("web.telemetry.send_failed",{attachmentCount:I.length,failureKind:H},"warn"),o(f)}finally{e.setBusy(!1)}}finally{k.finish()}},[o,d,e,t]),u=c.useCallback(async()=>{if(!n||n.retrying||e.busy)return;const m=e.clientRef.current;if(!m?.isConnected){s(k=>k?{...k,kind:"network"}:null);return}let g=e.resolveCachedMessageSession(n.sessionId,n.clientMessageId);const y=t.start(g);s(k=>k?{...k,retrying:!0}:null),e.ensureCachedHistoryEntry(g,{role:"user",content:n.message,historyKey:n.historyKey,...n.images?.length?{images:n.images}:{}}),e.setCachedMessageDelivery(g,n.clientMessageId,"sending"),e.setBusy(!0),e.setErrorText(null),e.respondingSessionsRef.current=new Set(e.respondingSessionsRef.current).add(g),e.setRespondingSessions(k=>new Set(k).add(g));try{const k=await m.request({action:"session.send",id:m.makeId("retry_send"),sessionId:g,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 Os("agentSkills"):void 0},{timeoutMs:qr,timeoutMessage:zr});tn(k)&&typeof k.oldSessionId=="string"&&typeof k.sessionId=="string"&&(y.remap(k.sessionId),e.remapLocalSessionState(k.oldSessionId,k.sessionId)),e.setCachedMessageDelivery(tn(k)&&typeof k.sessionId=="string"?k.sessionId:g,n.clientMessageId,"delivered"),e.reportLog("web.telemetry.retry_accepted",{attachmentCount:n.images?.length??0}),s(null)}catch(k){g=e.resolveCachedMessageSession(g,n.clientMessageId);const x=k instanceof Error?k.message:String(k),b=Wr(br(x,!!n.skillInvocation));if(e.setCachedMessageDelivery(g,n.clientMessageId,"failed")==="delivered"){s(null);return}s(p=>p?{...p,sessionId:g,kind:b,retrying:!1}:null),e.reportLog("web.telemetry.retry_failed",{attachmentCount:n.images?.length??0,failureKind:b},"warn"),o(g)}finally{e.setBusy(!1),y.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:u,stagePendingSession:l,sendDraft:Object.assign(h,{submission:t})}}function qh({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 d=l[i];return d?{...l,[i]:{...d,model:zn(o)}}:l})},[i,n,s])}function zh(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 Bh(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=In(),o=e.historyCacheRef.current[s.sessionId]??[],l=zh(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 d=!1;try{d=await ks({message:a.confirmRewind})}finally{t.current=!1}if(!(!d||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 Os("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 u={...s,sessionId:h.sessionId,archived:!1};e.setOptimisticSessions(m=>{const g={...m};return delete g[s.sessionId],g[h.sessionId]=u,g}),e.setSessions(m=>[...m.filter(g=>g.sessionId!==h.sessionId).map(g=>g.sessionId===s.sessionId?{...g,archived:!0,pinned:!1}:g),u]),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 Hh(e,t,n,s,i){if(t===n)return e;const a=!t&&i?i:s||tt;return a===e.path?e:{path:a,entries:[],loading:!1,loaded:!1}}function xs(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function en(e=window.location.search){const t=new URLSearchParams(e),n=xs(t.get("folder")),s=xs(t.get("file")),i=xs(t.get("cwd"));return{...n?{folder:n}:{},...s?{file:s}:{},...i?{cwd:i}:{}}}function Kh(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 Br(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=Kh(s.search,e,i),o=`${s.pathname}${a}${s.hash}`;if(t.replace){n.replaceState(null,"",o);return}n.pushState(null,"",o)}function Xt(e,t){c.useEffect(()=>{e.current=t},[e,t])}function Uh({activeSessionIdRef:e,composerDraftsRef:t,setComposerDrafts:n,setDraft:s}){const i=c.useCallback(o=>{s(o),n(l=>{const d=Tn(l,e.current,o);return t.current=d,Rn(d),d})},[e,t,n,s]),a=c.useCallback(o=>{n(l=>{const d=Tn(l,null,o);return t.current=d,Rn(d),d}),e.current||s(o)},[e,t,n,s]);return{updateDraft:i,updateNewSessionDraft:a}}function Gh(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 Vh(e){const{clientRef:t,pairing:n,cwd:s,phase:i,controlTab:a,setControlTab:o,setBusy:l,setErrorText:d,t:h}=e,u=c.useRef(!1),[m,g]=c.useState([]),[y,k]=c.useState(!1),[x,b]=c.useState({path:en().folder||en().cwd||tt,entries:[],loading:!1,loaded:!1}),[p,f]=c.useState(""),[v,S]=c.useState(null),[j,C]=c.useState(!1),w=c.useRef(null),I=c.useRef(0),E=c.useRef(x.path);c.useEffect(()=>{E.current!==x.path&&(I.current++,E.current=x.path)},[x.path]),c.useEffect(()=>(I.current++,b({path:en().folder||en().cwd||s||tt,entries:[],loading:!1,loaded:!1}),S(null),()=>{I.current++,w.current?.abort()}),[n?.pairToken]),c.useEffect(()=>{x.path!==tt||en().folder||(I.current++,b(A=>({...A,entries:[],loaded:!1,loading:!1})))},[s]);const L=c.useRef(new Set);c.useEffect(()=>{v?.objectUrl&&L.current.add(v.objectUrl)},[v?.objectUrl]),c.useEffect(()=>()=>{for(const A of L.current)URL.revokeObjectURL(A);L.current.clear()},[n?.pairToken]);const Y=c.useCallback(async A=>{if(!(!A?.length||!n)){k(!0),d(null);try{const M=[];for(const W of Array.from(A)){const z=await fetch(`/upload?name=${encodeURIComponent(W.name)}`,{method:"POST",headers:{authorization:`Bearer ${n.pairToken}`,"content-type":W.type||"application/octet-stream"},body:W});if(!z.ok)throw new Error(await z.text().catch(()=>h.uploadFailed)||h.uploadFailed);const K=Ac(await z.json());if(!K)throw new Error(h.uploadPathMissing);M.push({path:K,name:W.name,type:W.type||"application/octet-stream",size:W.size})}g(W=>[...W,...M])}catch(M){d(M instanceof Error?M.message:String(M))}finally{k(!1)}}},[n,d,h.uploadFailed,h.uploadPathMissing]),B=c.useCallback(async(A,M,W)=>{if(!n)return;w.current?.abort();const z=new AbortController;w.current=z,d(null);try{const K=/^(?:https?:\/\/|data:image\/|blob:)/i.test(A),J=await fetch(K?A:Bn(A,M),{headers:K?{}:{authorization:`Bearer ${n.pairToken}`},signal:z.signal});if(!J.ok)throw new Error(await J.text().catch(()=>h.fileOpenFailed)||h.fileOpenFailed);const Q=J.headers.get("content-type")??"application/octet-stream";if(K&&!Q.startsWith("image/"))throw new Error(h.fileOpenFailed);const oe=Jn(A,Q,!1);if(oe==="html"||oe==="unsupported"&&Fc(A,Q)){const $=await J.text();if(z.signal.aborted)return;S({path:A,cwd:M,kind:"text",contentType:Q,text:$,etag:On(J.headers,"etag"),lastModified:On(J.headers,"last-modified"),size:Number(J.headers.get("content-length"))||void 0,dirty:!1})}else{const $=await J.blob();if(z.signal.aborted)return;const V=Jn(A,Q,!1)==="pdf"?new Blob([$],{type:"application/pdf"}):$;S({path:A,cwd:M,kind:$c(A,Q)?"image":"binary",contentType:Q,text:"",objectUrl:URL.createObjectURL(V),etag:On(J.headers,"etag"),lastModified:On(J.headers,"last-modified"),size:$.size,dirty:!1})}C(!1),o("files"),W?.updateRoute&&Br({file:A,...M?{cwd:M}:{}},{replace:W.replaceRoute})}catch(K){if(z.signal.aborted)return;d(K instanceof Error?K.message:String(K))}},[n,o,d]),T=c.useCallback(async A=>{if(!(!n||!v||v.kind!=="text")){l(!0),d(null);try{const M=await fetch(Bn(v.path,v.cwd),{method:"PUT",headers:{authorization:`Bearer ${n.pairToken}`,"content-type":"text/markdown; charset=utf-8",...v.etag&&!A?.force?{"if-match":v.etag}:{}},body:v.text});if(!M.ok)throw M.status===409?(C(!0),new Error(h.remoteFileConflict(v.path))):new Error(await M.text().catch(()=>h.fileSaveFailed)||h.fileSaveFailed);C(!1);const W=await M.json().catch(()=>({}));S(z=>Gh(z,v,W))}catch(M){d(M instanceof Error?M.message:String(M))}finally{l(!1)}}},[n,v,l,d]),X=c.useCallback(async()=>{if(!(!n||!v))try{const A=/^(?:https?:\/\/|data:image\/|blob:)/i.test(v.path),M=await fetch(A?v.path:Bn(v.path,v.cwd),{headers:A?{}:{authorization:`Bearer ${n.pairToken}`}});if(!M.ok)throw new Error(h.downloadFailed);const W=URL.createObjectURL(await M.blob()),z=document.createElement("a");z.href=W,z.download=Bt(v.path),z.click(),URL.revokeObjectURL(W)}catch(A){d(A instanceof Error?A.message:String(A))}},[n,v,d]),H=c.useCallback(async(A=x.path,M)=>{const W=t.current;if(!W?.isConnected)return;E.current=A;const z=++I.current;b(K=>({...K,path:A,entries:A===K.path?K.entries:[],loading:!0,loaded:!1,error:void 0}));try{const K=await W.request({action:"dirs.list",id:W.makeId("dirs"),path:A,cwd:s||void 0});if(z!==I.current)return;b({path:A,entries:K.entries??[],loading:!1,loaded:!0}),M?.updateRoute&&Br({folder:A},{replace:M.replaceRoute})}catch(K){if(z!==I.current)return;b(J=>({...J,loading:!1,loaded:!0,error:K instanceof Error?K.message:String(K)}))}},[t,s,x.path]),se=c.useCallback(async A=>{const M=t.current;if(!M?.isConnected)throw new Error(h.webSocketNotConnected);return(await M.request({action:"dirs.list",id:M.makeId("dirs"),path:A,cwd:s||void 0},{timeoutMs:1e4,timeoutMessage:h.directoryListTimedOut})).entries??[]},[t,s]),Se=c.useCallback(async A=>(await se(A)).filter(M=>M.isDirectory),[se]);c.useEffect(()=>{!u.current||a!=="files"||i!=="connected"||x.loading||x.loaded||H(x.path||s||tt)},[a,s,x.loaded,x.loading,x.path,H,i]),c.useEffect(()=>{if(i!=="connected"||u.current)return;const A=en();if(!A.folder&&!A.file){u.current=!0;return}if(u.current=!0,o("files"),A.folder){H(A.folder,{updateRoute:!1});return}A.file&&(A.cwd&&b(M=>({...M,path:A.cwd,loaded:!1})),B(A.file,A.cwd,{updateRoute:!1}))},[H,B,i,o]);const ve=c.useCallback(async()=>{const A=t.current;if(!(!A?.isConnected||p.trim().length===0)){l(!0),d(null);try{await A.request({action:"dirs.create",id:A.makeId("mkdir"),path:Lc(x.path,p),cwd:s||void 0}),f(""),await H(x.path)}catch(M){d(M instanceof Error?M.message:String(M))}finally{l(!1)}}},[t,s,x.path,H,p,l,d]),xe=c.useCallback(async A=>{const M=t.current;if(!M?.isConnected)throw new Error(h.webSocketNotConnected);await M.request({action:"dirs.create",id:M.makeId("mkdir"),path:A,cwd:s||void 0},{timeoutMs:1e4,timeoutMessage:h.directoryCreationTimedOut})},[t,s]);return{attachments:m,setAttachments:g,uploadBusy:y,directory:x,setDirectory:b,newDirName:p,setNewDirName:f,remoteFile:v,setRemoteFile:S,remoteFileConflict:j,uploadFiles:Y,openRemoteFile:B,saveRemoteFile:T,downloadRemoteFile:X,listDirectory:H,listSessionDirectories:Se,listFileTreeDirectory:se,createDirectory:ve,createSessionDirectory:xe}}function Qh({clientRef:e,setSessions:t}){return c.useCallback(async n=>{const s=e.current;if(!s?.isConnected)return;const i=[...new Set(n.map(o=>o.cwd).filter(Boolean))];if(i.length===0)return;const a=new Set(i);try{const o=await s.request({action:"sessions.gitMetadata",id:s.makeId("git"),cwds:i});t(l=>l.map(d=>a.has(d.cwd)?{...d,pullRequest:o.pullRequests?.[d.cwd],branchUrl:o.branchUrls?.[d.cwd],branch:o.branches[d.cwd]??d.branch,diffStat:o.diffStats[d.cwd]??d.diffStat}:d))}catch{}},[])}const Ws=15e3,Hr=500,ws=1e3;function Zh(e){const t=c.useRef({}),n=c.useRef(null),s=c.useRef({}),i=c.useRef(null),[a,o]=c.useState(!1),[l,d]=c.useState([]),h=c.useCallback(w=>w&&n.current&&n.current!==w?!1:(n.current=null,o(!1),!0),[]),u=c.useCallback(w=>os(t.current,w)?(i.current=w,d(t.current[w]??[]),!0):!1,[]),m=c.useCallback((w,I,E)=>{t.current=Eh(t.current,w,I);const L=t.current[w]??[];return E?.renderActive!==!1&&w===e.activeSessionIdRef.current&&(i.current=w,d(L)),L},[e.activeSessionIdRef]),g=c.useCallback((w,I,E)=>{if(!E)return s.current[w]=void 0,m(w,I);const L=s.current[w],Y=t.current[w]??[],B=E.start+I.length;if(L===void 0||B<L||E.start>L+Y.length)return s.current[w]=E.start,m(w,I);s.current[w]=Math.min(L,E.start);const T=Y.slice(0,Math.max(0,E.start-L)),X=Y.slice(Math.max(0,B-L),Math.max(0,E.total-L));return m(w,[...T,...I,...X])},[m]),y=c.useCallback((w,I)=>{s.current[w]=0;const E=m(w,I,{renderActive:!1});i.current=w,d(E)},[m]),k=c.useCallback((w,I)=>{t.current=ia(t.current,w,I),w===e.activeSessionIdRef.current&&(i.current=w,d(t.current[w]??[]))},[e.activeSessionIdRef]),x=c.useCallback((w,I)=>{t.current=Rh(t.current,w,I),w===e.activeSessionIdRef.current&&(i.current=w,d(t.current[w]??[]))},[e.activeSessionIdRef]),b=c.useCallback((w,I)=>xl(t.current,w,I),[]),p=c.useCallback((w,I,E,L)=>{w=b(w,I);const Y=wl(t.current[w]??[],I,E,L);return t.current={...t.current,[w]:Y},(w===e.activeSessionIdRef.current||w===i.current)&&(i.current=w,d(t.current[w]??[])),Y.find(B=>B.localClientMessageId===I)?.localDelivery},[e.activeSessionIdRef]),f=c.useCallback((w,I)=>{t.current=Th(t.current,w,I),w===e.activeSessionIdRef.current&&(i.current=w,d(t.current[w]??[]))},[e.activeSessionIdRef]),v=c.useCallback((w,I)=>{k(w,[{role:"assistant",type:"info",content:I,timestamp:new Date().toISOString()}])},[k]),S=c.useCallback(w=>{t.current=Mh(t.current,w),delete s.current[w]},[]),j=c.useCallback((w,I)=>{t.current=Ah(t.current,w,I),s.current[I]=s.current[w],delete s.current[w]},[]),C=c.useCallback(async w=>{const I=e.clientRef.current;if(!I?.isConnected)return;const E=u(w.sessionId);E?h(w.sessionId):(n.current=w.sessionId,delete s.current[w.sessionId],o(!0),e.setErrorText(null));try{const L=s.current[w.sessionId]??0,Y=t.current[w.sessionId]?.length??0;if(E&&(L===0||Y>=ws)){const X=(await I.request({action:"reconnect.snapshot",id:I.makeId("snapshot"),activeSessionId:w.sessionId,activeAgent:w.agent,skipActiveSessionHistory:!0,skipGitMetadata:!0})).snapshot.activeSession;X?.sessionId===w.sessionId&&e.setPendingQueues(H=>({...H,[w.sessionId]:X.pendingQueue??[]}));return}await I.request({action:"session.history",id:I.makeId("history"),sessionId:w.sessionId,agent:w.agent,limit:Hr},{timeoutMessage:e.historyTimeoutMessage,timeoutMs:Ws});let B=s.current[w.sessionId];for(;typeof B=="number"&&B>0&&(t.current[w.sessionId]?.length??0)<ws;){const T=t.current[w.sessionId]?.length??0;await I.request({action:"session.history",id:I.makeId("history_older"),sessionId:w.sessionId,agent:w.agent,before:B,limit:Math.min(Hr,ws-T)},{timeoutMessage:e.historyTimeoutMessage,timeoutMs:Ws});const X=s.current[w.sessionId];if(typeof X!="number"||X>=B)break;B=X}}catch(L){e.activeSessionIdRef.current===w.sessionId&&e.setErrorText(L instanceof Error?L.message:String(L))}finally{h(w.sessionId)}},[h,e.activeSessionIdRef,e.clientRef,e.historyTimeoutMessage,e.setErrorText,e.setPendingQueues,u]);return{resolveCachedMessageSession:b,setCachedMessageDelivery:p,appendCachedDelta:f,appendCachedHistory:k,appendInfoMessage:v,clearHistoryLoading:h,ensureCachedHistoryEntry:x,historyCacheRef:t,historyLoading:a,historyPageStartRef:s,hydrateVisibleHistory:y,messages:l,messagesSessionIdRef:i,mergeCachedHistoryPage:g,remapCachedHistory:j,removeCachedHistory:S,renderCachedHistory:u,replaceCachedHistory:m,requestHistory:C,setMessages:d}}function Jh(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 Yh(e,t){const n=t.trim().toLowerCase();return n?[St(e),e.cwd,e.agent,e.branch??"",...e.titleAliases??[]].some(s=>s.toLowerCase().includes(n)):!0}function Xh(e,t){return e.filter(n=>t.hideArchived&&n.archived||t.agentFilter!=="all"&&n.agent!==t.agentFilter?!1:Yh(n,t.search))}function ef(e){const t=c.useRef([]),n=c.useMemo(()=>Es(Es(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(y=>y.sessionId===e.activeSessionId)??null,[e.activeSessionId,n]),a=Object.values(e.pendingApprovals)[0]??null,o=Object.values(e.pendingQuestions)[0]??null,l=c.useMemo(()=>Xh(n,{search:e.search,hideArchived:e.hideArchived,agentFilter:e.sessionAgentFilter}),[n,e.hideArchived,e.search,e.sessionAgentFilter]),d=c.useMemo(()=>new Set([...Object.keys(e.pendingApprovals),...Object.keys(e.pendingQuestions)]),[e.pendingApprovals,e.pendingQuestions]),h=l.filter(y=>e.respondingSessionIds.has(y.sessionId)).map(y=>y.sessionId),u=new Set(h),m=t.current.filter(y=>u.has(y));for(const y of h)m.includes(y)||m.push(y);t.current=m;const g=c.useMemo(()=>Ic(l,{needsAttentionSessionIds:d,respondingSessionIds:e.respondingSessionIds,runningSessionOrder:m,separatePinnedGroup:e.separatePinnedGroup,showNeedsAttentionGroup:e.showNeedsAttentionGroup,showRunningGroup:e.showRunningGroup}),[d,e.respondingSessionIds,e.separatePinnedGroup,e.showNeedsAttentionGroup,e.showRunningGroup,l,m]);return{activeApproval:a,activeQuestion:o,activeSession:i,displaySessions:n,groupedSessions:g,pendingSessionIds:s,visibleSessions:l}}const tf=new Set(["attachmentCount","domNodes","durationMs","errorKind","failureKind","longTaskCount","maxLongTaskMs","online","phase","visibilityState"]);function nf(e){const t={};for(const[n,s]of Object.entries(e))tf.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 Kr(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 sf(e){c.useEffect(()=>{const t=performance.now(),n=(h,u,m="info")=>e(h,nf(u),m),s=h=>{n("web.telemetry.runtime_error",{errorKind:Kr(h.error)},"error")},i=h=>{n("web.telemetry.unhandled_rejection",{errorKind:Kr(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,d=null;return typeof PerformanceObserver<"u"&&PerformanceObserver.supportedEntryTypes.includes("longtask")&&(d=new PerformanceObserver(h=>{for(const u of h.getEntries())o+=1,l=Math.max(l,u.duration)}),d.observe({entryTypes:["longtask"]})),window.addEventListener("error",s),window.addEventListener("unhandledrejection",i),()=>{window.clearTimeout(a),window.removeEventListener("error",s),window.removeEventListener("unhandledrejection",i),d?.disconnect(),o>0&&n("web.telemetry.long_tasks",{longTaskCount:o,maxLongTaskMs:l},"warn")}},[e])}const rf=6;function af(e,t){return t.has(e.sessionId)||e.runtime?.isResponding===!0||e.runtime?.state==="daemonActive"||e.runtime?.state==="externalRunning"}function of(e,t,n,s,i=rf){if(i<=0)return[];const a=[];for(const o of e){if(a.length>=i)break;!o.sessionId||!af(o,n)||os(t,o.sessionId)||s.has(o.sessionId)||a.push(o)}return a}function cf(e,t,n=!1){const s=new Set(t.map(i=>i.sessionId));return Es(n?e:e.filter(i=>s.has(i.sessionId)),t)}class lf{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 df(){const e=c.useRef(new lf),[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(d=>e.current.live(d,o,l))},[]),a=c.useCallback((o,l)=>{e.current.remap(o,l)},[]);return{pendingQueues:t,setPendingQueues:s,setLivePendingQueue:i,remapPendingQueue:a}}function uf(e,t,n=1/0){return Math.min(Math.max(Math.round(e),t),n)}function hf(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 ff(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 Ur=96,mf=64,pf=252,gf=234;function yf(e,t){const[n,s]=c.useState(288),[i,a]=c.useState(297),[o,l]=c.useState(()=>window.innerWidth);c.useEffect(()=>{const u=()=>l(window.innerWidth);return window.addEventListener("resize",u),()=>window.removeEventListener("resize",u)},[]);const d=hf({leftCollapsed:e,rightCollapsed:t,leftPaneWidth:n,rightPaneWidth:i},o-Ur-mf),h=c.useCallback(u=>m=>{m.preventDefault();const g=m.clientX,y=u==="left"?d.leftPaneWidth:d.rightPaneWidth,k=m.currentTarget.closest(".workspace")?.querySelector(".chat-pane"),x=y+Math.max(0,(k?.getBoundingClientRect().width??0)-Ur),b=f=>{const v=(f.clientX-g)*(u==="left"?1:-1),S=uf(y+v,u==="left"?pf:gf,x);u==="left"?s(S):a(S)},p=()=>{document.body.classList.remove("pane-resizing"),window.removeEventListener("pointermove",b),window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p),window.removeEventListener("blur",p)};document.body.classList.add("pane-resizing"),window.addEventListener("pointermove",b),window.addEventListener("pointerup",p,{once:!0}),window.addEventListener("pointercancel",p,{once:!0}),window.addEventListener("blur",p,{once:!0})},[d.leftPaneWidth,d.rightPaneWidth]);return{...d,beginPaneResize:h}}function bf(e,t){const[n,s]=c.useState(e);c.useEffect(()=>{const $=()=>{const V=ze();s(ee=>({...ee,theme:V.theme,language:V.language,composer:V.composer}))};return window.addEventListener("vibelet.preferences.changed",$),()=>window.removeEventListener("vibelet.preferences.changed",$)},[]);const[i,a]=c.useState(""),[o,l]=c.useState(e.sessionList.searchHistory),[d,h]=c.useState(e.sessionList.sinceFilter),[u,m]=c.useState(e.sessionList.hideArchived),[g,y]=c.useState(e.sessionList.groupFolders),[k,x]=c.useState(e.sessionList.showNeedsAttentionGroup),[b,p]=c.useState(e.sessionList.showRunningGroup),[f,v]=c.useState(e.sessionList.separatePinnedGroup),[S,j]=c.useState(e.sessionList.collapsedFolders),[C,w]=c.useState(e.sessionList.agentFilter),[I,E]=c.useState(t),[L,Y]=c.useState(e.layout.leftSidebarCollapsed),[B,T]=c.useState(e.layout.rightSidebarCollapsed),{leftPaneWidth:X,rightPaneWidth:H,beginPaneResize:se}=yf(L,B),Se=n.sessionList.directoryTags,ve=n.sessionList.archiveSyncedDaemonIds,xe=n.sessionList.archiveSyncCardDismissedDaemonIds,A=n.composer,M=ff({leftCollapsed:L,rightCollapsed:B,leftPaneWidth:X,rightPaneWidth:H});c.useEffect(()=>{s($=>{const V={...$,sessionList:{...$.sessionList,searchHistory:o,sinceFilter:d,hideArchived:u,groupFolders:g,showNeedsAttentionGroup:k,showRunningGroup:b,separatePinnedGroup:f,collapsedFolders:S,agentFilter:C},layout:{...$.layout,leftSidebarCollapsed:L,rightSidebarCollapsed:B}};return gn(V),V})},[S,g,u,L,B,o,f,C,k,b,d]);const W=c.useCallback(()=>{l($=>ha($,i))},[i]),z=c.useCallback($=>{E($),na($)},[]),K=c.useCallback($=>{s(V=>{const ee={...V,language:$};return gn(ee),ee})},[]),J=c.useCallback($=>{s(V=>{const ee={...V,theme:$};return gn(ee),ee})},[]),Q=c.useCallback($=>{s(V=>{const ee={...V,sessionList:$(V.sessionList)};return gn(ee),ee})},[]),oe=c.useCallback($=>{s(V=>{const ee={...V,composer:$(V.composer)};return gn(ee),ee})},[]);return{webPreferences:n,search:i,setSearch:a,sinceFilter:d,setSinceFilter:h,hideArchived:u,setHideArchived:m,groupFolders:g,setGroupFolders:y,showNeedsAttentionGroup:k,setShowNeedsAttentionGroup:x,showRunningGroup:b,setShowRunningGroup:p,separatePinnedGroup:f,setSeparatePinnedGroup:v,collapsedFolders:S,setCollapsedFolders:j,sessionAgentFilter:C,setSessionAgentFilter:w,directoryTags:Se,archiveSyncedDaemonIds:ve,archiveSyncCardDismissedDaemonIds:xe,composerPreferences:A,savedTargets:I,setSavedTargets:E,leftSidebarCollapsed:L,setLeftSidebarCollapsed:Y,rightSidebarCollapsed:B,setRightSidebarCollapsed:T,workspaceClassName:M.workspaceClassName,wideMainClassName:M.wideMainClassName,workspaceStyle:M.style,beginPaneResize:se,commitSearch:W,saveTargets:z,setLanguagePreference:K,setThemePreference:J,updateSessionListPreferences:Q,updateComposerPreferences:oe}}function vf(e){c.useEffect(()=>{const t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>fa(e,document.documentElement,t.matches);if(n(),e==="system")return t.addEventListener("change",n),()=>t.removeEventListener("change",n)},[e])}function xf(){const e=c.useRef(null),t=c.useRef(async()=>{}),n=c.useRef(null),s=c.useRef(Sn()),i=c.useRef(Is()),a=c.useRef(ze()),o=c.useRef(_h()),l=c.useRef(lh()),d=c.useRef(s.current),h=c.useRef(i.current),u=c.useRef(o.current),m=c.useRef(null),g=c.useRef(null),y=c.useRef(new Set),k=c.useRef(null),x=c.useRef(new Set),b=c.useRef(null),p=c.useRef(0),f=c.useRef(new Set),v=c.useRef({}),S=c.useRef(!1),[j,C]=c.useState("connecting"),[w,I]=c.useState(()=>Ss[qe(a.current.language)].preparingVibeletWeb),[E,L]=c.useState(null),[Y,B]=c.useState(null),[T,X]=c.useState([]),[H,se]=c.useState({}),[Se,ve]=c.useState({}),[xe,A]=c.useState(),[M,W]=c.useState({}),[z,K]=c.useState(),[J,Q]=c.useState(null),[oe,$]=c.useState(null),[V,ee]=c.useState(()=>new Set),[Ge,we]=c.useState({}),[Be,ae]=c.useState({}),[ke,le]=c.useState({}),{pendingQueues:je,setPendingQueues:de,setLivePendingQueue:ue,remapPendingQueue:ce}=df(),[me,Me]=c.useState("claude"),[He,Ke]=c.useState(tt),[Ze,$e]=c.useState(Gs),[Ce]=c.useState(!1),[Je,Pe]=c.useState(""),[Ve,Ee]=c.useState(""),[fe,Z]=c.useState(!1),[he,U]=c.useState(""),[G,pe]=c.useState(o.current),[N,Ie]=c.useState(()=>An(o.current,null)),{webPreferences:De,setRightSidebarCollapsed:ht,search:Rt,setSearch:Ye,sinceFilter:ge,setSinceFilter:kt,hideArchived:ft,setHideArchived:jt,groupFolders:ot,setGroupFolders:Ct,showNeedsAttentionGroup:Xe,setShowNeedsAttentionGroup:mt,showRunningGroup:Tt,setShowRunningGroup:Oe,separatePinnedGroup:It,setSeparatePinnedGroup:At,collapsedFolders:Ue,setCollapsedFolders:st,sessionAgentFilter:pt,setSessionAgentFilter:gt,directoryTags:yt,archiveSyncedDaemonIds:bt,archiveSyncCardDismissedDaemonIds:ct,composerPreferences:_,savedTargets:q,setSavedTargets:re,leftSidebarCollapsed:Re,setLeftSidebarCollapsed:et,rightSidebarCollapsed:ye,workspaceClassName:rt,wideMainClassName:Te,workspaceStyle:vt,beginPaneResize:it,commitSearch:Le,saveTargets:at,setLanguagePreference:Ot,setThemePreference:Ht,updateSessionListPreferences:Mt,updateComposerPreferences:Wt}=bf(a.current,l.current),lt=qe(De.language),xt=Ss[lt],[wt,Pt]=c.useState(!1),[Kt,Dt]=c.useState("session"),[Ut,Gt]=c.useState(!1);vf(De.theme);const qt=c.useCallback(pn=>{Dt(pn),ht(!1)},[ht]),[_t,Vt]=c.useState({}),[Qt,P]=c.useState({}),[D,O]=c.useState([]),[te,Ne]=c.useState({statusText:"",loading:!1,action:null}),[dt,Lt]=c.useState(or),[an,on]=c.useState(i.current),[fn,_n]=c.useState(s.current),[Ln,Fn]=c.useState(null),[mn,$n]=c.useState(null);return{clientRef:e,connectWithPairingRef:t,activeSessionIdRef:n,initialNotificationPermissionRef:s,initialNotificationSettingsRef:i,initialPreferencesRef:a,initialComposerDraftsRef:o,initialSavedTargetsRef:l,notificationPermissionRef:d,notificationSettingsRef:h,composerDraftsRef:u,lastHistorySessionIdRef:m,historyCacheDaemonIdRef:g,historyPrefetchingSessionIdsRef:y,pairingRef:k,notifiedEventsRef:x,reconnectTimerRef:b,connectionAttemptIdRef:p,respondingSessionsRef:f,turnNotificationCountsRef:v,intentionalDisconnectRef:S,phase:j,setPhase:C,statusText:w,setStatusText:I,errorText:E,setErrorText:L,pairing:Y,setPairing:B,sessions:T,setSessions:X,pendingSessions:H,setPendingSessions:se,optimisticSessions:Se,setOptimisticSessions:ve,nextCursor:xe,setNextCursor:A,folderCounts:M,setFolderCounts:W,inventoryVersion:z,setInventoryVersion:K,activeSessionId:J,setActiveSessionId:Q,diffSessionId:oe,setDiffSessionId:$,respondingSessions:V,setRespondingSessions:ee,pendingApprovals:Ge,setPendingApprovals:we,pendingQuestions:Be,setPendingQuestions:ae,questionAnswers:ke,setQuestionAnswers:le,pendingQueues:je,setPendingQueues:de,setLivePendingQueue:ue,remapPendingQueue:ce,agent:me,setAgent:Me,cwd:He,setCwd:Ke,approvalMode:Ze,setApprovalMode:$e,continueSession:Ce,model:Je,setModel:Pe,effort:Ve,setEffort:Ee,fastMode:fe,setFastMode:Z,renameTitle:he,setRenameTitle:U,composerDrafts:G,setComposerDrafts:pe,draft:N,setDraft:Ie,webPreferences:De,search:Rt,setSearch:Ye,sinceFilter:ge,setSinceFilter:kt,hideArchived:ft,setHideArchived:jt,groupFolders:ot,setGroupFolders:Ct,showNeedsAttentionGroup:Xe,setShowNeedsAttentionGroup:mt,showRunningGroup:Tt,setShowRunningGroup:Oe,separatePinnedGroup:It,setSeparatePinnedGroup:At,collapsedFolders:Ue,setCollapsedFolders:st,sessionAgentFilter:pt,setSessionAgentFilter:gt,directoryTags:yt,archiveSyncedDaemonIds:bt,archiveSyncCardDismissedDaemonIds:ct,composerPreferences:_,savedTargets:q,setSavedTargets:re,leftSidebarCollapsed:Re,setLeftSidebarCollapsed:et,rightSidebarCollapsed:ye,setRightSidebarCollapsed:ht,workspaceClassName:rt,wideMainClassName:Te,workspaceStyle:vt,beginPaneResize:it,commitSearch:Le,saveTargets:at,setLanguagePreference:Ot,setThemePreference:Ht,updateSessionListPreferences:Mt,updateComposerPreferences:Wt,language:lt,t:xt,busy:wt,setBusy:Pt,controlTab:Kt,setControlTab:Dt,detailsOpen:Ut,setDetailsOpen:Gt,setControlTabAndOpen:qt,modelOptions:_t,setModelOptions:Vt,usageLimits:Qt,setUsageLimits:P,skills:D,setSkills:O,admin:te,setAdmin:Ne,daemonMetadata:dt,setDaemonMetadata:Lt,notificationSettings:an,setNotificationSettings:on,notificationPermission:fn,setNotificationPermission:_n,archiveSyncBusy:Ln,setArchiveSyncBusy:Fn,archiveSyncStatus:mn,setArchiveSyncStatus:$n}}function wf(){const e=xf(),t=Jh(e),{clientRef:n,activeSessionIdRef:s,notificationPermissionRef:i,notificationSettingsRef:a,composerDraftsRef:o,lastHistorySessionIdRef:l,historyPrefetchingSessionIdsRef:d,pairingRef:h,reconnectTimerRef:u,respondingSessionsRef:m,phase:g,setStatusText:y,setErrorText:k,pairing:x,setSessions:b,setOptimisticSessions:p,setNextCursor:f,setFolderCounts:v,setInventoryVersion:S,activeSessionId:j,setActiveSessionId:C,respondingSessions:w,setRespondingSessions:I,pendingApprovals:E,setPendingApprovals:L,pendingQuestions:Y,setPendingQuestions:B,setQuestionAnswers:T,pendingQueues:X,setPendingQueues:H,agent:se,setAgent:Se,cwd:ve,setCwd:xe,setApprovalMode:A,composerDrafts:M,setComposerDrafts:W,search:z,sinceFilter:K,hideArchived:J,sessionAgentFilter:Q,setRightSidebarCollapsed:oe,t:$,controlTab:V,setControlTab:ee,setControlTabAndOpen:Ge,modelOptions:we,setModelOptions:Be,usageLimits:ae,setUsageLimits:ke,setSkills:le,setDaemonMetadata:je,notificationSettings:de,setNotificationSettings:ue,notificationPermission:ce,setNotificationPermission:me,sessions:Me,pendingSessions:He,optimisticSessions:Ke,setDraft:Ze,setBusy:$e}=e,{remoteFile:Ce,attachments:Je,setAttachments:Pe,uploadBusy:Ve,directory:Ee,setDirectory:fe,newDirName:Z,setNewDirName:he,setRemoteFile:U,remoteFileConflict:G,uploadFiles:pe,openRemoteFile:N,saveRemoteFile:Ie,downloadRemoteFile:De,listDirectory:ht,listSessionDirectories:Rt,listFileTreeDirectory:Ye,createDirectory:ge,createSessionDirectory:kt}=Vh({clientRef:n,pairing:x,cwd:ve,phase:g,controlTab:V,setControlTab:Ge,setBusy:$e,setErrorText:k,t:$}),ft=Object.keys(E).length+Object.keys(Y).length,jt=j?X[j]??[]:[],ot=we[se]??[],Ct=ae[se],{activeSession:Xe,activeApproval:mt,activeQuestion:Tt,displaySessions:Oe,groupedSessions:It,pendingSessionIds:At,visibleSessions:Ue}=ef({activeSessionId:j,hideArchived:J,optimisticSessions:Ke,pendingApprovals:E,pendingQuestions:Y,pendingSessions:He,respondingSessionIds:w,search:z,separatePinnedGroup:t.separatePinnedGroup,sessionAgentFilter:Q,sessions:Me,showNeedsAttentionGroup:t.showNeedsAttentionGroup,showRunningGroup:t.showRunningGroup}),{historyCacheRef:st,historyPageStartRef:pt,hydrateVisibleHistory:gt,messagesSessionIdRef:yt,remapCachedHistory:bt,appendCachedDelta:ct,appendCachedHistory:_,appendInfoMessage:q,clearHistoryLoading:re,ensureCachedHistoryEntry:Re,setCachedMessageDelivery:et,resolveCachedMessageSession:ye,historyLoading:rt,messages:Te,mergeCachedHistoryPage:vt,removeCachedHistory:it,renderCachedHistory:Le,replaceCachedHistory:at,requestHistory:Ot,setMessages:Ht}=Zh({activeSessionIdRef:s,clientRef:n,historyTimeoutMessage:$.historyRequestTimedOut,setPendingQueues:H,setErrorText:k});Xt(s,j),Xt(h,x),Xt(m,w),Xt(a,de),Xt(i,ce),Xt(o,M);const{updateNewSessionDraft:Mt,updateDraft:Wt}=Uh({activeSessionIdRef:s,composerDraftsRef:o,setComposerDrafts:W,setDraft:Ze});c.useEffect(()=>{ma();const P=pa();P&&(Mt(P),ee("session"),ga())},[Mt]),c.useEffect(()=>{const P=()=>{ue(Is()),me(Sn())};return window.addEventListener("vibelet.notifications.changed",P),()=>window.removeEventListener("vibelet.notifications.changed",P)},[]),c.useEffect(()=>{V==="admin"&&me(Sn())},[V]),c.useEffect(()=>()=>{u.current&&window.clearTimeout(u.current),Ce?.objectUrl&&URL.revokeObjectURL(Ce.objectUrl)},[Ce?.objectUrl]);const lt=c.useCallback((P,D=!1)=>{b(O=>cf(O,P.sessions,D)),p(O=>{const te=new Set(P.sessions.map(dt=>dt.sessionId)),Ne=Object.fromEntries(Object.entries(O).filter(([dt])=>!te.has(dt)));return Object.keys(Ne).length===Object.keys(O).length?O:Ne}),f(P.nextCursor),S(P.inventoryVersion),P.folderCounts&&v(P.folderCounts),D||Sh(h.current?.daemonId,P),y(P.inventoryBackfillInFlight?$.connectedIndexing:$.connected)},[$.connected,$.connectedIndexing]),xt=Qh({clientRef:n,setSessions:b}),wt=c.useCallback((P,D=m.current)=>{const O=n.current;if(!O?.isConnected||P.length===0)return;const te=of(P,st.current,D,d.current);for(const Ne of te)d.current.add(Ne.sessionId),O.request({action:"session.history",id:O.makeId("history_prefetch"),sessionId:Ne.sessionId,agent:Ne.agent},{timeoutMessage:$.historyPrefetchTimedOut,timeoutMs:Ws}).catch(()=>{}).finally(()=>{d.current.delete(Ne.sessionId)})},[$.historyPrefetchTimedOut]),Pt=c.useCallback(P=>{const D=zc(P,{currentActiveSessionId:s.current,currentCwd:ve});lt(D.page,!1),f(D.page.nextCursor),S(D.page.inventoryVersion),D.messages&&D.activeSessionId&>(D.activeSessionId,D.messages),C(D.activeSessionId),D.activeAgent&&Se(D.activeAgent),D.activeCwd&&xe(D.activeCwd),D.activeApprovalMode&&A(D.activeApprovalMode),D.questionAnswers&&T(D.questionAnswers),m.current=new Set(D.respondingSessionIds),I(m.current),L(D.pendingApprovals),B(D.pendingQuestions),H(D.pendingQueues),xt(P.sessions),wt(P.sessions,new Set(D.respondingSessionIds))},[ve,xt,gt,wt,lt]),Kt=c.useCallback(async()=>{const P=n.current;if(!P?.isConnected)return;const D=await P.request({action:"reconnect.snapshot",id:P.makeId("snapshot"),activeSessionId:s.current??void 0,activeAgent:Xe?.agent??se,agent:Q==="all"?void 0:Q,search:z.trim()||void 0,sinceMs:gr(K),hideArchived:J,skipGitMetadata:!0});Pt(D.snapshot)},[Xe?.agent,se,Pt,J,z,Q,K]),Dt=c.useRef(Me.length);Xt(Dt,Me.length);const Ut=c.useCallback(async P=>{const D=n.current;if(!D?.isConnected)return;const O=await D.request({action:"sessions.list",id:D.makeId(P?.append?"sessions_more":"sessions"),limit:P?.preserveLoaded?Math.max(pr,Dt.current):pr,cursor:P?.cursor,agent:Q==="all"?void 0:Q,search:z.trim()||void 0,sinceMs:gr(K),hideArchived:J,skipGitMetadata:!0,force:P?.force}),te=ki(O);lt(te,P?.append),C(Ne=>Ne??te.sessions[0]?.sessionId??null),xt(te.sessions),wt(te.sessions)},[J,xt,wt,z,Q,lt,K]),Gt=c.useCallback(async(P,D)=>{const O=n.current;if(O?.isConnected)try{const[te,Ne,dt]=await Promise.all([O.request({action:"models.list",id:O.makeId("models"),agent:P}),O.request({action:"usage.limits.fetch",id:O.makeId("usage"),agent:P}),O.request({action:"skills.list",id:O.makeId("skills"),cwd:D||void 0})]);Be(Lt=>({...Lt,[P]:te.options??[]})),ke(Lt=>({...Lt,[P]:Ne})),le(Array.isArray(dt.skills)?dt.skills:[])}catch(te){k(te instanceof Error?te.message:String(te))}},[]),qt=c.useCallback((P,D,O="info")=>{const te=n.current;te?.isConnected&&te.request({action:"log.report",id:te.makeId("log"),entries:[{level:O,event:P,data:D,ts:new Date().toISOString()}]}).catch(()=>{})},[]);sf(qt);const _t=c.useCallback(async(P=h.current)=>{if(!P){je(or);return}je(D=>({...D,loading:!0,error:null}));try{const D=await fetch(qu(P,window.location,{sameOrigin:!1}),{cache:"no-store"});if(!D.ok)throw new Error(`HTTP ${D.status}`);const O=zu(await D.json().catch(()=>null));je({...O,loading:!1,error:null})}catch{je(D=>({...D,loading:!1,error:$.connectorVersionFailed}))}},[$.connectorVersionFailed]);c.useEffect(()=>{const P=()=>{ue(Is()),me(Sn())};return window.addEventListener("vibelet.notifications.changed",P),()=>window.removeEventListener("vibelet.notifications.changed",P)},[]),c.useEffect(()=>{V==="admin"&&g==="connected"&&_t()},[V,g,_t]);const Vt=c.useCallback(P=>{ue(D=>{const O={...D,...P};return a.current=O,yc(O),O})},[]),Qt=c.useCallback((P,D)=>{!P||!D||P===D||(C(O=>O===P?D:O),l.current===P&&(l.current=D),yt.current===P&&(yt.current=D),bt(P,D),m.current=yr(m.current,P,D),I(O=>yr(O,P,D)),L(O=>gs(O,P,D)),B(O=>gs(O,P,D)),e.remapPendingQueue(P,D),H(O=>gs(O,P,D)),p(O=>{const te=O[P];if(!te)return O;const Ne={...O};return delete Ne[P],Ne[D]={...te,sessionId:D},Ne}),W(O=>{const te=Lh(O,P,D);return te!==O&&(o.current=te,Rn(te)),te}))},[]);return{...e,...t,attachments:Je,setAttachments:Pe,uploadBusy:Ve,directory:Ee,setDirectory:fe,newDirName:Z,setNewDirName:he,remoteFile:Ce,setRemoteFile:U,remoteFileConflict:G,uploadFiles:pe,openRemoteFile:N,saveRemoteFile:Ie,downloadRemoteFile:De,listDirectory:ht,listSessionDirectories:Rt,listFileTreeDirectory:Ye,createDirectory:ge,createSessionDirectory:kt,pendingActionsCount:ft,activeQueue:jt,activeModelOptions:ot,activeUsage:Ct,activeApproval:mt,activeQuestion:Tt,activeSession:Xe,displaySessions:Oe,groupedSessions:It,pendingSessionIds:At,visibleSessions:Ue,appendCachedDelta:ct,appendCachedHistory:_,appendInfoMessage:q,clearHistoryLoading:re,ensureCachedHistoryEntry:Re,setCachedMessageDelivery:et,resolveCachedMessageSession:ye,historyCacheRef:st,historyLoading:rt,historyPageStartRef:pt,hydrateVisibleHistory:gt,messages:Te,messagesSessionIdRef:yt,mergeCachedHistoryPage:vt,remapCachedHistory:bt,removeCachedHistory:it,renderCachedHistory:Le,replaceCachedHistory:at,requestHistory:Ot,setMessages:Ht,updateDraft:Wt,updateNewSessionDraft:Mt,setSessionsFromPage:lt,hydrateGitMetadata:xt,prefetchActiveHistories:wt,applyReconnectSnapshot:Pt,requestReconnectSnapshot:Kt,requestSessions:Ut,fetchAgentResources:Gt,reportLog:qt,refreshDaemonMetadata:_t,updateNotificationSettings:Vt,remapLocalSessionState:Qt}}function Sf(){const e=wf(),t=c.useRef(void 0),n=Bh(e),{initialSavedTargetsRef:s,composerDraftsRef:i,lastHistorySessionIdRef:a,respondingSessionsRef:o,phase:l,setErrorText:d,pairing:h,setSessions:u,pendingSessions:m,activeSessionId:g,setActiveSessionId:y,setRespondingSessions:k,setPendingApprovals:x,setPendingQuestions:b,setPendingQueues:p,setLivePendingQueue:f,agent:v,setAgent:S,cwd:j,setCwd:C,setApprovalMode:w,setModel:I,setEffort:E,setFastMode:L,setRenameTitle:Y,setDraft:B,archiveSyncedDaemonIds:T,archiveSyncCardDismissedDaemonIds:X,setControlTabAndOpen:H,daemonMetadata:se,notificationPermission:Se,setDirectory:ve,displaySessions:xe,appendInfoMessage:A,clearHistoryLoading:M,messagesSessionIdRef:W,renderCachedHistory:z,replaceCachedHistory:K,requestHistory:J,setMessages:Q,requestSessions:oe,remapLocalSessionState:$,attachments:V,setAttachments:ee,listDirectory:Ge,activeApproval:we,activeQuestion:Be,activeSession:ae,appendCachedDelta:ke,appendCachedHistory:le,ensureCachedHistoryEntry:je,setCachedMessageDelivery:de,resolveCachedMessageSession:ue,historyCacheRef:ce,messages:me,mergeCachedHistoryPage:Me,removeCachedHistory:He,updateDraft:Ke,setSessionsFromPage:Ze,requestReconnectSnapshot:$e,fetchAgentResources:Ce,reportLog:Je,refreshDaemonMetadata:Pe,updateNotificationSettings:Ve,clientRef:Ee,connectWithPairingRef:fe,activeSessionIdRef:Z,notificationPermissionRef:he,notificationSettingsRef:U,historyCacheDaemonIdRef:G,pairingRef:pe,notifiedEventsRef:N,reconnectTimerRef:Ie,connectionAttemptIdRef:De,turnNotificationCountsRef:ht,intentionalDisconnectRef:Rt,setPhase:Ye,setStatusText:ge,setPairing:kt,setPendingSessions:ft,setOptimisticSessions:jt,questionAnswers:ot,setQuestionAnswers:Ct,approvalMode:Xe,continueSession:mt,model:Tt,effort:Oe,fastMode:It,renameTitle:At,setComposerDrafts:Ue,draft:st,search:pt,sinceFilter:gt,savedTargets:yt,setSavedTargets:bt,saveTargets:ct,updateSessionListPreferences:_,t:q,busy:re,setBusy:Re,setDetailsOpen:et,setAdmin:ye,setDaemonMetadata:rt,setNotificationPermission:Te,archiveSyncBusy:vt,setArchiveSyncBusy:it,setArchiveSyncStatus:Le}=e,at=c.useCallback(async(R,be,We)=>{const ie=typeof We.sessionId=="string"?We.sessionId:R,ut=typeof We.oldSessionId=="string"?We.oldSessionId:R;ut&&ie&&ut!==ie&&$(ut,ie),be.name==="clear"?(K(ie,[]),p(Ft=>{const Qe={...Ft};return delete Qe[ie],delete Qe[ut],Qe}),x(Ft=>{const Qe={...Ft};return delete Qe[ie],delete Qe[ut],Qe}),b(Ft=>{const Qe={...Ft};return delete Qe[ie],delete Qe[ut],Qe}),y(ie)):be.name==="new"?(y(ie),W.current=ie,z(ie)):be.name==="exit"?(u(Ft=>Ft.map(Qe=>Qe.sessionId===ie?{...Qe,archived:!0}:Qe)),y(null),W.current=null,a.current=null,Q([])):be.name==="goal"&&"goal"in We&&A(ie,mc(We.goal)),We.turnStarted&&!We.queued&&(o.current=new Set(o.current).add(ie),k(Ft=>new Set(Ft).add(ie))),await oe({force:!0})},[A,$,z,K,oe]),Ot=Dh({notificationSettingsRef:U,notifiedEventsRef:N,notificationPermissionRef:he,activeSessionIdRef:Z,respondingSessionsRef:o,turnNotificationCountsRef:ht,t:q,setActiveSessionId:y,setErrorText:d,setPendingQueues:p,setLivePendingQueue:f,setPendingApprovals:x,setPendingQuestions:b,setQuestionAnswers:Ct,setRespondingSessions:k,setSessions:u,remapLocalSessionState:$,requestSessions:oe,clearHistoryLoading:M,replaceCachedHistory:K,mergeCachedHistoryPage:Me,appendCachedHistory:le,appendCachedDelta:ke});Ch({clientRef:Ee,connectWithPairingRef:fe,pairingRef:pe,reconnectTimerRef:Ie,connectionAttemptIdRef:De,intentionalDisconnectRef:Rt,historyCacheRef:ce,historyCacheDaemonIdRef:G,messagesSessionIdRef:W,lastHistorySessionIdRef:a,rememberedTarget:s.current[0]??null,agent:v,cwd:j,phase:l,search:pt,sinceFilter:gt,t:q,handleServerMessage:Ot,setPhase:Ye,setStatusText:ge,setErrorText:d,setMessages:Q,setPairing:kt,setSavedTargets:bt,setSessionsFromPage:Ze,refreshDaemonMetadata:Pe,requestReconnectSnapshot:$e,fetchAgentResources:Ce,reportLog:Je,requestSessions:oe}),c.useEffect(()=>{const R=xe.find(ut=>ut.sessionId===g);if(!R){a.current=null,W.current=null,M(),Q([]),B(An(i.current,null));return}S(R.agent),C(R.cwd||tt),E(R.effort??""),L(R.fastMode??!1),w(R.approvalMode??Gs),Y(R.customTitle??R.title??""),B(An(i.current,R.sessionId));const be=t.current,We=`${h?.daemonId}:${R.sessionId}`;t.current=We;const ie=en();if(ve(ut=>Hh(ut,be,We,R.cwd||tt,ie.folder||ie.cwd)),m[R.sessionId]){a.current=R.sessionId,M(),W.current!==R.sessionId&&(W.current=R.sessionId,Q([]));return}if(z(R.sessionId)){const ut=a.current!==R.sessionId;a.current=R.sessionId,M(R.sessionId),ut&&J(R);return}a.current!==R.sessionId&&(a.current=R.sessionId,W.current!==R.sessionId&&(W.current=R.sessionId,Q([])),J(R))},[g,M,xe,m,z,J]);const Ht=qh({daemonId:h?.daemonId,session:ae,setModel:I,setPendingSessions:ft}),{stagePendingSession:Mt,failedSend:Wt,dismissFailedSend:lt,retryFailedSend:xt,sendDraft:wt}=Wh({clientRef:Ee,activeSessionIdRef:Z,composerDraftsRef:i,lastHistorySessionIdRef:a,messagesSessionIdRef:W,respondingSessionsRef:o,agent:v,cwd:j,approvalMode:Xe,continueSession:mt,model:Tt,effort:Oe,fastMode:It,activeSessionId:g,activeSession:ae,pendingSessions:m,draft:st,busy:re,attachments:V,t:q,setPendingSessions:ft,setOptimisticSessions:jt,setComposerDrafts:Ue,setCwd:C,setAgent:S,setActiveSessionId:y,setMessages:Q,setDraft:B,setErrorText:d,setBusy:Re,setAttachments:ee,setRespondingSessions:k,clearHistoryLoading:M,reportLog:Je,remapLocalSessionState:$,requestSessions:oe,updateDraft:Ke,appendCachedHistory:le,ensureCachedHistoryEntry:je,setCachedMessageDelivery:de,resolveCachedMessageSession:ue,renderCachedHistory:z,handleSessionCommandResponse:at,appendInfoMessage:A}),{respondApproval:Pt,respondQuestion:Kt,cancelQuestion:Dt,setQuestionChoice:Ut,requestActiveAction:Gt,interruptActiveSession:qt,retrySessions:_t,updateApprovalMode:Vt,cancelQueuedTurn:Qt,setSessionPinned:P,setSessionArchived:D,deleteSession:O,updatePinned:te,updateArchived:Ne,renameSession:dt}=$h({clientRef:Ee,activeSessionIdRef:Z,composerDraftsRef:i,lastHistorySessionIdRef:a,messagesSessionIdRef:W,respondingSessionsRef:o,activeApproval:we,activeQuestion:Be,activeSession:ae,activeSessionId:g,questionAnswers:ot,pendingSessions:m,phase:l,renameTitle:At,setBusy:Re,setErrorText:d,setPendingApprovals:x,setPendingQuestions:b,setQuestionAnswers:Ct,setPendingQueues:p,setActiveSessionId:y,setMessages:Q,setApprovalMode:w,setSessions:u,setPendingSessions:ft,setComposerDrafts:Ue,setDraft:B,setDetailsOpen:et,setRespondingSessions:k,setOptimisticSessions:jt,removeCachedHistory:He,requestSessions:oe}),{runArchiveSync:Lt,skipArchiveSync:an,runAdminAction:on,exportActiveSession:fn,clearPairing:_n,setNotificationsEnabled:Ln,connectSavedTarget:Fn,forgetSavedTarget:mn,openSessionDetails:$n,editFolderTags:pn,browseFolder:cs,copyResumeCommand:cr,resumeInTerminal:ls}=gh({clientRef:Ee,pairingRef:pe,connectWithPairingRef:fe,notificationPermissionRef:he,intentionalDisconnectRef:Rt,connectionAttemptIdRef:De,historyCacheRef:ce,historyCacheDaemonIdRef:G,messagesSessionIdRef:W,lastHistorySessionIdRef:a,displaySessions:xe,pairing:h,t:q,archiveSyncBusy:vt,daemonMetadata:se,activeSession:ae,messages:me,notificationPermission:Se,savedTargets:yt,setArchiveSyncBusy:it,setArchiveSyncStatus:Le,setSessions:u,setAdmin:ye,setErrorText:d,setNotificationPermission:Te,setStatusText:ge,setMessages:Q,setPairing:kt,setDaemonMetadata:rt,setPhase:Ye,setActiveSessionId:y,setRenameTitle:Y,setDetailsOpen:et,setControlTab:H,updateSessionListPreferences:_,requestSessions:oe,refreshDaemonMetadata:Pe,updateNotificationSettings:Ve,saveTargets:ct,listDirectory:Ge}),ds=c.useCallback(async R=>{const be=Ee.current;return be?.isConnected?(await be.request({action:"models.list",id:be.makeId("models"),agent:R})).options??[]:[]},[]),us=Se==="denied"||Se==="unsupported",hs=!!(se.version&&se.latestVersion&&Ji(se.version,se.latestVersion)),Zt=h?.daemonId,lr=!!(Zt&&T[Zt]),dr=!!(Zt&&X[Zt]),ur=Ih(e);return{...e,setModel:Ht,queueControls:ur,listSessionModels:ds,rewindMessage:n,handleSessionCommandResponse:at,handleServerMessage:Ot,failedSend:Wt,dismissFailedSend:lt,retryFailedSend:xt,stagePendingSession:Mt,sendDraft:wt,respondApproval:Pt,respondQuestion:Kt,cancelQuestion:Dt,setQuestionChoice:Ut,requestActiveAction:Gt,interruptActiveSession:qt,retrySessions:_t,updateApprovalMode:Vt,cancelQueuedTurn:Qt,setSessionPinned:P,setSessionArchived:D,deleteSession:O,updatePinned:te,updateArchived:Ne,renameSession:dt,runArchiveSync:Lt,skipArchiveSync:an,runAdminAction:on,exportActiveSession:fn,clearPairing:_n,setNotificationsEnabled:Ln,connectSavedTarget:Fn,forgetSavedTarget:mn,openSessionDetails:$n,editFolderTags:pn,browseFolder:cs,copyResumeCommand:cr,resumeInTerminal:ls,notificationsBlocked:us,hasDaemonUpdate:hs,activeDaemonId:Zt,archiveSynced:lr,archiveSyncDismissed:dr}}const kf=c.lazy(()=>nt(()=>import("./NewSessionDialog-tL5HWBLl.js"),__vite__mapDeps([20,1,2,12,21]))),jf=c.lazy(()=>nt(()=>import("./GlobalPendingDialog-DpTYtgOQ.js"),__vite__mapDeps([22,1,2])));function Cf(){return r.jsx(cu,{children:r.jsx(If,{})})}function If(){const[e,t]=c.useState(!0),[n,s]=c.useState(!1),i=Sf();ah(i);const[a,o]=c.useState(null);c.useEffect(()=>{const R=()=>o(ie=>ie??{cwd:i.cwd}),be=ne().subscribeCommand?.(ie=>{ie==="new-session"&&R()}),We=ie=>{ne().kind==="browser"&&(ie.metaKey||ie.ctrlKey)&&!ie.altKey&&!ie.shiftKey&&ie.key.toLowerCase()==="n"&&(ie.preventDefault(),R())};return window.addEventListener("keydown",We),()=>{be?.(),window.removeEventListener("keydown",We)}},[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"||ne().kind==="desktop"&&i.controlTab==="admin")&&i.setControlTab("files");const R=()=>i.setControlTabAndOpen("admin");return window.addEventListener("vibelet.browser.settings",R),()=>window.removeEventListener("vibelet.browser.settings",R)},[i.controlTab,i.setControlTab,i.setControlTabAndOpen]),c.useEffect(()=>{i.activeQuestion&&i.setQuestionAnswers(Qs(i.activeQuestion))},[i.activeQuestion,i.setQuestionAnswers]);const{clientRef:l,phase:d,statusText:h,errorText:u,pairing:m,sessions:g,nextCursor:y,folderCounts:k,inventoryVersion:x,activeSessionId:b,setActiveSessionId:p,diffSessionId:f,setDiffSessionId:v,respondingSessions:S,questionAnswers:j,agent:C,cwd:w,approvalMode:I,model:E,setModel:L,effort:Y,setEffort:B,fastMode:T,setFastMode:X,renameTitle:H,setRenameTitle:se,draft:Se,webPreferences:ve,search:xe,setSearch:A,sinceFilter:M,setSinceFilter:W,hideArchived:z,setHideArchived:K,groupFolders:J,setGroupFolders:Q,showNeedsAttentionGroup:oe,setShowNeedsAttentionGroup:$,showRunningGroup:V,setShowRunningGroup:ee,separatePinnedGroup:Ge,setSeparatePinnedGroup:we,collapsedFolders:Be,setCollapsedFolders:ae,sessionAgentFilter:ke,setSessionAgentFilter:le,directoryTags:je,composerPreferences:de,savedTargets:ue,leftSidebarCollapsed:ce,setLeftSidebarCollapsed:me,rightSidebarCollapsed:Me,setRightSidebarCollapsed:He,workspaceClassName:Ke,wideMainClassName:Ze,workspaceStyle:$e,beginPaneResize:Ce,commitSearch:Je,saveTargets:Pe,setLanguagePreference:Ve,setThemePreference:Ee,updateComposerPreferences:fe,t:Z,busy:he,rewindMessage:U,controlTab:G,setControlTab:pe,detailsOpen:N,setDetailsOpen:Ie,setControlTabAndOpen:De,skills:ht,admin:Rt,daemonMetadata:Ye,notificationSettings:ge,notificationPermission:kt,archiveSyncBusy:ft,archiveSyncStatus:jt,attachments:ot,setAttachments:Ct,uploadBusy:Xe,directory:mt,newDirName:Tt,setNewDirName:Oe,remoteFile:It,uploadFiles:At,openRemoteFile:Ue,listDirectory:st,listSessionDirectories:pt,listFileTreeDirectory:gt,createDirectory:yt,createSessionDirectory:bt,pendingActionsCount:ct,activeQueue:_,activeModelOptions:q,activeUsage:re,activeApproval:Re,activeQuestion:et,activeSession:ye,displaySessions:rt,groupedSessions:Te,pendingSessionIds:vt,visibleSessions:it,historyLoading:Le,messages:at,messagesSessionIdRef:Ot,updateDraft:Ht,requestReconnectSnapshot:Mt,requestSessions:Wt,fetchAgentResources:lt,failedSend:xt,dismissFailedSend:wt,retryFailedSend:Pt,stagePendingSession:Kt,listSessionModels:Dt,sendDraft:Ut,respondApproval:Gt,respondQuestion:qt,cancelQuestion:_t,setQuestionChoice:Vt,requestActiveAction:Qt,interruptActiveSession:P,retrySessions:D,updateApprovalMode:O,cancelQueuedTurn:te,setSessionPinned:Ne,setSessionArchived:dt,deleteSession:Lt,updatePinned:an,updateArchived:on,renameSession:fn,runArchiveSync:_n,skipArchiveSync:Ln,runAdminAction:Fn,exportActiveSession:mn,clearPairing:$n,setNotificationsEnabled:pn,connectSavedTarget:cs,forgetSavedTarget:cr,openSessionDetails:ls,editFolderTags:ds,copyResumeCommand:us,resumeInTerminal:hs,notificationsBlocked:Zt,hasDaemonUpdate:lr,archiveSynced:dr,archiveSyncDismissed:ur}=i;return d==="missing-pair"?r.jsxs(r.Fragment,{children:[r.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:Z.skipToConversation}),r.jsx(ru,{errorText:u,t:Z})]}):r.jsxs("main",{className:Ke,id:"vibelet-workspace",style:$e,children:[a&&r.jsx(c.Suspense,{fallback:null,children:r.jsx(kf,{cwd:a.cwd,agent:C,device:m?.daemonId??"disconnected",connected:d==="connected",approvalMode:I,model:E,t:Z,onClose:()=>o(null),onCreate:Kt,onListModels:Dt,onListDirectories:pt,onCreateDirectory:bt})}),r.jsx("a",{className:"skip-link",href:"#vibelet-main-content",children:Z.skipToConversation}),r.jsx($u,{collapsed:ce,onExpand:()=>me(R=>!R),onResize:Ce("left"),t:Z,children:r.jsx(Fu,{activeDaemonId:m?.daemonId,activeSessionId:b,busy:he,collapsedFolders:Be,currentCwd:w,directoryTags:je,displayName:m?.displayName,savedTargets:ue,folderCounts:k,groupFolders:J,groupedSessions:Te,hideArchived:z,separatePinnedGroup:Ge,showNeedsAttentionGroup:oe,showRunningGroup:V,inventoryVersion:x,nextCursor:y,phase:d,respondingSessionIds:S,search:xe,sessionAgentFilter:ke,sessionsCount:rt.length,sinceFilter:M,statusText:h,t:Z,visibleSessions:it,onLoadMore:R=>Wt({append:!0,cursor:R}),onCopyResumeCommand:us,onResumeInTerminal:hs,onConnectTarget:cs,pendingSessionIds:vt,onRequestNewSession:R=>o({cwd:R??w}),onDeleteSession:R=>{Lt(R)},onEditFolderTags:ds,onOpenSessionDetails:ls,onResetFilters:()=>{le("all"),W("30d"),K(!1),Q(!0),$(!1),ee(!1),we(!1)},onRenameTarget:(R,be)=>Pe(uh(ue,R,be)),onSearchChange:A,onSearchCommit:Je,onSelectSession:p,onToggleSessionArchived:R=>{dt(R,!R.archived)},onToggleSessionPinned:R=>{Ne(R,!R.pinned)},onSessionAgentFilterChange:le,onSinceFilterChange:W,onToggleFolder:R=>ae(be=>({...be,[R]:!be[R]})),onToggleGroupFolders:()=>Q(R=>!R),onToggleHideArchived:()=>K(R=>!R),onToggleNeedsAttentionGroup:()=>{i.toggleSessionViewGroup("needsAttention")},onToggleRunningGroup:()=>{i.toggleSessionViewGroup("running")},onToggleSeparatePinnedGroup:()=>{i.toggleSessionViewGroup("pinned")},onToggleCollapse:()=>me(!0)})}),r.jsxs("section",{className:Ze,"aria-label":Z.vibeletWorkspace,id:"vibelet-main-content",tabIndex:-1,children:[r.jsx(ih,{workspace:i,children:r.jsx(Id,{activeSession:ye,activeSessionId:b,activeModelOptions:q,activeQueue:_,activeUsage:re,agent:C,approvalMode:I,attachments:ot,busy:he,cwd:w,draft:Se,effort:Y,errorText:u,failedSend:xt,onDismissFailedSend:wt,fastMode:T,historyLoading:Le,messages:at,messagesSessionId:Ot.current,model:E,phase:d,quickReplies:de.quickReplies,renameTitle:H,respondingSessionIds:S,sendShortcut:de.sendShortcut,skills:ht,uploadBusy:Xe,detailsOpen:N,t:Z,onApprovalModeChange:R=>{O(R)},onBrowseFiles:()=>{const R=ye?.cwd||w||tt;De("files"),st(R,{updateRoute:!0})},queueControls:i.queueControls,onCancelQueuedTurn:R=>{te(R)},onClearInterrupt:()=>{Qt("session.clearInterrupt")},onDraftChange:Ht,onDetailsOpenChange:Ie,onEffortChange:B,onExportActiveSession:()=>{mn()},onRewindMessage:R=>{U(R)},onFastModeChange:X,onRetryFailedSend:Pt,onModelChange:L,onOpenRemoteFile:(R,be)=>{Ue(R,be,{updateRoute:!0})},onInterrupt:P,onDismissError:()=>i.setErrorText(null),onRetry:D,onRenameSession:()=>{fn()},onRenameTitleChange:se,onRemoveAttachment:R=>Ct(be=>be.filter(We=>We.path!==R)),onRefreshSkills:()=>{lt(ye?.agent??C,w)},onSubmit:Ut,onToggleArchived:()=>{on()},onTogglePinned:()=>{an()},onUploadFiles:At,onViewChanges:v})}),r.jsxs(Xu,{collapsed:Me,t:Z,value:G,showSession:!1,onChange:pe,onResize:Ce("right"),children:[G==="files"?r.jsx(c.Suspense,{fallback:r.jsx(Dr,{t:Z}),children:r.jsx(xu,{busy:he,cwd:w,directory:mt,onLoadChildren:gt,newDirName:Tt,remoteFile:It,t:Z,onCreateDirectory:()=>{yt()},onListDirectory:R=>{st(R,{updateRoute:!0})},onNewDirNameChange:Oe,onOpenRemoteFile:(R,be)=>{Ue(R,be,{updateRoute:!0})}},`${m?.daemonId}:${w}`)}):null,n?r.jsxs("div",{hidden:G!=="terminal",className:"terminal-tab-content",children:[r.jsx(_s,{location:"right",kind:"terminal",t:Z,cwd:w===tt?mt.path:w}),r.jsx(Zn,{location:"right",kind:"terminal"})]}):null,e?r.jsxs("div",{hidden:G!=="browser",className:"browser-tab-content",children:[r.jsx(_s,{location:"right",kind:"browser",t:Z}),r.jsx(Zn,{location:"right",kind:"browser"})]}):null,G==="admin"?r.jsxs(c.Suspense,{fallback:r.jsx(Dr,{t:Z}),children:[r.jsx(wu,{language:ve.language,t:Z,onLanguageChange:Ve}),!ne().settingsTarget&&r.jsx(Qu,{}),r.jsx(Su,{t:Z,theme:ve.theme,onThemeChange:Ee}),r.jsx(ku,{notificationsBlocked:Zt,permission:kt,settings:ge,t:Z,onToggleEnabled:pn}),!ne().settingsTarget&&r.jsx(Fr,{workspace:i})]}):null]})]}),ne().settingsTarget&&r.jsx(Fr,{workspace:i,portalOnly:!0}),r.jsx("div",{className:"workspace-header-actions",children:r.jsx(ac,{activeSession:ye,busy:he,controlsOpen:!Me,t:Z,onOpenControls:()=>{Me&&ct===0&&G==="session"&&pe("files"),He(R=>!R)},onRefreshSessions:()=>{Wt({force:!0})},onRestoreSnapshot:()=>{Mt()},onToggleArchived:()=>{on()},onTogglePinned:()=>{an()},onViewChanges:v})}),ct>0&&r.jsx(c.Suspense,{fallback:null,children:r.jsx(jf,{activeApproval:Re,activeQuestion:et,pendingCount:ct,requestKey:JSON.stringify([...Object.values(i.pendingApprovals),...Object.values(i.pendingQuestions)].map(R=>JSON.stringify([R.sessionId,R.requestId])).sort()),sessions:g,busy:he,errorText:u,questionAnswers:j,t:Z,onCancelQuestion:()=>{_t()},onQuestionChoice:Vt,onRespondApproval:R=>{Gt(R)},onRespondQuestion:()=>{qt()}})}),r.jsx(au,{}),r.jsx(pu,{onOpenRight:De,client:d==="connected"?l.current:null,daemonId:m?.daemonId,deviceName:m?.displayName??"",controlTab:G,rightVisible:!Me,t:Z}),r.jsx(Cu,{activeSession:ye,client:l.current,close:()=>v(null),id:f,sessions:g,t:Z})]})}const Df=Object.freeze(Object.defineProperty({__proto__:null,App:Cf},Symbol.toStringTag,{value:"Module"}));export{Vr as A,Pn as B,$t as C,ns as D,Df as E,su as F,Xr as G,ho as I,po as K,es as L,fd as M,Co as P,kn as R,zs as S,li as T,_e as X,hn as a,yu as b,Yr as c,Mc as d,Un as e,Bt as f,xn as g,ms as h,sr as i,Lc as j,Ef as k,gu as l,Pf as m,ln as n,Ea as o,Af as p,eo as q,Nn as r,Qr as s,St as t,hd as u,Zr as v,Ni as w,Mf as x,Rf as y,Tf as z};
|