diff --git a/agent/cmd/mc-agent/uidist/index.html b/agent/cmd/mc-agent/uidist/index.html index 63e08ca4..6beb8668 100644 --- a/agent/cmd/mc-agent/uidist/index.html +++ b/agent/cmd/mc-agent/uidist/index.html @@ -10,7 +10,7 @@ - +`):"";function _y(i){const s={};for(const o of i){const u=o.name.trim();if(!u)continue;const d=o.source?{source:o.source}:{};if(o.type==="stdio"){if(!o.command.trim())continue;const p=o.args.trim()?o.args.trim().split(/\s+/):void 0;s[u]={...o.extra,command:o.command.trim(),args:p,env:Of(o.kv),...d}}else{if(!o.url.trim())continue;s[u]={...o.extra,url:o.url.trim(),headers:Of(o.kv),...d}}}return s}function Mf(i){return Object.entries(i).map(([s,o])=>{const u=o??{},d=typeof u.command=="string"&&u.command!=="",p=Object.fromEntries(Object.entries(u).filter(([g])=>!Ny.has(g)));return{name:s,type:d?"stdio":"http",url:typeof u.url=="string"?u.url:"",command:typeof u.command=="string"?u.command:"",args:Array.isArray(u.args)?u.args.map(String).join(" "):"",kv:Ay(d?u.env:u.headers),source:typeof u.source=="string"?u.source:void 0,extra:Object.keys(p).length?p:void 0}})}function Ry({version:i,update:s,onUpdateStatus:o}){const[u,d]=D.useState("idle"),[p,g]=D.useState(null),m=!!(s!=null&&s.available),x=async()=>{d("checking"),g(null);try{const P=await Uf();o(P),P.available||g({text:"已是最新版本",color:"var(--ok)"})}catch(P){g({text:P instanceof Error?P.message:String(P),color:"var(--err)"})}finally{d("idle")}},v=async()=>{d("installing"),g(null);try{await Hg()}catch(P){g({text:P instanceof Error?P.message:String(P),color:"var(--err)"}),d("idle")}},E=u!=="idle",z=u==="checking"?"检查中":u==="installing"?"更新中":m?"下载更新":"检查更新",T=m&&u!=="checking";return a.jsxs("div",{className:"card card-lg",style:{padding:"14px 16px",display:"flex",alignItems:"center",gap:12},children:[a.jsx("div",{style:{width:34,height:34,borderRadius:9,background:"var(--accBg)",display:"flex",alignItems:"center",justifyContent:"center",flex:"none"},children:a.jsx("img",{src:ul,alt:"",draggable:!1,style:{width:22,height:22,borderRadius:5}})}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:1,minWidth:0},children:[a.jsx("span",{style:{fontWeight:700,fontSize:13},children:"MonkeyCode"}),a.jsx("span",{className:"ellipsis",style:{fontSize:11.5,color:"var(--t5)",fontFamily:Tt},children:m?`${(s==null?void 0:s.current)??i} → ${s==null?void 0:s.latest} 可用`:i})]}),a.jsx("span",{style:{flex:1}}),p&&a.jsx("span",{style:{fontSize:12,color:p.color,flex:"none"},children:p.text}),a.jsxs("button",{className:T?"hv-acc":"hv",onClick:()=>!E&&void(T?v():x()),style:{...gr,gap:6,flex:"none",...T?{background:"var(--acc)",borderColor:"var(--acc)",color:"var(--onAcc)"}:{},opacity:E?.7:1,cursor:E?"default":"pointer"},children:[E&&a.jsx("span",{style:{width:11,height:11,border:`1.5px solid ${T?"var(--onAcc)":"var(--t1)"}`,borderTopColor:"transparent",borderRadius:"50%",animation:"mcspin .9s linear infinite",display:"inline-block"}}),z]})]})}const Cy=()=>({name:"",provider:"anthropic",base_url:"",api_key:"",model:""}),Iy=()=>({name:"",type:"http",url:"",command:"",args:"",kv:""});function jf(i,s,o){const u=i.filter(g=>g.name.trim()&&g.source!==_r),d=new Map(u.map(g=>[g.name.trim(),g])),p=new Set(d.keys());for(const g of s){const m=g.name.trim();o&&p.has(m)||d.set(m,g)}return[...d.values()]}const Lf=[{key:"account",label:"百智云账号",icon:il},{key:"models",label:"模型",icon:xp},{key:"mcp",label:"MCP 服务器",icon:Ec},{key:"general",label:"通用",icon:vp}],Ja={flex:"none",fontSize:10.5,fontWeight:600,padding:"1px 7px",borderRadius:5,background:"var(--hov)",color:"var(--t4)",whiteSpace:"nowrap"},$a={color:"var(--t5)",fontSize:12.5,border:"1px dashed var(--dashBd)",borderRadius:10,padding:16,lineHeight:1.7};function Oy({onClose:i,hostVersion:s,update:o,onUpdateStatus:u,onDirtyChange:d}){var _n;const p=hi(),[g,m]=D.useState("account"),[x,v]=D.useState([]),[E,z]=D.useState(0),[T,P]=D.useState({}),[B,W]=D.useState(null),[Y,de]=D.useState(!0),[ve,ye]=D.useState([]),[ae,ge]=D.useState(null),[j,re]=D.useState(!0),[te,ce]=D.useState(!1),[Be,Ze]=D.useState(""),[Me,Qe]=D.useState(!1),[Ke,tt]=D.useState(null),[Xe,We]=D.useState(""),U=async()=>{try{const G=await Tg();tt(G),We("")}catch(G){We(G instanceof Error?G.message:String(G))}};D.useEffect(()=>{U()},[]);const le=!!(Ke!=null&&Ke.logged_in),V=(G,q,Se)=>({models:G.map((me,He)=>({...me,name:me.name.trim(),default:He===q})),mcp_servers:_y(Se)}),S=D.useRef(""),_=D.useRef(null);D.useEffect(()=>{if(!p){ce(!0);return}Mg().then(G=>{const q=(G==null?void 0:G.models)??[],Se=Math.max(0,q.findIndex(He=>He.default)),me=Mf((G==null?void 0:G.mcp_servers)??{});v(q),z(Se),ye(me),_.current={models:q,defaultIdx:Se,mcps:me},S.current=JSON.stringify(V(q,Se,me)),ce(!0)}).catch(G=>Ze("读取配置失败: "+(G instanceof Error?G.message:String(G))))},[p]);const H=D.useMemo(()=>p&&te&&JSON.stringify(V(x,E,ve))!==S.current,[p,te,x,E,ve]);D.useEffect(()=>{d==null||d(H)},[H]),D.useEffect(()=>()=>d==null?void 0:d(!1),[]);const se=()=>{const G=_.current;G&&(v(G.models),z(G.defaultIdx),ye(G.mcps),W(null),ge(null),P({}),Ze(""))},Ne=(G,q)=>v(Se=>Se.map((me,He)=>He===G?{...me,...q}:me)),_e=(G,q)=>ye(Se=>Se.map((me,He)=>He===G?{...me,...q}:me)),ue=G=>{var Se,me;if(G.models.length){const He=((me=(Se=x[E])==null?void 0:Se.name)==null?void 0:me.trim())??"",Xt=G.models.map(gt=>({name:gt.name,provider:gt.provider,base_url:gt.base_url,api_key:gt.api_key,model:gt.model,context_window:gt.context_window,vision:gt.vision,source:gt.source})),Wt=jf(x,Xt,!1);v(Wt);const Lt=Wt.findIndex(gt=>gt.name.trim()===He);z(Lt>=0?Lt:0),P({}),W(null),de(!0)}const q=Mf(G.mcp_servers);q.length&&(ye(He=>jf(He,q,!0)),ge(null)),m("models")},O=async()=>{for(const q of x)if(!q.name.trim()||!q.base_url.trim()||!q.api_key.trim()||!q.model.trim()){Ze(`模型「${q.name.trim()||"未命名"}」信息不完整(需名称/接口地址/API Key/模型标识)`),m("models");return}const G=new Set;for(const q of x){if(G.has(q.name.trim())){Ze(`模型名称重复: ${q.name.trim()}`),m("models");return}G.add(q.name.trim())}Ze(""),Qe(!0);try{await jg(V(x,E,ve))}catch(q){Ze(q instanceof Error?q.message:String(q)),Qe(!1)}},pe=(G,q)=>a.jsxs("button",{className:"hv",onClick:q,style:{...gr,height:24,padding:"0 9px",fontSize:11.5,gap:4},children:[a.jsx(cl,{}),G]}),Re=(G,q)=>{const Se=B===q;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"hrow hv2",onClick:()=>W(Se?null:q),style:{display:"flex",alignItems:"center",gap:8,height:40,padding:"0 14px",cursor:"pointer",userSelect:"none"},children:[a.jsx("span",{className:"ellipsis",style:{fontSize:12.5,fontFamily:Tt,color:G.name.trim()?"var(--t1)":"var(--t5)",minWidth:0},children:G.name.trim()||"未命名模型"}),a.jsx("span",{style:Ja,children:G.provider||"anthropic"}),G.vision&&a.jsx("span",{style:{...Ja,background:"var(--accBg)",color:"var(--acc)"},children:"视觉"}),q===E&&a.jsx("span",{style:{flex:"none",fontSize:11,fontWeight:700,color:"var(--acc)",whiteSpace:"nowrap"},children:"✓ 默认"}),a.jsx("span",{style:{flex:1}}),a.jsxs("span",{className:"row-acts",style:{display:"flex",alignItems:"center",gap:12,fontSize:12,flex:"none"},children:[q!==E&&a.jsx("span",{className:"hv-t1",style:{color:"var(--t4)",fontWeight:600},onClick:me=>{me.stopPropagation(),z(q)},children:"设为默认"}),a.jsx("span",{className:"hv-err",style:{color:"var(--t5)"},onClick:me=>{me.stopPropagation(),v(He=>He.filter((Xt,Wt)=>Wt!==q)),z(He=>qa.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"4px 14px 14px"},children:[a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 240px",gap:12},children:[a.jsx(Nn,{label:"名称",children:a.jsx("input",{style:Yn,value:G.name,placeholder:"如: 主力模型",onChange:Se=>Ne(q,{name:Se.target.value}),className:"hv-bd"})}),a.jsx(Nn,{label:"协议",children:a.jsxs("select",{style:Cf,value:G.provider||"anthropic",onChange:Se=>Ne(q,{provider:Se.target.value}),children:[a.jsx("option",{value:"anthropic",children:"anthropic"}),a.jsx("option",{value:"openai",children:"openai(Chat Completions)"}),a.jsx("option",{value:"openai_responses",children:"openai_responses(Responses)"})]})})]}),a.jsx(Nn,{label:"接口地址",children:a.jsx("input",{style:Yn,value:G.base_url,placeholder:"https://api.example.com",onChange:Se=>Ne(q,{base_url:Se.target.value}),className:"hv-bd"})}),a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[a.jsx(Nn,{label:"API Key",children:a.jsx("input",{style:Yn,type:"password",value:G.api_key,placeholder:"sk-...",onChange:Se=>Ne(q,{api_key:Se.target.value}),className:"hv-bd"})}),a.jsx(Nn,{label:"模型标识",children:a.jsx("input",{style:Yn,value:G.model,placeholder:"请求中的 model 字段",onChange:Se=>Ne(q,{model:Se.target.value}),className:"hv-bd"})})]}),T[q]&&a.jsxs(a.Fragment,{children:[a.jsx(Nn,{label:"上下文窗口(token)",children:a.jsx("input",{style:Yn,type:"number",min:1,value:G.context_window??"",placeholder:"200000(默认)",onChange:Se=>{const me=parseInt(Se.target.value,10);Ne(q,{context_window:Number.isFinite(me)&&me>0?me:void 0})},className:"hv-bd"})}),a.jsxs("label",{title:"跳过 HTTPS 证书校验,连接可被窃听或篡改。仅用于自签名证书的内网网关;公网接口在老系统(如 Win7)验不过时内核会自动用内置根证书兜底,无需开启",style:{display:"flex",alignItems:"center",gap:5,color:"var(--t3)",cursor:"pointer",fontSize:12,userSelect:"none"},children:[a.jsx("input",{type:"checkbox",checked:!!G.skip_tls_verify,onChange:Se=>Ne(q,{skip_tls_verify:Se.target.checked||void 0}),style:{accentColor:"var(--err)",margin:0}}),"跳过 TLS 证书校验",G.skip_tls_verify&&a.jsx("span",{style:{color:"var(--err)",fontWeight:600},children:"(不安全,仅限内网自签名网关)"})]})]}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:14,paddingTop:2,fontSize:12},children:[a.jsxs("span",{className:"hv-t1",onClick:()=>P(Se=>({...Se,[q]:!Se[q]})),style:{display:"flex",alignItems:"center",gap:4,color:"var(--t5)",cursor:"pointer",userSelect:"none"},children:[a.jsx("span",{style:{display:"inline-block",transform:T[q]?"rotate(90deg)":"none",transition:"transform .15s ease",fontSize:9},children:"▸"}),"高级选项",!T[q]&&G.context_window?`(上下文窗口 ${G.context_window.toLocaleString()})`:""]}),a.jsxs("label",{title:"模型支持图片输入(视觉)。未勾选时对话里的图片以文件路径提供,模型不会收到图片内容",style:{display:"flex",alignItems:"center",gap:5,color:"var(--t3)",cursor:"pointer",fontWeight:600,userSelect:"none"},children:[a.jsx("input",{type:"checkbox",checked:!!G.vision,onChange:Se=>Ne(q,{vision:Se.target.checked}),style:{accentColor:"var(--acc)",margin:0}}),"支持图片"]})]})]}),it=(G,q)=>a.jsx("div",{className:"card",style:{overflow:"hidden"},children:G.map(({m:Se,i:me},He)=>a.jsx("div",{style:{borderTop:He>0?"1px solid var(--line2)":"none"},children:q(Se,me)},me))}),Fe=(G,q)=>a.jsx("span",{className:"hv-t1",onClick:q,style:{fontSize:11.5,color:"var(--t5)",cursor:"pointer",userSelect:"none"},children:G?"收起":"展开"}),dt=Ke&&!le&&a.jsxs("div",{className:"card card-lg",style:{display:"flex",alignItems:"center",gap:12,padding:"12px 16px"},children:[a.jsx(il,{size:16}),a.jsx("span",{style:{fontSize:12.5,color:"var(--t3)",flex:1},children:"登录百智云后可自动同步账号下的模型与 MCP,无需手工配置。"}),a.jsx("button",{className:"hv-acc",onClick:()=>m("account"),style:{...gr,flex:"none",background:"var(--acc)",borderColor:"var(--acc)",color:"var(--onAcc)"},children:"去登录"})]}),xe=()=>{if(!p)return a.jsx("div",{className:"card card-lg",style:{color:"var(--t4)",fontSize:12.5,lineHeight:1.7},children:"浏览器模式下配置只读:模型与 MCP 由启动 mc-agent 的宿主(桌面应用或环境变量)管理。"});if(!te)return a.jsx("div",{style:{fontSize:12.5,color:"var(--t5)"},children:"读取配置中…"});const G=x.map((me,He)=>({m:me,i:He})),q=G.filter(me=>me.m.source===_r),Se=G.filter(me=>me.m.source!==_r);return a.jsxs(a.Fragment,{children:[dt,a.jsx(Ki,{label:`${cc(_r)}${q.length?`(${q.length})`:""}`,action:q.length>0?Fe(Y,()=>de(me=>!me)):void 0,children:q.length===0?a.jsx("div",{style:$a,children:le?a.jsxs(a.Fragment,{children:["还没有同步的模型。到",a.jsx("span",{className:"hv-t1",onClick:()=>m("account"),style:{color:"var(--acc)",cursor:"pointer",fontWeight:600},children:"「百智云账号」"}),"页点「同步模型与 MCP」即可拉取。"]}):"登录百智云并同步后,账号下的模型会出现在这里(重新同步时整组更新)。"}):Y&&it(q,Re)}),a.jsx(Ki,{label:"自定义模型",action:pe("添加模型",()=>{v(me=>[...me,Cy()]),W(x.length)}),children:Se.length===0?a.jsx("div",{style:$a,children:"手工接入其他服务商的模型(高级)。需要名称、接口地址、API Key 与模型标识。"}):it(Se,Re)})]})},mn=G=>(G.type==="http"?G.url.trim():`${G.command} ${G.args}`.trim())||"未配置",vn=(G,q)=>{const Se=ae===q;return a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"hrow hv2",onClick:()=>ge(Se?null:q),style:{display:"flex",alignItems:"center",gap:8,height:40,padding:"0 14px",cursor:"pointer",userSelect:"none"},children:[a.jsx("span",{className:"ellipsis",style:{fontSize:12.5,fontFamily:Tt,color:G.name.trim()?"var(--t1)":"var(--t5)",flex:"none",maxWidth:180},children:G.name.trim()||"未命名"}),a.jsx("span",{style:Ja,children:G.type}),a.jsx("span",{className:"ellipsis",style:{fontSize:11.5,color:"var(--t5)",fontFamily:Tt,minWidth:0},children:mn(G)}),a.jsx("span",{style:{flex:1}}),a.jsx("span",{className:"row-acts",style:{display:"flex",alignItems:"center",fontSize:12,flex:"none"},children:a.jsx("span",{className:"hv-err",style:{color:"var(--t5)"},onClick:me=>{me.stopPropagation(),ye(He=>He.filter((Xt,Wt)=>Wt!==q)),ge(null)},children:"删除"})}),a.jsx("span",{style:{flex:"none",display:"inline-block",transform:Se?"rotate(90deg)":"none",transition:"transform .15s ease",fontSize:9,color:"var(--t5)"},children:"▸"})]}),Se&&a.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12,padding:"4px 14px 14px"},children:[a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 240px",gap:12},children:[a.jsx(Nn,{label:"名称",children:a.jsx("input",{style:Yn,value:G.name,placeholder:"如: context7",onChange:me=>_e(q,{name:me.target.value}),className:"hv-bd"})}),a.jsx(Nn,{label:"类型",children:a.jsxs("select",{style:Cf,value:G.type,onChange:me=>_e(q,{type:me.target.value}),children:[a.jsx("option",{value:"http",children:"HTTP(URL)"}),a.jsx("option",{value:"stdio",children:"stdio(本地命令)"})]})})]}),G.type==="http"?a.jsx(Nn,{label:"URL",children:a.jsx("input",{style:Yn,value:G.url,placeholder:"https://mcp.example.com/mcp",onChange:me=>_e(q,{url:me.target.value}),className:"hv-bd"})}):a.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[a.jsx(Nn,{label:"命令",children:a.jsx("input",{style:Yn,value:G.command,placeholder:"npx",onChange:me=>_e(q,{command:me.target.value}),className:"hv-bd"})}),a.jsx(Nn,{label:"参数(空格分隔)",children:a.jsx("input",{style:Yn,value:G.args,placeholder:"@playwright/mcp",onChange:me=>_e(q,{args:me.target.value}),className:"hv-bd"})})]}),a.jsx(Nn,{label:G.type==="http"?"Headers(每行 KEY=VALUE)":"环境变量(每行 KEY=VALUE)",children:a.jsx("textarea",{style:{...Yn,height:"auto",padding:"7px 10px",resize:"vertical",lineHeight:1.6},rows:2,value:G.kv,onChange:me=>_e(q,{kv:me.target.value}),className:"hv-bd"})})]})]})},Ut=()=>{if(!p)return a.jsx("div",{className:"card card-lg",style:{color:"var(--t4)",fontSize:12.5,lineHeight:1.7},children:"浏览器模式下配置只读:模型与 MCP 由启动 mc-agent 的宿主(桌面应用或环境变量)管理。"});if(!te)return a.jsx("div",{style:{fontSize:12.5,color:"var(--t5)"},children:"读取配置中…"});const G=ve.map((me,He)=>({m:me,i:He})),q=G.filter(me=>me.m.source===_r),Se=G.filter(me=>me.m.source!==_r);return a.jsxs(a.Fragment,{children:[dt,q.length>0&&a.jsx(Ki,{label:`${cc(_r)} MCP(${q.length})`,action:Fe(j,()=>re(me=>!me)),children:j&&it(q,vn)}),a.jsx(Ki,{label:"自定义 MCP",action:pe("添加 MCP",()=>{ye(me=>[...me,Iy()]),ge(ve.length)}),children:Se.length===0?a.jsx("div",{style:$a,children:"未配置自定义 MCP 服务器(可选)。项目级 .mc-agent/mcp.json 仍随仓库生效。"}):it(Se,vn)})]})},yn=()=>a.jsxs(a.Fragment,{children:[a.jsx(Ki,{label:"外观",children:a.jsxs("div",{className:"card card-lg",style:{padding:"14px 16px",display:"flex",alignItems:"center",gap:14},children:[a.jsxs("div",{style:{display:"flex",background:"var(--segBg)",borderRadius:8,padding:3,gap:2},children:[a.jsx("button",{style:{border:"none",borderRadius:6,height:26,padding:"0 15px",fontSize:12,fontWeight:600,cursor:"pointer",background:"var(--card)",color:"var(--t1)",boxShadow:"var(--segSh)"},children:"浅色"}),a.jsx("button",{title:"深色模式即将支持",style:{border:"none",borderRadius:6,height:26,padding:"0 15px",fontSize:12,fontWeight:600,cursor:"not-allowed",background:"transparent",color:"var(--tDis)"},children:"深色"})]}),a.jsx("span",{style:{fontSize:12,color:"var(--t5)"},children:"深色模式即将支持。"})]})}),p&&a.jsx(Ki,{label:"关于",children:a.jsx(Ry,{version:s??"—",update:o,onUpdateStatus:u})})]}),Ft=()=>a.jsx(Ty,{status:Ke,statusErr:Xe,refreshStatus:U,onSynced:ue,knownKeys:()=>x.map(G=>G.api_key.trim()).filter(G=>G.startsWith("sk-")),preselectNames:()=>x.filter(G=>G.source===_r||!G.source).map(G=>G.name.trim())}),nn=((_n=Lf.find(G=>G.key===g))==null?void 0:_n.label)??"设置";return a.jsxs("div",{style:{flex:1,display:"flex",minHeight:0,animation:"mcin .25s ease"},children:[a.jsxs("div",{style:{width:168,flex:"none",background:"var(--side)",borderRight:"1px solid var(--line)",display:"flex",flexDirection:"column",gap:2,padding:"0 10px 12px"},children:[a.jsx(Tp,{}),a.jsxs("div",{className:"hv",onClick:i,style:{display:"flex",alignItems:"center",gap:7,height:30,padding:"0 9px",borderRadius:6,cursor:"pointer",userSelect:"none",fontSize:12.5,color:"var(--t3)",fontWeight:600},children:[a.jsx(Hv,{size:10,color:"var(--t3)"}),"返回"]}),a.jsx("div",{style:{height:6}}),a.jsx("span",{style:{fontSize:11,fontWeight:700,letterSpacing:.4,color:"var(--t4)",padding:"2px 9px 6px"},children:"设置"}),Lf.map(G=>{const q=g===G.key,Se=G.icon;return a.jsxs("div",{className:q?void 0:"hv",onClick:()=>m(G.key),style:{display:"flex",alignItems:"center",gap:7,height:30,padding:"0 9px",borderRadius:6,cursor:"pointer",userSelect:"none",fontSize:12.5,background:q?"var(--accSel)":"transparent",color:q?"var(--onAcc)":"var(--t2)",fontWeight:q?500:400},children:[a.jsx(Se,{size:13,color:q?"var(--onAcc)":"var(--t4)"}),G.label]},G.key)})]}),a.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,minHeight:0},children:[a.jsx("div",{style:{flex:1,overflowY:"auto",minHeight:0},children:a.jsxs("div",{style:{maxWidth:640,margin:"0 auto",padding:"24px 32px 40px",display:"flex",flexDirection:"column",gap:18,animation:"mcin .18s ease"},children:[a.jsx("span",{style:{fontSize:17,fontWeight:800},children:nn}),g==="account"&&Ft(),g==="models"&&xe(),g==="mcp"&&Ut(),g==="general"&&yn(),Be&&!H&&a.jsx("div",{style:{fontSize:12.5,color:"var(--err)"},children:Be})]},g)}),H&&a.jsxs("div",{style:{flex:"none",borderTop:"1px solid var(--line)",background:"var(--card)",padding:"10px 20px",display:"flex",alignItems:"center",gap:12,animation:"mcin .15s ease"},children:[a.jsx("span",{style:{fontSize:12.5,color:"var(--t3)"},children:"有未保存的更改,保存后内核将重启(会话在磁盘不丢失)。"}),Be&&a.jsx("span",{className:"ellipsis",style:{fontSize:12,color:"var(--err)"},children:Be}),a.jsx("span",{style:{flex:1}}),a.jsx("button",{className:"hv",onClick:se,style:{...gr,flex:"none"},disabled:Me,children:"放弃更改"}),a.jsxs("button",{className:"hv-acc",onClick:()=>!Me&&void O(),style:{height:28,border:"none",borderRadius:8,background:"var(--acc)",color:"var(--onAcc)",fontWeight:700,fontSize:12.5,padding:"0 18px",cursor:Me?"default":"pointer",opacity:Me?.6:1,boxShadow:"var(--accSh)",display:"flex",alignItems:"center",gap:6,flex:"none"},children:[Me&&a.jsx("span",{style:{width:11,height:11,border:"1.5px solid var(--onAcc)",borderTopColor:"transparent",borderRadius:"50%",animation:"mcspin .9s linear infinite",display:"inline-block"}}),Me?"保存并重启内核中…":"保存"]})]})]})]})}const uc="mc.lastSession",My=()=>localStorage.getItem(uc);function jy(i={}){const[s,o]=D.useState(null),[u,d]=D.useState(Vo),[p,g]=D.useState("未连接"),[m,x]=D.useState(!1),[v,E]=D.useState(""),[z,T]=D.useState(!1),[P,B]=D.useState(""),[W,Y]=D.useState(null),[de,ve]=D.useState([]),[ye,ae]=D.useState(null),[ge,j]=D.useState(""),re=D.useRef(null),te=D.useRef(null),ce=D.useRef(i.onSessionsChanged);ce.current=i.onSessionsChanged;const Be=D.useCallback(async()=>{const _=re.current;if(!_)return[];try{const H=await _.call("repo_file_changes");if(H.error)return j(H.error),ae([]),[];j("");const se=H.result??[];return ae(se),se}catch(H){return j(H instanceof Error?H.message:String(H)),ae([]),[]}},[]),Ze=D.useCallback((_,H={})=>{var se,Ne;(se=re.current)==null||se.close(),o(_),d(Vo),Y(null),ve([]),ae(null),j(""),E(H.model??""),T(H.mode==="yolo"),te.current=H.firstMessage??null,localStorage.setItem(uc,_),re.current=Wf(_,{onFrames:_e=>d(ue=>wp(ue,_e)),onStatus:(_e,ue)=>{g(_e),x(ue)}}),(Ne=ce.current)==null||Ne.call(ce)},[]),Me=D.useCallback((_=!1)=>{var H;(H=re.current)==null||H.close(),re.current=null,te.current=null,o(null),d(Vo),g("未连接"),x(!1),E(""),T(!1),Y(null),ve([]),ae(null),j(""),_&&localStorage.removeItem(uc)},[]);return D.useEffect(()=>{u.model&&E(u.model)},[u.model]),D.useEffect(()=>{u.permMode&&T(u.permMode==="yolo")},[u.permMode]),D.useEffect(()=>{var H;if(!m)return;Be();const _=te.current;_&&((H=re.current)!=null&&H.send("user-input",{content:zs(_)}))&&(te.current=null)},[m,Be]),D.useEffect(()=>{var _;u.turnEnded&&(d(H=>({...H,turnEnded:!1})),Be(),(_=ce.current)==null||_.call(ce))},[u.turnEnded,Be]),D.useEffect(()=>{var _;u.running||!W||(_=re.current)!=null&&_.send("user-input",{content:zs(W)})&&Y(null)},[u.running,W]),D.useEffect(()=>()=>{var _;return(_=re.current)==null?void 0:_.close()},[]),{id:s,chat:u,status:p,connected:m,model:v,yolo:z,input:P,queued:W,atts:de,changes:ye,changesErr:ge,uploadUrl:s?_=>bg(s,_):void 0,open:Ze,close:Me,setInput:B,send:()=>{const _=de.map(se=>`${se.isImage?"[图片]":"[文件]"} ${se.path}`),H=[P.trim(),..._].filter(Boolean).join(` +`);if(!(!H||!re.current)){if(u.running){Y(H),B(""),ve([]);return}re.current.send("user-input",{content:zs(H)})&&(B(""),ve([]))}},stop:()=>{var _;return void((_=re.current)==null?void 0:_.send("user-cancel",{}))},clearQueued:()=>Y(null),addFiles:async _=>{if(s)for(const H of _){if(H.size>20*1024*1024){g(`⚠ ${H.name||"文件"} 过大(上限 20MB)`);continue}try{const se=await new Promise((O,pe)=>{const Re=new FileReader;Re.onload=()=>O(Re.result),Re.onerror=()=>pe(new Error("读取文件失败")),Re.readAsDataURL(H)}),Ne=se.slice(se.indexOf(",")+1),_e=H.type.startsWith("image/"),{path:ue}=await kg(s,H.name,H.type,Ne);ve(O=>[...O,{path:ue,isImage:_e,name:H.name||ue.split("/").pop()||"",preview:_e?se:void 0}])}catch(se){g("⚠ 附件上传失败: "+(se instanceof Error?se.message:String(se)))}}},removeAtt:_=>ve(H=>H.filter((se,Ne)=>Ne!==_)),answerPerm:(_,H)=>{var Ne;const se=H!=="deny";(Ne=re.current)!=null&&Ne.send("permission-resp",{id:_,approved:se,remember:H==="always"||H==="persist",persist:H==="persist"})&&d(_e=>Zv(_e,_,se))},switchModel:async _=>{var H;if(!(!re.current||!_||_===v))try{const se=await re.current.call("session_set_model",{model:_});if(se.error){g("⚠ 切换模型失败: "+se.error);return}E(_),(H=ce.current)==null||H.call(ce)}catch(se){g("⚠ 切换模型失败: "+(se instanceof Error?se.message:se))}},toggleYolo:async()=>{if(!re.current)return;const _=z,H=_?"default":"yolo";T(!_);try{const se=await re.current.call("session_set_mode",{mode:H});se.error&&(T(_),g("⚠ 切换权限模式失败: "+se.error))}catch(se){T(_),g("⚠ 切换权限模式失败: "+(se instanceof Error?se.message:se))}},refreshChanges:Be,fileDiff:_=>{const H=re.current;return H?H.call("repo_file_diff",{path:_}):Promise.reject(new Error("未连接"))},listFiles:_=>{const H=re.current;return H?H.call("repo_file_list",{path:_}):Promise.reject(new Error("未连接"))},readFile:_=>{const H=re.current;return H?H.call("repo_read_file",{path:_}):Promise.reject(new Error("未连接"))},reveal:_=>{const H=re.current;return H?H.call("repo_reveal",{path:_}):Promise.reject(new Error("未连接"))},notify:g}}const ec="~/MonkeyCode",Df=/Mac/.test(navigator.userAgent),fr={A:{text:"新增",fg:"var(--addT)",bg:"var(--addBg)"},M:{text:"修改",fg:"var(--warn)",bg:"var(--warnBg)"},D:{text:"删除",fg:"var(--delT)",bg:"var(--delBg)"}},Ly=i=>i>=1<<20?(i/(1<<20)).toFixed(1)+" MB":i>=1024?(i/1024).toFixed(1)+" KB":i+" B",js={height:32,display:"flex",alignItems:"center",gap:9,padding:"0 10px",borderRadius:8,cursor:"pointer",minWidth:0,flex:"none"},Ls={flex:"none",fontSize:10.5,fontWeight:600,borderRadius:9,padding:"2px 8px",lineHeight:1.4},zf=i=>({border:"none",background:"transparent",height:34,padding:"0 3px",marginBottom:-1,borderBottom:`2px solid ${i?"var(--acc)":"transparent"}`,fontSize:13,fontWeight:i?700:500,color:i?"var(--t1)":"var(--t5)",cursor:i?"default":"pointer",display:"flex",alignItems:"center",gap:6,flex:"none"});function Dy(){var Je,at;const[i,s]=D.useState([]),[o,u]=D.useState("new"),d=D.useRef(!1),p=()=>{d.current&&!window.confirm("有未保存的更改,确定离开设置?")||u(xe.id?"session":"new")},[g,m]=D.useState([]),[x,v]=D.useState(null),[E,z]=D.useState(null),[T,P]=D.useState(!1),[B,W]=D.useState("files"),[Y,de]=D.useState(new Map),[ve,ye]=D.useState(new Set),[ae,ge]=D.useState(new Set),[j,re]=D.useState(""),[te,ce]=D.useState(null),[Be,Ze]=D.useState(()=>{const k=parseInt(localStorage.getItem("mc.drawerWidth")??"",10);return Number.isFinite(k)?Math.min(Math.max(k,420),1200):600}),[Me,Qe]=D.useState(!1),[Ke,tt]=D.useState(()=>{const k=parseInt(localStorage.getItem("mc.drawerSplit")??"",10);return Number.isFinite(k)&&k>0?Math.max(k,80):0}),[Xe,We]=D.useState(!1),U=D.useRef(null),[le,V]=D.useState(null),[S,_]=D.useState(ec),[H,se]=D.useState(""),[Ne,_e]=D.useState(""),[ue,O]=D.useState(""),[pe,Re]=D.useState(!1),[Pe,it]=D.useState(!1),Fe=D.useRef(!1),dt=D.useCallback(async()=>{const k=await mg();return s(k),k},[]),xe=jy({onSessionsChanged:()=>void dt()}),[mn,vn]=D.useState(new Set),Ut=D.useRef(xe.id);Ut.current=xe.id;const yn=D.useRef(xe.notify);yn.current=xe.notify,D.useEffect(()=>vg(k=>{if(k.type!=="session-status"&&k.type!=="session-ask"||(dt(),k.id===Ut.current))return;if(k.type==="session-ask"){k.open&&yn.current(`「${k.title||"任务"}」等待权限审批`);return}if(k.status==="running")return;vn(L=>new Set(L).add(k.id));const R=k.status==="finished"?"已完成":k.status==="error"?"出错了":"已中断";yn.current(`「${k.title||"任务"}」${R}`)}),[dt]);const Ft=(k,R)=>{xe.open(k.id,{model:k.model,mode:k.mode,firstMessage:R}),vn(L=>{if(!L.has(k.id))return L;const Ee=new Set(L);return Ee.delete(k.id),Ee}),u("session"),P(!1),ce(null)},nn=async k=>{try{await Sg(k.id,!k.archived),await dt()}catch(R){xe.notify("⚠ 归档失败: "+(R instanceof Error?R.message:String(R)))}},_n=async(k,R)=>{try{await Eg(k.id,R),await dt()}catch(L){xe.notify("⚠ 重命名失败: "+(L instanceof Error?L.message:String(L)))}},G=async k=>{try{await wg(k.id)}catch(R){xe.notify("⚠ 删除失败: "+(R instanceof Error?R.message:String(R)));return}k.id===xe.id&&(xe.close(!0),u("new"),P(!1),ce(null)),dt()},q=D.useRef(!1),Se=()=>{P(!1),ce(null),u("settings")};D.useEffect(()=>{const k=Bf("open-settings",()=>{q.current=!0,Xd(),Se()});return Promise.all([yg().catch(()=>[]),dt()]).then(([R,L])=>{var It;m(R),se(((It=R.find(je=>je.default))==null?void 0:It.name)??"");const Ee=My(),qe=L.find(je=>je.id===Ee);qe&&Ft(qe),R.length===0&&hi()&&u("settings"),Xd().then(je=>{(je==="open-settings"||q.current)&&Se()})}).catch(R=>xe.notify("无法连接服务: "+(R instanceof Error?R.message:R))),hi()&&(Wg().then(R=>v((R==null?void 0:R.version)??null)),Uf().then(z).catch(()=>{})),()=>k()},[]);const me=((Je=[...i].sort((k,R)=>(R.updated_at??"").localeCompare(k.updated_at??""))[0])==null?void 0:Je.workdir)??"";D.useEffect(()=>{Fe.current||_(me||ec)},[me]);const He=async k=>{var R;ce({path:k,kind:"diff",text:"加载中…"});try{const L=await xe.fileDiff(k);ce({path:k,kind:"diff",text:L.error?"✗ "+L.error:((R=L.result)==null?void 0:R.diff)||"(无差异)"})}catch(L){ce({path:k,kind:"diff",text:"✗ "+(L instanceof Error?L.message:L)})}},Xt=async k=>{var R;ce({path:k,kind:"plain",text:"加载中…"});try{const L=await xe.readFile(k);if(L.error){ce({path:k,kind:"plain",text:"✗ "+L.error});return}const Ee=((R=L.result)==null?void 0:R.content)??"";Ee?Ee.includes("\0")?ce({path:k,kind:"plain",text:"二进制文件,不支持预览"}):ce({path:k,kind:"code",text:Ee}):ce({path:k,kind:"plain",text:"(空文件)"})}catch(L){ce({path:k,kind:"plain",text:"✗ "+(L instanceof Error?L.message:L)})}},Wt=async(k,R=!1)=>{if(!(!R&&(Y.has(k)||ae.has(k)))){ge(L=>new Set(L).add(k));try{const L=await xe.listFiles(k);L.error?re(L.error):de(Ee=>new Map(Ee).set(k,L.result??[]))}catch(L){re(L instanceof Error?L.message:String(L))}finally{ge(L=>{const Ee=new Set(L);return Ee.delete(k),Ee})}}},Lt=k=>{ye(R=>{const L=new Set(R);return L.has(k)?L.delete(k):(L.add(k),Wt(k)),L})},gt=(k,R,L)=>{document.body.style.cursor=k,document.body.style.userSelect="none";const Ee=()=>{document.body.style.cursor="",document.body.style.userSelect="",window.removeEventListener("mousemove",R),window.removeEventListener("mouseup",Ee),L()};window.addEventListener("mousemove",R),window.addEventListener("mouseup",Ee)},nr=k=>{k.preventDefault(),Qe(!0),gt("col-resize",R=>{const L=Math.round(window.innerWidth*.9);Ze(Math.min(Math.max(window.innerWidth-R.clientX,420),L))},()=>{Qe(!1),Ze(R=>(localStorage.setItem("mc.drawerWidth",String(R)),R))})},mr=k=>{var L;k.preventDefault();const R=((L=U.current)==null?void 0:L.getBoundingClientRect().top)??0;We(!0),gt("row-resize",Ee=>{const qe=Math.max(window.innerHeight-R-160,80);tt(Math.min(Math.max(Ee.clientY-R,80),qe))},()=>{We(!1),tt(Ee=>(localStorage.setItem("mc.drawerSplit",String(Ee)),Ee))})},rr=k=>{const R=(ft==null?void 0:ft.workdir)??"";if(!k)return R;const L=R.includes("\\")?"\\":"/",Ee=L==="\\"?k.split("/").join(L):k;return R.endsWith(L)?R+Ee:R+L+Ee},vr=async k=>{try{const R=await xe.reveal(k);if(R.error)throw new Error(R.error)}catch(R){const L=rr(k);try{await navigator.clipboard.writeText(L),xe.notify("⚠ 无法打开文件夹,已复制路径: "+L)}catch{xe.notify("⚠ 无法打开文件夹: "+(R instanceof Error?R.message:String(R)))}}},qn=(k="files")=>{P(!0),W(k),ce(null),de(new Map),ye(new Set),re(""),xe.refreshChanges(),Wt("",!0)},Kn=async(k=!1)=>{const R=S.trim();if(!(!R||Pe)){it(!0),O(""),Re(!1);try{const L=await xg(R,H,k||R===ec),Ee=Ne.trim();_e(""),await dt(),Ft(L,Ee||void 0)}catch(L){const Ee=L instanceof Error?L.message:String(L);O("创建失败: "+Ee),Ee.includes("目录不存在")&&Re(!0)}finally{it(!1)}}},ft=i.find(k=>k.id===xe.id),Dt=xe.model||((at=g.find(k=>k.default))==null?void 0:at.name)||"",zn=xe.model&&!g.some(k=>k.name===xe.model)?[...g,{name:xe.model,default:!1}]:g,rn=[...xe.chat.items].reverse().find(k=>k.kind==="perm"&&k.state==="open"),sn=o==="new"||xe.id===null,Nt=xe.changes,w=new Map((Nt??[]).map(k=>[k.path,k.status])),F=k=>(Nt??[]).filter(R=>R.path.startsWith(k+"/")).length,ie=(k,R)=>{const L=10+R*16,Ee=[],qe=Y.get(k);if(!qe){if(ae.has(k))for(let je=0;je<(k===""?4:1);je++)Ee.push(a.jsxs("div",{style:{...js,cursor:"default",paddingLeft:L+21},children:[a.jsx("span",{className:"skeleton",style:{width:14,height:14,borderRadius:4}}),a.jsx("span",{className:"skeleton",style:{height:10,width:110+je%3*52}})]},`ld:${k}:${je}`));return Ee}for(const je of qe){const on=je.is_dir?void 0:w.get(je.path),xn=on?fr[on]:void 0,ir=je.is_dir?F(je.path):0,ct=je.is_dir&&ve.has(je.path),zt=(te==null?void 0:te.path)===je.path;Ee.push(a.jsxs("div",{className:zt?void 0:"hv",title:je.path,onClick:()=>je.is_dir?Lt(je.path):xn?void He(je.path):void Xt(je.path),style:{...js,paddingLeft:L,background:zt?"var(--hov)":"transparent"},children:[a.jsx("span",{style:{width:12,flex:"none",display:"flex",alignItems:"center",justifyContent:"center"},children:je.is_dir&&a.jsx(Sc,{size:8,color:"var(--t5)",style:{transform:ct?"rotate(90deg)":"none",transition:"transform .15s ease"}})}),je.is_dir?a.jsx(Ir,{size:14,color:"var(--acc)"}):a.jsx(Ms,{color:xn?xn.fg:"var(--t4)"}),a.jsx("span",{className:"ellipsis",style:{flex:1,fontSize:12.5,color:"var(--t1)"},children:je.name}),je.is_dir&&ir>0&&a.jsxs("span",{style:{...Ls,color:"var(--acc)",background:"var(--accBg)"},children:[ir," 处改动"]}),!je.is_dir&&xn&&a.jsx("span",{style:{...Ls,color:xn.fg,background:xn.bg},children:xn.text}),!je.is_dir&&!xn&&a.jsx("span",{style:{flex:"none",width:60,textAlign:"right",font:"10.5px "+Tt,color:"var(--t6)"},children:Ly(je.size)})]},je.path)),ct&&Ee.push(...ie(je.path,R+1))}const It=(Nt??[]).filter(je=>je.status==="D"&&(je.path.includes("/")?je.path.slice(0,je.path.lastIndexOf("/")):"")===k);for(const je of It)Ee.push(a.jsxs("div",{className:"hv",title:je.path,onClick:()=>void He(je.path),style:{...js,paddingLeft:L},children:[a.jsx("span",{style:{width:12,flex:"none"}}),a.jsx(Ms,{color:fr.D.fg}),a.jsx("span",{className:"ellipsis",style:{flex:1,fontSize:12.5,color:"var(--t5)",textDecoration:"line-through"},children:Qi(je.path)}),a.jsx("span",{style:{...Ls,color:fr.D.fg,background:fr.D.bg},children:fr.D.text})]},"del:"+je.path));return qe.length===0&&It.length===0&&(k===""?Ee.push(a.jsxs("div",{style:{padding:"36px 0 28px",display:"flex",flexDirection:"column",alignItems:"center",gap:9},children:[a.jsx(Ir,{size:22,color:"var(--t6)"}),a.jsx("span",{style:{fontSize:12,color:"var(--t5)"},children:"工作区是空的"})]},"empty-root")):Ee.push(a.jsx("div",{style:{...js,cursor:"default",paddingLeft:L+21},children:a.jsx("span",{style:{fontSize:11.5,color:"var(--t6)"},children:"(空)"})},"empty:"+k))),Ee},Ce=(()=>{const k=Np(i.filter(R=>!R.archived)).map(R=>R.dir);return k.includes(S)||k.unshift(S),k.slice(0,6)})();return D.useEffect(()=>{const k=R=>{if(R.key==="Tab"&&R.shiftKey&&o==="session"&&xe.id){R.preventDefault(),xe.toggleYolo();return}if(R.key==="Escape"){if(le)return V(null);if(T)return te?ce(null):P(!1);const L=R.target,Ee=!!L&&(L.tagName==="TEXTAREA"||L.tagName==="INPUT"||L.tagName==="SELECT");if(o==="settings")return Ee?L.blur():p();if(Ee)return L.blur();rn&&!sn&&!R.isComposing&&xe.answerPerm(rn.id,"deny");return}if(R.key==="Enter"&&!R.isComposing&&rn&&!sn){const L=R.target;if(L&&(L.tagName==="TEXTAREA"||L.tagName==="INPUT")&&xe.input.trim())return;R.preventDefault(),xe.answerPerm(rn.id,"allow")}};return window.addEventListener("keydown",k),()=>window.removeEventListener("keydown",k)}),a.jsxs("div",{style:{display:"flex",flexDirection:"column",width:"100vw",height:"100vh",background:"var(--bg)",color:"var(--t1)",fontSize:13,overflow:"hidden"},children:[Dg()&&a.jsx(yy,{}),a.jsxs("div",{style:{flex:1,display:"flex",minHeight:0,position:"relative"},children:[o!=="settings"&&a.jsx(Ey,{sessions:i,currentId:xe.id,attention:mn,sessionActive:o==="session",connected:xe.connected,status:xe.status,updateAvailable:!!(E!=null&&E.available),onSelect:k=>Ft(k),onNewTask:k=>{k&&(Fe.current=!0,_(k)),O(""),Re(!1),u("new")},onOpenSettings:Se,onArchive:k=>void nn(k),onDelete:k=>void G(k),onRename:(k,R)=>void _n(k,R)}),a.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,minHeight:0},children:o==="settings"?a.jsx(Oy,{onClose:p,onDirtyChange:k=>{d.current=k},hostVersion:x,update:E,onUpdateStatus:z}):sn?a.jsx(vy,{dir:S,recentDirs:Ce,text:Ne,models:g,model:H,busy:Pe,err:ue,offerCreate:pe,onDirChange:k=>{Fe.current=!0,_(k),O(""),Re(!1)},onTextChange:_e,onModelChange:se,onCreate:k=>void Kn(k)}):a.jsx(my,{meta:ft,session:xe,models:zn,currentModel:Dt,onOpenDrawer:qn,onOpenChild:V,onArchive:()=>ft&&void nn(ft),onDelete:()=>ft&&void G(ft)})}),T&&a.jsxs(a.Fragment,{children:[a.jsx("div",{onClick:()=>P(!1),style:{position:"absolute",inset:0,background:"var(--scrim)",zIndex:35}}),a.jsxs("div",{style:{position:"absolute",top:0,right:0,bottom:0,width:Be,maxWidth:"90vw",background:"var(--pop)",borderLeft:"1px solid var(--line)",boxShadow:"var(--shadow)",zIndex:36,display:"flex",flexDirection:"column",animation:"mcslide .22s ease"},children:[a.jsx("div",{className:Me?"resize-handle dragging":"resize-handle",title:"拖动调整宽度",onMouseDown:nr}),a.jsxs("div",{style:{display:"flex",alignItems:"flex-end",gap:16,padding:"6px 14px 0 20px",borderBottom:"1px solid var(--line2)",flex:"none",whiteSpace:"nowrap"},children:[a.jsx("button",{className:B==="files"?void 0:"hv-t1",style:zf(B==="files"),onClick:()=>W("files"),children:"文件"}),a.jsxs("button",{className:B==="changes"?void 0:"hv-t1",style:zf(B==="changes"),onClick:()=>W("changes"),children:["改动",Nt&&Nt.length>0&&a.jsx("span",{style:{fontSize:10.5,fontWeight:700,color:"var(--acc)",background:"var(--accBg)",borderRadius:8,padding:"0 6px",lineHeight:"15px"},children:Nt.length})]}),a.jsx("button",{className:"hv2 icon-btn",title:"关闭 (esc)",onClick:()=>P(!1),style:{marginLeft:"auto",alignSelf:"center",width:24,height:24},children:a.jsx(Bs,{size:11,color:"var(--t4)"})})]}),(j||xe.changesErr)&&a.jsx("div",{style:{padding:"0 20px 8px",fontSize:12,color:"var(--err)",flex:"none"},children:j||xe.changesErr}),a.jsx("div",{ref:U,style:{flex:te?"none":1,height:te&&Ke?Ke:void 0,maxHeight:te?Ke?"calc(100% - 190px)":"38%":void 0,overflowY:"auto",padding:"0 12px 10px",display:"flex",flexDirection:"column",gap:1},children:B==="changes"?a.jsxs(a.Fragment,{children:[[...Nt??[]].sort((k,R)=>k.path.localeCompare(R.path)).map(k=>{const R=fr[k.status],L=k.path.lastIndexOf("/"),Ee=L>0?k.path.slice(0,L):"",qe=(te==null?void 0:te.path)===k.path;return a.jsxs("div",{className:qe?void 0:"hv",title:k.path,onClick:()=>void He(k.path),style:{...js,background:qe?"var(--hov)":"transparent"},children:[a.jsx(Ms,{color:R.fg}),a.jsx("span",{style:{flex:"none",fontSize:12.5,color:k.status==="D"?"var(--t5)":"var(--t1)",textDecoration:k.status==="D"?"line-through":"none"},children:Qi(k.path)}),a.jsx("span",{className:"ellipsis",style:{flex:1,fontSize:11,fontFamily:Tt,color:"var(--t5)"},children:Ee}),a.jsx("span",{style:{...Ls,color:R.fg,background:R.bg},children:R.text})]},k.path)}),(Nt??[]).length===0&&a.jsxs("div",{style:{padding:"36px 0 28px",display:"flex",flexDirection:"column",alignItems:"center",gap:9},children:[a.jsx(Ms,{size:22,color:"var(--t6)"}),a.jsx("span",{style:{fontSize:12,color:"var(--t5)"},children:"本轮还没有文件改动"})]})]}):a.jsx(a.Fragment,{children:ie("",0)})}),te&&a.jsxs(a.Fragment,{children:[a.jsx("div",{className:Xe?"resize-handle-h dragging":"resize-handle-h",title:"拖动调整列表/预览高度",onMouseDown:mr,style:{margin:"-5px 0 0"}}),a.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"9px 14px 9px 20px",borderTop:"1px solid var(--line2)",background:"var(--bg)",flex:"none",whiteSpace:"nowrap",overflow:"hidden"},children:[a.jsx(Ms,{color:w.get(te.path)?fr[w.get(te.path)].fg:"var(--t4)"}),a.jsx("span",{style:{font:"600 12.5px "+Tt,color:"var(--t1)",flex:"none"},children:Qi(te.path)}),a.jsx("span",{className:"ellipsis",style:{fontSize:11,fontFamily:Tt,color:"var(--t5)"},children:te.path}),w.get(te.path)&&a.jsx("span",{style:{...Ls,color:fr[w.get(te.path)].fg,background:fr[w.get(te.path)].bg},children:fr[w.get(te.path)].text}),a.jsxs("button",{className:"hv",title:"在系统文件管理器中定位此文件(浏览器模式复制路径)",onClick:()=>void vr(te.path),style:{marginLeft:"auto",flex:"none",height:22,display:"flex",alignItems:"center",gap:5,border:"none",background:"transparent",borderRadius:6,padding:"0 8px",fontSize:11.5,fontWeight:600,color:"var(--t3)",cursor:"pointer"},children:[a.jsx(Ir,{size:11,color:"var(--t4)"}),Df?"在访达中显示":"打开所在文件夹"]}),a.jsx("button",{className:"hv2 icon-btn",title:"关闭,回到文件列表 (esc)",onClick:()=>ce(null),style:{width:22,height:22},children:a.jsx(Bs,{size:10,color:"var(--t4)"})})]}),a.jsx("div",{style:{flex:1,overflowY:"auto",padding:"4px 0 20px"},children:te.kind==="diff"?a.jsx(uy,{text:te.text}):te.kind==="code"?a.jsx(py,{path:te.path,text:te.text}):a.jsx("pre",{style:{margin:0,padding:"10px 24px",font:"12px/1.9 "+Tt,color:"var(--t4)",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:te.text})})]}),a.jsxs("div",{style:{flex:"none",display:"flex",alignItems:"center",gap:10,padding:"9px 12px 9px 16px",borderTop:"1px solid var(--line2)",whiteSpace:"nowrap"},children:[a.jsx("span",{className:"ellipsis",style:{flex:1,fontSize:11.5,color:"var(--t5)"},children:"这个任务的文件都保存在这台电脑上"}),a.jsxs("button",{className:"hv-acc",title:(ft==null?void 0:ft.workdir)??"",onClick:()=>void vr(""),style:{flex:"none",height:26,border:"none",background:"var(--acc)",color:"var(--onAcc)",borderRadius:8,padding:"0 12px",fontSize:11.5,fontWeight:700,cursor:"pointer",display:"flex",alignItems:"center",gap:6,boxShadow:"var(--accSh)"},children:[a.jsx(Ir,{size:12,color:"var(--onAcc)"}),Df?"在访达中打开":"打开文件夹"]})]})]})]}),le&&a.jsx("div",{onClick:()=>V(null),style:{position:"fixed",inset:0,background:"var(--scrim2)",zIndex:40,display:"flex",alignItems:"center",justifyContent:"center"},children:a.jsxs("div",{onClick:k=>k.stopPropagation(),style:{width:"min(860px, 92vw)",maxHeight:"84vh",background:"var(--pop)",border:"1px solid var(--line)",borderRadius:16,boxShadow:"var(--shadowLg)",padding:"20px 24px",display:"flex",flexDirection:"column",overflow:"hidden",animation:"mcin .2s ease"},children:[a.jsxs("div",{style:{display:"flex",alignItems:"center",marginBottom:12,whiteSpace:"nowrap"},children:[a.jsxs("span",{className:"ellipsis",style:{fontSize:14,fontWeight:700},children:["子代理会话 ",le]}),a.jsx("button",{className:"hv2 icon-btn",onClick:()=>V(null),style:{marginLeft:"auto",width:24,height:24},children:a.jsx(Bs,{size:11,color:"var(--t4)"})})]}),a.jsx(zy,{id:le,workdir:ft==null?void 0:ft.workdir})]})})]})]})}function zy({id:i,workdir:s}){const[o,u]=D.useState(Vo),[d,p]=D.useState("连接中…");return D.useEffect(()=>{const g=Wf(i,{onFrames:m=>u(x=>wp(x,m)),onStatus:m=>p(m)});return()=>g.close()},[i]),a.jsxs("div",{style:{overflowY:"auto",flex:1,paddingRight:6,display:"flex",flexDirection:"column",gap:14,lineHeight:1.8},children:[a.jsx("div",{style:{color:"var(--t4)",fontSize:12},children:d}),a.jsx(Ep,{items:o.items,onPermAnswer:()=>{},workdir:s})]})}window.addEventListener("contextmenu",i=>{var o;if(!hi())return;const s=i.target instanceof Element?i.target:null;s!=null&&s.closest("input, textarea, [contenteditable='true']")||(o=window.getSelection())!=null&&o.toString()||i.preventDefault()});gg.createRoot(document.getElementById("root")).render(a.jsx(D.StrictMode,{children:a.jsx(Dy,{})})); diff --git a/agent/ui/src/chat.tsx b/agent/ui/src/chat.tsx index 267c1e55..7d45164c 100644 --- a/agent/ui/src/chat.tsx +++ b/agent/ui/src/chat.tsx @@ -9,6 +9,8 @@ import { type ClipboardEvent, type DragEvent, type KeyboardEvent, + type MouseEvent as ReactMouseEvent, + type WheelEvent as ReactWheelEvent, } from "react"; import { LogList, MONO } from "./components"; import { @@ -306,10 +308,18 @@ export function ChatView({ const saved = session.id ? scrollMemo.get(session.id) : undefined; pinnedRef.current = saved ? saved.pinned : true; // 首次打开默认贴底 restoreRef.current = saved && !saved.pinned ? { anchor: saved.anchor, offset: saved.offset } : null; + if (!restoreRef.current) return; + // 渲染后布局还会无事件地微调一次(实测 ~6px,RO 也抓不到这种再分配): + // 恢复期间低频轮询对齐兜底,对齐到位后是零修正的空转,用户接管即停 + const iv = window.setInterval(() => { + if (restoreRef.current) alignLog(); + else clearInterval(iv); + }, 200); + return () => clearInterval(iv); }, [session.id]); // 自动滚动:优先对齐记忆锚点,否则贴底跟随 - useEffect(() => { + const alignLog = () => { const el = logRef.current; if (!el) return; const a = restoreRef.current; @@ -323,7 +333,21 @@ export function ChatView({ } else if (pinnedRef.current) { el.scrollTop = el.scrollHeight; } - }, [chat.items, chat.running]); + }; + useEffect(alignLog, [chat.items, chat.running]); + + // 图片解码/字体加载等异步高度变化不经过 items,回放结束后仍会把位置顶漂 + // (实测漂 6px):监听内容列高度做兜底重对齐。用户接管后(restore 清空且 + // 未贴底)此路径自然不动作 + const hasLog = chat.items.length > 0; + useEffect(() => { + const col = logRef.current?.firstElementChild; + if (!col) return; + const ro = new ResizeObserver(alignLog); + ro.observe(col); + return () => ro.disconnect(); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [hasLog]); // 输入框随内容自适应高度 useEffect(() => { @@ -333,12 +357,10 @@ export function ChatView({ el.style.height = Math.min(el.scrollHeight, 160) + "px"; }, [input]); - const onLogScroll = () => { + const saveAnchor = () => { const el = logRef.current; - if (!el) return; - pinnedRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 40; // 恢复进行中的程序滚动不写记忆,避免中途切走时锚点被半成品覆盖 - if (!session.id || restoreRef.current) return; + if (!el || !session.id || restoreRef.current) return; const elTop = el.getBoundingClientRect().top; let anchor = 0; let offset = 0; @@ -354,11 +376,35 @@ export function ChatView({ } scrollMemo.set(session.id, { anchor, offset, pinned: pinnedRef.current }); }; + const saveTimer = useRef(0); - // 用户主动介入(滚轮/触摸/点击含拖滚动条)即终止锚点恢复,交还滚动控制权 + const onLogScroll = () => { + const el = logRef.current; + if (!el) return; + // scroll 事件只做"贴底→跟随"的单向判定,离底不在这里判:程序滚动同样发 + // scroll 事件,回放中一批内容长高 >40px 就会把跟随误判成用户离底(实测 + // 卡在中途)。离底判定只认用户真实输入(onWheel/滚动条拖拽) + if (el.scrollHeight - el.scrollTop - el.clientHeight < 40) pinnedRef.current = true; + saveAnchor(); + // 滚动停止后布局仍会微调一次(实测 ~6px,不发 scroll 事件),停稳后补一次校准 + clearTimeout(saveTimer.current); + saveTimer.current = window.setTimeout(saveAnchor, 600); + }; + + // 用户主动介入即终止锚点恢复,交还滚动控制权;向上意图同时解除贴底跟随 const cancelRestore = () => { restoreRef.current = null; }; + const onLogWheel = (e: ReactWheelEvent) => { + cancelRestore(); + if (e.deltaY < 0) pinnedRef.current = false; // 向上滚 = 离开底部去看历史 + }; + const onLogMouseDown = (e: ReactMouseEvent) => { + cancelRestore(); + // 按在右缘滚动条带上 = 准备拖动定位,解除跟随(拖回底部会经 scroll 事件重新贴上) + const el = logRef.current; + if (el && e.clientX > el.getBoundingClientRect().right - 20) pinnedRef.current = false; + }; const onKey = (e: KeyboardEvent) => { // 输入法组合态(选字/确认候选)的 Enter 不发送 @@ -590,9 +636,9 @@ export function ChatView({
diff --git a/tasks/lessons.md b/tasks/lessons.md index 4f5684fc..cb0327c0 100644 --- a/tasks/lessons.md +++ b/tasks/lessons.md @@ -148,3 +148,19 @@ 事件,区分"用户滚动"要靠 wheel/touchstart/mousedown,不能靠 scroll。 - 一并记着:ChatView 不按会话 key 重挂,组件级 ref(pinnedRef)会把上一 会话的状态带进新会话;会话级 UI 状态要么显式按 id 复位,要么存模块级 Map。 + +## 2026-07-18 补:滚动锚点被"你确定么"问出的三个真 bug(e2e 实测发现) + +- **静态审查+构建通过 ≠ 对**:被质疑后按"先自证"起 7440 实例 + Playwright + 写了 7 条断言的 e2e,连抓 3 个静态审查没看出的问题。滚动/布局类改动 + 必须 e2e,单测和 tsc 什么都证明不了。 +- **贴底跟随的判定不能吃程序滚动的回声**:scroll 事件里 `距底<40 → pinned` + 双向赋值时,回放一批长高 >40px 就把跟随误判成离底(必现卡在中途)。 + 正确:scroll 事件只做"贴底→true"单向判定;置 false 只认用户真实输入 + (wheel deltaY<0、滚动条带 mousedown)。 +- **滚动停止后布局还会无事件地微调 ~6px**(RO 观察列高也抓不到这种再分配): + 保存侧用 600ms 防抖补一次校准;恢复侧在 restore 存活期间 200ms 轮询 + 对齐(对齐后零修正空转,用户接管即停)。像素级验证轨迹:探针逐 200ms + 采样 childOffset = scrollTop - Δ,收敛值相等才算真对齐。 +- pkill 模式串会匹配到自己所在的复合命令行把 shell 一起杀掉(exit 144): + 模式里插字符类 `'scrolltest[ ]serve'` 或分独立调用执行。