@tencent-ai/agent-sdk 0.3.245-dev.cd0b453.202608251505 → 0.3.246
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/cli/CHANGELOG.md +33 -0
- package/cli/dist/codebuddy-headless.js +228 -293
- package/cli/dist/web-ui/assets/{CanvasPaneStandaloneView-Cmwt9Y8a.js → CanvasPaneStandaloneView-BD_qZwpK.js} +1 -1
- package/cli/dist/web-ui/assets/{CanvasView-kh-VwNZt.js → CanvasView-BAUxFLH1.js} +1 -1
- package/cli/dist/web-ui/assets/{ChangesView-LyTT64_e.js → ChangesView-Bvr-6a62.js} +1 -1
- package/cli/dist/web-ui/assets/{DocsView-DzT0XXMI.js → DocsView-BVidmMmQ.js} +1 -1
- package/cli/dist/web-ui/assets/EditorView-BWnNeB5q.js +75 -0
- package/cli/dist/web-ui/assets/{FileIcon-CiviXX19.js → FileIcon-BsViq6H0.js} +1 -1
- package/cli/dist/web-ui/assets/{KeybindingsView-CYLH1DTg.js → KeybindingsView-QuWWE_H3.js} +1 -1
- package/cli/dist/web-ui/assets/{LogsView-RDobPjF6.js → LogsView-DUMNTy8H.js} +3 -3
- package/cli/dist/web-ui/assets/{MetricsView-0TBamh3L.js → MetricsView-BY2YOvXi.js} +3 -3
- package/cli/dist/web-ui/assets/{PluginsView-CzAIf5_-.js → PluginsView-BzgBeIFp.js} +2 -2
- package/cli/dist/web-ui/assets/{RemoteControlView-CNsCKFhh.js → RemoteControlView-BuKYLVCs.js} +1 -1
- package/cli/dist/web-ui/assets/{SettingsView-B2RLsYo0.js → SettingsView-Bu_9EZ8x.js} +2 -2
- package/cli/dist/web-ui/assets/{SplitContainer-CJB8eH3c.js → SplitContainer-C2WbFxdL.js} +1 -1
- package/cli/dist/web-ui/assets/{StatsView-wHMAAyEJ.js → StatsView-h44ujqat.js} +2 -2
- package/cli/dist/web-ui/assets/{TasksView-DOFeNXmC.js → TasksView-D2q4JOBP.js} +2 -2
- package/cli/dist/web-ui/assets/{TerminalPaneView-BXNcwxsi.js → TerminalPaneView-lhajvnaH.js} +3 -3
- package/cli/dist/web-ui/assets/{TracesView-BtPCpydR.js → TracesView-B5i4emxN.js} +3 -3
- package/cli/dist/web-ui/assets/{WorkersView-sQMhvJ2l.js → WorkersView-Bw2bTNo6.js} +2 -2
- package/cli/dist/web-ui/assets/{canvas-store-0BnkCTHk.js → canvas-store-Smrtng_e.js} +1 -1
- package/cli/dist/web-ui/assets/{cssMode-jwjmt121.js → cssMode-EsOJVYiu.js} +1 -1
- package/cli/dist/web-ui/assets/{download-iNxRYv3J.js → download-BsdRqzY7.js} +1 -1
- package/cli/dist/web-ui/assets/{editor.main-CGYuAeQx.js → editor.main-q4R8cbC1.js} +3 -3
- package/cli/dist/web-ui/assets/{external-link-D5RWsA9l.js → external-link-Ea1Nar0e.js} +1 -1
- package/cli/dist/web-ui/assets/{freemarker2-CX3QfLDV.js → freemarker2-DVmHExbB.js} +1 -1
- package/cli/dist/web-ui/assets/{handlebars-C5TLi2Pr.js → handlebars-Cguwj4ew.js} +1 -1
- package/cli/dist/web-ui/assets/{html-VGWLEWVQ.js → html-DRfZqNG-.js} +1 -1
- package/cli/dist/web-ui/assets/{htmlMode-B7yDtJr6.js → htmlMode-mn7qxh39.js} +1 -1
- package/cli/dist/web-ui/assets/index-BOvl5ICo.css +1 -0
- package/cli/dist/web-ui/assets/{index-CHcoPr8x.js → index-CBmymKHy.js} +180 -175
- package/cli/dist/web-ui/assets/{javascript-rebq-3hM.js → javascript-Dv0-Ka9H.js} +1 -1
- package/cli/dist/web-ui/assets/{jsonMode-CisSEnRa.js → jsonMode-MVrw6wSj.js} +1 -1
- package/cli/dist/web-ui/assets/{liquid-C0GU_tuJ.js → liquid-2HR35IQO.js} +1 -1
- package/cli/dist/web-ui/assets/{lspLanguageFeatures-DdEy47qR.js → lspLanguageFeatures-BA4h_1Zp.js} +1 -1
- package/cli/dist/web-ui/assets/{markdown-DIY6o85n.js → markdown-CP9awqWt.js} +1 -1
- package/cli/dist/web-ui/assets/{mdx-DjEmR07p.js → mdx-CFi7brpM.js} +1 -1
- package/cli/dist/web-ui/assets/{minus-BHON617T.js → minus-Dw9-WG76.js} +1 -1
- package/cli/dist/web-ui/assets/{power-BoeeA3TI.js → power-BJk8Xq9U.js} +1 -1
- package/cli/dist/web-ui/assets/{python-YOuEQ1oe.js → python-BqoHrqNK.js} +1 -1
- package/cli/dist/web-ui/assets/{razor-DTO4iPoC.js → razor-CPnz313K.js} +1 -1
- package/cli/dist/web-ui/assets/{server-Gy9um44Z.js → server-D4446JKI.js} +1 -1
- package/cli/dist/web-ui/assets/{timer-CVn2LoSe.js → timer-D8MX3pYj.js} +1 -1
- package/cli/dist/web-ui/assets/{tsMode-J-jxLo7h.js → tsMode-DMOs1uPQ.js} +1 -1
- package/cli/dist/web-ui/assets/{typescript-BTZe1y3z.js → typescript-CP_zrnR8.js} +1 -1
- package/cli/dist/web-ui/assets/{vendor-D35k0Cos.js → vendor-iLJwFVtf.js} +1 -1
- package/cli/dist/web-ui/assets/{worker-store-CsMfXxjm.js → worker-store-qfd_N8Zm.js} +1 -1
- package/cli/dist/web-ui/assets/{xml-DaZe33xf.js → xml-BNASinsS.js} +1 -1
- package/cli/dist/web-ui/assets/{yaml-yofIoqGl.js → yaml-D_cB1VDT.js} +1 -1
- package/cli/dist/web-ui/assets/{zap-BeZalqcf.js → zap-yafQUspl.js} +1 -1
- package/cli/dist/web-ui/index.html +4 -4
- package/cli/dist/web-ui/sw.js +1 -1
- package/cli/package.json +2 -3
- package/cli/product.cloudhosted.json +4 -2
- package/cli/product.internal.json +4 -2
- package/cli/product.ioa.json +4 -2
- package/cli/product.json +383 -17
- package/cli/product.selfhosted.json +4 -2
- package/cli/vendor/shim/sitecustomize.py +43 -1
- package/package.json +2 -3
- package/cli/dist/web-ui/assets/EditorView-ZUnDw1V1.js +0 -75
- package/cli/dist/web-ui/assets/index-Ddq_addW.css +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as g,j as e}from"./markdown-
|
|
1
|
+
import{a as g,j as e}from"./markdown-CP9awqWt.js";import{c as O,e as W,bg as $,u as D,q as U,b1 as B,bh as K,o as q,aI as J,y as V,bi as X,ab as Y}from"./index-CBmymKHy.js";import{Z as w}from"./zap-yafQUspl.js";import{T as Q}from"./timer-D8MX3pYj.js";import"./vendor-iLJwFVtf.js";/**
|
|
2
2
|
* @license lucide-react v1.18.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -8,5 +8,5 @@ import{a as g,j as e}from"./markdown-DIY6o85n.js";import{c as O,e as W,bf as $,u
|
|
|
8
8
|
*
|
|
9
9
|
* This source code is licensed under the ISC license.
|
|
10
10
|
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const se=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],ne=O("trending-up",se),ae=W((t,a)=>({stats:null,statsLoading:!1,statsError:null,sessionStats:null,sessionLoading:!1,sessionError:null,fetchStats:async()=>{t({statsLoading:!a().stats,statsError:null});try{t({stats:await $("/api/v1/stats"),statsLoading:!1})}catch(n){t({statsError:n.message,statsLoading:!1})}},fetchSessionStats:async()=>{t({sessionLoading:!a().sessionStats,sessionError:null});try{t({sessionStats:await $("/api/v1/stats/session"),sessionLoading:!1})}catch(n){t({sessionError:n.message,sessionLoading:!1})}},fetchAll:async()=>{await Promise.all([a().fetchStats(),a().fetchSessionStats()])}}));function k(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":t.toString()}function P(t){if(t<=0)return"-";const a=Math.floor(t/1e3),n=Math.floor(a/60),r=Math.floor(n/60);return r>0?`${r}h ${n%60}m ${a%60}s`:n>0?`${n}m ${a%60}s`:`${a}s`}function F(t){return t.replace(/^anthropic\./,"").replace(/^openai\./,"").replace(/-\d{8}$/,"").replace(/@.*$/,"")}function oe(t){return new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric"})}const re=["#ebedf0","#9be9a8","#40c463","#30a14e","#216e39"],ie=["#161b22","#0e4429","#006d32","#26a641","#39d353"],z=["#3b82f6","#10b981","#8b5cf6"],le=[{name:"The Little Prince",tokens:22e3},{name:"The Old Man and the Sea",tokens:35e3},{name:"A Christmas Carol",tokens:37e3},{name:"Animal Farm",tokens:39e3},{name:"Fahrenheit 451",tokens:6e4},{name:"The Great Gatsby",tokens:62e3},{name:"Brave New World",tokens:83e3},{name:"Harry Potter and the Philosopher's Stone",tokens:103e3},{name:"1984",tokens:123e3},{name:"Pride and Prejudice",tokens:156e3},{name:"Dune",tokens:244e3},{name:"A Game of Thrones",tokens:381e3},{name:"The Lord of the Rings",tokens:576e3},{name:"War and Peace",tokens:73e4}],ce=[{name:"朝花夕拾",tokens:18e3},{name:"骆驼祥子",tokens:6e4},{name:"活着",tokens:72e3},{name:"围城",tokens:84e3},{name:"三体",tokens:126e3},{name:"射雕英雄传",tokens:234e3},{name:"红楼梦",tokens:438e3},{name:"三国演义",tokens:48e4},{name:"西游记",tokens:492e3},{name:"水浒传",tokens:576e3},{name:"平凡的世界",tokens:6e5},{name:"金庸全集",tokens:636e4}],de=[{en:"a TED talk",zh:"一场 TED 演讲",minutes:18},{en:"an episode of The Office",zh:"一集《办公室》",minutes:22},{en:"listening to Abbey Road",zh:"听一遍《Abbey Road》专辑",minutes:47},{en:"a yoga class",zh:"一节瑜伽课",minutes:60},{en:"a World Cup soccer match",zh:"一场世界杯比赛",minutes:90},{en:"a half marathon (average time)",zh:"一场半程马拉松",minutes:120},{en:"the movie Inception",zh:"电影《盗梦空间》",minutes:148},{en:"watching Titanic",zh:"电影《泰坦尼克号》",minutes:195},{en:"a transatlantic flight",zh:"一趟跨大西洋航班",minutes:420},{en:"a full night of sleep",zh:"一整晚的睡眠",minutes:480}];function xe(t,a,n,r){var m;const s=[],o=r==="zh"?ce:le;if(a>0){for(const l of o)if(a>=l.tokens){const h=a/l.tokens;s.push(h>=2?n("stats.funFact.moreTokens").replace("{times}",String(Math.floor(h))).replace("{book}",l.name):n("stats.funFact.sameTokens").replace("{book}",l.name))}}if(t.longestSession){const l=t.longestSession.duration/6e4;for(const h of de){const u=l/h.minutes;if(u>=2){const d=r==="zh"?h.zh:h.en;s.push(n("stats.funFact.longerSession").replace("{times}",String(Math.floor(u))).replace("{activity}",d))}}}if(s.length===0)return"";const i=Math.floor((((m=t.longestSession)==null?void 0:m.duration)??0)/6e4),c=Math.abs(Math.trunc(a+i))%s.length;return s[c]}function me({dailyModelTokens:t,topModels:a}){const n=g.useMemo(()=>{const o={top:20,right:20,bottom:40,left:60},i=700-o.left-o.right,c=220-o.top-o.bottom;let m=0;for(const y of t)for(const b of a){const p=y.tokensByModel[b.id]||0;p>m&&(m=p)}m===0&&(m=1);const l=a.map((y,b)=>{const p=t.map((N,E)=>{const T=o.left+E/Math.max(t.length-1,1)*i,A=N.tokensByModel[y.id]||0,C=o.top+c-A/m*c;return`${T},${C}`});return t.some(N=>(N.tokensByModel[y.id]||0)>0)?{path:`M${p.join("L")}`,color:z[b%z.length],id:y.id,label:y.label}:null}).filter(Boolean),h=Array.from({length:5},(y,b)=>{const p=m*(1-b/4);return{y:o.top+b/4*c,label:k(Math.round(p))}}),u=Math.min(5,t.length),d=Math.max(1,Math.floor((t.length-1)/(u-1))),M=Array.from({length:u},(y,b)=>{const p=Math.min(b*d,t.length-1);return{x:o.left+p/Math.max(t.length-1,1)*i,label:oe(t[p].date)}});return{W:700,H:220,PAD:o,CW:i,CH:c,lines:l,yGridLines:h,xLabels:M}},[t,a]);return e.jsxs("div",{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("svg",{viewBox:`0 0 ${n.W} ${n.H}`,className:"w-full min-w-[500px]",style:{maxHeight:"240px"},children:[n.yGridLines.map((r,s)=>e.jsxs("g",{children:[e.jsx("line",{x1:n.PAD.left,y1:r.y,x2:n.W-n.PAD.right,y2:r.y,className:"stroke-border-primary",strokeWidth:.5,strokeDasharray:"4 4"}),e.jsx("text",{x:n.PAD.left-8,y:r.y+4,textAnchor:"end",className:"fill-text-tertiary",fontSize:10,children:r.label})]},s)),n.lines.map((r,s)=>e.jsx("path",{d:r.path,fill:"none",stroke:r.color,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},s)),n.xLabels.map((r,s)=>e.jsx("text",{x:r.x,y:n.H-10,textAnchor:"middle",className:"fill-text-tertiary",fontSize:10,children:r.label},s))]})}),e.jsx("div",{className:"flex gap-4 mt-2 justify-center",children:n.lines.map(r=>e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full",style:{backgroundColor:r.color}}),e.jsx("span",{children:r.label})]},r.id))})]})}function he({stats:t}){const{t:a}=D(),n=g.useMemo(()=>Object.entries(t.modelUsage).map(([s,o])=>{const i=o.inputTokens>0?o.cacheReadInputTokens/o.inputTokens*100:0;return{name:s,shortName:o.displayName||F(s),inputTokens:o.inputTokens,outputTokens:o.outputTokens,cacheReadInputTokens:o.cacheReadInputTokens,cacheHitRate:i,total:o.inputTokens+o.outputTokens,costUSD:o.costUSD}}).sort((s,o)=>o.total-s.total),[t.modelUsage]),r=g.useMemo(()=>n.reduce((s,o)=>s+o.total,0),[n]);return n.length===0?e.jsx("div",{className:"text-center py-12 text-text-tertiary",children:a("stats.noData")}):e.jsxs(e.Fragment,{children:[t.dailyModelTokens.length>=2&&e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-sm font-medium text-text-primary mb-3",children:a("stats.tokensPerDay")}),e.jsx(me,{dailyModelTokens:t.dailyModelTokens,topModels:n.slice(0,3).map(s=>({id:s.name,label:s.shortName}))})]}),e.jsx("h2",{className:"text-sm font-medium text-text-primary mb-3",children:a("stats.allModels")}),e.jsx("div",{className:"space-y-3",children:n.map(s=>{const o=r>0?s.total/r*100:0;return e.jsxs("div",{className:"bg-bg-secondary rounded-lg p-3 border border-border-primary",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium text-text-primary",children:s.shortName}),e.jsxs("span",{className:"text-xs text-text-tertiary",children:[o.toFixed(1),"%"]})]}),e.jsx("div",{className:"h-1.5 bg-bg-tertiary rounded-full mb-2",children:e.jsx("div",{className:"h-full rounded-full bg-accent-brand transition-all duration-500",style:{width:`${Math.min(o,100)}%`}})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2 text-xs text-text-secondary",children:[e.jsxs("span",{children:[a("stats.input"),": ",k(s.inputTokens)]}),e.jsxs("span",{children:[a("stats.output"),": ",k(s.outputTokens)]}),s.cacheReadInputTokens>0&&e.jsxs("span",{children:[a("stats.cacheHitRate"),": ",s.cacheHitRate.toFixed(1),"%"]}),s.costUSD>0&&e.jsxs("span",{children:[a("stats.cost"),": $",s.costUSD.toFixed(2)]})]})]},s.name)})})]})}function ue({dailyActivity:t}){const{t:a}=D(),r=U(i=>i.resolved)==="dark"?ie:re,s=g.useMemo(()=>{const u=new Map;for(const x of t)u.set(x.date,x.messageCount);const d=t.map(x=>x.messageCount).filter(x=>x>0).sort((x,L)=>x-L),M=d.length>0?d[Math.floor(d.length*.25)]:0,y=d.length>0?d[Math.floor(d.length*.5)]:0,b=d.length>0?d[Math.floor(d.length*.75)]:0,p=x=>x===0||d.length===0?0:x>=b?4:x>=y?3:x>=M?2:1,v=new Date;v.setHours(0,0,0,0);const N=new Date(v);N.setDate(v.getDate()-v.getDay());const E=new Date(N);E.setDate(E.getDate()-357);const T=[],A=[];let C=-1;const f=new Date(E);for(let x=0;x<52;x++)for(let L=0;L<7;L++){if(f>v){f.setDate(f.getDate()+1);continue}const G=f.getFullYear(),H=String(f.getMonth()+1).padStart(2,"0"),R=String(f.getDate()).padStart(2,"0"),_=`${G}-${H}-${R}`,I=u.get(_)||0;if(L===0&&f.getMonth()!==C){const Z=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];A.push({text:Z[f.getMonth()],x:32+x*14}),C=f.getMonth()}T.push({key:_,x:32+x*14,y:20+L*14,level:p(I),date:_,count:I}),f.setDate(f.getDate()+1)}return{cells:T,monthLabels:A,width:770,height:128,CELL_SIZE:12,TOP_PADDING:20,LEFT_PADDING:32,CELL_GAP:2}},[t]),o=["","Mon","","Wed","","Fri",""];return e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("svg",{width:s.width,height:s.height+30,viewBox:`0 0 ${s.width} ${s.height+30}`,className:"min-w-[500px]",children:[s.monthLabels.map((i,c)=>e.jsx("text",{x:i.x,y:s.TOP_PADDING-6,className:"fill-text-tertiary",fontSize:10,children:i.text},c)),o.map((i,c)=>i?e.jsx("text",{x:s.LEFT_PADDING-6,y:s.TOP_PADDING+c*(s.CELL_SIZE+s.CELL_GAP)+s.CELL_SIZE-2,className:"fill-text-tertiary",fontSize:10,textAnchor:"end",children:i},c):null),s.cells.map(i=>e.jsx("rect",{x:i.x,y:i.y,width:s.CELL_SIZE,height:s.CELL_SIZE,rx:2,fill:r[i.level],children:e.jsxs("title",{children:[i.date,": ",i.count," ",a("stats.heatmap.messages")]})},i.key)),(()=>{const i=s.height+4,c=s.LEFT_PADDING;return e.jsxs("g",{children:[e.jsx("text",{x:c,y:i+10,className:"fill-text-tertiary",fontSize:10,children:a("stats.heatmap.less")}),r.map((m,l)=>e.jsx("rect",{x:c+30+l*(s.CELL_SIZE+2),y:i,width:s.CELL_SIZE,height:s.CELL_SIZE,rx:2,fill:m},l)),e.jsx("text",{x:c+30+5*(s.CELL_SIZE+2)+4,y:i+10,className:"fill-text-tertiary",fontSize:10,children:a("stats.heatmap.more")})]})})()]})})}function pe({sessionStats:t}){const{t:a}=D(),n=g.useMemo(()=>Object.values(t.tokenUsageByModel).reduce((r,s)=>r+s.inputTokens+s.outputTokens,0),[t.tokenUsageByModel]);return e.jsxs("div",{className:"flex flex-wrap gap-3 mb-6 p-3 bg-bg-secondary/50 rounded-xl border border-border-primary/50",children:[e.jsx(S,{label:a("stats.session.title"),icon:e.jsx(te,{size:12})}),e.jsx(S,{label:a("stats.session.apiDuration"),value:P(t.apiDuration)}),e.jsx(S,{label:a("stats.session.wallTime"),value:P(t.runningTime)}),e.jsx(S,{label:a("stats.session.linesAdded"),value:`+${t.fileChangeStats.totalAddedLines}`,valueClass:"text-green-500"}),e.jsx(S,{label:a("stats.session.linesDeleted"),value:`-${t.fileChangeStats.totalDeletedLines}`,valueClass:"text-red-500"}),e.jsx(S,{label:a("stats.session.tokens"),value:k(n)})]})}function S({label:t,value:a,icon:n,valueClass:r}){return e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[n,e.jsx("span",{className:"text-text-tertiary",children:t}),a&&e.jsx("span",{className:`font-medium text-text-primary ${r||""}`,children:a})]})}function j({icon:t,label:a,value:n}){return e.jsxs("div",{className:"bg-bg-secondary rounded-xl p-4 border border-border-primary",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-text-tertiary",children:t}),e.jsx("span",{className:"text-xs font-medium text-text-secondary",children:a})]}),e.jsx("div",{className:"text-lg font-semibold text-text-primary",style:{fontVariantNumeric:"tabular-nums"},children:n})]})}function fe({stats:t,sessionStats:a}){const{t:n,resolved:r}=D(),s=g.useMemo(()=>Object.entries(t.modelUsage).sort(([,l],[,h])=>h.inputTokens+h.outputTokens-(l.inputTokens+l.outputTokens)),[t.modelUsage]),o=g.useMemo(()=>s.reduce((l,[,h])=>l+h.inputTokens+h.outputTokens,0),[s]),i=g.useMemo(()=>{const l=s.reduce((u,[,d])=>u+d.inputTokens,0),h=s.reduce((u,[,d])=>u+d.cacheReadInputTokens,0);return l>0?h/l*100:0},[s]),c=s[0],m=g.useMemo(()=>xe(t,o,n,r),[t,o,n,r]);return e.jsxs(e.Fragment,{children:[a&&e.jsx(pe,{sessionStats:a}),t.dailyActivity.length>0&&e.jsx("div",{className:"mb-6",children:e.jsx(ue,{dailyActivity:t.dailyActivity})}),c&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-4",children:[e.jsx(j,{icon:e.jsx(B,{size:16}),label:n("stats.favoriteModel"),value:c[1].displayName||F(c[0])}),e.jsx(j,{icon:e.jsx(K,{size:16}),label:n("stats.totalTokens"),value:k(o)}),e.jsx(j,{icon:e.jsx(w,{size:16}),label:n("stats.cacheHitRate"),value:`${i.toFixed(1)}%`})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4 mb-6",children:[e.jsx(j,{icon:e.jsx(q,{size:16}),label:n("stats.sessions"),value:k(t.totalSessions)}),e.jsx(j,{icon:e.jsx(Q,{size:16}),label:n("stats.longestSession"),value:t.longestSession?P(t.longestSession.duration):n("stats.na")}),e.jsx(j,{icon:e.jsx(ne,{size:16}),label:n("stats.activeDays"),value:`${t.activeDays}/${t.totalDays}`}),e.jsx(j,{icon:e.jsx(w,{size:16}),label:n("stats.currentStreak"),value:`${t.streaks.currentStreak} ${n("stats.days")}`}),e.jsx(j,{icon:e.jsx(w,{size:16}),label:n("stats.longestStreak"),value:`${t.streaks.longestStreak} ${n("stats.days")}`}),e.jsx(j,{icon:e.jsx(J,{size:16}),label:n("stats.peakHour"),value:t.peakActivityHour!==null?`${t.peakActivityHour}:00-${t.peakActivityHour+1}:00`:n("stats.na")})]}),m&&e.jsx("div",{className:"p-3 bg-bg-secondary/50 rounded-lg border border-border-primary/50 text-sm text-accent-brand",children:m})]})}function ge({toolUsage:t}){var s;const{t:a}=D(),n=t.slice(0,20),r=((s=n[0])==null?void 0:s.count)||0;return n.length===0?e.jsx("div",{className:"text-center py-12 text-text-tertiary",children:a("stats.noData")}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-sm font-medium text-text-primary mb-4",children:a("stats.topTools")}),e.jsx("div",{className:"space-y-2",children:n.map(o=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xs text-text-secondary w-28 text-right truncate font-mono",children:o.toolName}),e.jsx("div",{className:"flex-1 h-6 bg-bg-tertiary rounded overflow-hidden",children:e.jsx("div",{className:"h-full bg-accent-brand/60 rounded transition-all duration-500 flex items-center pl-2",style:{width:`${Math.max(o.count/r*100,2)}%`},children:o.count/r>.15&&e.jsx("span",{className:"text-[10px] text-text-primary font-mono",children:k(o.count)})})}),o.count/r<=.15&&e.jsx("span",{className:"text-xs text-text-tertiary w-12 font-mono",children:k(o.count)})]},o.toolName))})]})}function Se(){const{t}=D(),{stats:a,statsLoading:n,statsError:r,sessionStats:s,fetchAll:o}=ae(),[i,c]=g.useState("overview");if(g.useEffect(()=>{o()},[o]),n&&!a)return e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(V,{size:"large",text:t("stats.loading")})});if(r&&!a)return e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-text-secondary mb-4",children:r}),e.jsx("button",{onClick:o,className:"px-4 py-2 bg-accent-brand text-accent-brand-foreground rounded-lg text-sm",children:t("stats.refresh")})]})});const m=[{key:"overview",label:t("stats.tab.overview")},{key:"models",label:t("stats.tab.models")},{key:"tools",label:t("stats.tab.tools")}];return e.jsxs("div",{className:"flex-1 overflow-auto p-4 md:p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(X,{size:20,className:"text-accent-brand"}),e.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:t("stats.title")})]}),e.jsxs("button",{onClick:o,className:`flex items-center gap-1.5 px-3 py-1.5 text-sm text-text-secondary
|
|
11
|
+
*/const se=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],ne=O("trending-up",se),ae=W((t,a)=>({stats:null,statsLoading:!1,statsError:null,sessionStats:null,sessionLoading:!1,sessionError:null,fetchStats:async()=>{t({statsLoading:!a().stats,statsError:null});try{t({stats:await $("/api/v1/stats"),statsLoading:!1})}catch(n){t({statsError:n.message,statsLoading:!1})}},fetchSessionStats:async()=>{t({sessionLoading:!a().sessionStats,sessionError:null});try{t({sessionStats:await $("/api/v1/stats/session"),sessionLoading:!1})}catch(n){t({sessionError:n.message,sessionLoading:!1})}},fetchAll:async()=>{await Promise.all([a().fetchStats(),a().fetchSessionStats()])}}));function k(t){return t>=1e6?(t/1e6).toFixed(1)+"M":t>=1e3?(t/1e3).toFixed(1)+"k":t.toString()}function I(t){if(t<=0)return"-";const a=Math.floor(t/1e3),n=Math.floor(a/60),r=Math.floor(n/60);return r>0?`${r}h ${n%60}m ${a%60}s`:n>0?`${n}m ${a%60}s`:`${a}s`}function F(t){return t.replace(/^anthropic\./,"").replace(/^openai\./,"").replace(/-\d{8}$/,"").replace(/@.*$/,"")}function oe(t){return new Date(t).toLocaleDateString("en-US",{month:"short",day:"numeric"})}const re=["#ebedf0","#9be9a8","#40c463","#30a14e","#216e39"],ie=["#161b22","#0e4429","#006d32","#26a641","#39d353"],z=["#3b82f6","#10b981","#8b5cf6"],le=[{name:"The Little Prince",tokens:22e3},{name:"The Old Man and the Sea",tokens:35e3},{name:"A Christmas Carol",tokens:37e3},{name:"Animal Farm",tokens:39e3},{name:"Fahrenheit 451",tokens:6e4},{name:"The Great Gatsby",tokens:62e3},{name:"Brave New World",tokens:83e3},{name:"Harry Potter and the Philosopher's Stone",tokens:103e3},{name:"1984",tokens:123e3},{name:"Pride and Prejudice",tokens:156e3},{name:"Dune",tokens:244e3},{name:"A Game of Thrones",tokens:381e3},{name:"The Lord of the Rings",tokens:576e3},{name:"War and Peace",tokens:73e4}],ce=[{name:"朝花夕拾",tokens:18e3},{name:"骆驼祥子",tokens:6e4},{name:"活着",tokens:72e3},{name:"围城",tokens:84e3},{name:"三体",tokens:126e3},{name:"射雕英雄传",tokens:234e3},{name:"红楼梦",tokens:438e3},{name:"三国演义",tokens:48e4},{name:"西游记",tokens:492e3},{name:"水浒传",tokens:576e3},{name:"平凡的世界",tokens:6e5},{name:"金庸全集",tokens:636e4}],de=[{en:"a TED talk",zh:"一场 TED 演讲",minutes:18},{en:"an episode of The Office",zh:"一集《办公室》",minutes:22},{en:"listening to Abbey Road",zh:"听一遍《Abbey Road》专辑",minutes:47},{en:"a yoga class",zh:"一节瑜伽课",minutes:60},{en:"a World Cup soccer match",zh:"一场世界杯比赛",minutes:90},{en:"a half marathon (average time)",zh:"一场半程马拉松",minutes:120},{en:"the movie Inception",zh:"电影《盗梦空间》",minutes:148},{en:"watching Titanic",zh:"电影《泰坦尼克号》",minutes:195},{en:"a transatlantic flight",zh:"一趟跨大西洋航班",minutes:420},{en:"a full night of sleep",zh:"一整晚的睡眠",minutes:480}];function xe(t,a,n,r){var m;const s=[],o=r==="zh"?ce:le;if(a>0){for(const l of o)if(a>=l.tokens){const h=a/l.tokens;s.push(h>=2?n("stats.funFact.moreTokens").replace("{times}",String(Math.floor(h))).replace("{book}",l.name):n("stats.funFact.sameTokens").replace("{book}",l.name))}}if(t.longestSession){const l=t.longestSession.duration/6e4;for(const h of de){const u=l/h.minutes;if(u>=2){const d=r==="zh"?h.zh:h.en;s.push(n("stats.funFact.longerSession").replace("{times}",String(Math.floor(u))).replace("{activity}",d))}}}if(s.length===0)return"";const i=Math.floor((((m=t.longestSession)==null?void 0:m.duration)??0)/6e4),c=Math.abs(Math.trunc(a+i))%s.length;return s[c]}function me({dailyModelTokens:t,topModels:a}){const n=g.useMemo(()=>{const o={top:20,right:20,bottom:40,left:60},i=700-o.left-o.right,c=220-o.top-o.bottom;let m=0;for(const y of t)for(const b of a){const p=y.tokensByModel[b.id]||0;p>m&&(m=p)}m===0&&(m=1);const l=a.map((y,b)=>{const p=t.map((N,E)=>{const T=o.left+E/Math.max(t.length-1,1)*i,A=N.tokensByModel[y.id]||0,C=o.top+c-A/m*c;return`${T},${C}`});return t.some(N=>(N.tokensByModel[y.id]||0)>0)?{path:`M${p.join("L")}`,color:z[b%z.length],id:y.id,label:y.label}:null}).filter(Boolean),h=Array.from({length:5},(y,b)=>{const p=m*(1-b/4);return{y:o.top+b/4*c,label:k(Math.round(p))}}),u=Math.min(5,t.length),d=Math.max(1,Math.floor((t.length-1)/(u-1))),M=Array.from({length:u},(y,b)=>{const p=Math.min(b*d,t.length-1);return{x:o.left+p/Math.max(t.length-1,1)*i,label:oe(t[p].date)}});return{W:700,H:220,PAD:o,CW:i,CH:c,lines:l,yGridLines:h,xLabels:M}},[t,a]);return e.jsxs("div",{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("svg",{viewBox:`0 0 ${n.W} ${n.H}`,className:"w-full min-w-[500px]",style:{maxHeight:"240px"},children:[n.yGridLines.map((r,s)=>e.jsxs("g",{children:[e.jsx("line",{x1:n.PAD.left,y1:r.y,x2:n.W-n.PAD.right,y2:r.y,className:"stroke-border-primary",strokeWidth:.5,strokeDasharray:"4 4"}),e.jsx("text",{x:n.PAD.left-8,y:r.y+4,textAnchor:"end",className:"fill-text-tertiary",fontSize:10,children:r.label})]},s)),n.lines.map((r,s)=>e.jsx("path",{d:r.path,fill:"none",stroke:r.color,strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"},s)),n.xLabels.map((r,s)=>e.jsx("text",{x:r.x,y:n.H-10,textAnchor:"middle",className:"fill-text-tertiary",fontSize:10,children:r.label},s))]})}),e.jsx("div",{className:"flex gap-4 mt-2 justify-center",children:n.lines.map(r=>e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-text-secondary",children:[e.jsx("span",{className:"w-2.5 h-2.5 rounded-full",style:{backgroundColor:r.color}}),e.jsx("span",{children:r.label})]},r.id))})]})}function he({stats:t}){const{t:a}=D(),n=g.useMemo(()=>Object.entries(t.modelUsage).map(([s,o])=>{const i=o.inputTokens>0?o.cacheReadInputTokens/o.inputTokens*100:0;return{name:s,shortName:o.displayName||F(s),inputTokens:o.inputTokens,outputTokens:o.outputTokens,cacheReadInputTokens:o.cacheReadInputTokens,cacheHitRate:i,total:o.inputTokens+o.outputTokens,costUSD:o.costUSD}}).sort((s,o)=>o.total-s.total),[t.modelUsage]),r=g.useMemo(()=>n.reduce((s,o)=>s+o.total,0),[n]);return n.length===0?e.jsx("div",{className:"text-center py-12 text-text-tertiary",children:a("stats.noData")}):e.jsxs(e.Fragment,{children:[t.dailyModelTokens.length>=2&&e.jsxs("div",{className:"mb-6",children:[e.jsx("h2",{className:"text-sm font-medium text-text-primary mb-3",children:a("stats.tokensPerDay")}),e.jsx(me,{dailyModelTokens:t.dailyModelTokens,topModels:n.slice(0,3).map(s=>({id:s.name,label:s.shortName}))})]}),e.jsx("h2",{className:"text-sm font-medium text-text-primary mb-3",children:a("stats.allModels")}),e.jsx("div",{className:"space-y-3",children:n.map(s=>{const o=r>0?s.total/r*100:0;return e.jsxs("div",{className:"bg-bg-secondary rounded-lg p-3 border border-border-primary",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium text-text-primary",children:s.shortName}),e.jsxs("span",{className:"text-xs text-text-tertiary",children:[o.toFixed(1),"%"]})]}),e.jsx("div",{className:"h-1.5 bg-bg-tertiary rounded-full mb-2",children:e.jsx("div",{className:"h-full rounded-full bg-accent-brand transition-all duration-500",style:{width:`${Math.min(o,100)}%`}})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2 text-xs text-text-secondary",children:[e.jsxs("span",{children:[a("stats.input"),": ",k(s.inputTokens)]}),e.jsxs("span",{children:[a("stats.output"),": ",k(s.outputTokens)]}),s.cacheReadInputTokens>0&&e.jsxs("span",{children:[a("stats.cacheHitRate"),": ",s.cacheHitRate.toFixed(1),"%"]}),s.costUSD>0&&e.jsxs("span",{children:[a("stats.cost"),": $",s.costUSD.toFixed(2)]})]})]},s.name)})})]})}function ue({dailyActivity:t}){const{t:a}=D(),r=U(i=>i.resolved)==="dark"?ie:re,s=g.useMemo(()=>{const u=new Map;for(const x of t)u.set(x.date,x.messageCount);const d=t.map(x=>x.messageCount).filter(x=>x>0).sort((x,L)=>x-L),M=d.length>0?d[Math.floor(d.length*.25)]:0,y=d.length>0?d[Math.floor(d.length*.5)]:0,b=d.length>0?d[Math.floor(d.length*.75)]:0,p=x=>x===0||d.length===0?0:x>=b?4:x>=y?3:x>=M?2:1,v=new Date;v.setHours(0,0,0,0);const N=new Date(v);N.setDate(v.getDate()-v.getDay());const E=new Date(N);E.setDate(E.getDate()-357);const T=[],A=[];let C=-1;const f=new Date(E);for(let x=0;x<52;x++)for(let L=0;L<7;L++){if(f>v){f.setDate(f.getDate()+1);continue}const G=f.getFullYear(),H=String(f.getMonth()+1).padStart(2,"0"),R=String(f.getDate()).padStart(2,"0"),_=`${G}-${H}-${R}`,P=u.get(_)||0;if(L===0&&f.getMonth()!==C){const Z=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];A.push({text:Z[f.getMonth()],x:32+x*14}),C=f.getMonth()}T.push({key:_,x:32+x*14,y:20+L*14,level:p(P),date:_,count:P}),f.setDate(f.getDate()+1)}return{cells:T,monthLabels:A,width:770,height:128,CELL_SIZE:12,TOP_PADDING:20,LEFT_PADDING:32,CELL_GAP:2}},[t]),o=["","Mon","","Wed","","Fri",""];return e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("svg",{width:s.width,height:s.height+30,viewBox:`0 0 ${s.width} ${s.height+30}`,className:"min-w-[500px]",children:[s.monthLabels.map((i,c)=>e.jsx("text",{x:i.x,y:s.TOP_PADDING-6,className:"fill-text-tertiary",fontSize:10,children:i.text},c)),o.map((i,c)=>i?e.jsx("text",{x:s.LEFT_PADDING-6,y:s.TOP_PADDING+c*(s.CELL_SIZE+s.CELL_GAP)+s.CELL_SIZE-2,className:"fill-text-tertiary",fontSize:10,textAnchor:"end",children:i},c):null),s.cells.map(i=>e.jsx("rect",{x:i.x,y:i.y,width:s.CELL_SIZE,height:s.CELL_SIZE,rx:2,fill:r[i.level],children:e.jsxs("title",{children:[i.date,": ",i.count," ",a("stats.heatmap.messages")]})},i.key)),(()=>{const i=s.height+4,c=s.LEFT_PADDING;return e.jsxs("g",{children:[e.jsx("text",{x:c,y:i+10,className:"fill-text-tertiary",fontSize:10,children:a("stats.heatmap.less")}),r.map((m,l)=>e.jsx("rect",{x:c+30+l*(s.CELL_SIZE+2),y:i,width:s.CELL_SIZE,height:s.CELL_SIZE,rx:2,fill:m},l)),e.jsx("text",{x:c+30+5*(s.CELL_SIZE+2)+4,y:i+10,className:"fill-text-tertiary",fontSize:10,children:a("stats.heatmap.more")})]})})()]})})}function pe({sessionStats:t}){const{t:a}=D(),n=g.useMemo(()=>Object.values(t.tokenUsageByModel).reduce((r,s)=>r+s.inputTokens+s.outputTokens,0),[t.tokenUsageByModel]);return e.jsxs("div",{className:"flex flex-wrap gap-3 mb-6 p-3 bg-bg-secondary/50 rounded-xl border border-border-primary/50",children:[e.jsx(S,{label:a("stats.session.title"),icon:e.jsx(te,{size:12})}),e.jsx(S,{label:a("stats.session.apiDuration"),value:I(t.apiDuration)}),e.jsx(S,{label:a("stats.session.wallTime"),value:I(t.runningTime)}),e.jsx(S,{label:a("stats.session.linesAdded"),value:`+${t.fileChangeStats.totalAddedLines}`,valueClass:"text-green-500"}),e.jsx(S,{label:a("stats.session.linesDeleted"),value:`-${t.fileChangeStats.totalDeletedLines}`,valueClass:"text-red-500"}),e.jsx(S,{label:a("stats.session.tokens"),value:k(n)})]})}function S({label:t,value:a,icon:n,valueClass:r}){return e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[n,e.jsx("span",{className:"text-text-tertiary",children:t}),a&&e.jsx("span",{className:`font-medium text-text-primary ${r||""}`,children:a})]})}function j({icon:t,label:a,value:n}){return e.jsxs("div",{className:"bg-bg-secondary rounded-xl p-4 border border-border-primary",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-text-tertiary",children:t}),e.jsx("span",{className:"text-xs font-medium text-text-secondary",children:a})]}),e.jsx("div",{className:"text-lg font-semibold text-text-primary",style:{fontVariantNumeric:"tabular-nums"},children:n})]})}function fe({stats:t,sessionStats:a}){const{t:n,resolved:r}=D(),s=g.useMemo(()=>Object.entries(t.modelUsage).sort(([,l],[,h])=>h.inputTokens+h.outputTokens-(l.inputTokens+l.outputTokens)),[t.modelUsage]),o=g.useMemo(()=>s.reduce((l,[,h])=>l+h.inputTokens+h.outputTokens,0),[s]),i=g.useMemo(()=>{const l=s.reduce((u,[,d])=>u+d.inputTokens,0),h=s.reduce((u,[,d])=>u+d.cacheReadInputTokens,0);return l>0?h/l*100:0},[s]),c=s[0],m=g.useMemo(()=>xe(t,o,n,r),[t,o,n,r]);return e.jsxs(e.Fragment,{children:[a&&e.jsx(pe,{sessionStats:a}),t.dailyActivity.length>0&&e.jsx("div",{className:"mb-6",children:e.jsx(ue,{dailyActivity:t.dailyActivity})}),c&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-4",children:[e.jsx(j,{icon:e.jsx(B,{size:16}),label:n("stats.favoriteModel"),value:c[1].displayName||F(c[0])}),e.jsx(j,{icon:e.jsx(K,{size:16}),label:n("stats.totalTokens"),value:k(o)}),e.jsx(j,{icon:e.jsx(w,{size:16}),label:n("stats.cacheHitRate"),value:`${i.toFixed(1)}%`})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-4 mb-6",children:[e.jsx(j,{icon:e.jsx(q,{size:16}),label:n("stats.sessions"),value:k(t.totalSessions)}),e.jsx(j,{icon:e.jsx(Q,{size:16}),label:n("stats.longestSession"),value:t.longestSession?I(t.longestSession.duration):n("stats.na")}),e.jsx(j,{icon:e.jsx(ne,{size:16}),label:n("stats.activeDays"),value:`${t.activeDays}/${t.totalDays}`}),e.jsx(j,{icon:e.jsx(w,{size:16}),label:n("stats.currentStreak"),value:`${t.streaks.currentStreak} ${n("stats.days")}`}),e.jsx(j,{icon:e.jsx(w,{size:16}),label:n("stats.longestStreak"),value:`${t.streaks.longestStreak} ${n("stats.days")}`}),e.jsx(j,{icon:e.jsx(J,{size:16}),label:n("stats.peakHour"),value:t.peakActivityHour!==null?`${t.peakActivityHour}:00-${t.peakActivityHour+1}:00`:n("stats.na")})]}),m&&e.jsx("div",{className:"p-3 bg-bg-secondary/50 rounded-lg border border-border-primary/50 text-sm text-accent-brand",children:m})]})}function ge({toolUsage:t}){var s;const{t:a}=D(),n=t.slice(0,20),r=((s=n[0])==null?void 0:s.count)||0;return n.length===0?e.jsx("div",{className:"text-center py-12 text-text-tertiary",children:a("stats.noData")}):e.jsxs(e.Fragment,{children:[e.jsx("h2",{className:"text-sm font-medium text-text-primary mb-4",children:a("stats.topTools")}),e.jsx("div",{className:"space-y-2",children:n.map(o=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-xs text-text-secondary w-28 text-right truncate font-mono",children:o.toolName}),e.jsx("div",{className:"flex-1 h-6 bg-bg-tertiary rounded overflow-hidden",children:e.jsx("div",{className:"h-full bg-accent-brand/60 rounded transition-all duration-500 flex items-center pl-2",style:{width:`${Math.max(o.count/r*100,2)}%`},children:o.count/r>.15&&e.jsx("span",{className:"text-[10px] text-text-primary font-mono",children:k(o.count)})})}),o.count/r<=.15&&e.jsx("span",{className:"text-xs text-text-tertiary w-12 font-mono",children:k(o.count)})]},o.toolName))})]})}function Se(){const{t}=D(),{stats:a,statsLoading:n,statsError:r,sessionStats:s,fetchAll:o}=ae(),[i,c]=g.useState("overview");if(g.useEffect(()=>{o()},[o]),n&&!a)return e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsx(V,{size:"large",text:t("stats.loading")})});if(r&&!a)return e.jsx("div",{className:"flex-1 flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-text-secondary mb-4",children:r}),e.jsx("button",{onClick:o,className:"px-4 py-2 bg-accent-brand text-accent-brand-foreground rounded-lg text-sm",children:t("stats.refresh")})]})});const m=[{key:"overview",label:t("stats.tab.overview")},{key:"models",label:t("stats.tab.models")},{key:"tools",label:t("stats.tab.tools")}];return e.jsxs("div",{className:"flex-1 overflow-auto p-4 md:p-6",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(X,{size:20,className:"text-accent-brand"}),e.jsx("h1",{className:"text-lg font-semibold text-text-primary",children:t("stats.title")})]}),e.jsxs("button",{onClick:o,className:`flex items-center gap-1.5 px-3 py-1.5 text-sm text-text-secondary
|
|
12
12
|
hover:text-text-primary hover:bg-bg-hover rounded-lg transition-colors`,title:t("stats.refresh"),children:[e.jsx(Y,{size:14}),e.jsx("span",{children:t("stats.refresh")})]})]}),e.jsx("div",{className:"flex gap-1 mb-6 bg-bg-secondary rounded-lg p-1 w-fit",children:m.map(l=>e.jsx("button",{onClick:()=>c(l.key),className:`px-4 py-1.5 text-sm rounded-md transition-colors ${i===l.key?"bg-bg-primary text-text-primary font-medium shadow-sm":"text-text-secondary hover:text-text-primary"}`,children:l.label},l.key))}),a?e.jsxs(e.Fragment,{children:[i==="overview"&&e.jsx(fe,{stats:a,sessionStats:s}),i==="models"&&e.jsx(he,{stats:a}),i==="tools"&&e.jsx(ge,{toolUsage:a.toolUsage}),e.jsx("div",{className:"mt-8 text-xs text-text-tertiary text-center",children:t("stats.timeRange").replace("{days}",String(a.totalDays))})]}):e.jsx("div",{className:"text-center py-12 text-text-tertiary",children:t("stats.noData")})]})}export{Se as StatsView};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as n,j as e}from"./markdown-
|
|
1
|
+
import{a as n,j as e}from"./markdown-CP9awqWt.js";import{c as F,e as B,h as I,aX as O,u as H,X as G,P as Z,aI as R,aO as X,a as J,ab as M,Z as K,y as Q,F as Y,Y as W}from"./index-CBmymKHy.js";import{T as ee}from"./timer-D8MX3pYj.js";import{Z as te}from"./zap-yafQUspl.js";import"./vendor-iLJwFVtf.js";/**
|
|
2
2
|
* @license lucide-react v1.18.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -18,4 +18,4 @@ import{a as n,j as e}from"./markdown-DIY6o85n.js";import{c as F,e as B,h as I,aW
|
|
|
18
18
|
*
|
|
19
19
|
* This source code is licensed under the ISC license.
|
|
20
20
|
* See the LICENSE file in the root directory of this source tree.
|
|
21
|
-
*/const le=[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]],oe=F("repeat",le);function H(){return O.getState().sessionId??void 0}const de=B((t,d)=>({tasks:[],loading:!1,error:null,fetchTasks:async()=>{const s=H();if(s){t({loading:!0,error:null});try{const c=new URLSearchParams({sessionId:s}),l=await fetch(`/api/v1/scheduled-tasks?${c}`,{headers:I()});if(!l.ok)throw new Error(`HTTP ${l.status}`);const o=await l.json(),i=o.data??o;t({tasks:i.tasks||[],loading:!1})}catch(c){console.error("[ScheduledTasks] Fetch error:",c),t({error:c.message,loading:!1})}}},createTask:async(s,c,l=!0,o=!1)=>{var f;const i=H();if(i)try{const x=await fetch("/api/v1/scheduled-tasks",{method:"POST",headers:{"Content-Type":"application/json",...I()},body:JSON.stringify({cron:s,prompt:c,recurring:l,durable:o,sessionId:i})});if(!x.ok){const p=await x.json().catch(()=>({}));throw new Error(((f=p.error)==null?void 0:f.message)||`HTTP ${x.status}`)}await d().fetchTasks()}catch(x){throw console.error("[ScheduledTasks] Create error:",x),t({error:x.message}),x}},deleteTask:async s=>{const c=H();if(c)try{const l=new URLSearchParams({sessionId:c}),o=await fetch(`/api/v1/scheduled-tasks/${s}?${l}`,{method:"DELETE",headers:I()});if(!o.ok&&o.status!==204)throw new Error(`HTTP ${o.status}`);await d().fetchTasks()}catch(l){throw console.error("[ScheduledTasks] Delete error:",l),t({error:l.message}),l}}})),ie=[{label:"5m",cron:"*/5 * * * *"},{label:"10m",cron:"*/10 * * * *"},{label:"15m",cron:"*/15 * * * *"},{label:"30m",cron:"*/30 * * * *"},{label:"1h",cron:"7 * * * *"},{label:"2h",cron:"7 */2 * * *"},{label:"6h",cron:"7 */6 * * *"},{label:"1d",cron:"3 9 * * *"},{label:"1w",cron:"3 9 * * 1"}];function xe(t,d){switch(d){case"minutes":return`*/${t} * * * *`;case"hours":return`0 */${t} * * *`;case"days":return`0 9 */${t} * *`;case"weeks":return"0 9 * * 1"}}function A(t){switch(t){case"minutes":return 59;case"hours":return 23;case"days":return 30;case"weeks":return 1}}function ue({onSubmit:t,onCancel:d}){const{t:s}=_(),[c,l]=n.useState("*/5 * * * *"),[o,i]=n.useState(""),[f,x]=n.useState(!0),[p,$]=n.useState(!1),[j,P]=n.useState(!1),[v,w]=n.useState(null),[S,y]=n.useState(10),[m,g]=n.useState("minutes"),N=(a,b)=>{const h=Math.min(a,A(b));y(h),g(b),l(xe(h,b))},T=async()=>{if(!(!c.trim()||!o.trim())){P(!0),w(null);try{await t(c.trim(),o.trim(),f,p),d()}catch(a){w(a.message||"Failed to create task")}finally{P(!1)}}};return e.jsxs("div",{className:"border border-accent-brand/30 rounded-xl p-4 bg-bg-secondary/30",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-medium text-text-primary",children:s("scheduled.create")}),e.jsx("button",{onClick:d,className:"p-1 rounded hover:bg-bg-secondary text-text-tertiary",children:e.jsx(G,{size:14})})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("label",{className:"text-xs text-text-secondary mb-1 block",children:s("scheduled.cron")}),e.jsx("input",{type:"text",value:c,onChange:a=>l(a.target.value),placeholder:"*/5 * * * *",className:"w-full px-3 py-1.5 text-sm rounded-lg border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none font-mono"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:ie.map(a=>e.jsx("button",{onClick:()=>l(a.cron),className:`text-[10px] px-2 py-0.5 rounded-full border transition-colors ${c===a.cron?"border-accent-brand/50 text-accent-brand bg-accent-brand/5":"border-border-default text-text-tertiary hover:text-text-secondary hover:border-border-default/80"}`,children:a.label},a.label))}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx("span",{className:"text-[10px] text-text-tertiary",children:s("scheduled.every")}),e.jsx("input",{type:"number",min:1,max:A(m),value:S,onChange:a=>N(Math.max(1,parseInt(a.target.value)||1),m),className:"w-14 px-2 py-0.5 text-[11px] rounded-md border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none text-center"}),e.jsxs("select",{value:m,onChange:a=>N(S,a.target.value),className:"px-2 py-0.5 text-[11px] rounded-md border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none",children:[e.jsx("option",{value:"minutes",children:s("scheduled.unit.minutes")}),e.jsx("option",{value:"hours",children:s("scheduled.unit.hours")}),e.jsx("option",{value:"days",children:s("scheduled.unit.days")}),e.jsx("option",{value:"weeks",children:s("scheduled.unit.weeks")})]})]})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("label",{className:"text-xs text-text-secondary mb-1 block",children:s("scheduled.prompt")}),e.jsx("textarea",{value:o,onChange:a=>i(a.target.value),placeholder:s("scheduled.promptPlaceholder"),rows:2,className:"w-full px-3 py-1.5 text-sm rounded-lg border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none resize-none"})]}),e.jsxs("div",{className:"flex items-center gap-4 mb-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:f,onChange:a=>x(a.target.checked),className:"rounded"}),s("scheduled.recurring")]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:a=>$(a.target.checked),className:"rounded"}),s("scheduled.durable")]})]}),v&&e.jsx("div",{className:"text-xs text-accent-red mb-2",children:v}),e.jsxs("button",{onClick:T,disabled:j||!c.trim()||!o.trim(),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-accent-brand text-accent-brand-foreground text-sm font-medium hover:bg-accent-brand/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[e.jsx(Z,{size:14}),s(j?"scheduled.creating":"scheduled.create")]})]})}function me({task:t,onDelete:d}){const{t:s}=_(),[c,l]=n.useState(!1),o=async()=>{l(!0);try{await d(t.id)}finally{l(!1)}},i=t.durable||t.permanent;return e.jsxs("div",{className:"group flex items-start gap-3 px-4 py-3 rounded-xl border border-border-default hover:border-accent-brand/30 transition-colors",children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:t.recurring?e.jsx(oe,{size:18,className:"text-accent-blue"}):e.jsx(ee,{size:18,className:"text-accent-yellow"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-sm font-medium text-text-primary",children:t.humanSchedule}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full ${t.recurring?"bg-accent-blue/10 text-accent-blue":"bg-accent-yellow/10 text-accent-yellow"}`,children:t.recurring?s("scheduled.recurring"):s("scheduled.oneShot")}),i&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-accent-green/10 text-accent-green",children:s("scheduled.durable")})]}),e.jsx("p",{className:"text-xs text-text-secondary truncate",title:t.prompt,children:t.prompt}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-[10px] text-text-tertiary",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(R,{size:10}),"ID: ",t.id]}),t.lastFiredAt&&e.jsxs("span",{children:[s("scheduled.lastFired"),": ",new Date(t.lastFiredAt).toLocaleString()]})]})]}),e.jsx("button",{onClick:o,disabled:c,className:"flex-shrink-0 p-1.5 rounded-lg opacity-0 group-hover:opacity-100 hover:bg-accent-red/10 text-text-tertiary hover:text-accent-red transition-all disabled:opacity-50",title:s("scheduled.delete"),children:e.jsx(J,{size:14})})]})}const he=3e3;function ve(){const{t}=_(),{setMainView:d}=K(),{setExternalInput:s,sessionId:c}=O(),{tasks:l,loading:o,fetchTasks:i,createTask:f,deleteTask:x}=de(),[p,$]=n.useState(!1);n.useEffect(()=>{i()},[i,c]);const[j,P]=n.useState([]),[v,w]=n.useState(!0),[S,y]=n.useState(null),[m,g]=n.useState(!1),[N,T]=n.useState(!1),a=n.useRef(c);a.current=c;const b=n.useRef(null),h=n.useCallback(()=>{b.current&&(clearInterval(b.current),b.current=null)},[]),z=n.useCallback(async()=>{const r=new URLSearchParams,u=a.current;u&&r.append("sessionId",u);const C=r.toString(),k=await fetch(`/api/v1/tasks/templates${C?"?"+C:""}`,{headers:I()});if(!k.ok)throw new Error(`HTTP ${k.status}`);const U=await k.json(),L=U.data??U;return P(L.templates||[]),y(L.error||null),L.status},[]),E=n.useCallback(()=>{h(),b.current=setInterval(async()=>{try{const r=await z();r!=="loading"&&(h(),g(!1),r==="done"&&(T(!0),setTimeout(()=>T(!1),2e3)))}catch(r){h(),g(!1),y(r.message||"Failed to load templates")}},he)},[z,h]);n.useEffect(()=>{let r=!1;return(async()=>{try{if(!a.current){r||w(!1);return}const u=await z();if(r)return;u==="loading"&&(g(!0),E())}catch(u){r||y(u.message)}finally{r||w(!1)}})(),()=>{r=!0,h()}},[z,E,h,c]);const D=n.useCallback(async()=>{g(!0),y(null),T(!1);try{const r=new URLSearchParams,u=a.current;u&&r.append("sessionId",u);const C=r.toString(),k=await fetch(`/api/v1/tasks/templates/refresh${C?"?"+C:""}`,{method:"POST",headers:I()});if(!k.ok)throw new Error(`HTTP ${k.status}`);E()}catch(r){y(r.message||"Failed to trigger refresh"),g(!1)}},[E]),q=n.useCallback(r=>{s({text:r.command}),d("chat")},[s,d]);return e.jsx("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsx("div",{className:"border-b border-border-default",children:e.jsxs("div",{className:"px-6 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:t("scheduled.title")}),e.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:t("scheduled.subtitle")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>i(),className:"p-2 rounded-lg border border-border-default text-text-secondary hover:text-text-primary hover:bg-bg-secondary transition-colors",title:t("tasks.refresh"),children:e.jsx(M,{size:14,className:o?"animate-spin":""})}),e.jsxs("button",{onClick:()=>$(!p),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-sm transition-colors ${p?"border-accent-brand/50 text-accent-brand bg-accent-brand/5":"border-border-default text-text-secondary hover:text-text-primary hover:border-accent-brand/30"}`,children:[e.jsx(Z,{size:14}),t("scheduled.create")]})]})]}),p&&e.jsx("div",{className:"mb-3",children:e.jsx(ue,{onSubmit:f,onCancel:()=>$(!1)})}),o&&l.length===0?e.jsxs("div",{className:"py-8 text-center text-text-tertiary text-sm",children:[e.jsx(M,{size:16,className:"animate-spin mx-auto mb-2"}),t("scheduled.loading")]}):l.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx(R,{size:32,className:"mx-auto mb-2 text-text-tertiary opacity-30"}),e.jsx("p",{className:"text-sm text-text-tertiary",children:t("scheduled.empty")}),e.jsx("p",{className:"text-xs text-text-tertiary mt-1",children:t("scheduled.emptyHint")})]}):e.jsx("div",{className:"space-y-2",children:l.map(r=>e.jsx(me,{task:r,onDelete:x},r.id))})]})}),e.jsxs("div",{className:"px-6 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:t("tasks.title")}),e.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:t("tasks.subtitle")})]}),e.jsxs("button",{onClick:D,disabled:m,className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm transition-all ${N?"border-green-500/50 text-green-500":m?"opacity-50 cursor-not-allowed border-border-default text-text-secondary":"border-border-default text-text-secondary hover:text-text-primary hover:border-accent-brand/50 hover:bg-bg-secondary"}`,children:[N?e.jsx(Q,{size:14}):e.jsx(M,{size:14,className:m?"animate-spin":""}),e.jsx("span",{children:t(N?"tasks.refreshed":"tasks.refresh")})]})]}),v&&!m&&e.jsx("div",{className:"flex flex-col items-center justify-center py-12 text-text-tertiary",children:e.jsx(W,{size:"small",text:t("tasks.loading")})}),S&&!v&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[e.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"!"}),e.jsx("div",{className:"text-text-secondary text-sm mb-4",children:t("tasks.error")}),e.jsx("button",{onClick:D,className:"px-4 py-2 rounded-lg bg-accent-brand text-accent-brand-foreground text-sm font-medium hover:bg-accent-brand/90 transition-colors",children:t("tasks.retry")})]}),!v&&j.length===0&&!S&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-text-tertiary",children:[e.jsx(re,{size:32,className:"mb-2 opacity-30"}),e.jsx("div",{className:"text-sm",children:t("tasks.empty")})]}),j.length>0&&e.jsx("div",{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 max-w-6xl transition-opacity duration-300 ${m?"opacity-50 pointer-events-none":"opacity-100"}`,children:j.map(r=>{const u=pe(r.icon);return e.jsxs("div",{onClick:()=>q(r),className:"group flex items-center gap-4 px-4 py-3.5 rounded-xl border border-border-default hover:border-accent-brand/40 hover:bg-bg-secondary/60 transition-all cursor-pointer",children:[e.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-lg bg-bg-secondary flex items-center justify-center group-hover:bg-accent-brand/10 transition-colors",children:e.jsx(u,{size:20,className:"text-text-tertiary group-hover:text-accent-brand transition-colors"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"text-sm font-semibold text-text-primary truncate",children:r.title}),e.jsx("p",{className:"text-xs text-text-tertiary mt-0.5 truncate",children:r.description})]})]},r.id)})})]})]})})}function pe(t){switch(t){case"Newspaper":return V;case"MessageSquare":return V;case"GitBranch":return Y;case"Package":return ce;case"FileText":return X;case"Zap":return te;case"Clock":return R;default:return R}}export{ve as TasksView};
|
|
21
|
+
*/const le=[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]],oe=F("repeat",le);function _(){return O.getState().sessionId??void 0}const de=B((t,d)=>({tasks:[],loading:!1,error:null,fetchTasks:async()=>{const s=_();if(s){t({loading:!0,error:null});try{const c=new URLSearchParams({sessionId:s}),l=await fetch(`/api/v1/scheduled-tasks?${c}`,{headers:I()});if(!l.ok)throw new Error(`HTTP ${l.status}`);const o=await l.json(),i=o.data??o;t({tasks:i.tasks||[],loading:!1})}catch(c){console.error("[ScheduledTasks] Fetch error:",c),t({error:c.message,loading:!1})}}},createTask:async(s,c,l=!0,o=!1)=>{var f;const i=_();if(i)try{const x=await fetch("/api/v1/scheduled-tasks",{method:"POST",headers:{"Content-Type":"application/json",...I()},body:JSON.stringify({cron:s,prompt:c,recurring:l,durable:o,sessionId:i})});if(!x.ok){const p=await x.json().catch(()=>({}));throw new Error(((f=p.error)==null?void 0:f.message)||`HTTP ${x.status}`)}await d().fetchTasks()}catch(x){throw console.error("[ScheduledTasks] Create error:",x),t({error:x.message}),x}},deleteTask:async s=>{const c=_();if(c)try{const l=new URLSearchParams({sessionId:c}),o=await fetch(`/api/v1/scheduled-tasks/${s}?${l}`,{method:"DELETE",headers:I()});if(!o.ok&&o.status!==204)throw new Error(`HTTP ${o.status}`);await d().fetchTasks()}catch(l){throw console.error("[ScheduledTasks] Delete error:",l),t({error:l.message}),l}}})),ie=[{label:"5m",cron:"*/5 * * * *"},{label:"10m",cron:"*/10 * * * *"},{label:"15m",cron:"*/15 * * * *"},{label:"30m",cron:"*/30 * * * *"},{label:"1h",cron:"7 * * * *"},{label:"2h",cron:"7 */2 * * *"},{label:"6h",cron:"7 */6 * * *"},{label:"1d",cron:"3 9 * * *"},{label:"1w",cron:"3 9 * * 1"}];function xe(t,d){switch(d){case"minutes":return`*/${t} * * * *`;case"hours":return`0 */${t} * * *`;case"days":return`0 9 */${t} * *`;case"weeks":return"0 9 * * 1"}}function A(t){switch(t){case"minutes":return 59;case"hours":return 23;case"days":return 30;case"weeks":return 1}}function ue({onSubmit:t,onCancel:d}){const{t:s}=H(),[c,l]=n.useState("*/5 * * * *"),[o,i]=n.useState(""),[f,x]=n.useState(!0),[p,$]=n.useState(!1),[j,P]=n.useState(!1),[v,w]=n.useState(null),[S,y]=n.useState(10),[m,g]=n.useState("minutes"),N=(a,b)=>{const h=Math.min(a,A(b));y(h),g(b),l(xe(h,b))},T=async()=>{if(!(!c.trim()||!o.trim())){P(!0),w(null);try{await t(c.trim(),o.trim(),f,p),d()}catch(a){w(a.message||"Failed to create task")}finally{P(!1)}}};return e.jsxs("div",{className:"border border-accent-brand/30 rounded-xl p-4 bg-bg-secondary/30",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-sm font-medium text-text-primary",children:s("scheduled.create")}),e.jsx("button",{onClick:d,className:"p-1 rounded hover:bg-bg-secondary text-text-tertiary",children:e.jsx(G,{size:14})})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("label",{className:"text-xs text-text-secondary mb-1 block",children:s("scheduled.cron")}),e.jsx("input",{type:"text",value:c,onChange:a=>l(a.target.value),placeholder:"*/5 * * * *",className:"w-full px-3 py-1.5 text-sm rounded-lg border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none font-mono"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:ie.map(a=>e.jsx("button",{onClick:()=>l(a.cron),className:`text-[10px] px-2 py-0.5 rounded-full border transition-colors ${c===a.cron?"border-accent-brand/50 text-accent-brand bg-accent-brand/5":"border-border-default text-text-tertiary hover:text-text-secondary hover:border-border-default/80"}`,children:a.label},a.label))}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx("span",{className:"text-[10px] text-text-tertiary",children:s("scheduled.every")}),e.jsx("input",{type:"number",min:1,max:A(m),value:S,onChange:a=>N(Math.max(1,parseInt(a.target.value)||1),m),className:"w-14 px-2 py-0.5 text-[11px] rounded-md border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none text-center"}),e.jsxs("select",{value:m,onChange:a=>N(S,a.target.value),className:"px-2 py-0.5 text-[11px] rounded-md border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none",children:[e.jsx("option",{value:"minutes",children:s("scheduled.unit.minutes")}),e.jsx("option",{value:"hours",children:s("scheduled.unit.hours")}),e.jsx("option",{value:"days",children:s("scheduled.unit.days")}),e.jsx("option",{value:"weeks",children:s("scheduled.unit.weeks")})]})]})]}),e.jsxs("div",{className:"mb-3",children:[e.jsx("label",{className:"text-xs text-text-secondary mb-1 block",children:s("scheduled.prompt")}),e.jsx("textarea",{value:o,onChange:a=>i(a.target.value),placeholder:s("scheduled.promptPlaceholder"),rows:2,className:"w-full px-3 py-1.5 text-sm rounded-lg border border-border-default bg-bg-primary text-text-primary focus:border-accent-brand/50 outline-none resize-none"})]}),e.jsxs("div",{className:"flex items-center gap-4 mb-3",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:f,onChange:a=>x(a.target.checked),className:"rounded"}),s("scheduled.recurring")]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-text-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:p,onChange:a=>$(a.target.checked),className:"rounded"}),s("scheduled.durable")]})]}),v&&e.jsx("div",{className:"text-xs text-accent-red mb-2",children:v}),e.jsxs("button",{onClick:T,disabled:j||!c.trim()||!o.trim(),className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-accent-brand text-accent-brand-foreground text-sm font-medium hover:bg-accent-brand/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[e.jsx(Z,{size:14}),s(j?"scheduled.creating":"scheduled.create")]})]})}function me({task:t,onDelete:d}){const{t:s}=H(),[c,l]=n.useState(!1),o=async()=>{l(!0);try{await d(t.id)}finally{l(!1)}},i=t.durable||t.permanent;return e.jsxs("div",{className:"group flex items-start gap-3 px-4 py-3 rounded-xl border border-border-default hover:border-accent-brand/30 transition-colors",children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:t.recurring?e.jsx(oe,{size:18,className:"text-accent-blue"}):e.jsx(ee,{size:18,className:"text-accent-yellow"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-sm font-medium text-text-primary",children:t.humanSchedule}),e.jsx("span",{className:`text-[10px] px-1.5 py-0.5 rounded-full ${t.recurring?"bg-accent-blue/10 text-accent-blue":"bg-accent-yellow/10 text-accent-yellow"}`,children:t.recurring?s("scheduled.recurring"):s("scheduled.oneShot")}),i&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-accent-green/10 text-accent-green",children:s("scheduled.durable")})]}),e.jsx("p",{className:"text-xs text-text-secondary truncate",title:t.prompt,children:t.prompt}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-[10px] text-text-tertiary",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(R,{size:10}),"ID: ",t.id]}),t.lastFiredAt&&e.jsxs("span",{children:[s("scheduled.lastFired"),": ",new Date(t.lastFiredAt).toLocaleString()]})]})]}),e.jsx("button",{onClick:o,disabled:c,className:"flex-shrink-0 p-1.5 rounded-lg opacity-0 group-hover:opacity-100 hover:bg-accent-red/10 text-text-tertiary hover:text-accent-red transition-all disabled:opacity-50",title:s("scheduled.delete"),children:e.jsx(X,{size:14})})]})}const he=3e3;function ve(){const{t}=H(),{setMainView:d}=J(),{setExternalInput:s,sessionId:c}=O(),{tasks:l,loading:o,fetchTasks:i,createTask:f,deleteTask:x}=de(),[p,$]=n.useState(!1);n.useEffect(()=>{i()},[i,c]);const[j,P]=n.useState([]),[v,w]=n.useState(!0),[S,y]=n.useState(null),[m,g]=n.useState(!1),[N,T]=n.useState(!1),a=n.useRef(c);a.current=c;const b=n.useRef(null),h=n.useCallback(()=>{b.current&&(clearInterval(b.current),b.current=null)},[]),z=n.useCallback(async()=>{const r=new URLSearchParams,u=a.current;u&&r.append("sessionId",u);const C=r.toString(),k=await fetch(`/api/v1/tasks/templates${C?"?"+C:""}`,{headers:I()});if(!k.ok)throw new Error(`HTTP ${k.status}`);const U=await k.json(),L=U.data??U;return P(L.templates||[]),y(L.error||null),L.status},[]),E=n.useCallback(()=>{h(),b.current=setInterval(async()=>{try{const r=await z();r!=="loading"&&(h(),g(!1),r==="done"&&(T(!0),setTimeout(()=>T(!1),2e3)))}catch(r){h(),g(!1),y(r.message||"Failed to load templates")}},he)},[z,h]);n.useEffect(()=>{let r=!1;return(async()=>{try{if(!a.current){r||w(!1);return}const u=await z();if(r)return;u==="loading"&&(g(!0),E())}catch(u){r||y(u.message)}finally{r||w(!1)}})(),()=>{r=!0,h()}},[z,E,h,c]);const D=n.useCallback(async()=>{g(!0),y(null),T(!1);try{const r=new URLSearchParams,u=a.current;u&&r.append("sessionId",u);const C=r.toString(),k=await fetch(`/api/v1/tasks/templates/refresh${C?"?"+C:""}`,{method:"POST",headers:I()});if(!k.ok)throw new Error(`HTTP ${k.status}`);E()}catch(r){y(r.message||"Failed to trigger refresh"),g(!1)}},[E]),q=n.useCallback(r=>{s({text:r.command}),d("chat")},[s,d]);return e.jsx("div",{className:"flex-1 flex flex-col overflow-hidden bg-bg-primary",children:e.jsxs("div",{className:"flex-1 overflow-y-auto",children:[e.jsx("div",{className:"border-b border-border-default",children:e.jsxs("div",{className:"px-6 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:t("scheduled.title")}),e.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:t("scheduled.subtitle")})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:()=>i(),className:"p-2 rounded-lg border border-border-default text-text-secondary hover:text-text-primary hover:bg-bg-secondary transition-colors",title:t("tasks.refresh"),children:e.jsx(M,{size:14,className:o?"animate-spin":""})}),e.jsxs("button",{onClick:()=>$(!p),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-lg border text-sm transition-colors ${p?"border-accent-brand/50 text-accent-brand bg-accent-brand/5":"border-border-default text-text-secondary hover:text-text-primary hover:border-accent-brand/30"}`,children:[e.jsx(Z,{size:14}),t("scheduled.create")]})]})]}),p&&e.jsx("div",{className:"mb-3",children:e.jsx(ue,{onSubmit:f,onCancel:()=>$(!1)})}),o&&l.length===0?e.jsxs("div",{className:"py-8 text-center text-text-tertiary text-sm",children:[e.jsx(M,{size:16,className:"animate-spin mx-auto mb-2"}),t("scheduled.loading")]}):l.length===0?e.jsxs("div",{className:"py-8 text-center",children:[e.jsx(R,{size:32,className:"mx-auto mb-2 text-text-tertiary opacity-30"}),e.jsx("p",{className:"text-sm text-text-tertiary",children:t("scheduled.empty")}),e.jsx("p",{className:"text-xs text-text-tertiary mt-1",children:t("scheduled.emptyHint")})]}):e.jsx("div",{className:"space-y-2",children:l.map(r=>e.jsx(me,{task:r,onDelete:x},r.id))})]})}),e.jsxs("div",{className:"px-6 py-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold text-text-primary",children:t("tasks.title")}),e.jsx("p",{className:"text-xs text-text-tertiary mt-0.5",children:t("tasks.subtitle")})]}),e.jsxs("button",{onClick:D,disabled:m,className:`flex items-center gap-2 px-3 py-1.5 rounded-lg border text-sm transition-all ${N?"border-green-500/50 text-green-500":m?"opacity-50 cursor-not-allowed border-border-default text-text-secondary":"border-border-default text-text-secondary hover:text-text-primary hover:border-accent-brand/50 hover:bg-bg-secondary"}`,children:[N?e.jsx(K,{size:14}):e.jsx(M,{size:14,className:m?"animate-spin":""}),e.jsx("span",{children:t(N?"tasks.refreshed":"tasks.refresh")})]})]}),v&&!m&&e.jsx("div",{className:"flex flex-col items-center justify-center py-12 text-text-tertiary",children:e.jsx(Q,{size:"small",text:t("tasks.loading")})}),S&&!v&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12",children:[e.jsx("div",{className:"text-text-tertiary text-[48px] mb-4 opacity-30",children:"!"}),e.jsx("div",{className:"text-text-secondary text-sm mb-4",children:t("tasks.error")}),e.jsx("button",{onClick:D,className:"px-4 py-2 rounded-lg bg-accent-brand text-accent-brand-foreground text-sm font-medium hover:bg-accent-brand/90 transition-colors",children:t("tasks.retry")})]}),!v&&j.length===0&&!S&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-text-tertiary",children:[e.jsx(re,{size:32,className:"mb-2 opacity-30"}),e.jsx("div",{className:"text-sm",children:t("tasks.empty")})]}),j.length>0&&e.jsx("div",{className:`grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3 max-w-6xl transition-opacity duration-300 ${m?"opacity-50 pointer-events-none":"opacity-100"}`,children:j.map(r=>{const u=pe(r.icon);return e.jsxs("div",{onClick:()=>q(r),className:"group flex items-center gap-4 px-4 py-3.5 rounded-xl border border-border-default hover:border-accent-brand/40 hover:bg-bg-secondary/60 transition-all cursor-pointer",children:[e.jsx("div",{className:"flex-shrink-0 w-10 h-10 rounded-lg bg-bg-secondary flex items-center justify-center group-hover:bg-accent-brand/10 transition-colors",children:e.jsx(u,{size:20,className:"text-text-tertiary group-hover:text-accent-brand transition-colors"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"text-sm font-semibold text-text-primary truncate",children:r.title}),e.jsx("p",{className:"text-xs text-text-tertiary mt-0.5 truncate",children:r.description})]})]},r.id)})})]})]})})}function pe(t){switch(t){case"Newspaper":return V;case"MessageSquare":return V;case"GitBranch":return W;case"Package":return ce;case"FileText":return Y;case"Zap":return te;case"Clock":return R;default:return R}}export{ve as TasksView};
|
package/cli/dist/web-ui/assets/{TerminalPaneView-BXNcwxsi.js → TerminalPaneView-lhajvnaH.js}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
2
|
-
var Zc=Object.defineProperty;var ed=(t,e,i)=>e in t?Zc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i;var Qs=(t,e,i)=>ed(t,typeof e!="symbol"?e+"":e,i);import{c as td,u as Co,n as id,X as Ul,a as it,h as sd,
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CBmymKHy.js","assets/markdown-CP9awqWt.js","assets/vendor-iLJwFVtf.js","assets/index-BOvl5ICo.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
var Zc=Object.defineProperty;var ed=(t,e,i)=>e in t?Zc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i;var Qs=(t,e,i)=>ed(t,typeof e!="symbol"?e+"":e,i);import{c as td,u as Co,n as id,X as Ul,a as it,h as sd,b7 as rd,q as nd,bm as od,T as zo,w as ad,ay as ld,K as Uo,aP as Go,_ as hd,b6 as Ko,E as cd,H as dd,I as ud,bn as _d,L as qo,R as fd,ab as gd,O as pd,Q as md}from"./index-CBmymKHy.js";import{a as $,j as ie}from"./markdown-CP9awqWt.js";import"./vendor-iLJwFVtf.js";/**
|
|
3
3
|
* @license lucide-react v1.18.0 - ISC
|
|
4
4
|
*
|
|
5
5
|
* This source code is licensed under the ISC license.
|
|
@@ -196,4 +196,4 @@ WARNING: This link could potentially be dangerous`)){let i=window.open();if(i){t
|
|
|
196
196
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Ll+1&&(this._liveRegion.textContent+=Qn.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(t){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(t)||this._charsToConsume.push(t)}_refreshRows(t,e){this._liveRegionDebouncer.refresh(t,e,this._terminal.rows)}_renderRows(t,e){let i=this._terminal.buffer,s=i.lines.length.toString();for(let r=t;r<=e;r++){let n=i.lines.get(i.ydisp+r),o=[],a=(n==null?void 0:n.translateToString(!0,void 0,void 0,o))||"",h=(i.ydisp+r+1).toString(),l=this._rowElements[r];l&&(a.length===0?(l.textContent=" ",this._rowColumns.set(l,[0,1])):(l.textContent=a,this._rowColumns.set(l,o)),l.setAttribute("aria-posinset",h),l.setAttribute("aria-setsize",s),this._alignRowWidth(l))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(t,e){let i=t.target,s=this._rowElements[e===0?1:this._rowElements.length-2],r=i.getAttribute("aria-posinset"),n=e===0?"1":`${this._terminal.buffer.lines.length}`;if(r===n||t.relatedTarget!==s)return;let o,a;if(e===0?(o=i,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(o=this._rowElements.shift(),a=i,this._rowContainer.removeChild(o)),o.removeEventListener("focus",this._topBoundaryFocusListener),a.removeEventListener("focus",this._bottomBoundaryFocusListener),e===0){let h=this._createAccessibilityTreeNode();this._rowElements.unshift(h),this._rowContainer.insertAdjacentElement("afterbegin",h)}else{let h=this._createAccessibilityTreeNode();this._rowElements.push(h),this._rowContainer.appendChild(h)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(e===0?-1:1),this._rowElements[e===0?1:this._rowElements.length-2].focus(),t.preventDefault(),t.stopImmediatePropagation()}_handleSelectionChange(){var a;if(this._rowElements.length===0)return;let t=this._coreBrowserService.mainDocument.getSelection();if(!t)return;if(t.isCollapsed){this._rowContainer.contains(t.anchorNode)&&this._terminal.clearSelection();return}if(!t.anchorNode||!t.focusNode){console.error("anchorNode and/or focusNode are null");return}let e={node:t.anchorNode,offset:t.anchorOffset},i={node:t.focusNode,offset:t.focusOffset};if((e.node.compareDocumentPosition(i.node)&Node.DOCUMENT_POSITION_PRECEDING||e.node===i.node&&e.offset>i.offset)&&([e,i]=[i,e]),e.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(e={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(e.node))return;let s=this._rowElements.slice(-1)[0];if(i.node.compareDocumentPosition(s)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(i={node:s,offset:((a=s.textContent)==null?void 0:a.length)??0}),!this._rowContainer.contains(i.node))return;let r=({node:h,offset:l})=>{let c=h instanceof Text?h.parentNode:h,d=parseInt(c==null?void 0:c.getAttribute("aria-posinset"),10)-1;if(isNaN(d))return console.warn("row is invalid. Race condition?"),null;let g=this._rowColumns.get(c);if(!g)return console.warn("columns is null. Race condition?"),null;let u=l<g.length?g[l]:g.slice(-1)[0]+1;return u>=this._terminal.cols&&(++d,u=0),{row:d,column:u}},n=r(e),o=r(i);if(!(!n||!o)){if(n.row>o.row||n.row===o.row&&n.column>=o.column)throw new Error("invalid range");this._terminal.select(n.column,n.row,(o.row-n.row)*this._terminal.cols-n.column+o.column)}}_handleResize(t){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;e<this._terminal.rows;e++)this._rowElements[e]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[e]);for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let t=this._coreBrowserService.mainDocument.createElement("div");return t.setAttribute("role","listitem"),t.tabIndex=-1,this._refreshRowDimensions(t),t}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let t=0;t<this._terminal.rows;t++)this._refreshRowDimensions(this._rowElements[t]),this._alignRowWidth(this._rowElements[t])}}_refreshRowDimensions(t){t.style.height=`${this._renderService.dimensions.css.cell.height}px`}_alignRowWidth(t){var r,n;t.style.transform="";let e=t.getBoundingClientRect().width,i=(n=(r=this._rowColumns.get(t))==null?void 0:r.slice(-1))==null?void 0:n[0];if(!i)return;let s=i*this._renderService.dimensions.css.cell.width;t.style.transform=`scaleX(${s/e})`}};Sr=Ee([O(1,Lo),O(2,ii),O(3,si)],Sr);var vo=class extends te{constructor(t,e,i,s,r){super(),this._element=t,this._mouseService=e,this._renderService=i,this._bufferService=s,this._linkProviderService=r,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new P),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new P),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register(pe(()=>{var n;Ti(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,(n=this._activeProviderReplies)==null||n.clear()})),this._register(this._bufferService.onResize(()=>{this._clearCurrentLink(),this._wasResized=!0})),this._register(J(this._element,"mouseleave",()=>{this._isMouseOut=!0,this._clearCurrentLink()})),this._register(J(this._element,"mousemove",this._handleMouseMove.bind(this))),this._register(J(this._element,"mousedown",this._handleMouseDown.bind(this))),this._register(J(this._element,"mouseup",this._handleMouseUp.bind(this)))}get currentLink(){return this._currentLink}_handleMouseMove(t){this._lastMouseEvent=t;let e=this._positionFromMouseEvent(t,this._element,this._mouseService);if(!e)return;this._isMouseOut=!1;let i=t.composedPath();for(let s=0;s<i.length;s++){let r=i[s];if(r.classList.contains("xterm"))break;if(r.classList.contains("xterm-hover"))return}(!this._lastBufferCell||e.x!==this._lastBufferCell.x||e.y!==this._lastBufferCell.y)&&(this._handleHover(e),this._lastBufferCell=e)}_handleHover(t){if(this._activeLine!==t.y||this._wasResized){this._clearCurrentLink(),this._askForLink(t,!1),this._wasResized=!1;return}this._currentLink&&this._linkAtPosition(this._currentLink.link,t)||(this._clearCurrentLink(),this._askForLink(t,!0))}_askForLink(t,e){var s,r;(!this._activeProviderReplies||!e)&&((s=this._activeProviderReplies)==null||s.forEach(n=>{n==null||n.forEach(o=>{o.link.dispose&&o.link.dispose()})}),this._activeProviderReplies=new Map,this._activeLine=t.y);let i=!1;for(let[n,o]of this._linkProviderService.linkProviders.entries())e?(r=this._activeProviderReplies)!=null&&r.get(n)&&(i=this._checkLinkProviderResult(n,t,i)):o.provideLinks(t.y,a=>{var l,c;if(this._isMouseOut)return;let h=a==null?void 0:a.map(d=>({link:d}));(l=this._activeProviderReplies)==null||l.set(n,h),i=this._checkLinkProviderResult(n,t,i),((c=this._activeProviderReplies)==null?void 0:c.size)===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(t.y,this._activeProviderReplies)})}_removeIntersectingLinks(t,e){let i=new Set;for(let s=0;s<e.size;s++){let r=e.get(s);if(r)for(let n=0;n<r.length;n++){let o=r[n],a=o.link.range.start.y<t?0:o.link.range.start.x,h=o.link.range.end.y>t?this._bufferService.cols:o.link.range.end.x;for(let l=a;l<=h;l++){if(i.has(l)){r.splice(n--,1);break}i.add(l)}}}}_checkLinkProviderResult(t,e,i){var n;if(!this._activeProviderReplies)return i;let s=this._activeProviderReplies.get(t),r=!1;for(let o=0;o<t;o++)(!this._activeProviderReplies.has(o)||this._activeProviderReplies.get(o))&&(r=!0);if(!r&&s){let o=s.find(a=>this._linkAtPosition(a.link,e));o&&(i=!0,this._handleNewLink(o))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!i)for(let o=0;o<this._activeProviderReplies.size;o++){let a=(n=this._activeProviderReplies.get(o))==null?void 0:n.find(h=>this._linkAtPosition(h.link,e));if(a){i=!0,this._handleNewLink(a);break}}return i}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(t){if(!this._currentLink)return;let e=this._positionFromMouseEvent(t,this._element,this._mouseService);e&&this._mouseDownLink&&dv(this._mouseDownLink.link,this._currentLink.link)&&this._linkAtPosition(this._currentLink.link,e)&&this._currentLink.link.activate(t,this._currentLink.link.text)}_clearCurrentLink(t,e){!this._currentLink||!this._lastMouseEvent||(!t||!e||this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=e)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,Ti(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(t){if(!this._lastMouseEvent)return;let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._linkAtPosition(t.link,e)&&(this._currentLink=t,this._currentLink.state={decorations:{underline:t.link.decorations===void 0?!0:t.link.decorations.underline,pointerCursor:t.link.decorations===void 0?!0:t.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,t.link,this._lastMouseEvent),t.link.decorations={},Object.defineProperties(t.link.decorations,{pointerCursor:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.pointerCursor},set:i=>{var s;(s=this._currentLink)!=null&&s.state&&this._currentLink.state.decorations.pointerCursor!==i&&(this._currentLink.state.decorations.pointerCursor=i,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",i))}},underline:{get:()=>{var i,s;return(s=(i=this._currentLink)==null?void 0:i.state)==null?void 0:s.decorations.underline},set:i=>{var s,r,n;(s=this._currentLink)!=null&&s.state&&((n=(r=this._currentLink)==null?void 0:r.state)==null?void 0:n.decorations.underline)!==i&&(this._currentLink.state.decorations.underline=i,this._currentLink.state.isHovered&&this._fireUnderlineEvent(t.link,i))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange(i=>{if(!this._currentLink)return;let s=i.start===0?0:i.start+1+this._bufferService.buffer.ydisp,r=this._bufferService.buffer.ydisp+1+i.end;if(this._currentLink.link.range.start.y>=s&&this._currentLink.link.range.end.y<=r&&(this._clearCurrentLink(s,r),this._lastMouseEvent)){let n=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);n&&this._askForLink(n,!1)}})))}_linkHover(t,e,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(e,!0),this._currentLink.state.decorations.pointerCursor&&t.classList.add("xterm-cursor-pointer")),e.hover&&e.hover(i,e.text)}_fireUnderlineEvent(t,e){let i=t.range,s=this._bufferService.buffer.ydisp,r=this._createLinkUnderlineEvent(i.start.x-1,i.start.y-s-1,i.end.x,i.end.y-s-1,void 0);(e?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(r)}_linkLeave(t,e,i){var s;(s=this._currentLink)!=null&&s.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(e,!1),this._currentLink.state.decorations.pointerCursor&&t.classList.remove("xterm-cursor-pointer")),e.leave&&e.leave(i,e.text)}_linkAtPosition(t,e){let i=t.range.start.y*this._bufferService.cols+t.range.start.x,s=t.range.end.y*this._bufferService.cols+t.range.end.x,r=e.y*this._bufferService.cols+e.x;return i<=r&&r<=s}_positionFromMouseEvent(t,e,i){let s=i.getCoords(t,e,this._bufferService.cols,this._bufferService.rows);if(s)return{x:s[0],y:s[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(t,e,i,s,r){return{x1:t,y1:e,x2:i,y2:s,cols:this._bufferService.cols,fg:r}}};vo=Ee([O(1,Do),O(2,si),O(3,ct),O(4,gc)],vo);function dv(t,e){return t.text===e.text&&t.range.start.x===e.range.start.x&&t.range.start.y===e.range.start.y&&t.range.end.x===e.range.end.x&&t.range.end.y===e.range.end.y}var uv=class extends sv{constructor(t={}){super(t),this._linkifier=this._register(new Ji),this.browser=Tc,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new Ji),this._onCursorMove=this._register(new P),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new P),this.onKey=this._onKey.event,this._onRender=this._register(new P),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new P),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new P),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new P),this.onBell=this._onBell.event,this._onFocus=this._register(new P),this._onBlur=this._register(new P),this._onA11yCharEmitter=this._register(new P),this._onA11yTabEmitter=this._register(new P),this._onWillOpen=this._register(new P),this._setup(),this._decorationService=this._instantiationService.createInstance(av),this._instantiationService.setService(Ds,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(tm),this._instantiationService.setService(gc,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance($n)),this._register(this._inputHandler.onRequestBell(()=>this._onBell.fire())),this._register(this._inputHandler.onRequestRefreshRows(e=>this.refresh((e==null?void 0:e.start)??0,(e==null?void 0:e.end)??this.rows-1))),this._register(this._inputHandler.onRequestSendFocus(()=>this._reportFocus())),this._register(this._inputHandler.onRequestReset(()=>this.reset())),this._register(this._inputHandler.onRequestWindowsOptionsReport(e=>this._reportWindowsOptions(e))),this._register(this._inputHandler.onColor(e=>this._handleColorEvent(e))),this._register(et.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(et.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(et.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(et.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize(e=>this._afterResize(e.cols,e.rows))),this._register(pe(()=>{var e,i;this._customKeyEventHandler=void 0,(i=(e=this.element)==null?void 0:e.parentNode)==null||i.removeChild(this.element)}))}get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}_handleColorEvent(t){if(this._themeService)for(let e of t){let i,s="";switch(e.index){case 256:i="foreground",s="10";break;case 257:i="background",s="11";break;case 258:i="cursor",s="12";break;default:i="ansi",s="4;"+e.index}switch(e.type){case 0:let r=_e.toColorRGB(i==="ansi"?this._themeService.colors.ansi[e.index]:this._themeService.colors[i]);this.coreService.triggerDataEvent(`${M.ESC}]${s};${jm(r)}${Mc.ST}`);break;case 1:if(i==="ansi")this._themeService.modifyColors(n=>n.ansi[e.index]=De.toColor(...e.color));else{let n=i;this._themeService.modifyColors(o=>o[n]=De.toColor(...e.color))}break;case 2:this._themeService.restoreColor(e.index);break}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(t){t?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(Sr,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(t){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(M.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){var t;return(t=this.textarea)==null?void 0:t.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(M.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let t=this.buffer.ybase+this.buffer.y,e=this.buffer.lines.get(t);if(!e)return;let i=Math.min(this.buffer.x,this.cols-1),s=this._renderService.dimensions.css.cell.height,r=e.getWidth(i),n=this._renderService.dimensions.css.cell.width*r,o=this.buffer.y*this._renderService.dimensions.css.cell.height,a=i*this._renderService.dimensions.css.cell.width;this.textarea.style.left=a+"px",this.textarea.style.top=o+"px",this.textarea.style.width=n+"px",this.textarea.style.height=s+"px",this.textarea.style.lineHeight=s+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this._register(J(this.element,"copy",e=>{this.hasSelection()&&pg(e,this._selectionService)}));let t=e=>mg(e,this.textarea,this.coreService,this.optionsService);this._register(J(this.textarea,"paste",t)),this._register(J(this.element,"paste",t)),Pc?this._register(J(this.element,"mousedown",e=>{e.button===2&&Fa(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})):this._register(J(this.element,"contextmenu",e=>{Fa(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)})),Oo&&this._register(J(this.element,"auxclick",e=>{e.button===1&&oc(e,this.textarea,this.screenElement)}))}_bindKeys(){this._register(J(this.textarea,"keyup",t=>this._keyUp(t),!0)),this._register(J(this.textarea,"keydown",t=>this._keyDown(t),!0)),this._register(J(this.textarea,"keypress",t=>this._keyPress(t),!0)),this._register(J(this.textarea,"compositionstart",()=>this._compositionHelper.compositionstart())),this._register(J(this.textarea,"compositionupdate",t=>this._compositionHelper.compositionupdate(t))),this._register(J(this.textarea,"compositionend",()=>this._compositionHelper.compositionend())),this._register(J(this.textarea,"input",t=>this._inputEvent(t),!0)),this._register(this.onRender(()=>this._compositionHelper.updateCompositionElements()))}open(t){var r;if(!t)throw new Error("Terminal requires a parent element.");if(t.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),((r=this.element)==null?void 0:r.ownerDocument.defaultView)&&this._coreBrowserService){this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView);return}this._document=t.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),t.appendChild(this.element);let e=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),e.appendChild(this._viewportElement),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this._register(J(this.screenElement,"mousemove",n=>this.updateCursorStyle(n))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),e.appendChild(this.screenElement);let i=this.textarea=this._document.createElement("textarea");this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",Pn.get()),$c||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange("disableStdin",()=>i.readOnly=this.optionsService.rawOptions.disableStdin)),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(Zp,this.textarea,t.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(ii,this._coreBrowserService),this._register(J(this.textarea,"focus",n=>this._handleTextAreaFocus(n))),this._register(J(this.textarea,"blur",()=>this._handleTextAreaBlur())),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(no,this._document,this._helperContainer),this._instantiationService.setService(Er,this._charSizeService),this._themeService=this._instantiationService.createInstance(ho),this._instantiationService.setService(Xi,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(Ar),this._instantiationService.setService(fc,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(ao,this.rows,this.screenElement)),this._instantiationService.setService(si,this._renderService),this._register(this._renderService.onRenderedViewportChange(n=>this._onRender.fire(n))),this.onResize(n=>this._renderService.resize(n.cols,n.rows)),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(io,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(oo),this._instantiationService.setService(Do,this._mouseService);let s=this._linkifier.value=this._register(this._instantiationService.createInstance(vo,this.screenElement));this.element.appendChild(e);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove(()=>{this._renderService.handleCursorMove(),this._syncTextArea()})),this._register(this.onResize(()=>this._renderService.handleResize(this.cols,this.rows))),this._register(this.onBlur(()=>this._renderService.handleBlur())),this._register(this.onFocus(()=>this._renderService.handleFocus())),this._viewport=this._register(this._instantiationService.createInstance(eo,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines(n=>{super.scrollLines(n,!1),this.refresh(0,this.rows-1)})),this._selectionService=this._register(this._instantiationService.createInstance(lo,this.element,this.screenElement,s)),this._instantiationService.setService(xg,this._selectionService),this._register(this._selectionService.onRequestScrollLines(n=>this.scrollLines(n.amount,n.suppressScrollEvent))),this._register(this._selectionService.onSelectionChange(()=>this._onSelectionChange.fire())),this._register(this._selectionService.onRequestRedraw(n=>this._renderService.handleSelectionChanged(n.start,n.end,n.columnSelectMode))),this._register(this._selectionService.onLinuxMouseSelection(n=>{this.textarea.value=n,this.textarea.focus(),this.textarea.select()})),this._register(et.any(this._onScroll.event,this._inputHandler.onScroll)(()=>{var n;this._selectionService.refresh(),(n=this._viewport)==null||n.queueSync()})),this._register(this._instantiationService.createInstance(to,this.screenElement)),this._register(J(this.element,"mousedown",n=>this._selectionService.handleMouseDown(n))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(Sr,this)),this._register(this.optionsService.onSpecificOptionChange("screenReaderMode",n=>this._handleScreenReaderModeOptionChange(n))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(vr,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRuler",n=>{!this._overviewRulerRenderer&&n&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(vr,this._viewportElement,this.screenElement)))}),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(ro,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let t=this,e=this.element;function i(n){var l,c,d,g,u;let o=t._mouseService.getMouseReportCoords(n,t.screenElement);if(!o)return!1;let a,h;switch(n.overrideType||n.type){case"mousemove":h=32,n.buttons===void 0?(a=3,n.button!==void 0&&(a=n.button<3?n.button:3)):a=n.buttons&1?0:n.buttons&4?1:n.buttons&2?2:3;break;case"mouseup":h=0,a=n.button<3?n.button:3;break;case"mousedown":h=1,a=n.button<3?n.button:3;break;case"wheel":if(t._customWheelEventHandler&&t._customWheelEventHandler(n)===!1)return!1;let _=n.deltaY;if(_===0||t.coreMouseService.consumeWheelEvent(n,(g=(d=(c=(l=t._renderService)==null?void 0:l.dimensions)==null?void 0:c.device)==null?void 0:d.cell)==null?void 0:g.height,(u=t._coreBrowserService)==null?void 0:u.dpr)===0)return!1;h=_<0?0:1,a=4;break;default:return!1}return h===void 0||a===void 0||a>4?!1:t.coreMouseService.triggerMouseEvent({col:o.col,row:o.row,x:o.x,y:o.y,button:a,action:h,ctrl:n.ctrlKey,alt:n.altKey,shift:n.shiftKey})}let s={mouseup:null,wheel:null,mousedrag:null,mousemove:null},r={mouseup:n=>(i(n),n.buttons||(this._document.removeEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.removeEventListener("mousemove",s.mousedrag)),this.cancel(n)),wheel:n=>(i(n),this.cancel(n,!0)),mousedrag:n=>{n.buttons&&i(n)},mousemove:n=>{n.buttons||i(n)}};this._register(this.coreMouseService.onProtocolChange(n=>{n?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(n)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),n&8?s.mousemove||(e.addEventListener("mousemove",r.mousemove),s.mousemove=r.mousemove):(e.removeEventListener("mousemove",s.mousemove),s.mousemove=null),n&16?s.wheel||(e.addEventListener("wheel",r.wheel,{passive:!1}),s.wheel=r.wheel):(e.removeEventListener("wheel",s.wheel),s.wheel=null),n&2?s.mouseup||(s.mouseup=r.mouseup):(this._document.removeEventListener("mouseup",s.mouseup),s.mouseup=null),n&4?s.mousedrag||(s.mousedrag=r.mousedrag):(this._document.removeEventListener("mousemove",s.mousedrag),s.mousedrag=null)})),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register(J(e,"mousedown",n=>{if(n.preventDefault(),this.focus(),!(!this.coreMouseService.areMouseEventsActive||this._selectionService.shouldForceSelection(n)))return i(n),s.mouseup&&this._document.addEventListener("mouseup",s.mouseup),s.mousedrag&&this._document.addEventListener("mousemove",s.mousedrag),this.cancel(n)})),this._register(J(e,"wheel",n=>{var o,a,h,l,c;if(!s.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(n)===!1)return!1;if(!this.buffer.hasScrollback){if(n.deltaY===0)return!1;if(t.coreMouseService.consumeWheelEvent(n,(l=(h=(a=(o=t._renderService)==null?void 0:o.dimensions)==null?void 0:a.device)==null?void 0:h.cell)==null?void 0:l.height,(c=t._coreBrowserService)==null?void 0:c.dpr)===0)return this.cancel(n,!0);let d=M.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(n.deltaY<0?"A":"B");return this.coreService.triggerDataEvent(d,!0),this.cancel(n,!0)}}},{passive:!1}))}refresh(t,e){var i;(i=this._renderService)==null||i.refreshRows(t,e)}updateCursorStyle(t){var e;(e=this._selectionService)!=null&&e.shouldColumnSelect(t)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(t,e){this._viewport?this._viewport.scrollLines(t):super.scrollLines(t,e),this.refresh(0,this.rows-1)}scrollPages(t){this.scrollLines(t*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(t){t&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(t){let e=t-this._bufferService.buffer.ydisp;e!==0&&this.scrollLines(e)}paste(t){nc(t,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(t){this._customKeyEventHandler=t}attachCustomWheelEventHandler(t){this._customWheelEventHandler=t}registerLinkProvider(t){return this._linkProviderService.registerLinkProvider(t)}registerCharacterJoiner(t){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");let e=this._characterJoinerService.register(t);return this.refresh(0,this.rows-1),e}deregisterCharacterJoiner(t){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(t)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(t){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+t)}registerDecoration(t){return this._decorationService.registerDecoration(t)}hasSelection(){return this._selectionService?this._selectionService.hasSelection:!1}select(t,e,i){this._selectionService.setSelection(t,e,i)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(!(!this._selectionService||!this._selectionService.hasSelection))return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){var t;(t=this._selectionService)==null||t.clearSelection()}selectAll(){var t;(t=this._selectionService)==null||t.selectAll()}selectLines(t,e){var i;(i=this._selectionService)==null||i.selectLines(t,e)}_keyDown(t){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(t)===!1)return!1;let e=this.browser.isMac&&this.options.macOptionIsMeta&&t.altKey;if(!e&&!this._compositionHelper.keydown(t))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;!e&&(t.key==="Dead"||t.key==="AltGraph")&&(this._unprocessedDeadKey=!0);let i=nv(t,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(t),i.type===3||i.type===2){let s=this.rows-1;return this.scrollLines(i.type===2?-s:s),this.cancel(t,!0)}if(i.type===1&&this.selectAll(),this._isThirdLevelShift(this.browser,t)||(i.cancel&&this.cancel(t,!0),!i.key)||t.key&&!t.ctrlKey&&!t.altKey&&!t.metaKey&&t.key.length===1&&t.key.charCodeAt(0)>=65&&t.key.charCodeAt(0)<=90)return!0;if(this._unprocessedDeadKey)return this._unprocessedDeadKey=!1,!0;if((i.key===M.ETX||i.key===M.CR)&&(this.textarea.value=""),this._onKey.fire({key:i.key,domEvent:t}),this._showCursor(),this.coreService.triggerDataEvent(i.key,!0),!this.optionsService.rawOptions.screenReaderMode||t.altKey||t.ctrlKey)return this.cancel(t,!0);this._keyDownHandled=!0}_isThirdLevelShift(t,e){let i=t.isMac&&!this.options.macOptionIsMeta&&e.altKey&&!e.ctrlKey&&!e.metaKey||t.isWindows&&e.altKey&&e.ctrlKey&&!e.metaKey||t.isWindows&&e.getModifierState("AltGraph");return e.type==="keypress"?i:i&&(!e.keyCode||e.keyCode>47)}_keyUp(t){this._keyDownSeen=!1,!(this._customKeyEventHandler&&this._customKeyEventHandler(t)===!1)&&(_v(t)||this.focus(),this.updateCursorStyle(t),this._keyPressHandled=!1)}_keyPress(t){let e;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(t)===!1)return!1;if(this.cancel(t),t.charCode)e=t.charCode;else if(t.which===null||t.which===void 0)e=t.keyCode;else if(t.which!==0&&t.charCode!==0)e=t.which;else return!1;return!e||(t.altKey||t.ctrlKey||t.metaKey)&&!this._isThirdLevelShift(this.browser,t)?!1:(e=String.fromCharCode(e),this._onKey.fire({key:e,domEvent:t}),this._showCursor(),this.coreService.triggerDataEvent(e,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,!0)}_inputEvent(t){if(t.data&&t.inputType==="insertText"&&(!t.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let e=t.data;return this.coreService.triggerDataEvent(e,!0),this.cancel(t),!0}return!1}resize(t,e){if(t===this.cols&&e===this.rows){this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure();return}super.resize(t,e)}_afterResize(t,e){var i;(i=this._charSizeService)==null||i.measure()}clear(){if(!(this.buffer.ybase===0&&this.buffer.y===0)){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let t=1;t<this.rows;t++)this.buffer.lines.push(this.buffer.getBlankLine(Ie));this._onScroll.fire({position:this.buffer.ydisp}),this.refresh(0,this.rows-1)}}reset(){var e;this.options.rows=this.rows,this.options.cols=this.cols;let t=this._customKeyEventHandler;this._setup(),super.reset(),(e=this._selectionService)==null||e.reset(),this._decorationService.reset(),this._customKeyEventHandler=t,this.refresh(0,this.rows-1)}clearTextureAtlas(){var t;(t=this._renderService)==null||t.clearTextureAtlas()}_reportFocus(){var t;(t=this.element)!=null&&t.classList.contains("focus")?this.coreService.triggerDataEvent(M.ESC+"[I"):this.coreService.triggerDataEvent(M.ESC+"[O")}_reportWindowsOptions(t){if(this._renderService)switch(t){case 0:let e=this._renderService.dimensions.css.canvas.width.toFixed(0),i=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${M.ESC}[4;${i};${e}t`);break;case 1:let s=this._renderService.dimensions.css.cell.width.toFixed(0),r=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${M.ESC}[6;${r};${s}t`);break}}cancel(t,e){if(!(!this.options.cancelEvents&&!e))return t.preventDefault(),t.stopPropagation(),!1}};function _v(t){return t.keyCode===16||t.keyCode===17||t.keyCode===18}var fv=class{constructor(){this._addons=[]}dispose(){for(let t=this._addons.length-1;t>=0;t--)this._addons[t].instance.dispose()}loadAddon(t,e){let i={instance:e,dispose:e.dispose,isDisposed:!1};this._addons.push(i),e.dispose=()=>this._wrappedAddonDispose(i),e.activate(t)}_wrappedAddonDispose(t){if(t.isDisposed)return;let e=-1;for(let i=0;i<this._addons.length;i++)if(this._addons[i]===t){e=i;break}if(e===-1)throw new Error("Could not dispose an addon that has not been loaded");t.isDisposed=!0,t.dispose.apply(t.instance),this._addons.splice(e,1)}},gv=class{constructor(t){this._line=t}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(t,e){if(!(t<0||t>=this._line.length))return e?(this._line.loadCell(t,e),e):this._line.loadCell(t,new xt)}translateToString(t,e,i){return this._line.translateToString(t,e,i)}},Dl=class{constructor(t,e){this._buffer=t,this.type=e}init(t){return this._buffer=t,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(t){let e=this._buffer.lines.get(t);if(e)return new gv(e)}getNullCell(){return new xt}},pv=class extends te{constructor(t){super(),this._core=t,this._onBufferChange=this._register(new P),this.onBufferChange=this._onBufferChange.event,this._normal=new Dl(this._core.buffers.normal,"normal"),this._alternate=new Dl(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate(()=>this._onBufferChange.fire(this.active))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}},mv=class{constructor(t){this._core=t}registerCsiHandler(t,e){return this._core.registerCsiHandler(t,i=>e(i.toArray()))}addCsiHandler(t,e){return this.registerCsiHandler(t,e)}registerDcsHandler(t,e){return this._core.registerDcsHandler(t,(i,s)=>e(i,s.toArray()))}addDcsHandler(t,e){return this.registerDcsHandler(t,e)}registerEscHandler(t,e){return this._core.registerEscHandler(t,e)}addEscHandler(t,e){return this.registerEscHandler(t,e)}registerOscHandler(t,e){return this._core.registerOscHandler(t,e)}addOscHandler(t,e){return this.registerOscHandler(t,e)}},vv=class{constructor(t){this._core=t}register(t){this._core.unicodeService.register(t)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(t){this._core.unicodeService.activeVersion=t}},Av=["cols","rows"],Pt=0,Cv=class extends te{constructor(t){super(),this._core=this._register(new uv(t)),this._addonManager=this._register(new fv),this._publicOptions={...this._core.options};let e=s=>this._core.options[s],i=(s,r)=>{this._checkReadonlyOptions(s),this._core.options[s]=r};for(let s in this._core.options){let r={get:e.bind(this,s),set:i.bind(this,s)};Object.defineProperty(this._publicOptions,s,r)}}_checkReadonlyOptions(t){if(Av.includes(t))throw new Error(`Option "${t}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new mv(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new vv(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this._register(new pv(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let t=this._core.coreService.decPrivateModes,e="none";switch(this._core.coreMouseService.activeProtocol){case"X10":e="x10";break;case"VT200":e="vt200";break;case"DRAG":e="drag";break;case"ANY":e="any";break}return{applicationCursorKeysMode:t.applicationCursorKeys,applicationKeypadMode:t.applicationKeypad,bracketedPasteMode:t.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:e,originMode:t.origin,reverseWraparoundMode:t.reverseWraparound,sendFocusMode:t.sendFocus,synchronizedOutputMode:t.synchronizedOutput,wraparoundMode:t.wraparound}}get options(){return this._publicOptions}set options(t){for(let e in t)this._publicOptions[e]=t[e]}blur(){this._core.blur()}focus(){this._core.focus()}input(t,e=!0){this._core.input(t,e)}resize(t,e){this._verifyIntegers(t,e),this._core.resize(t,e)}open(t){this._core.open(t)}attachCustomKeyEventHandler(t){this._core.attachCustomKeyEventHandler(t)}attachCustomWheelEventHandler(t){this._core.attachCustomWheelEventHandler(t)}registerLinkProvider(t){return this._core.registerLinkProvider(t)}registerCharacterJoiner(t){return this._checkProposedApi(),this._core.registerCharacterJoiner(t)}deregisterCharacterJoiner(t){this._checkProposedApi(),this._core.deregisterCharacterJoiner(t)}registerMarker(t=0){return this._verifyIntegers(t),this._core.registerMarker(t)}registerDecoration(t){return this._checkProposedApi(),this._verifyPositiveIntegers(t.x??0,t.width??0,t.height??0),this._core.registerDecoration(t)}hasSelection(){return this._core.hasSelection()}select(t,e,i){this._verifyIntegers(t,e,i),this._core.select(t,e,i)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(t,e){this._verifyIntegers(t,e),this._core.selectLines(t,e)}dispose(){super.dispose()}scrollLines(t){this._verifyIntegers(t),this._core.scrollLines(t)}scrollPages(t){this._verifyIntegers(t),this._core.scrollPages(t)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(t){this._verifyIntegers(t),this._core.scrollToLine(t)}clear(){this._core.clear()}write(t,e){this._core.write(t,e)}writeln(t,e){this._core.write(t),this._core.write(`\r
|
|
197
197
|
`,e)}paste(t){this._core.paste(t)}refresh(t,e){this._verifyIntegers(t,e),this._core.refresh(t,e)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(t){this._addonManager.loadAddon(this,t)}static get strings(){return{get promptLabel(){return Pn.get()},set promptLabel(t){Pn.set(t)},get tooMuchOutput(){return Qn.get()},set tooMuchOutput(t){Qn.set(t)}}}_verifyIntegers(...t){for(Pt of t)if(Pt===1/0||isNaN(Pt)||Pt%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...t){for(Pt of t)if(Pt&&(Pt===1/0||isNaN(Pt)||Pt%1!==0||Pt<0))throw new Error("This API only accepts positive integers")}};function wv({searchAddon:t,onClose:e,onFocusTerminal:i}){const{t:s}=Co(),r=$.useRef(null),[n,o]=$.useState(""),[a,h]=$.useState(!1),[l,c]=$.useState(!1),[d,g]=$.useState(!1),[u,_]=$.useState(null);$.useEffect(()=>{var D,z;(D=r.current)==null||D.focus(),(z=r.current)==null||z.select()},[]),$.useEffect(()=>{if(!t)return;const D=t.onDidChangeResults(z=>{_(z)});return()=>D.dispose()},[t]);const m={caseSensitive:a,wholeWord:l,regex:d,decorations:{matchBackground:"#e8a63880",matchBorder:"#e8a638",matchOverviewRuler:"#e8a638cc",activeMatchBackground:"#515c6a",activeMatchBorder:"#74879f",activeMatchColorOverviewRuler:"#74879fcc"}},y=$.useCallback(()=>{!t||!n||t.findNext(n,m)},[t,n,a,l,d]),B=$.useCallback(()=>{!t||!n||t.findPrevious(n,m)},[t,n,a,l,d]);$.useEffect(()=>{t&&(n?t.findNext(n,m)===!1&&_({resultIndex:-1,resultCount:0}):(t.clearDecorations(),_(null)))},[t,n,a,l,d]);const T=$.useCallback(()=>{t==null||t.clearDecorations(),e(),i()},[t,e,i]),L=$.useCallback(D=>{D.key==="Escape"?(D.preventDefault(),T()):D.key==="Enter"||D.key==="ArrowDown"?(D.preventDefault(),D.shiftKey?B():y()):D.key==="ArrowUp"&&(D.preventDefault(),B())},[T,y,B]),p=n.length>0,x=p&&u!==null&&u.resultCount===0,E=p?u===null||u.resultCount===0?s("terminal.search.noResults"):`${u.resultIndex+1} of ${u.resultCount}`:s("terminal.search.noResults");return ie.jsxs("div",{className:"terminal-search-bar",onKeyDown:L,onClick:D=>D.stopPropagation(),onMouseDown:D=>D.stopPropagation(),children:[ie.jsxs("div",{className:"terminal-search-input-wrapper",children:[ie.jsx("input",{ref:r,type:"text",className:"terminal-search-input",placeholder:s("terminal.search.placeholder"),value:n,onChange:D=>o(D.target.value),spellCheck:!1,autoComplete:"off"}),ie.jsx("button",{className:`terminal-search-toggle ${a?"active":""}`,onClick:()=>h(!a),title:s("terminal.search.caseSensitive"),children:"Aa"}),ie.jsx("button",{className:`terminal-search-toggle ${l?"active":""}`,onClick:()=>c(!l),title:s("terminal.search.wholeWord"),children:ie.jsx("span",{className:"terminal-search-toggle-ab",children:"ab"})}),ie.jsx("button",{className:`terminal-search-toggle ${d?"active":""}`,onClick:()=>g(!d),title:s("terminal.search.regex"),children:".*"})]}),ie.jsx("span",{className:`terminal-search-results ${x?"no-results":""}`,children:E}),ie.jsx("button",{className:"terminal-search-btn",onClick:B,title:s("terminal.search.previous"),disabled:!n,children:ie.jsx(Ad,{size:16})}),ie.jsx("button",{className:"terminal-search-btn",onClick:y,title:s("terminal.search.next"),disabled:!n,children:ie.jsx(id,{size:16})}),ie.jsx("button",{className:"terminal-search-btn",onClick:T,title:s("terminal.search.close"),children:ie.jsx(Ul,{size:16})})]})}const Jc=5e3,Sv=1e4,bv=25e3,yv=1e4,xv=3e3,Ml=[0,2e3,5e3,1e4,1e4,3e4];function Fo(t){return t>=200&&t<300?"alive":t===404?"missing":t===408||t===429||t>=500?"transient":"fatal"}async function Bv(t,e={},i=fetch,s=Jc){const r=new AbortController,n=setTimeout(()=>r.abort(),s);try{return{kind:"response",response:await i(t,{...e,signal:r.signal})}}catch{return{kind:"transient"}}finally{clearTimeout(n)}}async function Ho(t,e={},i=fetch,s=Jc){const r=new AbortController,n=setTimeout(()=>r.abort(),s);try{const o=await i(t,{...e,signal:r.signal});try{return{kind:"response",response:o,body:await o.json(),bodyError:!1}}catch{return r.signal.aborted?{kind:"transient"}:{kind:"response",response:o,body:null,bodyError:!0}}}catch{return{kind:"transient"}}finally{clearTimeout(n)}}async function Rl(t,e,i=fetch){const s=await Bv(`/api/v1/pty/${encodeURIComponent(t)}`,{headers:e},i);return s.kind==="transient"?"transient":Fo(s.response.status)}class Ev{constructor(){Qs(this,"attempt",0)}next(){if(this.attempt>=Ml.length)return{kind:"exhausted"};const e=this.attempt;return this.attempt+=1,{kind:"scheduled",delayMs:Ml[e],attempt:e}}reset(){this.attempt=0}}class kv{constructor(){Qs(this,"nonce",null);Qs(this,"timer",null)}arm(e,i){this.clear(),this.nonce=e,this.timer=setTimeout(()=>{this.timer=null,this.nonce===e&&(this.nonce=null,i())},yv)}acknowledge(e){return typeof e!="string"||e!==this.nonce?!1:(this.clear(),!0)}hasPendingPing(){return this.nonce!==null}clear(){this.timer&&(clearTimeout(this.timer),this.timer=null),this.nonce=null}}const Iv=2e3;function ks(){return sd({"Content-Type":"application/json"})}function Lv(t){const e=window.location,i=e.protocol==="https:"?"wss:":"ws:",s=rd(),r=s?`?token=${encodeURIComponent(s)}`:"";return`${i}//${e.host}/api/v1/pty/${t}/ws${r}`}class Ao extends Error{}async function Dv(t,e,i){const s={cols:t,rows:e};i&&(s.cwd=i);const r=await Ho("/api/v1/pty",{method:"POST",headers:ks(),body:JSON.stringify(s)});if(r.kind==="transient")throw new Ao;const{response:n,body:o,bodyError:a}=r;if(!n.ok){if(Fo(n.status)==="transient")throw new Ao;const d=o;let g=`HTTP ${n.status}`;throw typeof(d==null?void 0:d.error)=="string"?g=d.error:typeof(d==null?void 0:d.message)=="string"&&(g=d.message),new Error(g)}if(a)throw new Error;const h=o,l=h.data??h;if(typeof l.sessionId!="string")throw new Error;return{sessionId:l.sessionId,cwd:typeof l.cwd=="string"?l.cwd:"",shell:typeof l.shell=="string"?l.shell:void 0}}async function Yc(t){const e=await Ho(`/api/v1/pty/${encodeURIComponent(t)}`,{headers:ks()});if(e.kind==="transient"||!e.response.ok||e.bodyError)return null;const i=e.body,s=i.data??i;return{cwd:typeof s.cwd=="string"?s.cwd:""}}async function Mv(){const t=await Ho("/api/v1/pty",{headers:ks()});if(t.kind==="transient")return{kind:"transient"};const e=Fo(t.response.status);if(e!=="alive")return{kind:e};if(t.bodyError)return{kind:"fatal"};const i=t.body,s=i.data??i;return{kind:"alive",sessions:Array.isArray(s.sessions)?s.sessions:[]}}function Rv(t){const e=it.getState().panes,i=new Set;for(const[s,r]of Object.entries(e))s!==t&&r.ptySessionId&&i.add(r.ptySessionId);return i}function Tv(t,e){return t instanceof Error&&t.message?t.message:e}function Pv(t){const{paneId:e,initialCwd:i,onPtyCreated:s,xtermRef:r,fitAddonRef:n,terminalRef:o,userScrolledUpRef:a,isProgrammaticScrollRef:h,mountedRef:l}=t,{t:c}=Co(),d=$.useRef(c);d.current=c;const g=it(N=>N.setPaneSession),u=it(N=>N.setPaneStatus),_=it(N=>N.setPaneError),m=it(N=>N.setPaneTitle),y=$.useRef(null),B=$.useRef(!1),T=$.useRef(null),L=$.useRef(null),p=$.useRef(null),x=$.useRef(null),E=$.useRef(null),D=$.useRef(null),z=$.useRef(0),K=$.useRef(!1),ne=$.useRef(!1),F=$.useRef(new Ev),C=$.useRef(null),f=$.useRef(null),A=$.useRef(i);A.current=i;const v=$.useRef(s);v.current=s;const w=$.useCallback(N=>l.current&&!K.current&&z.current===N,[l]),b=$.useCallback(()=>{p.current&&(clearTimeout(p.current),p.current=null)},[]),S=$.useCallback(()=>{x.current&&(clearTimeout(x.current),x.current=null)},[]),k=$.useCallback(()=>{const N=f.current;N&&(clearTimeout(N.timer),f.current=null,N.resolve(!1))},[]),I=$.useCallback(N=>{if(N!==void 0&&z.current!==N)return!1;z.current+=1;const Y=E.current;return E.current=null,T.current=null,D.current=null,Y==null||Y(),y.current=null,!0},[]),G=$.useRef(null),V=$.useRef(null),Q=$.useRef(null),le=$.useCallback(()=>{if(b(),!l.current||K.current)return;const N=F.current.next();if(N.kind==="exhausted"){u(e,"error"),_(e,d.current("terminal.connectionLost"));return}const Y=r.current,U=L.current;if(!Y){u(e,"error"),_(e,d.current("terminal.reconnectFailed"));return}u(e,"reconnecting"),_(e,null);const W=z.current;p.current=setTimeout(async()=>{var de,ae;if(p.current=null,!w(W))return;if(!U){C.current&&await C.current(W);return}const re=await Rl(U,ks());if(w(W)){if(re==="alive"){(de=G.current)==null||de.call(G,Y,U);return}if(re==="transient"){(ae=Q.current)==null||ae.call(Q);return}re==="missing"&&(C.current=null),u(e,"error"),_(e,d.current("terminal.connectionLost"))}},N.delayMs)},[b,w,l,e,_,u,r]);Q.current=le;const j=$.useCallback((N,Y)=>{var Mt;if(!l.current||K.current)return;b(),I();const U=z.current;B.current=!0,u(e,"connecting"),_(e,null),L.current=Y;let W;try{W=new WebSocket(Lv(Y))}catch{(Mt=Q.current)==null||Mt.call(Q);return}y.current=W;let re=null,de=null,ae=null,Ce=null,ge=null,ce=!1,me=0,ri="",Lr=0;const ni=new kv,we=()=>w(U)&&y.current===W,ft=()=>{var se;we()&&I(U)&&((se=Q.current)==null||se.call(Q))},oi=()=>{de&&(clearTimeout(de),de=null)},es=()=>{if(!we()||W.readyState!==WebSocket.OPEN)return;oi();const se=`${U}:${++Lr}:${Date.now()}`;try{W.send(JSON.stringify({type:"ping",nonce:se}))}catch{ft();return}ni.arm(se,ft)},wi=()=>{!we()||ni.hasPendingPing()||(oi(),de=setTimeout(es,bv))};D.current={generation:U,send:es};const Z=()=>{if(!we())return;const se=n.current;if(se)try{se.fit()}catch{}N.refresh(0,N.rows-1),a.current||(h.current=!0,N.scrollToBottom(),h.current=!1)},nt=()=>{we()&&(ae&&clearTimeout(ae),ae=setTimeout(()=>{ae=null,we()&&Z()},0))},Ut=(se,Se)=>{var Bt;if(!we())return;if(!a.current){N.write(se,Se);return}const mt=(Bt=o.current)==null?void 0:Bt.querySelector(".xterm-viewport");if(!mt){N.write(se,Se);return}const ai=mt.scrollTop;h.current=!0,N.write(se,()=>{we()&&(mt.scrollTop=ai,h.current=!1,Se==null||Se())})},Gt=()=>{if(Ce=null,!we()||!ri)return;const se=ri;ri="",ce?(ce=!1,Ut(se,nt)):Ut(se)},ts=se=>{we()&&(ri+=se,Ce||(Ce=setTimeout(Gt,16)))},Dt=()=>{!we()||me<=0||W.readyState!==WebSocket.OPEN||(W.send(JSON.stringify({type:"ack",bytesReceived:me})),me=0)};re=setTimeout(()=>{re=null,we()&&W.readyState===WebSocket.CONNECTING&&ft()},Sv),W.onopen=()=>{we()&&(re&&(clearTimeout(re),re=null),B.current=!0,F.current.reset(),C.current=null,u(e,"connected"),_(e,null),ce=!0,ge=requestAnimationFrame(()=>{if(ge=null,!we())return;const se=n.current;if(se)try{const Se=se.proposeDimensions();Se&&W.readyState===WebSocket.OPEN&&W.send(JSON.stringify({type:"resize",cols:Se.cols,rows:Se.rows}))}catch{}}),N.focus(),wi())},W.onmessage=se=>{if(!we())return;let Se;try{Se=JSON.parse(se.data)}catch{return}if(!Se||typeof Se!="object"||Array.isArray(Se))return;const mt=Se;switch(mt.type){case"output":typeof mt.data=="string"&&mt.data&&(ts(mt.data),me+=mt.data.length,me>=100*1024&&Dt()),wi();break;case"exit":Gt(),Dt(),K.current=!0,B.current=!1,b(),S(),C.current=null,g(e,null),u(e,"disconnected"),L.current=null,N.write(`\r
|
|
198
198
|
${d.current("terminal.processExited")}\r
|
|
199
|
-
`),I(U);break;case"pause":case"resume":wi();break;case"pong":ni.acknowledge(mt.nonce)&&wi();break}},W.onerror=()=>{we()},W.onclose=()=>{we()&&ft()};const Si=N.onData(se=>{we()&&W.readyState===WebSocket.OPEN&&W.send(JSON.stringify({type:"input",data:se}))}),Ts=N.onResize(({cols:se,rows:Se})=>{we()&&W.readyState===WebSocket.OPEN&&W.send(JSON.stringify({type:"resize",cols:se,rows:Se}))}),Ps=()=>{var se;if(re&&(clearTimeout(re),re=null),oi(),ni.clear(),Ce&&(clearTimeout(Ce),Ce=null),ae&&(clearTimeout(ae),ae=null),ge!==null&&(cancelAnimationFrame(ge),ge=null),ri="",me=0,h.current=!1,Si.dispose(),Ts.dispose(),W.onopen=null,W.onmessage=null,W.onerror=null,W.onclose=null,W.readyState===WebSocket.OPEN||W.readyState===WebSocket.CONNECTING)try{W.close()}catch{}y.current===W&&(y.current=null),((se=D.current)==null?void 0:se.generation)===U&&(D.current=null)};E.current=Ps,T.current=()=>{l.current||(K.current=!0),b(),S(),k(),I(U)}},[b,k,S,n,w,h,l,e,I,_,g,u,o,a]);G.current=j;const R=$.useCallback((N,Y)=>{v.current&&Yc(N).then(U=>{var W;U&&w(Y)&&((W=v.current)==null||W.call(v,{sessionId:N,cwd:U.cwd}))}).catch(()=>{})},[w]),q=$.useCallback(async(N,Y,U,W)=>{var de,ae,Ce;if(!w(W))return;const re=await Mv();if(w(W)){if(re.kind==="transient"){(de=Q.current)==null||de.call(Q);return}if(re.kind==="fatal"){u(e,"error"),_(e,d.current("terminal.reconnectFailed"));return}if(re.kind==="alive"){const ge=Rv(e),ce=re.sessions.find(me=>!me.hasClient&&!ge.has(me.id));if(ce){g(e,ce.id),j(N,ce.id),R(ce.id,z.current);return}}u(e,"connecting");try{const ge=A.current||void 0,ce=await Dv(Y,U,ge);if(!w(W))return;g(e,ce.sessionId),ce.shell&&m(e,ce.shell),(ae=v.current)==null||ae.call(v,{sessionId:ce.sessionId,cwd:ce.cwd}),j(N,ce.sessionId)}catch(ge){if(!w(W))return;if(ge instanceof Ao){(Ce=Q.current)==null||Ce.call(Q);return}C.current=null,u(e,"error"),_(e,Tv(ge,d.current("terminal.createSessionFailed")))}}},[j,w,R,e,_,g,u,m]),H=$.useCallback(async(N,Y,U,W,re)=>{var ae;if(C.current=Ce=>q(N,U,W,Ce),!Y){await q(N,U,W,re);return}L.current=Y;const de=await Rl(Y,ks());if(w(re)){if(de==="alive"){j(N,Y),R(Y,z.current);return}if(de==="missing"){await q(N,U,W,re);return}if(de==="transient"){(ae=Q.current)==null||ae.call(Q);return}C.current=null,u(e,"error"),_(e,d.current("terminal.reconnectFailed"))}},[j,w,R,e,q,_,u]),X=$.useCallback(async()=>{var W,re;const N=r.current,Y=n.current;if(!N||!Y||!l.current||K.current||B.current||((W=y.current)==null?void 0:W.readyState)===WebSocket.CONNECTING||ne.current)return;ne.current=!0,B.current=!0;const U=z.current;try{let de=80,ae=24;try{const ge=Y.proposeDimensions();ge&&(de=ge.cols,ae=ge.rows)}catch{}const Ce=(re=it.getState().panes[e])==null?void 0:re.ptySessionId;await H(N,Ce,de,ae,U)}finally{ne.current=!1}},[H,n,l,e,r]);V.current=X;const oe=$.useCallback(async()=>{var ae,Ce;K.current=!1,ne.current=!1,C.current=null,F.current.reset(),b(),S(),k(),I(),L.current=null,u(e,"connecting"),_(e,null);const N=z.current;if(!await new Promise(ge=>{const ce=setTimeout(()=>{var me;((me=f.current)==null?void 0:me.timer)===ce&&(f.current=null),ge(w(N))},Iv);f.current={timer:ce,resolve:ge}})||!w(N))return;const U=r.current;if(!U)return;try{(ae=n.current)==null||ae.fit()}catch{}const W=U.cols||80,re=U.rows||24,de=(Ce=it.getState().panes[e])==null?void 0:Ce.ptySessionId;await H(U,de,W,re,N)},[b,k,S,H,n,w,e,I,_,u,r]);return $.useEffect(()=>{const N=()=>{if(!l.current||K.current)return;S();const U=z.current;x.current=setTimeout(()=>{var re,de,ae;if(x.current=null,!w(U))return;const W=y.current;if((W==null?void 0:W.readyState)===WebSocket.OPEN){(re=D.current)==null||re.send();return}(W==null?void 0:W.readyState)!==WebSocket.CONNECTING&&(I(),ne.current=!1,F.current.reset(),L.current||C.current?(de=Q.current)==null||de.call(Q):(B.current=!1,(ae=V.current)==null||ae.call(V).catch(()=>{})))},xv)},Y=()=>{document.visibilityState==="visible"&&N()};return document.addEventListener("visibilitychange",Y),window.addEventListener("online",N),window.addEventListener("pageshow",N),window.addEventListener("focus",N),()=>{document.removeEventListener("visibilitychange",Y),window.removeEventListener("online",N),window.removeEventListener("pageshow",N),window.removeEventListener("focus",N),S()}},[S,w,l,I]),$.useEffect(()=>(K.current=!1,()=>{K.current=!0,B.current=!1,C.current=null,b(),S(),k(),I()}),[b,k,S,I]),{connectToPty:j,initPtyConnection:X,handleManualReconnect:oe,wsRef:y,ptyConnectedRef:B,connectionCleanupRef:T,currentSessionIdRef:L,autoReconnectTimerRef:p}}const Qv={background:"#ffffff",foreground:"#1e1e1e",cursor:"#1e1e1e",cursorAccent:"#ffffff",selectionBackground:"#add6ff80",black:"#000000",red:"#cd3131",green:"#00bc00",yellow:"#949800",blue:"#0451a5",magenta:"#bc05bc",cyan:"#0598bc",white:"#555555",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#14ce14",brightYellow:"#b5ba00",brightBlue:"#0451a5",brightMagenta:"#bc05bc",brightCyan:"#0598bc",brightWhite:"#a5a5a5"},Nv={background:"#191a1b",foreground:"#cccccc",cursor:"#cccccc",cursorAccent:"#191a1b",selectionBackground:"#264f7880",black:"#000000",red:"#f44747",green:"#6a9955",yellow:"#d7ba7d",blue:"#569cd6",magenta:"#c586c0",cyan:"#4ec9b0",white:"#d4d4d4",brightBlack:"#808080",brightRed:"#f44747",brightGreen:"#6a9955",brightYellow:"#d7ba7d",brightBlue:"#569cd6",brightMagenta:"#c586c0",brightCyan:"#4ec9b0",brightWhite:"#e5e5e5"};function Tl(t,e){const i=t?Nv:Qv,s=e?getComputedStyle(e).getPropertyValue("--ide-side-panel-bg").trim():"";return s?{...i,background:s,cursorAccent:s}:i}function tA({paneId:t,initialCwd:e,onPtyCreated:i}){const{t:s}=Co(),{resolved:r}=nd(),n=it(R=>R.panes[t]),o=it(R=>R.activePaneId),a=it(R=>R.layout),h=it(R=>R.mainView),l=it(R=>R.setActivePaneId),c=it(R=>R.closePane),d=it(R=>R.setPaneTitle),g=it(R=>R.setTerminalTitle),u=o===t,_=od(a),[m,y]=$.useState(!1),[B,T]=$.useState(null),L=$.useRef(null),p=$.useRef(null),x=$.useRef(null),E=$.useRef(null),D=$.useRef(null),z=$.useRef(null),K=$.useRef(null),ne=$.useRef(!0),F=$.useRef(!1),C=$.useRef(!1),f=$.useRef(!1),{initPtyConnection:A,handleManualReconnect:v,ptyConnectedRef:w,connectionCleanupRef:b,autoReconnectTimerRef:S}=Pv({paneId:t,initialCwd:e,onPtyCreated:i,xtermRef:x,fitAddonRef:E,terminalRef:p,userScrolledUpRef:C,isProgrammaticScrollRef:f,mountedRef:ne}),k=$.useCallback(()=>{const R=p.current;if(!R||F.current)return;const q=Tl(r==="dark",R);for(;R.firstChild;)R.removeChild(R.firstChild);const H=new Cv({cursorBlink:!0,fontSize:13,fontFamily:'Menlo, Monaco, "Courier New", monospace',theme:q,allowProposedApi:!0,scrollback:5e4,scrollOnEraseInDisplay:!0}),X=new Pd;H.loadAddon(X);let oe=null;const N=(Z,nt)=>{oe&&oe.remove(),oe=document.createElement("div"),oe.textContent=nt,oe.className="xterm-link-tooltip",Object.assign(oe.style,{position:"fixed",left:`${Z.clientX}px`,top:`${Z.clientY+16}px`,padding:"2px 8px",borderRadius:"4px",fontSize:"12px",pointerEvents:"none",zIndex:"10000",maxWidth:"600px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",background:"var(--color-bg-tertiary, #333)",color:"var(--color-text-primary, #eee)",border:"1px solid var(--color-border-muted, #555)"}),document.body.appendChild(oe)},Y=()=>{oe&&(oe.remove(),oe=null)},U=new I_((Z,nt)=>{window.open(nt,"_blank","noopener")},{hover(Z,nt){N(Z,nt)},leave:Y});H.loadAddon(U);const W=/(?:(?:\.{1,2}\/|\/)[a-zA-Z0-9._\-~@+/]+[a-zA-Z0-9._\-~@+])(?::(\d+)(?::(\d+))?)?/g,re=["/api/","/http","/dev/","/proc/","/sys/","/tmp/"];H.registerLinkProvider({provideLinks(Z,nt){const Ut=H.buffer.active.getLine(Z-1);if(!Ut){nt(void 0);return}const Gt=Ut.translateToString(!0),ts=[];W.lastIndex=0;let Dt;for(;(Dt=W.exec(Gt))!==null;){const Si=Dt[0],Ts=Dt.index,Ps=Si.indexOf(":"),Mt=Ps>=0?Si.slice(0,Ps):Si;if(re.some(ai=>Mt.startsWith(ai)))continue;const se=Dt[1]?parseInt(Dt[1],10):void 0,Se=Dt[2]?parseInt(Dt[2],10):void 0,mt=se?`${Mt}:${se}${Se?":"+Se:""}`:Mt;ts.push({range:{start:{x:Ts+1,y:Z},end:{x:Ts+Si.length+1,y:Z}},text:Si,activate(){var Wo;const ai=zo()||((Wo=ad.getState().info)==null?void 0:Wo.cwd),Bt=Mt.startsWith("/")?Mt:ai?`${ai}/${Mt}`:Mt;ld(Bt).then(Vc=>{const{rootPath:Dr,revealInTree:jc}=Uo.getState();Vc==="directory"?Dr&&(Bt===Dr||Bt.startsWith(Dr+"/"))?(jc(Bt),Go("editor")):(hd(async()=>{const{useFolderStore:Mr}=await import("./index-CHcoPr8x.js").then(Xc=>Xc.bp);return{useFolderStore:Mr}},__vite__mapDeps([0,1,2,3])).then(({useFolderStore:Mr})=>{Mr.getState().setFolder(Bt)}),Go("editor")):(Ko(Bt,se,Se),setTimeout(()=>{Uo.getState().revealInTree(Bt)},150))}).catch(()=>{Ko(Bt,se,Se)})},hover(ai){N(ai,`${mt} — Click to open in editor`)},leave:Y})}nt(ts.length>0?ts:void 0)}}),H.attachCustomKeyEventHandler(Z=>Z.key==="f"&&(Z.metaKey||Z.ctrlKey)&&!Z.shiftKey&&!Z.altKey?(Z.type==="keydown"&&(Z.preventDefault(),y(!0)),!1):Z.key==="Enter"&&Z.shiftKey?(Z.type==="keydown"&&H.input("\x1B[13;2u",!0),!1):!0),H.open(R);const de=new b_;H.loadAddon(de),H.unicode.activeVersion="11";const ae=new Yu;H.loadAddon(ae);const Ce=new Uu;H.loadAddon(Ce),z.current=Ce;const ge=new Ld;H.loadAddon(ge);try{const Z=new dg;Z.onContextLoss(()=>{Z.dispose(),D.current=null,K.current&&(K.current.dispose(),K.current=null)}),H.loadAddon(Z),D.current=Z;const nt=new du;H.loadAddon(nt),K.current=nt}catch{}const ce=R.querySelector(".xterm-helper-textarea");ce&&(ce.setAttribute("autocomplete","off"),ce.setAttribute("autocorrect","off"),ce.setAttribute("autocapitalize","off"),ce.setAttribute("spellcheck","false"),ce.setAttribute("unselectable","on")),x.current=H,E.current=X,F.current=!0;const me=R.querySelector(".xterm-viewport"),ri=()=>{if(f.current||!me)return;const Z=me.scrollHeight-me.scrollTop-me.clientHeight<5;C.current=!Z};me==null||me.addEventListener("scroll",ri);const Lr=H.onTitleChange(Z=>{ne.current&&Z&&(g(Z),d(t,Z))});let ni=R.offsetParent===null;const we=()=>{if(ne.current)try{const Z=R.offsetParent!==null,nt=ni&&Z;if(ni=!Z,!Z)return;const Ut=X.proposeDimensions();if(Ut&&(Ut.cols!==H.cols||Ut.rows!==H.rows))X.fit();else if(nt){const Gt=H._core;Gt!=null&&Gt.viewport&&Gt.viewport.syncScrollArea(!0)}C.current||(f.current=!0,H.scrollToBottom(),f.current=!1)}catch{}};let ft=null;const oi=()=>{const Z=R.offsetParent!==null;if(ni&&Z){ft&&clearTimeout(ft),ft=null,we();return}ft&&clearTimeout(ft),ft=setTimeout(we,50)},es=new ResizeObserver(oi);es.observe(R),window.addEventListener("resize",oi);const wi=()=>{document.visibilityState==="visible"&&oi()};return document.addEventListener("visibilitychange",wi),()=>{me==null||me.removeEventListener("scroll",ri),Lr.dispose(),es.disconnect(),window.removeEventListener("resize",oi),document.removeEventListener("visibilitychange",wi),ft&&clearTimeout(ft),oe&&(oe.remove(),oe=null)}},[]),I=$.useRef(null);$.useEffect(()=>{ne.current=!0;const R=p.current;if(!R)return;const q=()=>{if(!ne.current)return;const{clientWidth:X,clientHeight:oe}=R;X===0||oe===0||(F.current||(I.current=k()||null),x.current&&E.current&&(w.current||A()))};if(R.clientWidth>0&&R.clientHeight>0){const X=requestAnimationFrame(q);return()=>cancelAnimationFrame(X)}const H=new ResizeObserver(X=>{for(const oe of X){const{width:N,height:Y}=oe.contentRect;if(N>0&&Y>0){H.disconnect(),q();break}}});return H.observe(R),()=>H.disconnect()},[k,A]),$.useEffect(()=>()=>{var R,q,H;ne.current=!1,S.current&&(clearTimeout(S.current),S.current=null),(R=b.current)==null||R.call(b),(q=I.current)==null||q.call(I);try{(H=x.current)==null||H.dispose()}catch{}x.current=null,E.current=null,D.current=null,z.current=null,K.current=null,F.current=!1,w.current=!1},[]),$.useEffect(()=>{const R=x.current;if(R){R.options.theme=Tl(r==="dark",p.current);try{R.refresh(0,R.rows-1)}catch{}}},[r,h]);const G=$.useCallback(()=>{var R;u||l(t),(R=x.current)==null||R.focus()},[u,t,l]),V=$.useCallback(R=>{var H;R.preventDefault(),R.stopPropagation();const q=((H=x.current)==null?void 0:H.getSelection())??"";T({x:R.clientX,y:R.clientY,text:q})},[]);$.useEffect(()=>{if(B)return cd({onClose:()=>T(null),isInside:R=>md(R,L.current)})},[B]),$.useLayoutEffect(()=>{!B||!L.current||dd(L.current,B.x+4,B.y+4)},[B]);const Q=$.useCallback(async()=>{var X,oe;const R=(B==null?void 0:B.text)??((X=x.current)==null?void 0:X.getSelection())??"";if(T(null),!R.trim())return;let q=e||zo();const H=(oe=it.getState().panes[t])==null?void 0:oe.ptySessionId;if(H){const N=await Yc(H);N!=null&&N.cwd&&(q=N.cwd)}ud(_d(R,q))},[B,e,t]),le=$.useCallback(()=>{var q;const R=(B==null?void 0:B.text)??"";T(null),R&&((q=navigator.clipboard)==null||q.writeText(R).catch(()=>{}))},[B]),j=$.useCallback(async()=>{var R,q;T(null);try{const H=await navigator.clipboard.readText();H&&((R=x.current)==null||R.paste(H))}catch{}(q=x.current)==null||q.focus()},[]);return n?ie.jsxs("div",{className:`terminal-pane flex flex-col h-full w-full min-h-0 ${u&&_>1?"active":""}`,style:{backgroundColor:"var(--ide-side-panel-bg)"},onClick:G,onContextMenu:V,children:[m&&ie.jsx(wv,{searchAddon:z.current,onClose:()=>y(!1),onFocusTerminal:()=>{var R;return(R=x.current)==null?void 0:R.focus()}}),_>1&&ie.jsx("div",{className:"terminal-pane-toolbar",children:ie.jsx("button",{onClick:R=>{R.stopPropagation(),c(t)},className:"w-6 h-6 flex items-center justify-center rounded bg-bg-tertiary/80 text-text-secondary hover:text-text-primary hover:bg-bg-hover transition-colors",title:s("terminal.closePane"),children:ie.jsx(Ul,{size:14})})}),ie.jsx("div",{ref:p,className:"flex-1 w-full min-h-0",style:{overflow:"hidden",padding:"4px"}}),n.ptyStatus==="connecting"&&ie.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{backgroundColor:"var(--ide-side-panel-bg)"},children:ie.jsx(qo,{size:20,className:"animate-spin",style:{color:"var(--color-text-tertiary)"}})}),n.ptyStatus==="reconnecting"&&ie.jsxs("div",{className:"absolute bottom-0 left-0 right-0 flex items-center px-4 py-2 bg-bg-secondary/80 border-t border-border-muted z-10",children:[ie.jsx(qo,{size:12,className:"animate-spin mr-2 text-text-tertiary"}),ie.jsx("span",{className:"text-text-secondary text-xs",children:s("terminal.reconnecting")})]}),n.ptyStatus==="error"&&ie.jsxs("div",{className:"absolute bottom-0 left-0 right-0 flex items-center justify-between px-4 py-2 bg-accent-red/10 border-t border-accent-red/30 z-10",children:[ie.jsxs("div",{className:"flex items-center gap-2 text-accent-red text-xs",children:[ie.jsx(fd,{size:14}),ie.jsx("span",{children:n.errorMessage||s("terminal.error")})]}),ie.jsxs("button",{onClick:v,className:"flex items-center gap-1.5 px-3 py-1 rounded-md bg-bg-secondary border border-border-muted text-text-primary text-xs hover:bg-bg-hover transition-colors",children:[ie.jsx(gd,{size:12}),ie.jsx("span",{children:s("terminal.reconnect")})]})]}),B&&pd.createPortal(ie.jsxs("div",{ref:L,className:"editor-context-menu",role:"menu",style:{left:B.x,top:B.y},onPointerDown:R=>R.stopPropagation(),onContextMenu:R=>R.preventDefault(),children:[ie.jsx("button",{type:"button",role:"menuitem",disabled:!B.text.trim(),onClick:()=>{Q().catch(()=>{})},children:s("composer.addToChat")}),ie.jsx("button",{type:"button",role:"menuitem",disabled:!B.text,onClick:le,children:s("terminal.copySelection")}),ie.jsx("button",{type:"button",role:"menuitem",onClick:()=>{j().catch(()=>{})},children:s("editor.paste")})]}),document.body)]}):ie.jsx("div",{})}export{tA as TerminalPaneView};
|
|
199
|
+
`),I(U);break;case"pause":case"resume":wi();break;case"pong":ni.acknowledge(mt.nonce)&&wi();break}},W.onerror=()=>{we()},W.onclose=()=>{we()&&ft()};const Si=N.onData(se=>{we()&&W.readyState===WebSocket.OPEN&&W.send(JSON.stringify({type:"input",data:se}))}),Ts=N.onResize(({cols:se,rows:Se})=>{we()&&W.readyState===WebSocket.OPEN&&W.send(JSON.stringify({type:"resize",cols:se,rows:Se}))}),Ps=()=>{var se;if(re&&(clearTimeout(re),re=null),oi(),ni.clear(),Ce&&(clearTimeout(Ce),Ce=null),ae&&(clearTimeout(ae),ae=null),ge!==null&&(cancelAnimationFrame(ge),ge=null),ri="",me=0,h.current=!1,Si.dispose(),Ts.dispose(),W.onopen=null,W.onmessage=null,W.onerror=null,W.onclose=null,W.readyState===WebSocket.OPEN||W.readyState===WebSocket.CONNECTING)try{W.close()}catch{}y.current===W&&(y.current=null),((se=D.current)==null?void 0:se.generation)===U&&(D.current=null)};E.current=Ps,T.current=()=>{l.current||(K.current=!0),b(),S(),k(),I(U)}},[b,k,S,n,w,h,l,e,I,_,g,u,o,a]);G.current=j;const R=$.useCallback((N,Y)=>{v.current&&Yc(N).then(U=>{var W;U&&w(Y)&&((W=v.current)==null||W.call(v,{sessionId:N,cwd:U.cwd}))}).catch(()=>{})},[w]),q=$.useCallback(async(N,Y,U,W)=>{var de,ae,Ce;if(!w(W))return;const re=await Mv();if(w(W)){if(re.kind==="transient"){(de=Q.current)==null||de.call(Q);return}if(re.kind==="fatal"){u(e,"error"),_(e,d.current("terminal.reconnectFailed"));return}if(re.kind==="alive"){const ge=Rv(e),ce=re.sessions.find(me=>!me.hasClient&&!ge.has(me.id));if(ce){g(e,ce.id),j(N,ce.id),R(ce.id,z.current);return}}u(e,"connecting");try{const ge=A.current||void 0,ce=await Dv(Y,U,ge);if(!w(W))return;g(e,ce.sessionId),ce.shell&&m(e,ce.shell),(ae=v.current)==null||ae.call(v,{sessionId:ce.sessionId,cwd:ce.cwd}),j(N,ce.sessionId)}catch(ge){if(!w(W))return;if(ge instanceof Ao){(Ce=Q.current)==null||Ce.call(Q);return}C.current=null,u(e,"error"),_(e,Tv(ge,d.current("terminal.createSessionFailed")))}}},[j,w,R,e,_,g,u,m]),H=$.useCallback(async(N,Y,U,W,re)=>{var ae;if(C.current=Ce=>q(N,U,W,Ce),!Y){await q(N,U,W,re);return}L.current=Y;const de=await Rl(Y,ks());if(w(re)){if(de==="alive"){j(N,Y),R(Y,z.current);return}if(de==="missing"){await q(N,U,W,re);return}if(de==="transient"){(ae=Q.current)==null||ae.call(Q);return}C.current=null,u(e,"error"),_(e,d.current("terminal.reconnectFailed"))}},[j,w,R,e,q,_,u]),X=$.useCallback(async()=>{var W,re;const N=r.current,Y=n.current;if(!N||!Y||!l.current||K.current||B.current||((W=y.current)==null?void 0:W.readyState)===WebSocket.CONNECTING||ne.current)return;ne.current=!0,B.current=!0;const U=z.current;try{let de=80,ae=24;try{const ge=Y.proposeDimensions();ge&&(de=ge.cols,ae=ge.rows)}catch{}const Ce=(re=it.getState().panes[e])==null?void 0:re.ptySessionId;await H(N,Ce,de,ae,U)}finally{ne.current=!1}},[H,n,l,e,r]);V.current=X;const oe=$.useCallback(async()=>{var ae,Ce;K.current=!1,ne.current=!1,C.current=null,F.current.reset(),b(),S(),k(),I(),L.current=null,u(e,"connecting"),_(e,null);const N=z.current;if(!await new Promise(ge=>{const ce=setTimeout(()=>{var me;((me=f.current)==null?void 0:me.timer)===ce&&(f.current=null),ge(w(N))},Iv);f.current={timer:ce,resolve:ge}})||!w(N))return;const U=r.current;if(!U)return;try{(ae=n.current)==null||ae.fit()}catch{}const W=U.cols||80,re=U.rows||24,de=(Ce=it.getState().panes[e])==null?void 0:Ce.ptySessionId;await H(U,de,W,re,N)},[b,k,S,H,n,w,e,I,_,u,r]);return $.useEffect(()=>{const N=()=>{if(!l.current||K.current)return;S();const U=z.current;x.current=setTimeout(()=>{var re,de,ae;if(x.current=null,!w(U))return;const W=y.current;if((W==null?void 0:W.readyState)===WebSocket.OPEN){(re=D.current)==null||re.send();return}(W==null?void 0:W.readyState)!==WebSocket.CONNECTING&&(I(),ne.current=!1,F.current.reset(),L.current||C.current?(de=Q.current)==null||de.call(Q):(B.current=!1,(ae=V.current)==null||ae.call(V).catch(()=>{})))},xv)},Y=()=>{document.visibilityState==="visible"&&N()};return document.addEventListener("visibilitychange",Y),window.addEventListener("online",N),window.addEventListener("pageshow",N),window.addEventListener("focus",N),()=>{document.removeEventListener("visibilitychange",Y),window.removeEventListener("online",N),window.removeEventListener("pageshow",N),window.removeEventListener("focus",N),S()}},[S,w,l,I]),$.useEffect(()=>(K.current=!1,()=>{K.current=!0,B.current=!1,C.current=null,b(),S(),k(),I()}),[b,k,S,I]),{connectToPty:j,initPtyConnection:X,handleManualReconnect:oe,wsRef:y,ptyConnectedRef:B,connectionCleanupRef:T,currentSessionIdRef:L,autoReconnectTimerRef:p}}const Qv={background:"#ffffff",foreground:"#1e1e1e",cursor:"#1e1e1e",cursorAccent:"#ffffff",selectionBackground:"#add6ff80",black:"#000000",red:"#cd3131",green:"#00bc00",yellow:"#949800",blue:"#0451a5",magenta:"#bc05bc",cyan:"#0598bc",white:"#555555",brightBlack:"#666666",brightRed:"#cd3131",brightGreen:"#14ce14",brightYellow:"#b5ba00",brightBlue:"#0451a5",brightMagenta:"#bc05bc",brightCyan:"#0598bc",brightWhite:"#a5a5a5"},Nv={background:"#191a1b",foreground:"#cccccc",cursor:"#cccccc",cursorAccent:"#191a1b",selectionBackground:"#264f7880",black:"#000000",red:"#f44747",green:"#6a9955",yellow:"#d7ba7d",blue:"#569cd6",magenta:"#c586c0",cyan:"#4ec9b0",white:"#d4d4d4",brightBlack:"#808080",brightRed:"#f44747",brightGreen:"#6a9955",brightYellow:"#d7ba7d",brightBlue:"#569cd6",brightMagenta:"#c586c0",brightCyan:"#4ec9b0",brightWhite:"#e5e5e5"};function Tl(t,e){const i=t?Nv:Qv,s=e?getComputedStyle(e).getPropertyValue("--ide-side-panel-bg").trim():"";return s?{...i,background:s,cursorAccent:s}:i}function tA({paneId:t,initialCwd:e,onPtyCreated:i}){const{t:s}=Co(),{resolved:r}=nd(),n=it(R=>R.panes[t]),o=it(R=>R.activePaneId),a=it(R=>R.layout),h=it(R=>R.mainView),l=it(R=>R.setActivePaneId),c=it(R=>R.closePane),d=it(R=>R.setPaneTitle),g=it(R=>R.setTerminalTitle),u=o===t,_=od(a),[m,y]=$.useState(!1),[B,T]=$.useState(null),L=$.useRef(null),p=$.useRef(null),x=$.useRef(null),E=$.useRef(null),D=$.useRef(null),z=$.useRef(null),K=$.useRef(null),ne=$.useRef(!0),F=$.useRef(!1),C=$.useRef(!1),f=$.useRef(!1),{initPtyConnection:A,handleManualReconnect:v,ptyConnectedRef:w,connectionCleanupRef:b,autoReconnectTimerRef:S}=Pv({paneId:t,initialCwd:e,onPtyCreated:i,xtermRef:x,fitAddonRef:E,terminalRef:p,userScrolledUpRef:C,isProgrammaticScrollRef:f,mountedRef:ne}),k=$.useCallback(()=>{const R=p.current;if(!R||F.current)return;const q=Tl(r==="dark",R);for(;R.firstChild;)R.removeChild(R.firstChild);const H=new Cv({cursorBlink:!0,fontSize:13,fontFamily:'Menlo, Monaco, "Courier New", monospace',theme:q,allowProposedApi:!0,scrollback:5e4,scrollOnEraseInDisplay:!0}),X=new Pd;H.loadAddon(X);let oe=null;const N=(Z,nt)=>{oe&&oe.remove(),oe=document.createElement("div"),oe.textContent=nt,oe.className="xterm-link-tooltip",Object.assign(oe.style,{position:"fixed",left:`${Z.clientX}px`,top:`${Z.clientY+16}px`,padding:"2px 8px",borderRadius:"4px",fontSize:"12px",pointerEvents:"none",zIndex:"10000",maxWidth:"600px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",background:"var(--color-bg-tertiary, #333)",color:"var(--color-text-primary, #eee)",border:"1px solid var(--color-border-muted, #555)"}),document.body.appendChild(oe)},Y=()=>{oe&&(oe.remove(),oe=null)},U=new I_((Z,nt)=>{window.open(nt,"_blank","noopener")},{hover(Z,nt){N(Z,nt)},leave:Y});H.loadAddon(U);const W=/(?:(?:\.{1,2}\/|\/)[a-zA-Z0-9._\-~@+/]+[a-zA-Z0-9._\-~@+])(?::(\d+)(?::(\d+))?)?/g,re=["/api/","/http","/dev/","/proc/","/sys/","/tmp/"];H.registerLinkProvider({provideLinks(Z,nt){const Ut=H.buffer.active.getLine(Z-1);if(!Ut){nt(void 0);return}const Gt=Ut.translateToString(!0),ts=[];W.lastIndex=0;let Dt;for(;(Dt=W.exec(Gt))!==null;){const Si=Dt[0],Ts=Dt.index,Ps=Si.indexOf(":"),Mt=Ps>=0?Si.slice(0,Ps):Si;if(re.some(ai=>Mt.startsWith(ai)))continue;const se=Dt[1]?parseInt(Dt[1],10):void 0,Se=Dt[2]?parseInt(Dt[2],10):void 0,mt=se?`${Mt}:${se}${Se?":"+Se:""}`:Mt;ts.push({range:{start:{x:Ts+1,y:Z},end:{x:Ts+Si.length+1,y:Z}},text:Si,activate(){var Wo;const ai=zo()||((Wo=ad.getState().info)==null?void 0:Wo.cwd),Bt=Mt.startsWith("/")?Mt:ai?`${ai}/${Mt}`:Mt;ld(Bt).then(Vc=>{const{rootPath:Dr,revealInTree:jc}=Uo.getState();Vc==="directory"?Dr&&(Bt===Dr||Bt.startsWith(Dr+"/"))?(jc(Bt),Go("editor")):(hd(async()=>{const{useFolderStore:Mr}=await import("./index-CBmymKHy.js").then(Xc=>Xc.bq);return{useFolderStore:Mr}},__vite__mapDeps([0,1,2,3])).then(({useFolderStore:Mr})=>{Mr.getState().setFolder(Bt)}),Go("editor")):(Ko(Bt,se,Se),setTimeout(()=>{Uo.getState().revealInTree(Bt)},150))}).catch(()=>{Ko(Bt,se,Se)})},hover(ai){N(ai,`${mt} — Click to open in editor`)},leave:Y})}nt(ts.length>0?ts:void 0)}}),H.attachCustomKeyEventHandler(Z=>Z.key==="f"&&(Z.metaKey||Z.ctrlKey)&&!Z.shiftKey&&!Z.altKey?(Z.type==="keydown"&&(Z.preventDefault(),y(!0)),!1):Z.key==="Enter"&&Z.shiftKey?(Z.type==="keydown"&&H.input("\x1B[13;2u",!0),!1):!0),H.open(R);const de=new b_;H.loadAddon(de),H.unicode.activeVersion="11";const ae=new Yu;H.loadAddon(ae);const Ce=new Uu;H.loadAddon(Ce),z.current=Ce;const ge=new Ld;H.loadAddon(ge);try{const Z=new dg;Z.onContextLoss(()=>{Z.dispose(),D.current=null,K.current&&(K.current.dispose(),K.current=null)}),H.loadAddon(Z),D.current=Z;const nt=new du;H.loadAddon(nt),K.current=nt}catch{}const ce=R.querySelector(".xterm-helper-textarea");ce&&(ce.setAttribute("autocomplete","off"),ce.setAttribute("autocorrect","off"),ce.setAttribute("autocapitalize","off"),ce.setAttribute("spellcheck","false"),ce.setAttribute("unselectable","on")),x.current=H,E.current=X,F.current=!0;const me=R.querySelector(".xterm-viewport"),ri=()=>{if(f.current||!me)return;const Z=me.scrollHeight-me.scrollTop-me.clientHeight<5;C.current=!Z};me==null||me.addEventListener("scroll",ri);const Lr=H.onTitleChange(Z=>{ne.current&&Z&&(g(Z),d(t,Z))});let ni=R.offsetParent===null;const we=()=>{if(ne.current)try{const Z=R.offsetParent!==null,nt=ni&&Z;if(ni=!Z,!Z)return;const Ut=X.proposeDimensions();if(Ut&&(Ut.cols!==H.cols||Ut.rows!==H.rows))X.fit();else if(nt){const Gt=H._core;Gt!=null&&Gt.viewport&&Gt.viewport.syncScrollArea(!0)}C.current||(f.current=!0,H.scrollToBottom(),f.current=!1)}catch{}};let ft=null;const oi=()=>{const Z=R.offsetParent!==null;if(ni&&Z){ft&&clearTimeout(ft),ft=null,we();return}ft&&clearTimeout(ft),ft=setTimeout(we,50)},es=new ResizeObserver(oi);es.observe(R),window.addEventListener("resize",oi);const wi=()=>{document.visibilityState==="visible"&&oi()};return document.addEventListener("visibilitychange",wi),()=>{me==null||me.removeEventListener("scroll",ri),Lr.dispose(),es.disconnect(),window.removeEventListener("resize",oi),document.removeEventListener("visibilitychange",wi),ft&&clearTimeout(ft),oe&&(oe.remove(),oe=null)}},[]),I=$.useRef(null);$.useEffect(()=>{ne.current=!0;const R=p.current;if(!R)return;const q=()=>{if(!ne.current)return;const{clientWidth:X,clientHeight:oe}=R;X===0||oe===0||(F.current||(I.current=k()||null),x.current&&E.current&&(w.current||A()))};if(R.clientWidth>0&&R.clientHeight>0){const X=requestAnimationFrame(q);return()=>cancelAnimationFrame(X)}const H=new ResizeObserver(X=>{for(const oe of X){const{width:N,height:Y}=oe.contentRect;if(N>0&&Y>0){H.disconnect(),q();break}}});return H.observe(R),()=>H.disconnect()},[k,A]),$.useEffect(()=>()=>{var R,q,H;ne.current=!1,S.current&&(clearTimeout(S.current),S.current=null),(R=b.current)==null||R.call(b),(q=I.current)==null||q.call(I);try{(H=x.current)==null||H.dispose()}catch{}x.current=null,E.current=null,D.current=null,z.current=null,K.current=null,F.current=!1,w.current=!1},[]),$.useEffect(()=>{const R=x.current;if(R){R.options.theme=Tl(r==="dark",p.current);try{R.refresh(0,R.rows-1)}catch{}}},[r,h]);const G=$.useCallback(()=>{var R;u||l(t),(R=x.current)==null||R.focus()},[u,t,l]),V=$.useCallback(R=>{var H;R.preventDefault(),R.stopPropagation();const q=((H=x.current)==null?void 0:H.getSelection())??"";T({x:R.clientX,y:R.clientY,text:q})},[]);$.useEffect(()=>{if(B)return cd({onClose:()=>T(null),isInside:R=>md(R,L.current)})},[B]),$.useLayoutEffect(()=>{!B||!L.current||dd(L.current,B.x+4,B.y+4)},[B]);const Q=$.useCallback(async()=>{var X,oe;const R=(B==null?void 0:B.text)??((X=x.current)==null?void 0:X.getSelection())??"";if(T(null),!R.trim())return;let q=e||zo();const H=(oe=it.getState().panes[t])==null?void 0:oe.ptySessionId;if(H){const N=await Yc(H);N!=null&&N.cwd&&(q=N.cwd)}ud(_d(R,q))},[B,e,t]),le=$.useCallback(()=>{var q;const R=(B==null?void 0:B.text)??"";T(null),R&&((q=navigator.clipboard)==null||q.writeText(R).catch(()=>{}))},[B]),j=$.useCallback(async()=>{var R,q;T(null);try{const H=await navigator.clipboard.readText();H&&((R=x.current)==null||R.paste(H))}catch{}(q=x.current)==null||q.focus()},[]);return n?ie.jsxs("div",{className:`terminal-pane flex flex-col h-full w-full min-h-0 ${u&&_>1?"active":""}`,style:{backgroundColor:"var(--ide-side-panel-bg)"},onClick:G,onContextMenu:V,children:[m&&ie.jsx(wv,{searchAddon:z.current,onClose:()=>y(!1),onFocusTerminal:()=>{var R;return(R=x.current)==null?void 0:R.focus()}}),_>1&&ie.jsx("div",{className:"terminal-pane-toolbar",children:ie.jsx("button",{onClick:R=>{R.stopPropagation(),c(t)},className:"w-6 h-6 flex items-center justify-center rounded bg-bg-tertiary/80 text-text-secondary hover:text-text-primary hover:bg-bg-hover transition-colors",title:s("terminal.closePane"),children:ie.jsx(Ul,{size:14})})}),ie.jsx("div",{ref:p,className:"flex-1 w-full min-h-0",style:{overflow:"hidden",padding:"4px"}}),n.ptyStatus==="connecting"&&ie.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-10",style:{backgroundColor:"var(--ide-side-panel-bg)"},children:ie.jsx(qo,{size:20,className:"animate-spin",style:{color:"var(--color-text-tertiary)"}})}),n.ptyStatus==="reconnecting"&&ie.jsxs("div",{className:"absolute bottom-0 left-0 right-0 flex items-center px-4 py-2 bg-bg-secondary/80 border-t border-border-muted z-10",children:[ie.jsx(qo,{size:12,className:"animate-spin mr-2 text-text-tertiary"}),ie.jsx("span",{className:"text-text-secondary text-xs",children:s("terminal.reconnecting")})]}),n.ptyStatus==="error"&&ie.jsxs("div",{className:"absolute bottom-0 left-0 right-0 flex items-center justify-between px-4 py-2 bg-accent-red/10 border-t border-accent-red/30 z-10",children:[ie.jsxs("div",{className:"flex items-center gap-2 text-accent-red text-xs",children:[ie.jsx(fd,{size:14}),ie.jsx("span",{children:n.errorMessage||s("terminal.error")})]}),ie.jsxs("button",{onClick:v,className:"flex items-center gap-1.5 px-3 py-1 rounded-md bg-bg-secondary border border-border-muted text-text-primary text-xs hover:bg-bg-hover transition-colors",children:[ie.jsx(gd,{size:12}),ie.jsx("span",{children:s("terminal.reconnect")})]})]}),B&&pd.createPortal(ie.jsxs("div",{ref:L,className:"editor-context-menu",role:"menu",style:{left:B.x,top:B.y},onPointerDown:R=>R.stopPropagation(),onContextMenu:R=>R.preventDefault(),children:[ie.jsx("button",{type:"button",role:"menuitem",disabled:!B.text.trim(),onClick:()=>{Q().catch(()=>{})},children:s("composer.addToChat")}),ie.jsx("button",{type:"button",role:"menuitem",disabled:!B.text,onClick:le,children:s("terminal.copySelection")}),ie.jsx("button",{type:"button",role:"menuitem",onClick:()=>{j().catch(()=>{})},children:s("editor.paste")})]}),document.body)]}):ie.jsx("div",{})}export{tA as TerminalPaneView};
|