ai-helper-agent 2.8.19 → 2.8.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{agent-store-_CfonCwg.js → agent-store-CeC2_dkP.js} +1 -1
- package/dist/assets/background.js +1 -1
- package/dist/assets/{chat-export-DRUG3mwM.js → chat-export-DcDe1GQ_.js} +1 -1
- package/dist/assets/content.js +2 -2
- package/dist/assets/{context-indicator-ZNMB0fDM.js → context-indicator-DAI73n4e.js} +174 -173
- package/dist/assets/{i18n-XUUSwfZZ.js → i18n-5c8prpFJ.js} +2 -2
- package/dist/assets/{model-profiles-C7nNtymU.js → model-profiles-ClPgbQ-J.js} +1 -1
- package/dist/assets/options.js +1 -1
- package/dist/assets/{page-snapshot-renderer-CaLLi6qB.js → page-snapshot-renderer-C_ZMW0pG.js} +1 -1
- package/dist/assets/{session-store-BU0hS2_b.js → session-store-M5mPmMr3.js} +3 -3
- package/dist/assets/side_panel.css +1 -1
- package/dist/assets/side_panel.js +97 -99
- package/dist/assets/{todo-model-BKnA8C59.js → todo-model--JIghLks.js} +1 -1
- package/dist/assets/{version-DbUttEL9.js → version-hglyyU4j.js} +3 -3
- package/dist/assets/{workspace-manager-DLH5XabD.js → workspace-manager-CL4JvHkJ.js} +1 -1
- package/dist/manifest.json +1 -1
- package/dist/offscreen/offscreen.js +2 -2
- package/dist/options.html +4 -4
- package/dist/side_panel.html +9 -9
- package/package.json +1 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agent-store-
|
|
2
|
-
import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as a}from"./i18n-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agent-store-CeC2_dkP.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-ClPgbQ-J.js","assets/i18n-5c8prpFJ.js","assets/pdf-DnVqBaAN.js","assets/__vite-browser-external-CM3Eme-n.js","assets/lib-YwkWjNcC.js","assets/jszip.min-DO6SOhXU.js","assets/dist-DuuG_8Br.js","assets/chat-export-DcDe1GQ_.js","assets/dist-BUuoW_84.js","assets/version-hglyyU4j.js","assets/voice-shortcut-Dx863RGz.js","assets/session-store-M5mPmMr3.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as a}from"./i18n-5c8prpFJ.js";import{$ as o,At as s,Dt as c,Et as l,H as u,Ht as d,Jt as f,Lt as p,Ot as m,Pt as h,Rt as g,S as _,St as v,U as y,Ut as b,Y as x,Yt as S,b as C,ct as w,dt as T,kt as E,lt as D,ut as O,wt as k,x as A}from"./model-profiles-ClPgbQ-J.js";import{A as j,B as M,C as N,D as ee,E as te,M as ne,O as re,S as ie,T as ae,a as oe,at as se,b as ce,c as le,d as ue,f as de,h as fe,j as pe,k as me,l as he,m as ge,n as _e,o as ve,ot as ye,p as be,r as xe,s as Se,t as Ce,u as we,v as Te,w as Ee,x as De,y as Oe}from"./session-store-M5mPmMr3.js";import{a as ke,n as Ae,o as je,r as Me,t as Ne}from"./voice-shortcut-Dx863RGz.js";import{A as P,B as Pe,C as Fe,D as Ie,F as Le,G as Re,H as ze,I as Be,J as F,L as Ve,O as He,P as Ue,R as I,S as We,T as Ge,U as Ke,V as qe,X as Je,Y as Ye,_ as Xe,b as Ze,d as Qe,f as $e,g as et,h as tt,i as nt,j as L,k as rt,l as it,m as at,n as ot,p as st,u as ct,v as lt,w as ut,x as dt,z as ft}from"./version-hglyyU4j.js";import{a as pt,c as mt,i as ht,n as gt,o as _t,r as vt,s as yt}from"./agent-store-CeC2_dkP.js";import{A as bt,C as xt,D as St,E as Ct,M as wt,O as Tt,S as Et,T as Dt,_ as Ot,a as kt,b as At,c as jt,d as Mt,f as Nt,g as Pt,h as Ft,i as It,k as Lt,l as Rt,m as zt,n as Bt,o as Vt,p as Ht,r as Ut,s as Wt,t as Gt,u as Kt,v as qt,w as Jt,x as Yt,y as Xt}from"./workspace-manager-CL4JvHkJ.js";var Zt=ne.map(e=>e.id),Qt=[...new Set([...S,`mcp`,`knowledge`])],$t=[{labelKey:`presetMode.preciseLabel`,tipKey:`presetMode.preciseTip`,temp:.2,topP:1},{labelKey:`presetMode.generalLabel`,tipKey:`presetMode.generalTip`,temp:.45,topP:.9},{labelKey:`presetMode.divergentLabel`,tipKey:`presetMode.divergentTip`,temp:.65,topP:.9},{labelKey:`presetMode.creativeLabel`,tipKey:`presetMode.creativeTip`,temp:.9,topP:.9}];n(`zh`,{contextUsage:{compactionInjection:`[上下文摘要|压缩了{count}条历史]`}}),n(`en`,{contextUsage:{compactionInjection:`[Context Summary | {count} messages compacted]`}});var en=2e3,tn=.7,nn=1e3;function rn(e,{isolateChat:t=!0,maxMemoryMessages:n=null,compaction:r=null,historyBudget:i=1/0,currentMessage:a=null}={}){let o=a||{role:`user`,content:``};if(!t)return{messages:[o],keptHistory:[],compactionApplied:!1,trimmedCount:0,historySummaryText:null};let c=Array.isArray(e)?e:[],l=!1,u=-1;r&&r.summary&&r.upToMessageId&&(u=c.findIndex(e=>e.messageId===r.upToMessageId),l=u>=0);let f=c,p=c.map((e,t)=>t);n&&n>0&&c.length>n&&(f=c.slice(c.length-n),p=p.slice(c.length-n));let m=[];for(let e=0;e<f.length;e++)l&&p[e]<=u||m.push(f[e]);let g=[],_=E([o]);for(let e=m.length-1;e>=0;e--){let t=m[e],n=E([{...t,content:d(t.content)}]);if(_+n<=i)g.unshift(t),_+=n;else break}let v=null,y=m.length-g.length;if(y>0){let e=h(m.slice(0,y));e&&(v=s(e)>nn?e.substring(0,nn*4)+`
|
|
3
3
|
...[历史摘要已截断]`:e)}return{messages:[...g,o],keptHistory:g,compactionApplied:l,trimmedCount:y,historySummaryText:v}}function an(e,t){return!t||!t.summary?e:`${e}\n\n${r(`contextUsage.compactionInjection`,{count:t.compressedCount||0})}\n${t.summary}`}function on(e,t,n,r){return t?.compactionApplied&&n?.summary?e[0]={...e[0],content:an(e[0].content,n)}:n?.summary&&r?.warn(`[SidePanel] contextCompaction invalid (upToMessageId not found), ignored this send`),e}function sn({model:e,customModelMap:t=null,systemPromptText:n=``,toolCount:r=0,history:i=[],inputText:a=``,maxMemoryMessages:o=null,compaction:u=null,isolateChat:d=!0,userConfiguredWindow:f=0}={}){let m=p(e,f,t),h=m-s(n)-l-en,g=Math.floor(Math.max(h,0)*tn),_={role:`user`,content:a},v=d?u:null,y=rn(i,{isolateChat:d,maxMemoryMessages:o,compaction:v,historyBudget:g,currentMessage:_}),b=s(y.compactionApplied?an(n,v):n),x=r*200,S=E(y.keptHistory),C=a&&a.trim()?E([_]):0,w=b+x+S+C,T=c(w,m);return{usedTokens:w,contextWindow:m,ratio:m>0?w/m:0,level:T.level,breakdown:{system:b,tools:x,history:S,input:C,outputReserve:l,safetyMargin:en,selectedCount:y.keptHistory.length,totalCount:i.length,trimmedCount:y.trimmedCount,compactionApplied:y.compactionApplied,compactionInvalid:!!(v&&v.summary&&!y.compactionApplied),historyBudget:g}}}function cn(e,{maxMemoryMessages:t=null,compaction:n=null}={}){let r=rn(e,{isolateChat:!0,maxMemoryMessages:t,compaction:n,historyBudget:1/0,currentMessage:null}),i=[],a=!!(r.compactionApplied&&n?.summary);a&&i.push({role:`user`,content:`【已有摘要】\n${n.summary}`});for(let e of r.keptHistory){let t=d(e.content);i.push({role:e.role,content:typeof t==`string`?t:JSON.stringify(t??``)||``})}return{material:i,includedCount:r.keptHistory.length,hasOldSummary:a}}function ln(e){if(!e||!e.trim()||e.trim()==`/`)return;let t=e.trim(),n=C.inputHistory.indexOf(t);n!==-1&&C.inputHistory.splice(n,1),C.inputHistory.push(t),C.inputHistory.length>20&&C.inputHistory.shift(),un()}function un(){try{chrome.storage.local.set({inputHistory:C.inputHistory}),i.debug(`[SidePanel] input history saved,count:`,C.inputHistory.length)}catch(e){i.error(`[SidePanel] saveinput history failed:`,e)}}var dn=[`workspace`,`bookmark`,`toc`,`search`,`todo`,`schedule`],fn=`.workspace-panel.expanded, .bookmark-panel.expanded, .message-toc-panel.expanded, .search-panel.expanded, .schedule-panel.open`,pn=null,mn=null;function hn(){if(pn)return pn;pn=document.createElement(`div`),pn.className=`side-rail`,pn.id=`sideRail`,pn.innerHTML=dn.map(e=>`<div class="side-rail-slot" data-slot="${e}"></div>`).join(``),document.body.appendChild(pn),_n();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(_n).observe(e),window.addEventListener(`resize`,_n),pn}function gn(e){return(pn||hn()).querySelector(`.side-rail-slot[data-slot="${e}"]`)}function _n(){if(!pn)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect(),n=window.innerHeight;pn.style.top=`${Math.max(0,Math.round(t.top))}px`,pn.style.bottom=`${Math.max(0,Math.round(n-t.bottom))}px`,vn()}function vn(){mn&&clearTimeout(mn),mn=setTimeout(()=>{mn=null,document.querySelectorAll(fn).forEach(Ie)},120)}n(`zh`,{panelFs:{enter:`全屏`,exit:`退出全屏`}}),n(`en`,{panelFs:{enter:`Fullscreen`,exit:`Exit fullscreen`}});var yn=`panel-fullscreen`,bn=`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3"/><path d="M16 3h3a2 2 0 0 1 2 2v3"/><path d="M8 21H5a2 2 0 0 1-2-2v-3"/><path d="M16 21h3a2 2 0 0 0 2-2v-3"/></svg>`,xn=`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8h3a2 2 0 0 0 2-2V3"/><path d="M21 8h-3a2 2 0 0 1-2-2V3"/><path d="M3 16h3a2 2 0 0 1 2 2v3"/><path d="M21 16h-3a2 2 0 0 0-2 2v3"/></svg>`,Sn=new WeakSet;function Cn(e){return!!e&&Sn.has(e)}function wn(e,t){e&&(t?Sn.add(e):Sn.delete(e),e.classList.add(`panel-fs-no-anim`),e.classList.toggle(yn,!!t),e.offsetWidth,requestAnimationFrame(()=>e.classList.remove(`panel-fs-no-anim`)))}function Tn(e){wn(e,!1)}function En(e,t){if(!e)return;let n=r(t?`panelFs.exit`:`panelFs.enter`);e.innerHTML=t?xn:bn,e.title=n,e.setAttribute(`aria-label`,n),e.setAttribute(`aria-pressed`,String(!!t))}function Dn(e=``){let t=document.createElement(`button`);return t.type=`button`,t.className=[`panel-fullscreen-btn`,e].filter(Boolean).join(` `),t.innerHTML=bn,t}function On(e,t,{onToggle:n}={}){if(!e||!t)return()=>{};let r=()=>En(e,Cn(t));return e.addEventListener(`click`,e=>{e.preventDefault(),e.stopPropagation();let i=!Cn(t);wn(t,i),r(),n&&n(i)}),r(),r}n(`zh`,{messageToc:{toggleTitle:`显示目录(H{count}个标题)`,title:`目录`,headingCount:`{count} 个`,lock:`锁定目录(不自动收起)`,unlock:`解锁目录`,close:`关闭目录`}}),n(`en`,{messageToc:{toggleTitle:`Show table of contents (H{count} headings)`,title:`Contents`,headingCount:`{count}`,lock:`Pin table of contents`,unlock:`Unpin table of contents`,close:`Close table of contents`}});var kn=`messageTocLocked`,An=!1,jn=null,Mn=null,Nn=null;function Pn(e){Mn=e,Nn={parent:e.parentElement,nextSibling:e.nextSibling},document.body.appendChild(e),e.classList.add(`expanded`),wn(e,!0)}function Fn(){let e=Mn;if(!e)return;Mn=null,wn(e,!1);let t=Nn;Nn=null,t?.parent?.isConnected?t.parent.insertBefore(e,t.nextSibling):e.remove()}var In=`<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 9.9-1"/></svg>`,Ln=`<svg viewBox="0 0 24 24" width="13" height="13" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2" ry="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>`;function Rn(e){e&&(e.innerHTML=An?Ln:In,e.title=r(An?`messageToc.unlock`:`messageToc.lock`),e.classList.toggle(`locked`,An))}function zn(){try{let e=chrome.storage?.local?.set?.({[kn]:An});e&&typeof e.catch==`function`&&e.catch(()=>{})}catch{}}function Bn(){document.addEventListener(`mouseover`,Vn,!0),document.addEventListener(`mouseout`,Hn,!0);try{let e=chrome.storage?.local?.get?.(kn);e&&typeof e.then==`function`?e.then(e=>{An=!!(e&&e[kn])}).catch(()=>{}):e&&typeof e==`object`&&(An=!!e[kn])}catch{}i.debug(`[SidePanel] messagedirectory featureinitializing`)}function Vn(e){if(!(e.target instanceof Element))return;if(e.target.closest(`.message-toc-container`)){C.isMouseOverToc=!0;return}let t=e.target.closest(`.message.assistant`),n=e.target.closest(`.workspace-preview-markdown`);if(!t&&!n)return;let r=t||n,i=r.querySelectorAll(`.markdown-body h1, .markdown-body h2, .markdown-body h3, .markdown-body h4, .markdown-body h5, .markdown-body h6`);if(i.length===0){!An&&!Mn&&Yn();return}Jn(r,i)}function Hn(e){if(!(e.target instanceof Element))return;if(e.target.closest(`.message-toc-container`)){C.isMouseOverToc=!1,C.tocHideTimer&&=(clearTimeout(C.tocHideTimer),null);return}let t=e.target.closest(`.message.assistant`),n=e.target.closest(`.workspace-preview-markdown`);if(!t&&!n||An)return;let r=e.relatedTarget;r&&(r.closest(`.message-toc-container`)||r.closest(`.message.assistant`)||r.closest(`.workspace-preview-markdown`))||C.isMouseOverToc||(C.tocHideTimer&&clearTimeout(C.tocHideTimer),C.tocHideTimer=setTimeout(()=>{!C.isMouseOverToc&&!Mn&&Yn(),C.tocHideTimer=null},800))}var Un=null,Wn=null;function Gn(e){let t=e.parentElement;for(;t&&t!==document.body&&t!==document.documentElement;){let e=getComputedStyle(t).overflowY;if((e===`auto`||e===`scroll`||e===`overlay`)&&t.scrollHeight>t.clientHeight)return t;t=t.parentElement}return null}function Kn(e,t,n,r){if(qn(),n.length===0)return;let i=Gn(t),a=e.querySelector(`.message-toc-content`),o=Array.from(e.querySelectorAll(`.message-toc-item`)),s=new Map(o.map(e=>[e.dataset.target,e])),c=0,l=null,u=-1,d=e=>{if(!a)return;let t=e.getBoundingClientRect(),n=a.getBoundingClientRect();(t.top<n.top||t.bottom>n.bottom)&&(a.scrollTop+=t.top-n.top-(n.height-t.height)/2)},f=()=>{let e=window.innerHeight||document.documentElement.clientHeight||0;if(!i)return{top:0,bottom:e};let t=i.getBoundingClientRect();return{top:Math.max(t.top,0),bottom:Math.min(t.top+i.clientHeight,e)}},p=()=>{if(i)return i.scrollTop+i.clientHeight>=i.scrollHeight-2;let e=document.documentElement;return window.scrollY+window.innerHeight>=e.scrollHeight-2},m=()=>i?i.scrollTop<=2:window.scrollY<=2,h=()=>{if(c=0,!e.isConnected)return;let t=f(),i=t.top,a=t.bottom,h=Math.max(a-i,1),g=n.map(e=>{let t=e.getBoundingClientRect();if(t.width||t.height)return t.top;let n=e.closest(`.markdown-body`);return n?n.getBoundingClientRect().top:t.top}),_=0;for(let e=0;e<g.length&&g[e]<=i;e++)_=e;let v=i+h*.75,y=_,b=_+1;if(b<g.length){let e=g[b];u===b?e<=a&&(y=b):e<=v&&(y=b)}m()?y=0:p()&&(y=n.length-1);let x=n[y];if(!x||x.id===l)return;u=y,l=x.id,o.forEach(e=>e.classList.toggle(`active`,e.dataset.target===l));let S=s.get(l);S&&r.classList.contains(`expanded`)&&d(S)},g=()=>{c||=requestAnimationFrame(h)};document.addEventListener(`scroll`,g,{capture:!0,passive:!0}),window.addEventListener(`resize`,g,{passive:!0});let _=typeof IntersectionObserver==`function`?new IntersectionObserver(g,{threshold:[0,.25,.5,.75,1]}):null;_&&n.forEach(e=>_.observe(e)),h(),Wn=()=>{if(h(),!l)return;let e=s.get(l);e&&d(e)},Un=()=>{c&&cancelAnimationFrame(c),c=0,document.removeEventListener(`scroll`,g,{capture:!0}),window.removeEventListener(`resize`,g),_&&_.disconnect()}}function qn(){Un&&=(Un(),null),Wn=null}function Jn(e,t){let n=Array.from(t),i=jn;C.messageTocContainer&&Yn(),jn=i,n.forEach((e,t)=>{e.id||=`toc-heading-${Date.now()}-${t}`});let a=document.createElement(`div`);a.className=`message-toc-container`,a.dataset.headingsCount=n.length;let o=0,s=n.map(e=>{let t=parseInt(e.tagName.charAt(1)),n=e.textContent.trim(),r=n.length>30?n.substring(0,30)+`...`:n,i=`H${t}`;return o++,`
|
|
4
4
|
<li class="message-toc-item level-${t}"
|
|
5
5
|
data-target="${e.id}"
|
|
@@ -26,7 +26,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
26
26
|
</ul>
|
|
27
27
|
</div>
|
|
28
28
|
</div>
|
|
29
|
-
`;let c=e.closest(`.message-fullscreen-overlay`),l=e.closest(`.workspace-preview-overlay.fullscreen`);(c?c.querySelector(`.message-fullscreen-rail`)||gn(`toc`):l&&l.querySelector(`.workspace-preview-rail`)||gn(`toc`)).appendChild(a),C.messageTocContainer=a;let u=a.querySelector(`.message-toc-toggle`),d=a.querySelector(`.message-toc-panel`),f=jn===e;f||(jn=null);let p=d.querySelector(`.message-toc-lock`),m=Dn(`message-toc-lock`);p.before(m);let h=On(m,d,{onToggle:t=>{t?(jn=e,Pn(d)):(jn=null,Fn(),Ie(d))}});An&&(d.classList.add(`expanded`,`locked`),Cn(d)||Ie(d)),p.addEventListener(`click`,e=>{e.stopPropagation(),An=!An,zn(),Rn(p),An?(d.classList.add(`expanded`,`locked`),Cn(d)||Ie(d),requestAnimationFrame(()=>Wn&&Wn())):d.classList.remove(`locked`)}),d.querySelector(`.message-toc-close`).addEventListener(`click`,e=>{e.stopPropagation(),An&&(An=!1,zn()),Yn()}),u.addEventListener(`mouseenter`,()=>{d.classList.add(`expanded`),Cn(d)||Ie(d),requestAnimationFrame(()=>Wn&&Wn())}),u.addEventListener(`click`,()=>{d.classList.toggle(`expanded`)?(Cn(d)||Ie(d),requestAnimationFrame(()=>Wn&&Wn())):(jn=null,Fn(),Re(d))}),d.addEventListener(`mouseenter`,()=>{d.classList.add(`expanded`),requestAnimationFrame(()=>Wn&&Wn())}),d.querySelectorAll(`.message-toc-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.target,n=document.getElementById(t);if(n){let e=n.closest(`.markdown-body`);e&&e.scrollIntoView({behavior:`smooth`,block:`start`}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{n.scrollIntoView({behavior:`smooth`,block:`start`})})}),n.classList.add(`toc-highlight`),setTimeout(()=>{n.classList.remove(`toc-highlight`)},1500)}})}),Kn(d,e,n,d),f&&(Pn(d),h())}function Yn(){jn=null,Fn(),C.tocHideTimer&&=(clearTimeout(C.tocHideTimer),null),qn(),C.messageTocContainer&&=(C.messageTocContainer.remove(),null)}var Xn=`promptQueues`,Zn=1,Qn=30*1e3,$n=15*1e3,er=20,tr={QUEUED:`queued`,DISPATCHING:`dispatching`,INJECTING:`injecting`,INJECTED:`injected`,DONE:`done`,FAILED:`failed`};new Set([tr.INJECTED,tr.DONE,tr.FAILED]);var nr={async get(e){let t=await chrome.storage.local.get(e);return t?t[e]:void 0},async set(e){await chrome.storage.local.set(e)}};function rr(){return{version:Zn,sessions:{}}}var R=rr(),ir=!1,ar=null,or=!1,sr=``,cr=new Set,lr=new Set;function ur(){return{items:[],recent:[],paused:!1,pausedReason:null}}function dr(e){return e?(R.sessions[e]||(R.sessions[e]=ur()),R.sessions[e]):ur()}function fr(){return JSON.stringify(R)}function pr(e,t){for(let n of lr)try{n(e,t)}catch(e){i.error(`[QueueStore] listener failed:`,e?.message)}}function mr(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`q_`+crypto.randomUUID():`q_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8)}function hr(e){return e.reduce((e,t)=>Math.max(e,Number(t.order)||0),0)+1}function gr(e,t){let n=e.indexOf(t);n<0||(e.splice(n,1),e.unshift(t),_r(e))}function _r(e){e.forEach((e,t)=>{e.order=t+1})}function vr(e){return e.slice().sort((e,t)=>(Number(e.order)||0)-(Number(t.order)||0))}async function yr(e){if(or)return i.error(`[QueueStore] persist skipped in degraded mode:`,e),!1;let t=fr();sr=t,br(t);try{await nr.set({[Xn]:R})}catch(e){i.error(`[QueueStore] persist failed:`,e?.message)}pr(e)}function br(e){if(cr.add(e),cr.size<=er)return;let t=cr.values().next().value;cr.delete(t)}function xr(e,{recoverInterrupted:t=!0}={}){let n=rr();if(!e||typeof e!=`object`)return n;let r=e.sessions&&typeof e.sessions==`object`?e.sessions:{};for(let[e,i]of Object.entries(r)){let r=Array.isArray(i?.items)?i.items:[],a=Array.isArray(i?.recent)?i.recent.slice(0,30):[],o=!1;for(let e of r)!e||typeof e!=`object`||t&&(e.status===tr.DISPATCHING||e.status===tr.INJECTING)&&(e.status=tr.QUEUED,e.interrupted=!0,e.previousStatus=e.previousStatus||tr.DISPATCHING,e.leaseOwner=null,e.leaseUntil=0,o=!0);let s=vr(r);if(o){let e=s.filter(e=>e.interrupted),t=s.filter(e=>!e.interrupted);s.splice(0,s.length,...e,...t)}_r(s);let c=s.slice(0,20),l=s.slice(20);for(let e of l.reverse())a.unshift(Wr({...e,status:tr.FAILED,lastError:`over_limit`}));n.sessions[e]={items:c,recent:a.slice(0,30),paused:i?.paused===!0,pausedReason:i?.pausedReason||null}}return n}function Sr(){return or}async function Cr(){return ir?R:ar||(ar=(async()=>{let e;try{e=await nr.get(Xn)}catch(e){return or=!0,ar=null,i.error(`[QueueStore] load failed, enter degraded mode:`,e?.message),R}return R=xr(e),ir=!0,or=!1,sr=fr(),R})(),ar)}function wr(){typeof chrome>`u`||!chrome.storage?.onChanged?.addListener||chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`||!e?.[Xn])return;let n=e[Xn].newValue;if(!n)return;let r=JSON.stringify(n);cr.has(r)||r===sr||(R=xr(n,{recoverInterrupted:!1}),ir=!0,sr=r,pr(`external`,null))})}function Tr(e){return typeof e==`function`?(lr.add(e),()=>lr.delete(e)):()=>{}}function Er(e){let t=R.sessions[e];return t?vr(t.items):[]}function Dr(e,t=30){let n=R.sessions[e];return n?n.recent.slice(0,t):[]}function Or(e){let t=R.sessions[e];return t?{items:vr(t.items),recent:t.recent.slice(),paused:t.paused===!0,pausedReason:t.pausedReason||null}:ur()}function kr(e){return Er(e).filter(e=>e.status===tr.QUEUED).length}function Ar(e){return Er(e).find(e=>e.status===tr.QUEUED)||null}function jr(e){let t=R.sessions[e];if(!t)return null;for(let e=t.items.length-1;e>=0;--e)if(t.items[e].status===tr.QUEUED)return t.items[e];return null}function Mr(e,t){let n=R.sessions[e];return n&&n.items.find(e=>e.id===t)||null}function Nr(){return Object.keys(R.sessions).filter(e=>(R.sessions[e]?.items?.length||0)>0)}function Pr(e){return R.sessions[e]?.paused===!0}async function Fr({sessionId:e,text:t,contextSnapshot:n=null,hasContext:r=!1,attachmentSummary:i=null,source:a=`manual`}){if(!e)return{ok:!1,error:`missing_session`};let o=String(t||``).trim();if(!o)return{ok:!1,error:`empty`};if(await Cr(),or)return{ok:!1,error:`storage_unavailable`};let s=dr(e);if(s.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let c={id:mr(),sessionId:e,text:o,contextSnapshot:n||null,attachmentSummary:i||null,hasContext:r===!0,status:tr.QUEUED,order:hr(s.items),createdAt:Date.now(),updatedAt:Date.now(),attempts:0,lastError:null,source:a,interrupted:!1,leaseOwner:null,leaseUntil:0,injectRequestedAt:0,injectDeadlineAt:0,injectedIntoCallId:null,absorbedIteration:null};return s.items.push(c),await yr(`enqueue`),{ok:!0,item:c,position:s.items.length}}async function Ir(e,t){let n=R.sessions[e];if(!n)return!1;let r=n.items.findIndex(e=>e.id===t);return r<0?!1:(n.items.splice(r,1),_r(n.items),await yr(`remove`),!0)}async function Lr(e,t){let n=R.sessions[e];if(!n||!Array.isArray(t))return!1;let r=new Map(n.items.map(e=>[e.id,e])),i=[];for(let e of t){let t=r.get(e);t&&!i.includes(t)&&i.push(t)}for(let e of vr(n.items))i.includes(e)||i.push(e);return n.items=i,_r(n.items),await yr(`reorder`),!0}async function Rr(e,t,n,r={}){let i=Mr(e,t);return i?(i.status=n,Object.assign(i,r,{updatedAt:Date.now()}),await yr(`status`),!0):!1}async function zr(e,t,n=$n){let r=Mr(e,t);return r?(r.previousStatus=r.status,r.status=tr.INJECTING,r.injectRequestedAt=Date.now(),r.injectDeadlineAt=Date.now()+n,r.updatedAt=Date.now(),await yr(`inject:request`),!0):!1}async function Br(e,t,n=`error`,r=null){let i=R.sessions[e];if(!i)return!1;let a=i.items.find(e=>e.id===t);return a?(a.status=tr.QUEUED,a.injectDeadlineAt=0,a.updatedAt=Date.now(),a.lastError=r||n,a.rollbackReason=n,gr(i.items,a),await yr(`inject:rollback`),!0):!1}async function Vr(e,t,{status:n,note:r=null,callId:i=null,iteration:a=null}={}){let o=R.sessions[e];if(!o)return!1;let s=o.items.findIndex(e=>e.id===t);if(s<0)return!1;let[c]=o.items.splice(s,1);return _r(o.items),c.status=n||tr.DONE,c.settledAt=Date.now(),c.settleNote=r,i&&(c.injectedIntoCallId=i),a!=null&&(c.absorbedIteration=a),o.recent.unshift(Wr(c)),o.recent=o.recent.slice(0,30),await yr(`settle`),!0}async function Hr(e,t){let n=R.sessions[e];if(!n)return{ok:!1,error:`missing_session`};let r=n.recent.findIndex(e=>e.id===t);if(r<0)return{ok:!1,error:`not_found`};if(n.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let[i]=n.recent.splice(r,1),a={...i,status:tr.QUEUED,order:hr(n.items),attempts:0,lastError:null,interrupted:!1,rollbackReason:null,settledAt:null,leaseOwner:null,leaseUntil:0,injectDeadlineAt:0,updatedAt:Date.now()};return n.items.push(a),await yr(`requeue`),{ok:!0,item:a}}async function Ur(e,t){let n=R.sessions[e];if(!n)return!1;let r=n.recent.findIndex(e=>e.id===t);return r<0?!1:(n.recent.splice(r,1),await yr(`recent-remove`),!0)}function Wr(e){let{leaseOwner:t,leaseUntil:n,injectDeadlineAt:r,contextSnapshot:i,...a}=e;return{...a,hasContext:e.hasContext===!0,contextDropped:!!i}}async function Gr(e,t=`user_stopped`){let n=dr(e);return n.paused?!1:(n.paused=!0,n.pausedReason=t,await yr(`pause`),!0)}async function Kr(e){let t=R.sessions[e];return!t||!t.paused?!1:(t.paused=!1,t.pausedReason=null,await yr(`resume`),!0)}async function qr(e,t,n){let r=Mr(e,t);if(!r)return!1;let i=Date.now();return r.leaseOwner&&r.leaseOwner!==n&&Number(r.leaseUntil)>i?!1:(r.leaseOwner=n,r.leaseUntil=i+Qn,await yr(`lease`),!0)}async function Jr(e){let t=R.sessions[e];if(!t)return 0;let n=t.items.length+t.recent.length;return delete R.sessions[e],n>0&&await yr(`drop-session`),n}var Yr=`ai-helper-queue-attachments`,Xr=1,Zr=`attachments`,Qr=null,$r=null;function ei(){return new Promise((e,t)=>{let n=indexedDB.open(Yr,Xr);n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(Zr)||t.createObjectStore(Zr,{keyPath:`id`}).createIndex(`sessionId`,`sessionId`,{unique:!1})},n.onsuccess=t=>{let n=t.target.result;n.onversionchange=()=>{try{n.close()}catch{}Qr=null},e(n)},n.onerror=()=>t(n.error||Error(`idb_open_failed`)),n.onblocked=()=>{}})}function ti(){return Qr||=ei(),Qr}function ni(e,t){return ti().then(n=>new Promise((r,i)=>{let a;try{a=n.transaction(Zr,e)}catch(e){Qr=null,i(e);return}let o=a.objectStore(Zr),s=null,c=e=>{s=e};try{t(o,c)}catch(e){i(e);return}a.oncomplete=()=>r(s),a.onerror=()=>i(a.error||Error(`idb_tx_failed`)),a.onabort=()=>i(a.error||Error(`idb_tx_aborted`))}))}function ri(){return{async put(e){await ni(`readwrite`,t=>{t.put(e)})},async get(e){return ni(`readonly`,(t,n)=>{let r=t.get(e);r.onsuccess=()=>n(r.result||null)})},async remove(e){await ni(`readwrite`,t=>{t.delete(e)})},async removeBySession(e){await ni(`readwrite`,t=>{let n=t.index(`sessionId`).getAllKeys(e);n.onsuccess=()=>{for(let e of n.result||[])t.delete(e)}})},async allKeys(){return ni(`readonly`,(e,t)=>{let n=e.getAllKeys();n.onsuccess=()=>t(n.result||[])})}}}function ii(){return $r||ri()}function ai(e){return e==null?0:typeof e==`string`?e.length:typeof e==`number`||typeof e==`boolean`?8:Array.isArray(e)?e.reduce((e,t)=>e+ai(t),0):typeof e==`object`?Object.values(e).reduce((e,t)=>e+ai(t),0):0}function oi(e){let t=e&&e.attachedImages||[],n=e&&e.attachedFiles||[];return!t.length&&!n.length?null:{imageCount:t.length,fileCount:n.length,fileNames:n.map(e=>e.name).filter(Boolean).slice(0,5)}}async function si(e,t,{images:n=[],files:r=[]}={}){if(!e)return{ok:!1,reason:`missing_id`};if(!n.length&&!r.length)return{ok:!0,skipped:!0};let i=ai(n)+ai(r);if(i>26214400)return{ok:!1,reason:`too_large`,size:i};try{return await ii().put({id:e,sessionId:t||null,size:i,images:n,files:r,updatedAt:Date.now()}),{ok:!0,size:i}}catch(e){return{ok:!1,reason:`idb_error`,message:e?.message||String(e)}}}async function ci(e){if(!e)return null;try{let t=await ii().get(e);return t?{images:t.images||[],files:t.files||[]}:null}catch{return null}}async function li(e){if(!e)return!1;try{return await ii().remove(e),!0}catch{return!1}}async function ui(e){if(!e)return!1;try{return await ii().removeBySession(e),!0}catch{return!1}}async function di(e){let t=e instanceof Set?e:new Set(e||[]);try{let e=await ii().allKeys(),n=0;for(let r of e||[])t.has(r)||(await ii().remove(r),n+=1);return n}catch{return 0}}var fi=t({appendMessageToSession:()=>Pi,archiveCurrentSession:()=>Di,archiveSession:()=>Ai,clearSessionCompleted:()=>_i,createSession:()=>Si,deleteArchivedSession:()=>Mi,deleteSession:()=>wi,duplicateSession:()=>Fi,hydrateSessionWorkdir:()=>bi,importSessions:()=>Ni,isSessionArchivable:()=>ki,loadArchivedSessions:()=>Oi,loadSessions:()=>vi,markSessionCompleted:()=>gi,persistSessionState:()=>xi,renameSession:()=>Ti,reorderSessions:()=>Ei,restoreCompletedSessions:()=>mi,restoreSession:()=>ji,saveCurrentSession:()=>yi,switchToSession:()=>Ci}),pi=`completedSessionIds`;async function mi(){try{let e=(await chrome.storage.local.get([pi]))[pi]||[];C.completedSessionIds=new Set(e)}catch(e){i.warn(`[SessionManager] restore completedSessionIds failed:`,e)}}async function hi(){try{await chrome.storage.local.set({[pi]:Array.from(C.completedSessionIds)})}catch(e){i.warn(`[SessionManager] persist completedSessionIds failed:`,e)}}async function gi(e){e&&e!==C.activeSessionId&&(C.completedSessionIds.has(e)||(C.completedSessionIds.add(e),await hi(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))))}async function _i(e){e&&C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await hi(),document.dispatchEvent(new CustomEvent(`generating-state-changed`)))}async function vi(){return ue()}async function yi(){return fe()}function bi(e){return le(e)}async function xi(e,t){return de(e,t)}async function Si(){return oe()}async function Ci(e){return Te(e)}async function wi(e){await Jr(e)>0&&ui(e);let t=await ve(e);try{chrome.runtime.sendMessage({type:`DROP_GOAL`,sessionId:e},()=>{chrome.runtime.lastError&&i.debug(`[SessionManager] DROP_GOAL skipped:`,chrome.runtime.lastError.message)})}catch(e){i.debug(`[SessionManager] DROP_GOAL send failed:`,e?.message)}return C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await hi()),t}async function Ti(e,t){return be(e,t)}async function Ei(e){return ge(e)}async function Di(){return _e()}async function Oi(){return we()}function ki(e){return e?C.generatingSessionIds.has(e)||C.pendingCallApiSessionIds.has(e)?{ok:!1,reason:`running`}:kr(e)>0?{ok:!1,reason:`queued`}:{ok:!0}:{ok:!1,reason:`missing`}}async function Ai(e){let t=ki(e);return t.ok?await xe(e)?(C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await hi(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))),{ok:!0}):{ok:!1,reason:`missing`}:t}async function ji(e){return Oe(e)}async function Mi(e){return wi(e)}async function Ni(e){return he(e)}async function Pi(e,t){return Ce(e,t)}async function Fi(e,t=null){return Se(e,t)}n(`zh`,{toolPanel:{agentRestrictedBanner:`当前 Agent 限制了可用工具,部分工具已禁用`,noMatch:`没有匹配的工具`,enabledCount:`已启用 {enabled}/{total} 个工具`,toolsEnabled:`工具已启用`,allToolsDisabled:`所有工具已禁用`,toggleBtnEnabled:`禁用所有工具`,toggleBtnDisabled:`启用所有工具`,mcpServiceToolCount:`{count} 个工具`,mcpServiceExpand:`展开/收起工具列表`,mcpExcludedByAgent:`已被当前助手排除,可在助手编辑中调整`,categorySelectAllHint:`对该分类下可见项全选/取消全选`,stateOn:`已开启`,stateOff:`已关闭`,stateLine:`{name}:{state}`}}),n(`en`,{toolPanel:{agentRestrictedBanner:`Current agent has restricted available tools, some tools are disabled`,noMatch:`No matching tools`,enabledCount:`{enabled}/{total} tools enabled`,toolsEnabled:`Tools enabled`,allToolsDisabled:`All tools disabled`,toggleBtnEnabled:`Disable all tools`,toggleBtnDisabled:`Enable all tools`,mcpServiceToolCount:`{count} tools`,mcpServiceExpand:`Show/hide tool list`,mcpExcludedByAgent:`Excluded by current assistant; adjust in assistant editor`,categorySelectAllHint:`Select/deselect all visible items in this category`,stateOn:`On`,stateOff:`Off`,stateLine:`{name}: {state}`}});var Ii=[],Li=[];function Ri(e){if(!e)return``;let t=`tool.${e.id}`,n=r(t);return n===t?e.description||``:n}function zi(e){if(!e)return``;let t=e.description||``;if(t.startsWith(`[MCP:`)){let e=t.indexOf(`]`);e!==-1&&(t=t.slice(e+1).trim())}return t===(e.name||``)?``:t}async function Bi(){try{let e=await chrome.runtime.sendMessage({type:`GET_MCP_TOOLS`});if(e?.success&&e.tools)return Ii=e.tools,Ii}catch{}try{return Ii=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[],Ii}catch{return Ii=[],[]}}async function Vi(){try{Li=(await chrome.storage.local.get([`ragTools`])).ragTools||[]}catch{Li=[]}return Li}async function Hi(){let e=`agentMcpClosedServers_${C.activeAgentId||`default`}`;try{C.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}catch{C.mcpClosedServers=[]}try{let{getAgent:e}=await A(async()=>{let{getAgent:e}=await import(`./agent-store-_CfonCwg.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3])),t=C.activeAgentId?await e(C.activeAgentId):null;C.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null}catch{}}var Ui=!1,Wi=!0;chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{Ui=e.enableToolPreselect===!0,Wi=e.toolConfirmationEnabled!==!1,ga()}),chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`)return;let n=!1;e.mcpTools&&(Ii=e.mcpTools.newValue||[],i.debug(`[SidePanel] MCP toolcache updated:`,Ii.length,``),n=!0),e.ragTools&&(Li=e.ragTools.newValue||[],i.debug(`[SidePanel] RAG toolcache updated:`,Li.length),n=!0),e.mcpEnabled&&(Gi=e.mcpEnabled.newValue===!0,i.debug(`[SidePanel] MCP globaltoggle changed:`,Gi),n=!0),e.skillsEnabled&&(Ki=e.skillsEnabled.newValue!==!1,i.debug(`[SidePanel] Skill global toggle changed:`,Ki),n=!0),e.enableImageInput&&(qi=e.enableImageInput.newValue===!0,i.debug(`[SidePanel] 图片识别全局开关变更:`,qi),n=!0);let r=!1;e.enableToolPreselect&&(Ui=e.enableToolPreselect.newValue===!0,r=!0),e.toolConfirmationEnabled&&(Wi=e.toolConfirmationEnabled.newValue!==!1,r=!0),r&&ga(),n&&(document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(da(),fa(),ra()),ha())}),Bi().then(()=>ha()),Vi().then(()=>ha());var Gi=!1,Ki=!0,qi=!1;chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`enableImageInput`],e=>{Gi=e.mcpEnabled===!0,Ki=e.skillsEnabled!==!1,qi=e.enableImageInput===!0,ha()});function Ji(){let e=[...f,...Li],t=C.activeAgentToolIds,n=e;if(t!=null){let r=new Set(t);n=e.filter(e=>r.has(e.id))}return Ki||(n=n.filter(e=>e.id!==`agent_skill`)),C.agentPlatform?.connected!==!0&&(n=n.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),qi||(n=n.filter(e=>e.id!==`read_image`)),n}function Yi(){if(!Gi||C.agentPlatform?.connected!==!0)return[];let e=new Map;return Ii.forEach(t=>{let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[],toolCount:0});let r=e.get(n);r.tools.push(t),r.toolCount++}),Array.from(e.values())}function Xi(e){return Array.isArray(C.mcpClosedServers)&&C.mcpClosedServers.includes(e)}function Zi(e){return Array.isArray(C.activeAgentMcpExcludedServerIds)&&C.activeAgentMcpExcludedServerIds.includes(e)}function Qi(e){return!Xi(e)&&!Zi(e)}function $i(){if(C.currentCategory!==`all`&&C.currentCategory!==`mcp`)return[];let e=Yi();if(C.currentSearch){let t=C.currentSearch;e=e.filter(e=>(e.serverName||``).toLowerCase().includes(t)||(e.serverId||``).toLowerCase().includes(t)||e.tools.some(e=>(e.name||``).toLowerCase().includes(t)||Ri(e).toLowerCase().includes(t)))}return e}function ea(e,t){Array.isArray(C.mcpClosedServers)||(C.mcpClosedServers=[]);let n=C.mcpClosedServers.indexOf(e);t?n>-1&&C.mcpClosedServers.splice(n,1):n===-1&&C.mcpClosedServers.push(e)}async function ta(){let e=document.getElementById(`toolsPopupOverlay`);if(!e)return;C.currentCategory=`all`,C.currentSearch=``;let t=document.getElementById(`toolsSearchInput`);t&&(t.value=``),await Bi(),await Vi(),await Hi(),da(),fa(),chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{let t=document.getElementById(`toolsPreselectToggle`);t&&(t.checked=e.enableToolPreselect===void 0?!1:e.enableToolPreselect);let n=document.getElementById(`toolConfirmToggle`);n&&(n.checked=e.toolConfirmationEnabled===void 0?!0:e.toolConfirmationEnabled)}),document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),ra(),e.classList.add(`show`),i.debug(`[SidePanel] opentool popup`)}function na(){let e=document.getElementById(`toolsPopupOverlay`);e&&(document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.style.background=``,e.style.color=``,e.style.borderColor=``}),e.classList.remove(`show`),i.debug(`[SidePanel] closetool popup`))}function ra(){let e=document.getElementById(`toolsPopupList`);if(!e)return;e.innerHTML=``;let t=Ji();if(C.activeAgentToolIds!==null&&C.activeAgentToolIds!==void 0){let t=document.createElement(`div`);t.className=`popup-tool-agent-banner`,t.innerHTML=`<span>${r(`toolPanel.agentRestrictedBanner`)}</span>`,e.appendChild(t)}let n={};t.forEach(e=>{if(C.currentCategory!==`all`&&e.category!==C.currentCategory)return;if(C.currentSearch){let t=e.name.toLowerCase().includes(C.currentSearch),n=Ri(e).toLowerCase().includes(C.currentSearch);if(!t&&!n)return}let t=e.category||`other`;n[t]||(n[t]=[]),n[t].push(e)});let i=$i();if(Qt.forEach(a=>{let o=a===`mcp`,s=n[a]||[],c=o?i:[];if(o?c.length===0:s.length===0)return;let l;if(o)l=`${c.filter(e=>Qi(e.serverId)).length}/${c.length}`;else{let e=t.filter(e=>e.category===a);l=`${e.filter(e=>C.enabledTools.includes(e.id)).length}/${e.length}`}let u=document.createElement(`div`);u.className=`popup-tool-category-group`,u.dataset.category=a;let d=document.createElement(`div`);d.className=`popup-tool-category`,d.dataset.category=a;let f=C.collapsedCategories[a]||!1;d.innerHTML=`
|
|
29
|
+
`;let c=e.closest(`.message-fullscreen-overlay`),l=e.closest(`.workspace-preview-overlay.fullscreen`);(c?c.querySelector(`.message-fullscreen-rail`)||gn(`toc`):l&&l.querySelector(`.workspace-preview-rail`)||gn(`toc`)).appendChild(a),C.messageTocContainer=a;let u=a.querySelector(`.message-toc-toggle`),d=a.querySelector(`.message-toc-panel`),f=jn===e;f||(jn=null);let p=d.querySelector(`.message-toc-lock`),m=Dn(`message-toc-lock`);p.before(m);let h=On(m,d,{onToggle:t=>{t?(jn=e,Pn(d)):(jn=null,Fn(),Ie(d))}});An&&(d.classList.add(`expanded`,`locked`),Cn(d)||Ie(d)),p.addEventListener(`click`,e=>{e.stopPropagation(),An=!An,zn(),Rn(p),An?(d.classList.add(`expanded`,`locked`),Cn(d)||Ie(d),requestAnimationFrame(()=>Wn&&Wn())):d.classList.remove(`locked`)}),d.querySelector(`.message-toc-close`).addEventListener(`click`,e=>{e.stopPropagation(),An&&(An=!1,zn()),Yn()}),u.addEventListener(`mouseenter`,()=>{d.classList.add(`expanded`),Cn(d)||Ie(d),requestAnimationFrame(()=>Wn&&Wn())}),u.addEventListener(`click`,()=>{d.classList.toggle(`expanded`)?(Cn(d)||Ie(d),requestAnimationFrame(()=>Wn&&Wn())):(jn=null,Fn(),Re(d))}),d.addEventListener(`mouseenter`,()=>{d.classList.add(`expanded`),requestAnimationFrame(()=>Wn&&Wn())}),d.querySelectorAll(`.message-toc-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.target,n=document.getElementById(t);if(n){let e=n.closest(`.markdown-body`);e&&e.scrollIntoView({behavior:`smooth`,block:`start`}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{n.scrollIntoView({behavior:`smooth`,block:`start`})})}),n.classList.add(`toc-highlight`),setTimeout(()=>{n.classList.remove(`toc-highlight`)},1500)}})}),Kn(d,e,n,d),f&&(Pn(d),h())}function Yn(){jn=null,Fn(),C.tocHideTimer&&=(clearTimeout(C.tocHideTimer),null),qn(),C.messageTocContainer&&=(C.messageTocContainer.remove(),null)}var Xn=`promptQueues`,Zn=1,Qn=30*1e3,$n=15*1e3,er=20,tr={QUEUED:`queued`,DISPATCHING:`dispatching`,INJECTING:`injecting`,INJECTED:`injected`,DONE:`done`,FAILED:`failed`};new Set([tr.INJECTED,tr.DONE,tr.FAILED]);var nr={async get(e){let t=await chrome.storage.local.get(e);return t?t[e]:void 0},async set(e){await chrome.storage.local.set(e)}};function rr(){return{version:Zn,sessions:{}}}var R=rr(),ir=!1,ar=null,or=!1,sr=``,cr=new Set,lr=new Set;function ur(){return{items:[],recent:[],paused:!1,pausedReason:null}}function dr(e){return e?(R.sessions[e]||(R.sessions[e]=ur()),R.sessions[e]):ur()}function fr(){return JSON.stringify(R)}function pr(e,t){for(let n of lr)try{n(e,t)}catch(e){i.error(`[QueueStore] listener failed:`,e?.message)}}function mr(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`q_`+crypto.randomUUID():`q_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8)}function hr(e){return e.reduce((e,t)=>Math.max(e,Number(t.order)||0),0)+1}function gr(e,t){let n=e.indexOf(t);n<0||(e.splice(n,1),e.unshift(t),_r(e))}function _r(e){e.forEach((e,t)=>{e.order=t+1})}function vr(e){return e.slice().sort((e,t)=>(Number(e.order)||0)-(Number(t.order)||0))}async function yr(e){if(or)return i.error(`[QueueStore] persist skipped in degraded mode:`,e),!1;let t=fr();sr=t,br(t);try{await nr.set({[Xn]:R})}catch(e){i.error(`[QueueStore] persist failed:`,e?.message)}pr(e)}function br(e){if(cr.add(e),cr.size<=er)return;let t=cr.values().next().value;cr.delete(t)}function xr(e,{recoverInterrupted:t=!0}={}){let n=rr();if(!e||typeof e!=`object`)return n;let r=e.sessions&&typeof e.sessions==`object`?e.sessions:{};for(let[e,i]of Object.entries(r)){let r=Array.isArray(i?.items)?i.items:[],a=Array.isArray(i?.recent)?i.recent.slice(0,30):[],o=!1;for(let e of r)!e||typeof e!=`object`||t&&(e.status===tr.DISPATCHING||e.status===tr.INJECTING)&&(e.status=tr.QUEUED,e.interrupted=!0,e.previousStatus=e.previousStatus||tr.DISPATCHING,e.leaseOwner=null,e.leaseUntil=0,o=!0);let s=vr(r);if(o){let e=s.filter(e=>e.interrupted),t=s.filter(e=>!e.interrupted);s.splice(0,s.length,...e,...t)}_r(s);let c=s.slice(0,20),l=s.slice(20);for(let e of l.reverse())a.unshift(Wr({...e,status:tr.FAILED,lastError:`over_limit`}));n.sessions[e]={items:c,recent:a.slice(0,30),paused:i?.paused===!0,pausedReason:i?.pausedReason||null}}return n}function Sr(){return or}async function Cr(){return ir?R:ar||(ar=(async()=>{let e;try{e=await nr.get(Xn)}catch(e){return or=!0,ar=null,i.error(`[QueueStore] load failed, enter degraded mode:`,e?.message),R}return R=xr(e),ir=!0,or=!1,sr=fr(),R})(),ar)}function wr(){typeof chrome>`u`||!chrome.storage?.onChanged?.addListener||chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`||!e?.[Xn])return;let n=e[Xn].newValue;if(!n)return;let r=JSON.stringify(n);cr.has(r)||r===sr||(R=xr(n,{recoverInterrupted:!1}),ir=!0,sr=r,pr(`external`,null))})}function Tr(e){return typeof e==`function`?(lr.add(e),()=>lr.delete(e)):()=>{}}function Er(e){let t=R.sessions[e];return t?vr(t.items):[]}function Dr(e,t=30){let n=R.sessions[e];return n?n.recent.slice(0,t):[]}function Or(e){let t=R.sessions[e];return t?{items:vr(t.items),recent:t.recent.slice(),paused:t.paused===!0,pausedReason:t.pausedReason||null}:ur()}function kr(e){return Er(e).filter(e=>e.status===tr.QUEUED).length}function Ar(e){return Er(e).find(e=>e.status===tr.QUEUED)||null}function jr(e){let t=R.sessions[e];if(!t)return null;for(let e=t.items.length-1;e>=0;--e)if(t.items[e].status===tr.QUEUED)return t.items[e];return null}function Mr(e,t){let n=R.sessions[e];return n&&n.items.find(e=>e.id===t)||null}function Nr(){return Object.keys(R.sessions).filter(e=>(R.sessions[e]?.items?.length||0)>0)}function Pr(e){return R.sessions[e]?.paused===!0}async function Fr({sessionId:e,text:t,contextSnapshot:n=null,hasContext:r=!1,attachmentSummary:i=null,source:a=`manual`}){if(!e)return{ok:!1,error:`missing_session`};let o=String(t||``).trim();if(!o)return{ok:!1,error:`empty`};if(await Cr(),or)return{ok:!1,error:`storage_unavailable`};let s=dr(e);if(s.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let c={id:mr(),sessionId:e,text:o,contextSnapshot:n||null,attachmentSummary:i||null,hasContext:r===!0,status:tr.QUEUED,order:hr(s.items),createdAt:Date.now(),updatedAt:Date.now(),attempts:0,lastError:null,source:a,interrupted:!1,leaseOwner:null,leaseUntil:0,injectRequestedAt:0,injectDeadlineAt:0,injectedIntoCallId:null,absorbedIteration:null};return s.items.push(c),await yr(`enqueue`),{ok:!0,item:c,position:s.items.length}}async function Ir(e,t){let n=R.sessions[e];if(!n)return!1;let r=n.items.findIndex(e=>e.id===t);return r<0?!1:(n.items.splice(r,1),_r(n.items),await yr(`remove`),!0)}async function Lr(e,t){let n=R.sessions[e];if(!n||!Array.isArray(t))return!1;let r=new Map(n.items.map(e=>[e.id,e])),i=[];for(let e of t){let t=r.get(e);t&&!i.includes(t)&&i.push(t)}for(let e of vr(n.items))i.includes(e)||i.push(e);return n.items=i,_r(n.items),await yr(`reorder`),!0}async function Rr(e,t,n,r={}){let i=Mr(e,t);return i?(i.status=n,Object.assign(i,r,{updatedAt:Date.now()}),await yr(`status`),!0):!1}async function zr(e,t,n=$n){let r=Mr(e,t);return r?(r.previousStatus=r.status,r.status=tr.INJECTING,r.injectRequestedAt=Date.now(),r.injectDeadlineAt=Date.now()+n,r.updatedAt=Date.now(),await yr(`inject:request`),!0):!1}async function Br(e,t,n=`error`,r=null){let i=R.sessions[e];if(!i)return!1;let a=i.items.find(e=>e.id===t);return a?(a.status=tr.QUEUED,a.injectDeadlineAt=0,a.updatedAt=Date.now(),a.lastError=r||n,a.rollbackReason=n,gr(i.items,a),await yr(`inject:rollback`),!0):!1}async function Vr(e,t,{status:n,note:r=null,callId:i=null,iteration:a=null}={}){let o=R.sessions[e];if(!o)return!1;let s=o.items.findIndex(e=>e.id===t);if(s<0)return!1;let[c]=o.items.splice(s,1);return _r(o.items),c.status=n||tr.DONE,c.settledAt=Date.now(),c.settleNote=r,i&&(c.injectedIntoCallId=i),a!=null&&(c.absorbedIteration=a),o.recent.unshift(Wr(c)),o.recent=o.recent.slice(0,30),await yr(`settle`),!0}async function Hr(e,t){let n=R.sessions[e];if(!n)return{ok:!1,error:`missing_session`};let r=n.recent.findIndex(e=>e.id===t);if(r<0)return{ok:!1,error:`not_found`};if(n.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let[i]=n.recent.splice(r,1),a={...i,status:tr.QUEUED,order:hr(n.items),attempts:0,lastError:null,interrupted:!1,rollbackReason:null,settledAt:null,leaseOwner:null,leaseUntil:0,injectDeadlineAt:0,updatedAt:Date.now()};return n.items.push(a),await yr(`requeue`),{ok:!0,item:a}}async function Ur(e,t){let n=R.sessions[e];if(!n)return!1;let r=n.recent.findIndex(e=>e.id===t);return r<0?!1:(n.recent.splice(r,1),await yr(`recent-remove`),!0)}function Wr(e){let{leaseOwner:t,leaseUntil:n,injectDeadlineAt:r,contextSnapshot:i,...a}=e;return{...a,hasContext:e.hasContext===!0,contextDropped:!!i}}async function Gr(e,t=`user_stopped`){let n=dr(e);return n.paused?!1:(n.paused=!0,n.pausedReason=t,await yr(`pause`),!0)}async function Kr(e){let t=R.sessions[e];return!t||!t.paused?!1:(t.paused=!1,t.pausedReason=null,await yr(`resume`),!0)}async function qr(e,t,n){let r=Mr(e,t);if(!r)return!1;let i=Date.now();return r.leaseOwner&&r.leaseOwner!==n&&Number(r.leaseUntil)>i?!1:(r.leaseOwner=n,r.leaseUntil=i+Qn,await yr(`lease`),!0)}async function Jr(e){let t=R.sessions[e];if(!t)return 0;let n=t.items.length+t.recent.length;return delete R.sessions[e],n>0&&await yr(`drop-session`),n}var Yr=`ai-helper-queue-attachments`,Xr=1,Zr=`attachments`,Qr=null,$r=null;function ei(){return new Promise((e,t)=>{let n=indexedDB.open(Yr,Xr);n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(Zr)||t.createObjectStore(Zr,{keyPath:`id`}).createIndex(`sessionId`,`sessionId`,{unique:!1})},n.onsuccess=t=>{let n=t.target.result;n.onversionchange=()=>{try{n.close()}catch{}Qr=null},e(n)},n.onerror=()=>t(n.error||Error(`idb_open_failed`)),n.onblocked=()=>{}})}function ti(){return Qr||=ei(),Qr}function ni(e,t){return ti().then(n=>new Promise((r,i)=>{let a;try{a=n.transaction(Zr,e)}catch(e){Qr=null,i(e);return}let o=a.objectStore(Zr),s=null,c=e=>{s=e};try{t(o,c)}catch(e){i(e);return}a.oncomplete=()=>r(s),a.onerror=()=>i(a.error||Error(`idb_tx_failed`)),a.onabort=()=>i(a.error||Error(`idb_tx_aborted`))}))}function ri(){return{async put(e){await ni(`readwrite`,t=>{t.put(e)})},async get(e){return ni(`readonly`,(t,n)=>{let r=t.get(e);r.onsuccess=()=>n(r.result||null)})},async remove(e){await ni(`readwrite`,t=>{t.delete(e)})},async removeBySession(e){await ni(`readwrite`,t=>{let n=t.index(`sessionId`).getAllKeys(e);n.onsuccess=()=>{for(let e of n.result||[])t.delete(e)}})},async allKeys(){return ni(`readonly`,(e,t)=>{let n=e.getAllKeys();n.onsuccess=()=>t(n.result||[])})}}}function ii(){return $r||ri()}function ai(e){return e==null?0:typeof e==`string`?e.length:typeof e==`number`||typeof e==`boolean`?8:Array.isArray(e)?e.reduce((e,t)=>e+ai(t),0):typeof e==`object`?Object.values(e).reduce((e,t)=>e+ai(t),0):0}function oi(e){let t=e&&e.attachedImages||[],n=e&&e.attachedFiles||[];return!t.length&&!n.length?null:{imageCount:t.length,fileCount:n.length,fileNames:n.map(e=>e.name).filter(Boolean).slice(0,5)}}async function si(e,t,{images:n=[],files:r=[]}={}){if(!e)return{ok:!1,reason:`missing_id`};if(!n.length&&!r.length)return{ok:!0,skipped:!0};let i=ai(n)+ai(r);if(i>26214400)return{ok:!1,reason:`too_large`,size:i};try{return await ii().put({id:e,sessionId:t||null,size:i,images:n,files:r,updatedAt:Date.now()}),{ok:!0,size:i}}catch(e){return{ok:!1,reason:`idb_error`,message:e?.message||String(e)}}}async function ci(e){if(!e)return null;try{let t=await ii().get(e);return t?{images:t.images||[],files:t.files||[]}:null}catch{return null}}async function li(e){if(!e)return!1;try{return await ii().remove(e),!0}catch{return!1}}async function ui(e){if(!e)return!1;try{return await ii().removeBySession(e),!0}catch{return!1}}async function di(e){let t=e instanceof Set?e:new Set(e||[]);try{let e=await ii().allKeys(),n=0;for(let r of e||[])t.has(r)||(await ii().remove(r),n+=1);return n}catch{return 0}}var fi=t({appendMessageToSession:()=>Pi,archiveCurrentSession:()=>Di,archiveSession:()=>Ai,clearSessionCompleted:()=>_i,createSession:()=>Si,deleteArchivedSession:()=>Mi,deleteSession:()=>wi,duplicateSession:()=>Fi,hydrateSessionWorkdir:()=>bi,importSessions:()=>Ni,isSessionArchivable:()=>ki,loadArchivedSessions:()=>Oi,loadSessions:()=>vi,markSessionCompleted:()=>gi,persistSessionState:()=>xi,renameSession:()=>Ti,reorderSessions:()=>Ei,restoreCompletedSessions:()=>mi,restoreSession:()=>ji,saveCurrentSession:()=>yi,switchToSession:()=>Ci}),pi=`completedSessionIds`;async function mi(){try{let e=(await chrome.storage.local.get([pi]))[pi]||[];C.completedSessionIds=new Set(e)}catch(e){i.warn(`[SessionManager] restore completedSessionIds failed:`,e)}}async function hi(){try{await chrome.storage.local.set({[pi]:Array.from(C.completedSessionIds)})}catch(e){i.warn(`[SessionManager] persist completedSessionIds failed:`,e)}}async function gi(e){e&&e!==C.activeSessionId&&(C.completedSessionIds.has(e)||(C.completedSessionIds.add(e),await hi(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))))}async function _i(e){e&&C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await hi(),document.dispatchEvent(new CustomEvent(`generating-state-changed`)))}async function vi(){return ue()}async function yi(){return fe()}function bi(e){return le(e)}async function xi(e,t){return de(e,t)}async function Si(){return oe()}async function Ci(e){return Te(e)}async function wi(e){await Jr(e)>0&&ui(e);let t=await ve(e);try{chrome.runtime.sendMessage({type:`DROP_GOAL`,sessionId:e},()=>{chrome.runtime.lastError&&i.debug(`[SessionManager] DROP_GOAL skipped:`,chrome.runtime.lastError.message)})}catch(e){i.debug(`[SessionManager] DROP_GOAL send failed:`,e?.message)}return C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await hi()),t}async function Ti(e,t){return be(e,t)}async function Ei(e){return ge(e)}async function Di(){return _e()}async function Oi(){return we()}function ki(e){return e?C.generatingSessionIds.has(e)||C.pendingCallApiSessionIds.has(e)?{ok:!1,reason:`running`}:kr(e)>0?{ok:!1,reason:`queued`}:{ok:!0}:{ok:!1,reason:`missing`}}async function Ai(e){let t=ki(e);return t.ok?await xe(e)?(C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await hi(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))),{ok:!0}):{ok:!1,reason:`missing`}:t}async function ji(e){return Oe(e)}async function Mi(e){return wi(e)}async function Ni(e){return he(e)}async function Pi(e,t){return Ce(e,t)}async function Fi(e,t=null){return Se(e,t)}n(`zh`,{toolPanel:{agentRestrictedBanner:`当前 Agent 限制了可用工具,部分工具已禁用`,noMatch:`没有匹配的工具`,enabledCount:`已启用 {enabled}/{total} 个工具`,toolsEnabled:`工具已启用`,allToolsDisabled:`所有工具已禁用`,toggleBtnEnabled:`禁用所有工具`,toggleBtnDisabled:`启用所有工具`,mcpServiceToolCount:`{count} 个工具`,mcpServiceExpand:`展开/收起工具列表`,mcpExcludedByAgent:`已被当前助手排除,可在助手编辑中调整`,categorySelectAllHint:`对该分类下可见项全选/取消全选`,stateOn:`已开启`,stateOff:`已关闭`,stateLine:`{name}:{state}`}}),n(`en`,{toolPanel:{agentRestrictedBanner:`Current agent has restricted available tools, some tools are disabled`,noMatch:`No matching tools`,enabledCount:`{enabled}/{total} tools enabled`,toolsEnabled:`Tools enabled`,allToolsDisabled:`All tools disabled`,toggleBtnEnabled:`Disable all tools`,toggleBtnDisabled:`Enable all tools`,mcpServiceToolCount:`{count} tools`,mcpServiceExpand:`Show/hide tool list`,mcpExcludedByAgent:`Excluded by current assistant; adjust in assistant editor`,categorySelectAllHint:`Select/deselect all visible items in this category`,stateOn:`On`,stateOff:`Off`,stateLine:`{name}: {state}`}});var Ii=[],Li=[];function Ri(e){if(!e)return``;let t=`tool.${e.id}`,n=r(t);return n===t?e.description||``:n}function zi(e){if(!e)return``;let t=e.description||``;if(t.startsWith(`[MCP:`)){let e=t.indexOf(`]`);e!==-1&&(t=t.slice(e+1).trim())}return t===(e.name||``)?``:t}async function Bi(){try{let e=await chrome.runtime.sendMessage({type:`GET_MCP_TOOLS`});if(e?.success&&e.tools)return Ii=e.tools,Ii}catch{}try{return Ii=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[],Ii}catch{return Ii=[],[]}}async function Vi(){try{Li=(await chrome.storage.local.get([`ragTools`])).ragTools||[]}catch{Li=[]}return Li}async function Hi(){let e=`agentMcpClosedServers_${C.activeAgentId||`default`}`;try{C.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}catch{C.mcpClosedServers=[]}try{let{getAgent:e}=await A(async()=>{let{getAgent:e}=await import(`./agent-store-CeC2_dkP.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3])),t=C.activeAgentId?await e(C.activeAgentId):null;C.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null}catch{}}var Ui=!1,Wi=!0;chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{Ui=e.enableToolPreselect===!0,Wi=e.toolConfirmationEnabled!==!1,ga()}),chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`)return;let n=!1;e.mcpTools&&(Ii=e.mcpTools.newValue||[],i.debug(`[SidePanel] MCP toolcache updated:`,Ii.length,``),n=!0),e.ragTools&&(Li=e.ragTools.newValue||[],i.debug(`[SidePanel] RAG toolcache updated:`,Li.length),n=!0),e.mcpEnabled&&(Gi=e.mcpEnabled.newValue===!0,i.debug(`[SidePanel] MCP globaltoggle changed:`,Gi),n=!0),e.skillsEnabled&&(Ki=e.skillsEnabled.newValue!==!1,i.debug(`[SidePanel] Skill global toggle changed:`,Ki),n=!0),e.enableImageInput&&(qi=e.enableImageInput.newValue===!0,i.debug(`[SidePanel] 图片识别全局开关变更:`,qi),n=!0);let r=!1;e.enableToolPreselect&&(Ui=e.enableToolPreselect.newValue===!0,r=!0),e.toolConfirmationEnabled&&(Wi=e.toolConfirmationEnabled.newValue!==!1,r=!0),r&&ga(),n&&(document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(da(),fa(),ra()),ha())}),Bi().then(()=>ha()),Vi().then(()=>ha());var Gi=!1,Ki=!0,qi=!1;chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`enableImageInput`],e=>{Gi=e.mcpEnabled===!0,Ki=e.skillsEnabled!==!1,qi=e.enableImageInput===!0,ha()});function Ji(){let e=[...f,...Li],t=C.activeAgentToolIds,n=e;if(t!=null){let r=new Set(t);n=e.filter(e=>r.has(e.id))}return Ki||(n=n.filter(e=>e.id!==`agent_skill`)),C.agentPlatform?.connected!==!0&&(n=n.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),qi||(n=n.filter(e=>e.id!==`read_image`)),n}function Yi(){if(!Gi||C.agentPlatform?.connected!==!0)return[];let e=new Map;return Ii.forEach(t=>{let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[],toolCount:0});let r=e.get(n);r.tools.push(t),r.toolCount++}),Array.from(e.values())}function Xi(e){return Array.isArray(C.mcpClosedServers)&&C.mcpClosedServers.includes(e)}function Zi(e){return Array.isArray(C.activeAgentMcpExcludedServerIds)&&C.activeAgentMcpExcludedServerIds.includes(e)}function Qi(e){return!Xi(e)&&!Zi(e)}function $i(){if(C.currentCategory!==`all`&&C.currentCategory!==`mcp`)return[];let e=Yi();if(C.currentSearch){let t=C.currentSearch;e=e.filter(e=>(e.serverName||``).toLowerCase().includes(t)||(e.serverId||``).toLowerCase().includes(t)||e.tools.some(e=>(e.name||``).toLowerCase().includes(t)||Ri(e).toLowerCase().includes(t)))}return e}function ea(e,t){Array.isArray(C.mcpClosedServers)||(C.mcpClosedServers=[]);let n=C.mcpClosedServers.indexOf(e);t?n>-1&&C.mcpClosedServers.splice(n,1):n===-1&&C.mcpClosedServers.push(e)}async function ta(){let e=document.getElementById(`toolsPopupOverlay`);if(!e)return;C.currentCategory=`all`,C.currentSearch=``;let t=document.getElementById(`toolsSearchInput`);t&&(t.value=``),await Bi(),await Vi(),await Hi(),da(),fa(),chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{let t=document.getElementById(`toolsPreselectToggle`);t&&(t.checked=e.enableToolPreselect===void 0?!1:e.enableToolPreselect);let n=document.getElementById(`toolConfirmToggle`);n&&(n.checked=e.toolConfirmationEnabled===void 0?!0:e.toolConfirmationEnabled)}),document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.classList.contains(`category-all`)?(e.classList.add(`active`),e.style.background=`linear-gradient(135deg, var(--brand-500) 0%, var(--brand-accent) 100%)`,e.style.color=`var(--text-on-brand)`,e.style.borderColor=`transparent`):(e.style.background=`var(--bg-surface)`,e.style.color=`var(--text-secondary)`,e.style.borderColor=`var(--border-subtle)`)}),ra(),e.classList.add(`show`),i.debug(`[SidePanel] opentool popup`)}function na(){let e=document.getElementById(`toolsPopupOverlay`);e&&(document.querySelectorAll(`.category-btn`).forEach(e=>{e.classList.remove(`active`),e.style.background=``,e.style.color=``,e.style.borderColor=``}),e.classList.remove(`show`),i.debug(`[SidePanel] closetool popup`))}function ra(){let e=document.getElementById(`toolsPopupList`);if(!e)return;e.innerHTML=``;let t=Ji();if(C.activeAgentToolIds!==null&&C.activeAgentToolIds!==void 0){let t=document.createElement(`div`);t.className=`popup-tool-agent-banner`,t.innerHTML=`<span>${r(`toolPanel.agentRestrictedBanner`)}</span>`,e.appendChild(t)}let n={};t.forEach(e=>{if(C.currentCategory!==`all`&&e.category!==C.currentCategory)return;if(C.currentSearch){let t=e.name.toLowerCase().includes(C.currentSearch),n=Ri(e).toLowerCase().includes(C.currentSearch);if(!t&&!n)return}let t=e.category||`other`;n[t]||(n[t]=[]),n[t].push(e)});let i=$i();if(Qt.forEach(a=>{let o=a===`mcp`,s=n[a]||[],c=o?i:[];if(o?c.length===0:s.length===0)return;let l;if(o)l=`${c.filter(e=>Qi(e.serverId)).length}/${c.length}`;else{let e=t.filter(e=>e.category===a);l=`${e.filter(e=>C.enabledTools.includes(e.id)).length}/${e.length}`}let u=document.createElement(`div`);u.className=`popup-tool-category-group`,u.dataset.category=a;let d=document.createElement(`div`);d.className=`popup-tool-category`,d.dataset.category=a;let f=C.collapsedCategories[a]||!1;d.innerHTML=`
|
|
30
30
|
<span class="category-expand-icon">${f?`▶`:`▼`}</span>
|
|
31
31
|
<span class="category-name">${r(`toolCategory.`+a)}</span>
|
|
32
32
|
<span class="category-count">${l}</span>
|
|
@@ -51,47 +51,49 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
51
51
|
</div>
|
|
52
52
|
<button type="button" class="popup-mcp-expand-btn" title="${r(`toolPanel.mcpServiceExpand`)}">▶</button>
|
|
53
53
|
`,a.appendChild(o);let s=document.createElement(`div`);s.className=`popup-mcp-tool-list collapsed`,e.tools.forEach(e=>{let t=e.name||``,n=zi(e),r=document.createElement(`div`);r.className=`popup-mcp-tool-row`,r.title=n?`${t}:${n}`:t,r.innerHTML=`<span class="popup-mcp-tool-name">${L(t)}</span>`+(n?`<span class="popup-mcp-tool-desc">${L(n)}</span>`:``),s.appendChild(r)}),a.appendChild(s);let c=o.querySelector(`.popup-mcp-expand-btn`),l=()=>{let e=s.classList.toggle(`collapsed`);c&&(c.textContent=e?`▶`:`▼`)};c&&c.addEventListener(`click`,e=>{e.stopPropagation(),l()}),o.addEventListener(`click`,e=>{e.target.closest(`input[type="checkbox"]`)||e.target.closest(`.popup-mcp-expand-btn`)||l()});let u=o.querySelector(`input[type="checkbox"]`);return u&&u.addEventListener(`change`,t=>{t.stopPropagation(),ea(e.serverId,t.target.checked),ca(`mcp`),da(),fa(),sa(`mcp`)}),a}function aa(e){C.collapsedCategories[e]=!C.collapsedCategories[e];let t=document.querySelector(`.popup-tool-category-group[data-category="${e}"]`);if(!t)return;let n=t.querySelector(`.popup-tool-category`).querySelector(`.category-expand-icon`),r=t.querySelector(`.popup-tool-items`);C.collapsedCategories[e]?(n.textContent=`▶`,r.classList.add(`collapsed`)):(n.textContent=`▼`,r.classList.remove(`collapsed`))}function oa(e){let t=document.querySelector(`.popup-tool-category-group[data-category="${e}"]`);if(!t)return;let n=Array.from(t.querySelectorAll(`.popup-tool-items input[type="checkbox"]:not(:disabled)`));if(n.length===0)return;let r=!n.every(e=>e.checked);n.forEach(e=>{e.checked!==r&&(e.checked=r,e.dispatchEvent(new Event(`change`)))}),sa(e)}function sa(e){let t=document.querySelector(`.popup-tool-category-group[data-category="${e}"]`),n=t?t.querySelector(`.category-select-all`):null;if(!n)return;let i=Array.from(t.querySelectorAll(`.popup-tool-items input[type="checkbox"]:not(:disabled)`));if(i.length===0){n.style.display=`none`;return}n.style.display=``,n.textContent=i.every(e=>e.checked)?r(`common.deselectAll`):r(`common.selectAll`)}function ca(e){let t=document.querySelector(`.popup-tool-category[data-category="${e}"]`);if(!t)return;let n=t.querySelector(`.category-count`);if(!n)return;let r=0,i=0;if(e===`mcp`){let e=$i();i=e.length,e.forEach(e=>{if(Zi(e.serverId))return;let t=document.getElementById(`mcpsvc_`+e.serverId);(t?t.checked:!Xi(e.serverId))&&r++})}else{let t=e===`knowledge`?Li:f.filter(t=>t.category===e);i=t.length,t.forEach(e=>{let t=document.getElementById(`tool_`+e.id);t&&t.checked&&r++})}n.textContent=`${r}/${i}`}function la(){return Ji().filter(e=>{if(C.currentCategory!==`all`&&e.category!==C.currentCategory)return!1;if(C.currentSearch){let t=e.name.toLowerCase().includes(C.currentSearch.toLowerCase()),n=Ri(e).toLowerCase().includes(C.currentSearch.toLowerCase());if(!t&&!n)return!1}return!0})}function ua(){Qt.forEach(e=>{ca(e),sa(e)})}function da(){let e=[`all`,...Qt],t=Ji(),n=Yi(),r=n.filter(e=>Qi(e.serverId)).length,i=new Set(t.map(e=>e.id)),a=C.enabledTools.filter(e=>i.has(e)).length;e.forEach(e=>{let i=document.getElementById(`badge-`+e);if(!i)return;let o=0,s=0;if(e===`all`)o=t.length+n.length,s=a+r;else if(e===`mcp`)o=n.length,s=r;else{let n=t.filter(t=>t.category===e);o=n.length,s=n.filter(e=>C.enabledTools.includes(e.id)).length}i.textContent=`${s}/${o}`,e!==`all`&&i.parentElement&&(i.parentElement.style.display=o===0?`none`:``)})}function fa(){let e=document.getElementById(`toolsEnabledCount`);if(!e)return;let t=Ji(),n=new Set(t.map(e=>e.id)),i=C.enabledTools.filter(e=>n.has(e)).length,a=Yi(),o=a.filter(e=>Qi(e.serverId)).length;e.textContent=r(`toolPanel.enabledCount`,{enabled:i+o,total:t.length+a.length})}function pa(){let e=[];[...va(Li)].forEach(t=>{let n=document.getElementById(`tool_`+t);n?n.checked&&e.push(t):C.enabledTools.includes(t)&&e.push(t)}),C.enabledTools=e,typeof document<`u`&&document.dispatchEvent(new CustomEvent(`agent-tools-changed`));let t=Yi(),n=new Set(t.map(e=>e.serverId)),a=(C.mcpClosedServers||[]).filter(e=>!n.has(e)),o=0;t.forEach(e=>{if(Zi(e.serverId)){Xi(e.serverId)&&a.push(e.serverId);return}let t=document.getElementById(`mcpsvc_`+e.serverId);(t?t.checked:!Xi(e.serverId))?o++:a.push(e.serverId)}),C.mcpClosedServers=a;let s=`agentEnabledTools_${C.activeAgentId||`default`}`,c=`agentMcpClosedServers_${C.activeAgentId||`default`}`;chrome.storage.local.set({[s]:C.enabledTools,[c]:C.mcpClosedServers},()=>{i.debug(`[SidePanel] tool configurationsavedto agent:`,s,C.enabledTools,c,C.mcpClosedServers)}),yi().catch(()=>{});let l=document.getElementById(`toolsPreselectToggle`);l&&chrome.storage.local.set({enableToolPreselect:l.checked},()=>{i.debug(`[SidePanel] toolpre-filter toggle saved:`,l.checked)});let u=document.getElementById(`toolConfirmToggle`);u&&chrome.storage.local.set({toolConfirmationEnabled:u.checked},()=>{i.debug(`[SidePanel] sensitive-operation confirmation toggle saved:`,u.checked)}),ha();let d=Ji(),f=new Set(d.map(e=>e.id)),p=C.enabledTools.filter(e=>f.has(e)).length+o;F(p>0?r(`toolPanel.toolsEnabled`,{count:p}):r(`toolPanel.allToolsDisabled`),`success`)}function ma(e){$i().forEach(t=>{if(Zi(t.serverId))return;let n=document.getElementById(`mcpsvc_`+t.serverId);n&&(n.checked=e),ea(t.serverId,e)})}function ha(){if(typeof document>`u`)return;let e=document.getElementById(`toolsToggleBtn`),t=document.getElementById(`toolsBadge`),n=Ji(),i=new Set(n.map(e=>e.id)),a=C.enabledTools.filter(e=>i.has(e)).length+Yi().filter(e=>Qi(e.serverId)).length;e&&(C.useTools&&a>0?(e.classList.add(`active`),e.title=r(`toolPanel.toggleBtnEnabled`,{count:a})):(e.classList.remove(`active`),e.title=r(`toolPanel.toggleBtnDisabled`))),t&&(a>0?(t.textContent=a,t.style.display=`inline`):t.style.display=`none`);let o=document.getElementById(`toolsConfigCount`);o&&(o.textContent=a);let s=document.getElementById(`toolsConfigBtn`);s&&s.classList.toggle(`active`,C.useTools&&a>0)}function ga(){let e=document.getElementById(`toolsConfigBtn`);if(!e)return;let t=document.getElementById(`toolsConfigFlagPreselect`),n=document.getElementById(`toolsConfigFlagConfirm`);t&&t.classList.toggle(`on`,Ui),n&&n.classList.toggle(`on`,Wi);let i=(e,t)=>r(`toolPanel.stateLine`,{name:e,state:r(t?`toolPanel.stateOn`:`toolPanel.stateOff`)});e.title=[r(`toolPanel.configBtnTitle`),i(r(`toolPanel.preselect`),Ui),i(r(`react.toolConfirmation`),Wi)].join(`
|
|
54
|
-
`)}function _a(e,t,n){let r=Array.isArray(e)?e:[];if(n===!0||!Array.isArray(t)||t.length===0)return{tools:r,migrated:!1};let i=[...r];for(let e of t)i.includes(e.id)||i.push(e.id);return{tools:i,migrated:i.length!==r.length}}function va(e=[]){let t=Array.isArray(e)?e:[];return new Set([...f.map(e=>e.id),...Zt,...t.map(e=>e.id)])}function ya(){document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(da(),fa(),ra()),ha()}n(`zh`,{agentToolFilter:{selectedCountHint:`已勾选 {count} 项`}}),n(`en`,{agentToolFilter:{selectedCountHint:`{count} selected`}});function ba(e,{query:t,selectedOnly:n,selectedSet:r,getDesc:i}){if(n&&!r.has(e.id))return!1;let a=String(t||``).toLowerCase();return!a||(e.name||``).toLowerCase().includes(a)?!0:String((i?i(e):e.description)||``).toLowerCase().includes(a)}function xa(e,{query:t,selectedOnly:n,excludedSet:r,getDesc:i}){if(n&&r.has(e.serverId))return!1;let a=String(t||``).toLowerCase();return!a||[e.serverName,e.serverId].filter(Boolean).join(` `).toLowerCase().includes(a)?!0:(e.tools||[]).some(e=>(e.name||``).toLowerCase().includes(a)?!0:String((i?i(e):e.description)||``).toLowerCase().includes(a))}function Sa({tools:e,services:t,selectedSet:n,excludedSet:r,query:i,selectedOnly:a,getDesc:o}){let s={query:String(i||``).trim().toLowerCase(),selectedOnly:a===!0,selectedSet:n,excludedSet:r,getDesc:o};return{tools:(e||[]).filter(e=>ba(e,s)),services:(t||[]).filter(e=>xa(e,s))}}var Ca={
|
|
54
|
+
`)}function _a(e,t,n){let r=Array.isArray(e)?e:[];if(n===!0||!Array.isArray(t)||t.length===0)return{tools:r,migrated:!1};let i=[...r];for(let e of t)i.includes(e.id)||i.push(e.id);return{tools:i,migrated:i.length!==r.length}}function va(e=[]){let t=Array.isArray(e)?e:[];return new Set([...f.map(e=>e.id),...Zt,...t.map(e=>e.id)])}function ya(){document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(da(),fa(),ra()),ha()}n(`zh`,{agentToolFilter:{selectedCountHint:`已勾选 {count} 项`}}),n(`en`,{agentToolFilter:{selectedCountHint:`{count} selected`}});function ba(e,{query:t,selectedOnly:n,selectedSet:r,getDesc:i}){if(n&&!r.has(e.id))return!1;let a=String(t||``).toLowerCase();return!a||(e.name||``).toLowerCase().includes(a)?!0:String((i?i(e):e.description)||``).toLowerCase().includes(a)}function xa(e,{query:t,selectedOnly:n,excludedSet:r,getDesc:i}){if(n&&r.has(e.serverId))return!1;let a=String(t||``).toLowerCase();return!a||[e.serverName,e.serverId].filter(Boolean).join(` `).toLowerCase().includes(a)?!0:(e.tools||[]).some(e=>(e.name||``).toLowerCase().includes(a)?!0:String((i?i(e):e.description)||``).toLowerCase().includes(a))}function Sa({tools:e,services:t,selectedSet:n,excludedSet:r,query:i,selectedOnly:a,getDesc:o}){let s={query:String(i||``).trim().toLowerCase(),selectedOnly:a===!0,selectedSet:n,excludedSet:r,getDesc:o};return{tools:(e||[]).filter(e=>ba(e,s)),services:(t||[]).filter(e=>xa(e,s))}}var Ca={"/":`slash`,"@":`at`,$:`dollar`};function wa({value:e,caret:t}){if(typeof e!=`string`)return null;let n=typeof t==`number`&&t>=0&&t<=e.length?t:e.length,r=e.substring(0,n),i=null;for(let t of Object.keys(Ca)){let a=r.lastIndexOf(t);if(a===-1)continue;if(a!==0){let t=e[a-1];if(t!==` `&&t!==`
|
|
55
|
+
`)continue}let o=e.substring(a+1,n);if(o.includes(` `)||o.includes(`
|
|
56
|
+
`))continue;let s={key:Ca[t],index:a,filterText:o};(!i||s.index>i.index)&&(i=s)}return i}function Ta(e,t,n,r){let i=wa({value:e,caret:t});return!i||n&&i.key!==n?null:{value:e.substring(0,i.index)+r+e.substring(t),caret:i.index+r.length}}function Ea(e,t,n){return Ta(e,t,n,``)}var Da={CONFIRM:`confirm`,CLARIFY:`clarify`},Oa=new Map,ka=null,Aa=[];function ja(e,t){Oa.set(e,t)}function Ma(e){if(ka===e){Fa(e)||(ka=null,Pa());return}if(ka===null){ka=e,Fa(e)||(ka=null,Pa());return}Aa.includes(e)||Aa.push(e),i.debug(`[SidePanel] interaction ${e} queued behind ${ka}`)}function Na(e){ka===e&&(ka=null,Pa())}function Pa(){for(;Aa.length>0;){let e=Aa.shift();if(ka=e,Fa(e))return;ka=null}}function Fa(e){let t=Oa.get(e);if(!t||typeof t.present!=`function`)return!1;try{return t.present()===!0}catch(t){return i.error(`[SidePanel] present ${e} failed:`,t?.message),!1}}function Ia(e){if(!ka||ka===e)return;let t=Oa.get(ka);if(!(!t||typeof t.refresh!=`function`))try{t.refresh()}catch(t){i.error(`[SidePanel] refresh ${ka} hint for ${e} change failed:`,t?.message)}}function La(e){let t=0;for(let[n,r]of Oa){if(n===e)continue;let i=typeof r.pendingCount==`function`?r.pendingCount():0;t+=Number.isFinite(i)&&i>0?i:0}return t}function Ra(e,t){if(!t||!t.toolCallId)return;let n={type:`INTERACTION_DISPLAYED`,data:{kind:e,toolCallId:t.toolCallId,sessionId:t.sessionId||null}};Promise.resolve(chrome.runtime.sendMessage(n)).catch(t=>{i.debug(`[SidePanel] report ${e} displayed failed:`,t?.message)})}var za=Da.CLARIFY;n(`zh`,{clarify:{remainingTimeDynamic:`剩余时间: {time}`,timeoutSoon:`时间即将耗尽`,sessionNameTitle:`{title}`,sessionNameId:`会话 ID: {id}`,recommended:`推荐`,otherOption:`其他(自定义输入)`,timedOut:`已超时`,timedOutDefaulted:`已超时,已按推荐项「{option}」继续`,dropped:`澄清弹窗无法显示,已按未澄清继续`,extend:`延长时间`,extended:`已延长倒计时`,extendLimit:`已达延长上限`}}),n(`en`,{clarify:{remainingTimeDynamic:`Remaining time: {time}`,timeoutSoon:`Time is almost up`,sessionNameTitle:`{title}`,sessionNameId:`Session ID: {id}`,recommended:`Recommended`,otherOption:`Other (custom input)`,timedOut:`Timed out`,timedOutDefaulted:`Timed out — continued with the recommended option "{option}"`,dropped:`Clarification dialog could not be shown; continuing as unanswered`,extend:`Extend time`,extended:`Countdown extended`,extendLimit:`Extend limit reached`}});var Ba=[],z=null,Va=null,Ha=!1;function Ua(e){return`${Math.floor(e/60)}:${(e%60).toString().padStart(2,`0`)}`}function Wa(e=`default`){try{let t=new(window.AudioContext||window.webkitAudioContext),n=t.createOscillator(),r=t.createGain();n.connect(r),r.connect(t.destination);let a={default:{frequency:800,duration:.3},success:{frequency:523,duration:.2},warning:{frequency:440,duration:.4},error:{frequency:220,duration:.5}},o=a[e]||a.default;n.frequency.value=o.frequency,n.type=`sine`,r.gain.setValueAtTime(.3,t.currentTime),r.gain.exponentialRampToValueAtTime(.01,t.currentTime+o.duration),n.start(t.currentTime),n.stop(t.currentTime+o.duration),i.debug(`[SidePanel] soundplay:`,e)}catch(e){i.error(`[SidePanel] play sound failed:`,e.message)}}function Ga(e,t){let n=document.getElementById(`clarifyTimer`),i=document.getElementById(`clarifyTimerText`);if(!n||!i)return;i.textContent=r(`clarify.remainingTimeDynamic`,{time:Ua(e)});let a=e/t*100,o=document.getElementById(`clarifyTimerBarFill`);o&&(o.style.width=`${Math.max(0,Math.min(100,a))}%`),n.classList.remove(`warning`,`critical`),e<=10?(n.classList.add(`critical`),i.textContent=r(`clarify.timeoutSoon`,{time:Ua(e)})):(e<=30||a<=15)&&n.classList.add(`warning`);let s=document.getElementById(`clarifyExtendBtn`);s&&s.classList.toggle(`show`,e<=60||a<=50),e===30&&Wa(`warning`)}function Ka(e){qa(),C.clarifyTimeoutValue=e;let t=Math.ceil(e/1e3),n=t;Ga(n,t),C.clarifyTimerInterval=setInterval(()=>{n--,n<=0?(qa(),z&&Ra(za,z)):Ga(n,t)},1e3)}function qa(){C.clarifyTimerInterval&&=(clearInterval(C.clarifyTimerInterval),null)}function Ja(){let e=document.getElementById(`clarifyExtendBtn`);if(!e)return;let t=Va===0;e.disabled=t||Ha,e.textContent=r(t?`clarify.extendLimit`:`clarify.extend`)}function Ya(){!z||Ha||Va!==0&&(Ha=!0,Ja(),Promise.resolve(chrome.runtime.sendMessage({type:`CLARIFY_EXTEND`,toolCallId:z.toolCallId,sessionId:z.sessionId})).catch(e=>{i.debug(`[SidePanel] send clarify extend failed:`,e?.message)}),setTimeout(()=>{Ha&&(Ha=!1,Ja())},3e3))}function Xa(e){let t=e?.toolCallId;if(!(!z||z.toolCallId!==t)){if(Ha=!1,e.denied||typeof e.remainingMs!=`number`){Va=0,Ja(),F(r(`clarify.extendLimit`),`warning`);return}Va=typeof e.extendsLeft==`number`?e.extendsLeft:Va,Ka(e.remainingMs),Ja(),F(r(`clarify.extended`),`success`),i.debug(`[SidePanel] clarify extended, remainingMs:`,e.remainingMs,`left:`,Va)}}function Za(e){let t=Ba.length,n=La(za),i=e.question||``;return t>0&&(i+=` ${r(`dialog.pendingQueueClarify`,{count:t})}`),n>0&&(i+=` ${r(`dialog.otherPending`,{count:n})}`),i}function Qa(){if(!z)return;let e=document.getElementById(`clarifyQuestion`);e&&(e.textContent=Za(z))}function $a(e){let{question:t,recommendedOption:n,allowCustomInput:a=!0,allowAdditionalInfo:o=!0,timeout:s=3e5,sessionId:c}=e,l=document.getElementById(`clarifyOverlay`);if(!l)return!1;let u=Array.isArray(e.options)?e.options:e.options?[String(e.options)]:[];C.currentClarifyToolCallId=e.toolCallId,C.currentClarifySessionId=c||null;let d=document.getElementById(`clarifySessionName`);if(d)if(c&&C.sessions){let e=C.sessions.find(e=>e.id===c);e?(d.textContent=r(`clarify.sessionNameTitle`,{title:e.title}),d.style.display=`block`,d.title=e.title||``):(d.textContent=r(`clarify.sessionNameId`,{id:c.substring(0,8)}),d.style.display=`block`,d.title=c)}else d.textContent=``,d.title=``,d.style.display=`none`;let f=n!==void 0&&n>=0?n:0,p=[f],m=f,h=document.getElementById(`clarifyQuestion`);h&&(h.textContent=Za(e));let g=document.getElementById(`clarifyOptionsList`);if(g&&(document.querySelectorAll(`.clarify-option-item`).forEach(e=>{e.remove()}),u.forEach((e,t)=>{let n=p.includes(t),i=document.createElement(`div`);i.className=`clarify-option-item ${m===t?`selected`:``} ${n?`recommended`:``}`,i.dataset.index=t,i.setAttribute(`role`,`radio`),i.setAttribute(`aria-checked`,m===t?`true`:`false`),i.setAttribute(`tabindex`,m===t?`0`:`-1`),i.innerHTML=`
|
|
55
57
|
<div class="clarify-option-radio"></div>
|
|
56
58
|
<div class="clarify-option-content">${e}${n?`<span class="clarify-option-badge">${r(`clarify.recommended`)}</span>`:``}</div>
|
|
57
|
-
`,i.addEventListener(`click`,()=>
|
|
59
|
+
`,i.addEventListener(`click`,()=>co(t)),g.appendChild(i)}),a)){let e=document.createElement(`div`);e.className=`clarify-option-item`,e.dataset.index=-1,e.setAttribute(`role`,`radio`),e.setAttribute(`aria-checked`,`false`),e.setAttribute(`tabindex`,`-1`),e.innerHTML=`
|
|
58
60
|
<div class="clarify-option-radio"></div>
|
|
59
61
|
<div class="clarify-option-content clarify-option-other">${r(`clarify.otherOption`)}</div>
|
|
60
|
-
`,e.addEventListener(`click`,()=>io(-1)),g.appendChild(e);let t=document.getElementById(`clarifyCustomInput`);t&&g.appendChild(t)}let _=document.getElementById(`clarifyCustomInput`);_&&_.classList.remove(`show`);let v=document.getElementById(`clarifyAdditionalInfo`);v&&v.classList.toggle(`show`,o);let y=document.getElementById(`clarifyCustomTextarea`);y&&(y.value=``);let b=document.getElementById(`clarifyAdditionalTextarea`);b&&(b.value=``),l.classList.add(`show`);let x=document.querySelector(`#clarifyContainer .clarify-content`),S=document.querySelector(`#clarifyContainer .clarify-header`);return x&&(x.scrollTop=0),S&&S.classList.remove(`scrolled`),La=null,Ra=!1,Wa(),Ha(s),i.debug(`[SidePanel] clarification dialogshown:`,e.toolCallId,t),!0}function Xa(){if(z)return!0;if(Ia.length===0)return!1;let e=Ia.shift();return Ya(e)?(z=e,Pa(Fa,e),!0):(i.error(`[SidePanel] clarify overlay missing, settle as unanswered:`,e.toolCallId),Za(e),F(r(`clarify.dropped`),`warning`),!1)}function Za(e){Promise.resolve(chrome.runtime.sendMessage({type:`CLARIFY_RESPONSE`,toolCallId:e.toolCallId,selectedOption:-1,customInput:``,additionalInfo:``})).catch(e=>{i.debug(`[SidePanel] send unanswered clarify response failed:`,e?.message)})}function Qa(){if(Ia.length>0){Oa(Fa);return}$a(),ka(Fa)}function $a(){let e=document.getElementById(`clarifyOverlay`);e&&e.classList.remove(`show`),C.currentClarifyToolCallId=null,C.currentClarifySessionId=null,Ua()}function eo(){z=null,Qa()}function to(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&e.question===t.question}function no(e){let t={...e,sessionId:e.sessionId||null};if(i.debug(`[SidePanel] showclarification dialog:`,t.toolCallId,e),z&&to(z,t)){i.debug(`[SidePanel] duplicate clarify request, ignored:`,t.toolCallId);return}if(Ia.some(e=>to(e,t))){i.debug(`[SidePanel] queued duplicate clarify, ignored:`,t.toolCallId);return}Ia.push(t),Oa(Fa),Ja(),Ma(Fa)}function ro(){if(z){eo();return}$a()}function io(e){document.querySelectorAll(`.clarify-option-item`).forEach(e=>{e.classList.remove(`selected`),e.setAttribute(`aria-checked`,`false`),e.setAttribute(`tabindex`,`-1`)});let t=document.querySelector(`.clarify-option-item[data-index="${e}"]`);t&&(t.classList.add(`selected`),t.setAttribute(`aria-checked`,`true`),t.setAttribute(`tabindex`,`0`));let n=document.getElementById(`clarifyCustomInput`);if(n)if(e===-1){n.classList.add(`show`);let e=document.getElementById(`clarifyCustomTextarea`);e&&e.focus()}else n.classList.remove(`show`);i.debug(`[SidePanel] selectclarificationselect :`,e)}function ao(){if(!z){i.error(`[SidePanel] no has currenttool callID`);return}let e=z.toolCallId,t=z.sessionId,n=-1;document.querySelectorAll(`.clarify-option-item`).forEach((e,t)=>{e.classList.contains(`selected`)&&(n=parseInt(e.dataset.index))});let r=document.getElementById(`clarifyCustomTextarea`),a=r?r.value.trim():``,o=document.getElementById(`clarifyAdditionalTextarea`),s=o?o.value.trim():``,c={type:`CLARIFY_RESPONSE`,toolCallId:e,sessionId:t,selectedOption:n,customInput:a,additionalInfo:s};i.debug(`[SidePanel] send clarificationresponse:`,c),chrome.runtime.sendMessage(c),eo()}function oo(){if(z){let e={type:`CLARIFY_RESPONSE`,toolCallId:z.toolCallId,sessionId:z.sessionId,selectedOption:-1,customInput:``,additionalInfo:``};chrome.runtime.sendMessage(e)}ro()}function so(e){return e?.reason===`timeout`&&e?.defaultOption||null}function co(e){i.debug(`[SidePanel] received clarificationtimeoutnotification:`,e);let t=e?.toolCallId;if(!t){if(e?.sessionId&&C.currentClarifySessionId&&e.sessionId!==C.currentClarifySessionId){i.debug(`[SidePanel] clarificationtimeoutfrom othersession,ignore`);return}if(!z)return;lo(so(e));return}if(z&&z.toolCallId===t){lo(so(e));return}let n=Ia.findIndex(e=>e.toolCallId===t);n>=0&&(i.debug(`[SidePanel] drop queued clarify (already settled by background):`,t),Ia.splice(n,1),Ja(),Ma(Fa))}function lo(e=null){let t=z?.question;eo(),F(e?r(`clarify.timedOutDefaulted`,{option:e}):`${r(`clarify.timedOut`)}${t?`:${t}`:``}`,`warning`),Ba(`error`)}Da(Fa,{present:Xa,pendingCount:()=>Ia.length,refresh:Ja});function uo(){let e=document.getElementById(`clarifyConfirmBtn`);e&&e.addEventListener(`click`,ao);let t=document.getElementById(`clarifyCancelBtn`);t&&t.addEventListener(`click`,oo);let n=document.getElementById(`clarifyExtendBtn`);n&&n.addEventListener(`click`,Ga);let r=document.querySelector(`#clarifyContainer .clarify-content`),a=document.querySelector(`#clarifyContainer .clarify-header`);r&&a&&r.addEventListener(`scroll`,()=>{a.classList.toggle(`scrolled`,r.scrollTop>2)}),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_CLARIFY_DIALOG`?(i.debug(`[SidePanel] received clarificationrequested :`,e,`currently activesession:`,C.activeSessionId),no(e.data),n({success:!0})):e.type===`PLAY_NOTIFICATION_SOUND`?(i.debug(`[SidePanel] recei to play soundrequested :`,e),Ba(e.soundType),n({success:!0})):e.type===`CLARIFY_TIMEOUT`?co(e):e.type===`CLARIFY_EXTENDED`&&Ka(e)}),i.debug(`[SidePanel] clarification dialogeventinitializing`)}var fo=Ca.CONFIRM,po=[],mo=null,ho=null,go=null;function _o(e){let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`}function vo(){ho&&=(clearInterval(ho),null),go&&=(clearTimeout(go),null)}function yo(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&JSON.stringify(e.args??null)===JSON.stringify(t.args??null)}function bo(e){let t=e.message||r(`dialog.confirmAction`,{name:e.toolLabel||e.toolName}),n=po.length,i=Na(fo),a=t;return n>0&&(a+=` ${r(`dialog.pendingQueue`,{count:n})}`),i>0&&(a+=` ${r(`dialog.otherPending`,{count:i})}`),a}function xo(e){let{toolName:t,toolLabel:n,args:a,timeout:o=3e5}=e;C.currentConfirmToolCallId=e.toolCallId,C.currentConfirmSessionId=e.sessionId||null;let s=document.getElementById(`confirmOverlay`);if(!s)return!1;document.getElementById(`confirmToolName`).textContent=n||t;let c=e.variant===`network`,l=document.getElementById(`confirmTitle`);l&&(l.textContent=r(c?`dialog.networkTitle`:`dialog.operationConfirm`));let u=document.getElementById(`confirmApproveLoopBtn`);u&&(u.textContent=r(c?`dialog.approveWhitelist`:`dialog.approveLoop`));let d=document.getElementById(`confirmArgsSummary`);if(d&&a){let e=Object.entries(a).filter(([e,t])=>t!=null&&t!==``).slice(0,5);e.length>0?(d.textContent=``,e.forEach(([e,t],n)=>{n>0&&d.appendChild(document.createTextNode(`、 `));let r=typeof t==`string`?t:JSON.stringify(t),i=r.length>80?r.substring(0,80)+`...`:r,a=document.createElement(`span`);a.className=`confirm-arg`,a.style.marginRight=`8px`,r.length>80&&(a.title=r);let o=document.createElement(`strong`);o.textContent=`${e}:`,a.appendChild(o),a.appendChild(document.createTextNode(` ${i}`)),d.appendChild(a)}),d.style.display=`block`):d.style.display=`none`}let f=document.getElementById(`confirmMessage`);f&&(f.textContent=bo(e)),vo();let p=Math.floor(o/1e3),m=document.getElementById(`confirmCountdownText`),h=document.getElementById(`confirmCountdown`);return m&&h&&(h.classList.remove(`warning`),h.style.display=`flex`,m.textContent=r(`dialog.remainingTime`,{time:_o(p)}),ho=setInterval(()=>{if(p--,p<=0){clearInterval(ho),ho=null,m.textContent=r(`dialog.remainingTime`,{time:`0:00`});return}m.textContent=r(`dialog.remainingTime`,{time:_o(p)}),p<=30&&h.classList.add(`warning`)},1e3)),s.style.display=`flex`,go=setTimeout(()=>{i.debug(`[SidePanel] confirm dialogtimeout,autodeny`),Do(!1,`single`)},o),!0}function So(){if(mo)return!0;if(po.length===0)return!1;let e=po.shift();return xo(e)?(mo=e,Pa(fo,e),!0):(e.resolve&&e.resolve(!1),!1)}function Co(){let e=document.getElementById(`confirmOverlay`);e&&(e.style.display=`none`);let t=document.getElementById(`confirmCountdown`);t&&(t.classList.remove(`warning`),t.style.display=`none`),C.currentConfirmToolCallId=null,C.currentConfirmSessionId=null}function wo(){if(po.length>0){Oa(fo);return}Co(),ka(fo)}function To(e){let t=mo?.resolve;mo=null,vo(),t&&t(e),wo()}function Eo(e){let t={...e,sessionId:e.sessionId||null};return i.debug(`[SidePanel] showconfirm dialog:`,t.toolName,e),mo&&yo(mo,t)?(i.debug(`[SidePanel] duplicate confirm request, ignored:`,t.toolCallId),Promise.resolve(!1)):po.some(e=>yo(e,t))?(i.debug(`[SidePanel] queued duplicate confirm, ignored:`,t.toolCallId),Promise.resolve(!1)):new Promise(e=>{po.push({...t,resolve:e}),Oa(fo),mo&&Oo(),Ma(fo)})}function Do(e,t=`single`){if(!mo)return;let n=mo.toolCallId,r=mo.sessionId;vo(),chrome.runtime.sendMessage({type:`TOOL_CONFIRMATION_RESPONSE`,toolCallId:n,confirmed:e,scope:t,sessionId:r}).catch(e=>{i.debug(`[SidePanel] send confirmationresponse failed:`,e.message)}),To(e)}function Oo(){if(!mo)return;let e=document.getElementById(`confirmMessage`);e&&(e.textContent=bo(mo))}function ko(e){let t=e?.toolCallId;if(!t)return;if(mo&&mo.toolCallId===t){i.debug(`[SidePanel] dismiss active confirm dialog (already settled by background):`,t),To(!1);return}let n=po.findIndex(e=>e.toolCallId===t);if(n>=0){i.debug(`[SidePanel] drop queued confirm dialog (already settled by background):`,t);let[e]=po.splice(n,1);e.resolve&&e.resolve(!1),Oo(),Ma(fo)}}Da(fo,{present:So,pendingCount:()=>po.length,refresh:()=>{mo&&Oo()}});function Ao(){let e=document.getElementById(`confirmApproveOnceBtn`),t=document.getElementById(`confirmApproveLoopBtn`),n=document.getElementById(`confirmDenyBtn`);e&&e.addEventListener(`click`,()=>Do(!0,`single`)),t&&t.addEventListener(`click`,()=>{Do(!0,mo?.variant===`network`?`whitelist`:`loop`)}),n&&n.addEventListener(`click`,()=>Do(!1,`single`)),chrome.runtime.onMessage.addListener((e,t,n)=>e.type===`SHOW_CONFIRM_DIALOG`?(Eo(e.data),n({received:!0}),!1):e.type===`DISMISS_CONFIRM_DIALOG`?(ko(e.data),n({received:!0}),!1):!1)}var jo=t({closeCurrentSession:()=>Sc,handleDuplicateSession:()=>pc,handleSessionSwitch:()=>fc,newSession:()=>Ro,renderSessionTabs:()=>Io});n(`zh`,{session:{newSession:`新会话`,closeSession:`关闭会话`,taskCompleted:`任务已完成`,noMatch:`未找到匹配的会话`,rename:`重命名`,duplicate:`复制会话`,confirmCloseMessageWithTitle:`确定要关闭会话 "{title}" 吗?`,confirmCloseAllMessage:`确定要关闭所有 {count} 个会话吗?`,confirmCloseAllTitle:`关闭全部会话`,forkedFrom:`已从 "{title}" 分叉`,forkedSession:`已复制会话 "{title}"`,operationFailed:`操作失败:{message}`,sessionListTitle:`会话列表`,closeGroupAll:`全部关闭`,confirmCloseGroupMessage:`确定要关闭“{group}”下的 {count} 个会话吗?`,today:`今天`,yesterday:`昨天`,last7Days:`近 7 天`,earlier:`更早`,todayFormat:`{hour}:{minute}`,yesterdayFormat:`昨天 {hour}:{minute}`,daysAgo:`{count} 天前`,archive:`归档会话`,archiveEntry:`归档区`,archiveEntryTitle:`查看归档会话`,archivePanelTitle:`归档区`,archiveSearchPlaceholder:`搜索归档会话...`,archiveEmpty:`暂无归档会话`,archiveNoMatch:`未找到匹配的归档会话`,archiveHint:`归档只是移出视野,随时可以恢复`,archiveBusyRunning:`该会话任务还在执行,完成后再归档`,archiveBusyQueued:`该会话还有排队任务,先清空队列再归档`,archived:`已归档到归档区`,archivedRestored:`已恢复会话「{title}」`,archivedAt:`归档于 {time}`,restore:`恢复`,restoreTitle:`恢复到会话列表`,deleteForever:`彻底删除`,confirmDeleteForeverTitle:`彻底删除会话`,confirmDeleteForeverMessage:`「{title}」将被彻底删除,消息与执行记录都无法恢复。确定继续吗?`,archiveDeleted:`已彻底删除会话「{title}」`,backToSessionList:`返回会话列表`,expandSidebar:`展开会话列表`,collapseSidebar:`收起会话列表`,searchSessions:`搜索会话`,sortModeTitle:`会话排序`,sortManual:`手动排序(拖拽调整,与标签栏一致)`,sortRecent:`最近更新优先(按时间倒序,带时间分组)`}}),n(`en`,{session:{newSession:`New Session`,closeSession:`Close Session`,taskCompleted:`Task completed`,noMatch:`No matching sessions found`,rename:`Rename`,duplicate:`Duplicate`,confirmCloseMessageWithTitle:`Are you sure you want to close session "{title}"?`,confirmCloseAllMessage:`Are you sure you want to close all {count} sessions?`,confirmCloseAllTitle:`Close All Sessions`,forkedFrom:`Forked from "{title}"`,forkedSession:`Duplicated session "{title}"`,operationFailed:`Operation failed: {message}`,sessionListTitle:`Sessions`,closeGroupAll:`Close all`,confirmCloseGroupMessage:`Are you sure you want to close {count} sessions in "{group}"?`,today:`Today`,yesterday:`Yesterday`,last7Days:`Last 7 days`,earlier:`Earlier`,todayFormat:`{hour}:{minute}`,yesterdayFormat:`Yesterday {hour}:{minute}`,daysAgo:`{count}d ago`,archive:`Archive session`,archiveEntry:`Archived`,archiveEntryTitle:`View archived sessions`,archivePanelTitle:`Archived sessions`,archiveSearchPlaceholder:`Search archived sessions...`,archiveEmpty:`No archived sessions`,archiveNoMatch:`No archived sessions found`,archiveHint:`Archiving only hides a session — you can restore it anytime`,archiveBusyRunning:`This session is still running. Archive it when it finishes`,archiveBusyQueued:`This session still has queued tasks. Clear the queue first`,archived:`Moved to archive`,archivedRestored:`Session "{title}" restored`,archivedAt:`Archived {time}`,restore:`Restore`,restoreTitle:`Restore to session list`,deleteForever:`Delete permanently`,confirmDeleteForeverTitle:`Delete session permanently`,confirmDeleteForeverMessage:`"{title}" will be permanently deleted. Messages and execution logs cannot be recovered. Continue?`,archiveDeleted:`Session "{title}" permanently deleted`,backToSessionList:`Back to sessions`,expandSidebar:`Expand session list`,collapseSidebar:`Collapse session list`,searchSessions:`Search sessions`,sortModeTitle:`Session order`,sortManual:`Manual order (drag to arrange, same as tabs)`,sortRecent:`Most recent first (time order with day groups)`}});var B={visible:!1,highlightIndex:-1,filteredSessions:[]},Mo={draggedId:null,sourceType:null};function No(e){if(!e)return``;let t=new Date(e),n=new Date,i=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),a=t.getTime();if(a>=i)return r(`session.todayFormat`,{hour:String(t.getHours()).padStart(2,`0`),minute:String(t.getMinutes()).padStart(2,`0`)});if(a>=i-864e5)return r(`session.yesterdayFormat`,{hour:String(t.getHours()).padStart(2,`0`),minute:String(t.getMinutes()).padStart(2,`0`)});let o=Math.floor((i-a)/864e5);return o<=7?r(`session.daysAgo`,{count:o}):t.getFullYear()===n.getFullYear()?`${t.getMonth()+1}/${t.getDate()}`:`${t.getFullYear()}/${t.getMonth()+1}/${t.getDate()}`}function Po(e){return e.sort((e,t)=>{let n=e.updatedAt?new Date(e.updatedAt).getTime():0;return(t.updatedAt?new Date(t.updatedAt).getTime():0)-n})}function Fo(e){if(!e)return`earlier`;let t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),i=t.getTime();return i>=r?`today`:i>=r-864e5?`yesterday`:Math.floor((r-i)/864e5)<=7?`last7Days`:`earlier`}async function Io(e=null){let t=e||await vi({withActiveHistory:!1});C.sessions=t.list,C.activeSessionId=t.activeSessionId;let n=document.getElementById(`sessionTabs`),i=document.getElementById(`sessionTabsScroll`),a=document.getElementById(`sessionTabsActions`);!n||!i||!a||(i.style.opacity=``,i.innerHTML=``,t.list.forEach(e=>{let t=document.createElement(`div`);t.className=`session-tab`,t.dataset.sessionId=e.id,e.id===C.activeSessionId&&t.classList.add(`active`),t.title=e.title;let n=document.createElement(`span`);n.className=`session-tab-title`,n.textContent=e.title||r(`session.newSession`),t.appendChild(n);let a=document.createElement(`span`);if(a.className=`session-tab-close`,a.innerHTML=`✕`,a.title=r(`session.closeSession`),a.addEventListener(`click`,async t=>{if(t.stopPropagation(),(e.id===C.activeSessionId?C.messageHistory?.length||0:e.messageCount??e.messageHistory?.length??0)===0){ds(await us(e.id)),await xc();return}vc(e,async()=>{await xc()})}),t.appendChild(a),e.isGenerating||C.generatingSessionIds.has(e.id)){let e=document.createElement(`span`);e.className=`session-tab-indicator`,t.appendChild(e)}else if(C.completedSessionIds.has(e.id)&&e.id!==C.activeSessionId){let e=document.createElement(`span`);e.className=`session-tab-completed-indicator`,e.title=r(`session.taskCompleted`),t.appendChild(e)}let o=kr(e.id);if(o>0){let e=document.createElement(`span`);e.className=`session-tab-queue-badge`,e.textContent=String(o>99?`99+`:o),e.title=r(`queue.badgeTitle`,{count:o}),t.appendChild(e)}t.addEventListener(`click`,async n=>{if(n.preventDefault(),e.id!==C.activeSessionId&&!cc){cc=!0,i.querySelectorAll(`.session-tab.active`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`);try{await fc(e.id)}finally{cc=!1,C.activeSessionId!==e.id&&Io({list:C.sessions,activeSessionId:C.activeSessionId})}}}),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),yc(t,e)}),t.addEventListener(`mousedown`,async t=>{t.button===1&&(t.preventDefault(),t.stopPropagation(),ds(await us(e.id)),await xc())}),t.draggable=!0,t.addEventListener(`dragstart`,t=>qo(t,e.id)),t.addEventListener(`dragover`,e=>Jo(e)),t.addEventListener(`dragleave`,e=>Yo(e)),t.addEventListener(`drop`,t=>Xo(t,e.id)),t.addEventListener(`dragend`,e=>Zo(e)),i.appendChild(t)}),Lo(),zo(),hs(),sc(),gc(i),Ho(i),Uo(i),Ko(i),Bs(),qs())}function Lo(){let e=document.getElementById(`sessionTabsMore`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,e=>{e.stopPropagation(),Fs()})}async function Ro(){let e=C.activeSessionId;await yi();let t=await Si();C.activeSessionId=t.id,C.messageHistory=[],C.activeCompaction=null,bi(t),document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:t.id,previousSessionId:e}})),Io()}function zo(){let e=document.getElementById(`sessionTabsAdd`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,()=>Ro())}var Bo=0,Vo=0;function Ho(e){let t=document.getElementById(`sessionTabsMore`);if(!t)return;if(!ks()){t.style.display=`none`;return}let n=e.scrollWidth>e.clientWidth;t.style.display=n||Bo>0?`flex`:`none`}async function Uo(e){let t=++Vo,n;try{n=await Oi()}catch{return}t===Vo&&(Bo=n.length,Ho(e))}var Wo=null;function Go(){if(Wo)return;let e=document.getElementById(`sessionTabsScroll`);e&&(Wo=new ResizeObserver(()=>{requestAnimationFrame(()=>{Ho(e)})}),Wo.observe(e))}function Ko(e){let t=e.querySelector(`.session-tab.active`);if(t){let n=t.offsetLeft,r=t.offsetWidth;e.scrollLeft=n-(e.clientWidth-r)/2}e.style.opacity=`1`}function qo(e,t){Mo.draggedId=t,Mo.sourceType=`tab`,e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),e.currentTarget.classList.add(`dragging`)}function Jo(e){e.preventDefault(),e.dataTransfer.dropEffect=`move`,e.currentTarget.classList.add(`drag-over`)}function Yo(e){e.currentTarget.classList.remove(`drag-over`)}async function Xo(e,t){e.preventDefault(),e.currentTarget.classList.remove(`drag-over`);let n=Mo.draggedId;if(!n||n===t)return;let r=C.sessions||[],i=r.findIndex(e=>e.id===n),a=r.findIndex(e=>e.id===t);if(i===-1||a===-1)return;let o=[...r],[s]=o.splice(i,1);o.splice(a,0,s),C.sessions=o,await Ei(o.map(e=>e.id)),Io()}function Zo(e){e.currentTarget.classList.remove(`dragging`),document.querySelectorAll(`.session-tab.drag-over`).forEach(e=>e.classList.remove(`drag-over`)),Mo.draggedId=null,Mo.sourceType=null}function Qo(){B.visible?es():$o()}async function $o(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);if(!e||!t)return;let n=await vi();C.sessions=n.list,C.activeSessionId=n.activeSessionId,B.filteredSessions=Po([...n.list]),B.highlightIndex=-1,B.visible=!0,$s(),ns(),t.classList.add(`show`);let r=document.getElementById(`sessionDropdownCloseBtn`);r&&(r.onclick=()=>es());let i=document.getElementById(`sessionDropdownSearch`),a=document.getElementById(`sessionDropdownSearchClear`);i&&(i.value=B.lastSearchText||``,ts(),B.lastSearchText&&cs(B.lastSearchText),setTimeout(()=>i.focus(),50),i.oninput=()=>{B.lastSearchText=i.value,ts(),cs(i.value)},i.onkeydown=e=>{gs(e)}),a&&(a.onclick=()=>{i&&(i.value=``,B.lastSearchText=``,ts(),cs(``),i.focus())}),e.classList.add(`active`)}function es(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);t&&t.classList.remove(`show`),e&&e.classList.remove(`active`);let n=document.getElementById(`sessionDropdownSearch`);n&&(B.lastSearchText=n.value,n.oninput=null,n.onkeydown=null);let r=document.getElementById(`sessionDropdownSearchClear`);r&&(r.onclick=null),B.visible=!1,B.highlightIndex=-1,B.filteredSessions=[]}function ts(){let e=document.getElementById(`sessionDropdownSearch`),t=document.getElementById(`sessionDropdownSearchClear`);t&&e&&(t.style.display=e.value?`flex`:`none`)}function ns(){rs({listEl:document.getElementById(`sessionDropdownList`),filteredSessions:B.filteredSessions,highlightIndex:B.highlightIndex,onSelect:e=>ls(e)})}function rs({listEl:e,filteredSessions:t,highlightIndex:n,onSelect:i,grouped:a=!0,draggable:o=!1}){if(!e)return;if(e.innerHTML=``,t.length===0){let t=document.createElement(`div`);t.className=`session-dropdown-empty`,t.textContent=r(`session.noMatch`),e.appendChild(t);return}let s={today:r(`session.today`),yesterday:r(`session.yesterday`),last7Days:r(`session.last7Days`),earlier:r(`session.earlier`)},c={};a&&t.forEach(e=>{let t=Fo(e.updatedAt);c[t]=(c[t]||0)+1});let l=null;t.forEach((t,u)=>{if(a){let n=Fo(t.updatedAt);if(n!==l){l=n;let t=document.createElement(`div`);t.className=`session-dropdown-group-header`;let i=document.createElement(`span`);if(i.textContent=s[n]||n,t.appendChild(i),(c[n]||0)>0){let e=document.createElement(`button`);e.className=`session-dropdown-group-close`,e.textContent=r(`session.closeGroupAll`),e.onclick=e=>{e.stopPropagation(),ms(n,s[n]||n)},t.appendChild(e)}e.appendChild(t)}}let d=ss(t,{index:u,highlightIndex:n,onSelect:i});o&&as(d,t.id),e.appendChild(d)})}var is=null;function as(e,t){e.draggable=!0,e.classList.add(`draggable`),e.addEventListener(`dragstart`,n=>{is=t,n.dataTransfer.effectAllowed=`move`,n.dataTransfer.setData(`text/plain`,t),e.classList.add(`dragging`)}),e.addEventListener(`dragover`,n=>{!is||is===t||(n.preventDefault(),n.dataTransfer.dropEffect=`move`,e.classList.add(`drag-over`))}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drag-over`)),e.addEventListener(`drop`,n=>{n.preventDefault(),n.stopPropagation(),e.classList.remove(`drag-over`),os(is,t)}),e.addEventListener(`dragend`,()=>{e.classList.remove(`dragging`),document.querySelectorAll(`.session-dropdown-item.drag-over`).forEach(e=>e.classList.remove(`drag-over`)),is=null})}async function os(e,t){let n=e;if(is=null,!n||n===t)return;let r=C.sessions||[],i=r.findIndex(e=>e.id===n),a=r.findIndex(e=>e.id===t);if(i===-1||a===-1)return;let o=[...r],[s]=o.splice(i,1);o.splice(a,0,s),C.sessions=o,await Ei(o.map(e=>e.id)),await Io()}function ss(e,{index:t,highlightIndex:n,onSelect:i}){let a=document.createElement(`div`);a.className=`session-dropdown-item`,a.dataset.sessionId=e.id,a.dataset.index=t,e.id===C.activeSessionId&&a.classList.add(`active`),t===n&&a.classList.add(`highlighted`);let o=e.isGenerating||C.generatingSessionIds.has(e.id);if(C.completedSessionIds.has(e.id)&&e.id!==C.activeSessionId&&!o){let e=document.createElement(`span`);e.className=`session-dropdown-item-completed`,e.title=r(`session.taskCompleted`),a.appendChild(e)}let s=kr(e.id);if(s>0){let e=document.createElement(`span`);e.className=`session-dropdown-item-queue`,e.textContent=String(s>99?`99+`:s),e.title=r(`queue.badgeTitle`,{count:s}),a.appendChild(e)}let c=document.createElement(`span`);if(c.className=`session-dropdown-item-icon`,o){let e=document.createElement(`span`);e.className=`session-dropdown-item-running`,c.appendChild(e)}else c.innerHTML=`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>`;a.appendChild(c);let l=document.createElement(`span`);if(l.className=`session-dropdown-item-title`,l.textContent=e.title||r(`session.newSession`),l.title=e.title||r(`session.newSession`),a.appendChild(l),e.id===C.activeSessionId){let e=document.createElement(`span`);e.className=`session-dropdown-item-check`,e.innerHTML=`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>`,a.appendChild(e)}let u=document.createElement(`span`);u.className=`session-dropdown-item-time`,u.textContent=No(e.updatedAt),a.appendChild(u);let d=document.createElement(`span`);d.className=`session-dropdown-item-actions`;let f=document.createElement(`span`);f.className=`session-dropdown-item-rename`,f.title=r(`session.rename`),f.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,f.addEventListener(`click`,t=>{t.stopPropagation(),t.preventDefault(),_c(e)}),d.appendChild(f);let p=document.createElement(`span`);p.className=`session-dropdown-item-duplicate`,p.title=r(`session.duplicate`),p.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="6" r="2.5"/><path d="M6 8.5v7"/><path d="M18 8.5c0 4-6 3.5-6 3.5"/></svg>`,p.addEventListener(`click`,async t=>{t.stopPropagation(),t.preventDefault(),await pc(e.id);let n=await vi({withActiveHistory:!1});C.sessions=n.list,C.activeSessionId=n.activeSessionId,cs(document.getElementById(`sessionDropdownSearch`)?.value||``)}),d.appendChild(p);let m=document.createElement(`span`);m.className=`session-dropdown-item-archive`,m.title=r(`session.archive`),m.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,m.addEventListener(`click`,async t=>{t.stopPropagation(),t.preventDefault(),await Zs(e.id),cs(document.getElementById(`sessionDropdownSearch`)?.value||``)}),d.appendChild(m);let h=document.createElement(`span`);return h.className=`session-dropdown-item-close`,h.innerHTML=`✕`,h.title=r(`session.closeSession`),h.addEventListener(`click`,async t=>{t.stopPropagation(),t.preventDefault(),await fs(e.id)}),d.appendChild(h),a.appendChild(d),a.addEventListener(`click`,async t=>{t.preventDefault(),await i(e.id)}),a}function cs(e){let t=C.sessions||[],n;if(!e.trim())n=[...t];else{let i=e.trim().toLowerCase();n=t.filter(e=>(e.title||r(`session.newSession`)).toLowerCase().includes(i))}B.filteredSessions=Po(n),B.highlightIndex=-1,ns()}async function ls(e){es(),e!==C.activeSessionId&&await fc(e)}async function us(e){let t=kr(e)+Dr(e).length;return await wi(e),t}function ds(e){e<=0||F(r(`queue.sessionDropped`,{count:e}),`info`,3e3)}async function fs(e){let t=(C.sessions||[]).find(t=>t.id===e);t&&((e===C.activeSessionId?C.messageHistory?.length||0:t.messageCount??t.messageHistory?.length??0)>0&&!await Js(r(`session.confirmCloseMessageWithTitle`,{title:t.title}),r(`session.closeSession`))||(ds(await us(e)),await xc(),cs(document.getElementById(`sessionDropdownSearch`)?.value||``)))}async function ps(){let e=C.sessions||[];if(e.length===0||!await Js(r(`session.confirmCloseAllMessage`,{count:e.length}),r(`session.confirmCloseAllTitle`)))return;let t=0;for(let n of e)t+=await us(n.id);ds(t),await xc(),cs(document.getElementById(`sessionDropdownSearch`)?.value||``)}async function ms(e,t){let n=(C.sessions||[]).filter(t=>Fo(t.updatedAt)===e);if(n.length===0||!await Js(r(`session.confirmCloseGroupMessage`,{group:t,count:n.length}),r(`session.closeSession`)))return;let i=0;for(let e of n)i+=await us(e.id);ds(i),await xc(),cs(document.getElementById(`sessionDropdownSearch`)?.value||``)}function hs(){let e=document.getElementById(`sessionDropdownCloseAll`),t=document.getElementById(`sessionDropdown`);if(t){if(e){let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,async e=>{e.stopPropagation(),await ps()})}t.addEventListener(`click`,e=>{e.stopPropagation()})}}function gs(e){if(!B.visible)return;let t=B.filteredSessions.length;if(t===0){e.key===`Escape`&&es();return}switch(e.key){case`ArrowDown`:e.preventDefault(),B.highlightIndex=Math.min(B.highlightIndex+1,t-1),ns(),_s(document.getElementById(`sessionDropdownList`));break;case`ArrowUp`:e.preventDefault(),B.highlightIndex=Math.max(B.highlightIndex-1,0),ns(),_s(document.getElementById(`sessionDropdownList`));break;case`Enter`:if(e.preventDefault(),B.highlightIndex>=0&&B.highlightIndex<t){let e=B.filteredSessions[B.highlightIndex];ls(e.id)}break;case`Escape`:e.preventDefault(),es();break}}function _s(e){let t=(e||document).querySelector(`.session-dropdown-item.highlighted`);t&&t.scrollIntoView({block:`nearest`})}var vs=560,ys=200,bs=480,xs=360,Ss=240,Cs=`sessionSidebarExpanded`,ws=`sessionSidebarWidth`,Ts=`sessionSidebarSortMode`,Es=`manual`,Ds=`recent`,V={expanded:!1,width:Ss,sortMode:Es,narrow:!1,pendingRestore:!1,highlightIndex:-1,filteredSessions:[],inited:!1,lastActiveId:null};function Os(e){let t=document.getElementById(`mainRow`),n=t?Math.max(ys,t.clientWidth-xs):bs;return Math.max(ys,Math.min(e,bs,n))}function ks(){let e=document.getElementById(`mainRow`);return e?e.clientWidth<vs:!0}function As(){let e=document.getElementById(`sessionSidebar`);if(!e)return;V.narrow=ks(),e.classList.toggle(`sidebar-hidden`,V.narrow),e.classList.toggle(`expanded`,!V.narrow&&V.expanded),e.style.setProperty(`--session-sidebar-width`,`${V.width}px`),js();let t=document.getElementById(`sessionSidebarToggle`);t&&t.classList.toggle(`sidebar-hidden`,V.narrow||V.expanded);let n=document.getElementById(`sessionTabs`);if(n){let e=!V.narrow&&V.expanded;if(n.classList.toggle(`tabs-hidden`,e),!e){let e=document.getElementById(`sessionTabsScroll`);e&&Ko(e)}}}function js(){let e=!V.narrow&&V.expanded?V.width:0;document.body.style.setProperty(`--session-sidebar-offset`,`${e}px`)}async function Ms(){try{await chrome.storage.local.set({[Cs]:V.expanded,[ws]:V.width,[Ts]:V.sortMode})}catch{}}function Ns(){ks()||(V.expanded=!0,As(),Ms(),Bs())}function Ps(){V.expanded=!1,As(),Ms()}function Fs(){if(ks()){Qo();return}V.expanded?Ps():Ns()}function Is(){let e=document.getElementById(`sessionSidebarList`),t=V.sortMode===Ds,n=!!(document.getElementById(`sessionSidebarSearch`)?.value||``).trim();rs({listEl:e,filteredSessions:V.filteredSessions,highlightIndex:V.highlightIndex,onSelect:e=>Vs(e),grouped:t,draggable:!t&&!n});let r=C.activeSessionId;r&&V.lastActiveId!==r&&(V.lastActiveId=r,e?.querySelector(`.session-dropdown-item.active`)?.scrollIntoView({block:`nearest`}))}function Ls(e){let t=C.sessions||[],n;if(!e.trim())n=[...t];else{let i=e.trim().toLowerCase();n=t.filter(e=>(e.title||r(`session.newSession`)).toLowerCase().includes(i))}V.filteredSessions=V.sortMode===Ds?Po(n):n.reverse(),V.highlightIndex=-1,Is()}function Rs(){document.querySelectorAll(`.session-sidebar-sort-btn`).forEach(e=>{let t=e.dataset.mode===V.sortMode;e.classList.toggle(`active`,t),e.setAttribute(`aria-pressed`,t?`true`:`false`)})}function zs(e){e!==Es&&e!==Ds||V.sortMode!==e&&(V.sortMode=e,Rs(),V.lastActiveId=null,Ls(document.getElementById(`sessionSidebarSearch`)?.value||``),Ms())}function Bs(){let e=document.getElementById(`sessionSidebar`);!e||!e.classList.contains(`expanded`)||Ls(document.getElementById(`sessionSidebarSearch`)?.value||``)}async function Vs(e){e!==C.activeSessionId&&await fc(e)}function Hs(e){let t=V.filteredSessions,n=t.length;if(n===0){e.key===`Escape`&&Ps();return}switch(e.key){case`ArrowDown`:e.preventDefault(),V.highlightIndex=Math.min(V.highlightIndex+1,n-1),Is(),_s(document.getElementById(`sessionSidebarList`));break;case`ArrowUp`:e.preventDefault(),V.highlightIndex=Math.max(V.highlightIndex-1,0),Is(),_s(document.getElementById(`sessionSidebarList`));break;case`Enter`:e.preventDefault(),V.highlightIndex>=0&&V.highlightIndex<n&&Vs(t[V.highlightIndex].id);break;case`Escape`:e.preventDefault(),Ps();break}}function Us(){let e=document.getElementById(`sessionSidebarSearch`),t=document.getElementById(`sessionSidebarSearchClear`);t&&e&&(t.style.display=e.value?`flex`:`none`)}function Ws(){let e=document.getElementById(`sessionSidebar`),t=document.getElementById(`sessionSidebarGrip`);!e||!t||t.addEventListener(`mousedown`,t=>{t.preventDefault();let n=t.clientX,r=V.width;e.classList.add(`resizing`);function i(t){let i=Os(r+(t.clientX-n));V.width=i,e.style.setProperty(`--session-sidebar-width`,`${i}px`),js()}function a(){document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),e.classList.remove(`resizing`),Ms()}document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)})}function Gs(){let e=document.getElementById(`mainRow`);!e||typeof ResizeObserver>`u`||new ResizeObserver(()=>{requestAnimationFrame(()=>{let e=ks();e!==V.narrow&&(e&&V.expanded?V.pendingRestore=!0:!e&&V.pendingRestore&&(V.pendingRestore=!1),As(),!e&&V.expanded&&Bs())})}).observe(e)}function Ks(){ks()?$o():Ns()}async function qs(){if(V.inited||!document.getElementById(`sessionSidebar`))return;V.inited=!0;try{let e=await chrome.storage.local.get([Cs,ws,Ts]);V.expanded=e[Cs]===!0,typeof e[ws]==`number`&&(V.width=Os(e[ws])),(e[Ts]===Ds||e[Ts]===Es)&&(V.sortMode=e[Ts])}catch{}Rs(),ks()&&V.expanded&&(V.pendingRestore=!0),As(),Bs(),document.getElementById(`sessionSidebarToggle`)?.addEventListener(`click`,()=>Fs()),document.getElementById(`sessionSidebarAdd`)?.addEventListener(`click`,()=>{Ro()}),document.getElementById(`sessionSidebarCollapse`)?.addEventListener(`click`,()=>Ps()),document.querySelectorAll(`.session-sidebar-sort-btn`).forEach(e=>{e.addEventListener(`click`,()=>zs(e.dataset.mode))}),document.getElementById(`sessionSidebarArchiveEntry`)?.addEventListener(`click`,()=>{ec()}),document.getElementById(`sessionSidebarCloseAll`)?.addEventListener(`click`,async e=>{e.stopPropagation(),await ps()});let e=document.getElementById(`sessionSidebarSearch`),t=document.getElementById(`sessionSidebarSearchClear`);e&&(e.addEventListener(`input`,()=>{Us(),Ls(e.value)}),e.addEventListener(`keydown`,e=>{Hs(e)})),t&&t.addEventListener(`click`,()=>{e&&(e.value=``,Us(),Ls(``),e.focus())}),Ws(),Gs(),$s()}function Js(e,t){return new Promise(t=>{let n=document.getElementById(`sessionDeleteModal`),r=document.getElementById(`sessionDeleteMessage`),i=document.getElementById(`sessionDeleteConfirmBtn`),a=document.getElementById(`sessionDeleteCancelBtn`),o=document.getElementById(`sessionDeleteCloseBtn`);if(!n||!r){t(!1);return}r.textContent=e;let s=()=>{n.classList.remove(`show`),i.removeEventListener(`click`,c),a.removeEventListener(`click`,l),o.removeEventListener(`click`,l)},c=()=>{s(),t(!0)},l=()=>{s(),t(!1)};i.addEventListener(`click`,c),a.addEventListener(`click`,l),o.addEventListener(`click`,l),n.classList.add(`show`)})}var Ys=``,Xs=!1;async function Zs(e){if(!e)return;let t=ki(e);if(!t.ok){t.reason===`running`?F(r(`session.archiveBusyRunning`),`warning`):t.reason===`queued`&&F(r(`session.archiveBusyQueued`),`warning`);return}let n=e===C.activeSessionId,i=await Ai(e);if(!i?.ok){i?.reason===`running`?F(r(`session.archiveBusyRunning`),`warning`):i?.reason===`queued`?F(r(`session.archiveBusyQueued`),`warning`):F(r(`session.operationFailed`,{message:i?.reason||`unknown`}),`error`);return}if(document.dispatchEvent(new CustomEvent(`session-archived`,{detail:{sessionId:e}})),n)await Qs(e);else{let e=await vi();C.sessions=e.list,Io(e)}await $s(),F(r(`session.archived`),`info`)}async function Qs(e){let t=Po([...(await vi()).list]).filter(t=>t.id!==e);if(t.length>0){await fc(t[0].id);return}await Si(),await xc()}async function $s(){let e=[`sessionArchiveEntryLabel`,`sessionSidebarArchiveLabel`].map(e=>document.getElementById(e));if(!e.some(Boolean))return;Bo=(await Oi()).length;let t=document.getElementById(`sessionTabsScroll`);t&&Ho(t);let n=r(`session.archiveEntry`);e.forEach(e=>{e&&(e.textContent=n)})}async function ec(){let e=document.getElementById(`sessionArchivePanel`);if(!e)return;sc(),Ys=``;let t=document.getElementById(`sessionArchiveSearch`);t&&(t.value=``),nc(),await rc(),e.classList.add(`show`),es()}function tc(){let e=document.getElementById(`sessionArchivePanel`);e&&e.classList.remove(`show`)}function nc(){let e=document.getElementById(`sessionArchiveSearchClear`);e&&(e.style.display=Ys?`flex`:`none`)}async function rc(){let e=document.getElementById(`sessionArchiveList`);if(!e)return;let t=await Oi(),n=Ys.trim().toLowerCase(),i=n?t.filter(e=>(e.title||``).toLowerCase().includes(n)):t;if(e.innerHTML=``,i.length===0){let t=document.createElement(`div`);t.className=`session-dropdown-empty`,t.textContent=r(n?`session.archiveNoMatch`:`session.archiveEmpty`),e.appendChild(t);return}let a={today:r(`session.today`),yesterday:r(`session.yesterday`),last7Days:r(`session.last7Days`),earlier:r(`session.earlier`)},o=null;i.forEach(t=>{let n=Fo(t.archivedAt);if(n!==o){o=n;let t=document.createElement(`div`);t.className=`session-dropdown-group-header`;let r=document.createElement(`span`);r.textContent=a[n]||n,t.appendChild(r),e.appendChild(t)}e.appendChild(ic(t))})}function ic(e){let t=document.createElement(`div`);t.className=`session-dropdown-item session-archive-item`,t.dataset.sessionId=e.id,t.title=e.title||r(`session.newSession`);let n=document.createElement(`span`);n.className=`session-dropdown-item-icon`,n.innerHTML=`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,t.appendChild(n);let i=document.createElement(`span`);i.className=`session-dropdown-item-title`,i.textContent=e.title||r(`session.newSession`),t.appendChild(i);let a=document.createElement(`span`);a.className=`session-dropdown-item-time`,a.textContent=r(`session.archivedAt`,{time:No(e.archivedAt)}),t.appendChild(a);let o=document.createElement(`span`);o.className=`session-dropdown-item-actions`;let s=document.createElement(`span`);s.className=`session-dropdown-item-restore`,s.title=r(`session.restoreTitle`),s.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 14 4 9 9 4"/><path d="M20 20v-7a4 4 0 0 0-4-4H4"/></svg>`,s.addEventListener(`click`,async t=>{t.stopPropagation(),await ac(e.id)}),o.appendChild(s);let c=document.createElement(`span`);return c.className=`session-dropdown-item-delete`,c.title=r(`session.deleteForever`),c.innerHTML=`✕`,c.addEventListener(`click`,async t=>{t.stopPropagation(),await oc(e)}),o.appendChild(c),t.appendChild(o),t.addEventListener(`click`,async()=>{await ac(e.id,{enter:!0})}),t}async function ac(e,{enter:t=!1}={}){if(!await ji(e)){F(r(`session.operationFailed`,{message:`not found`}),`error`),await rc();return}let n=await vi();C.sessions=n.list;let i=n.list.find(t=>t.id===e)?.title||r(`session.newSession`);tc(),await rc(),await $s(),t?await fc(e):Io(n),F(r(`session.archivedRestored`,{title:i}),`success`)}async function oc(e){let t=e.title||r(`session.newSession`);await Js(r(`session.confirmDeleteForeverMessage`,{title:t}),r(`session.confirmDeleteForeverTitle`))&&(await Mi(e.id),await rc(),await $s(),document.dispatchEvent(new CustomEvent(`session-deleted`,{detail:{sessionId:e.id}})),F(r(`session.archiveDeleted`,{title:t}),`success`))}function sc(){if(Xs)return;let e=document.getElementById(`sessionArchivePanel`),t=document.getElementById(`sessionArchiveEntry`);if(!e||!t)return;Xs=!0,t.addEventListener(`click`,()=>{ec()});let n=document.getElementById(`sessionArchiveBackBtn`);n&&n.addEventListener(`click`,()=>{tc(),Ks()});let r=document.getElementById(`sessionArchiveCloseBtn`);r&&r.addEventListener(`click`,()=>tc());let i=document.getElementById(`sessionArchiveSearch`),a=document.getElementById(`sessionArchiveSearchClear`);i&&(i.addEventListener(`input`,()=>{Ys=i.value,nc(),rc()}),i.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.stopPropagation(),tc(),Ks())})),a&&a.addEventListener(`click`,()=>{i&&(i.value=``,Ys=``,nc(),rc(),i.focus())}),document.addEventListener(`session-archived`,()=>{e.classList.contains(`show`)&&rc()}),document.addEventListener(`session-deleted`,()=>{e.classList.contains(`show`)&&rc()})}var cc=!1,lc=500;function uc(e){let t=`scrollPosition_${e||`default`}`;chrome.storage.local.get([t],e=>{let n=document.getElementById(`chatContainer`);n&&e[t]!==void 0&&(n.scrollTop=e[t]),A(async()=>{let{updateScrollButtonState:e}=await Promise.resolve().then(()=>WS);return{updateScrollButtonState:e}},void 0).then(({updateScrollButtonState:e})=>e()).catch(()=>{})})}function dc(e,t){setTimeout(()=>{C.activeSessionId===e&&(Ue(t)||uc(e))},lc)}async function fc(e,{focusMessageId:t=null}={}){let n=C.activeSessionId;if(!await Ci(e))return;let r=`agentEnabledTools_${C.activeAgentId||`default`}`,i=`agentMcpClosedServers_${C.activeAgentId||`default`}`,[a,o,s,c]=await Promise.all([vi(),chrome.storage.local.get([i,`ragTools`,`ragToolsIntroduced`]),chrome.storage.local.get([r,`enabledTools`]),C.activeAgentId?pt(C.activeAgentId):Promise.resolve(null)]);C.sessions=a.list,C.activeSessionId=e;let l=o.ragTools||[];C.mcpClosedServers=o[i]||[];let u=!!s[r],d=s[r]||s.enabledTools;if(u||d&&d.length>0){let e=va(l),t=d.filter(t=>e.has(t));if(u)C.enabledTools=t;else{let e=f.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);C.enabledTools=[...t,...e]}let n=_a(C.enabledTools,l,o.ragToolsIntroduced);C.enabledTools=n.tools,C.enabledTools.length!==d.length&&chrome.storage.local.set({[r]:C.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{C.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let e=_a(C.enabledTools,l,o.ragToolsIntroduced);C.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[r]:C.enabledTools})}C.activeAgentToolIds=c?c.toolIds:null,C.activeAgentMcpExcludedServerIds=c?c.mcpExcludedServerIds??null:null,document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,...t?{skipScrollRestore:!0}:{}}})),_i(e),Io(a),mc(),ND();try{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await A(async()=>{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await Promise.resolve().then(()=>oh);return{refreshBookmarkPanel:e,updateBookmarkButtons:t}},void 0);e(),setTimeout(()=>t(),100)}catch{}let p=document.getElementById(`toolsPopupOverlay`);p&&p.classList.contains(`show`)&&(ra(),da(),fa()),ha(),t&&dc(e,t)}async function pc(e,t=null){if(e)try{let n=await Fi(e,t);await fc(n.id),F(r(t?`session.forkedFrom`:`session.forkedSession`,{title:n.title}),`success`)}catch(e){i.error(`[SessionUI] copy/forksession failed:`,e),F(r(`session.operationFailed`,{message:e.message}),`error`)}}function mc(){let e=document.querySelector(`.model-display`);e&&C.currentModel&&(e.textContent=C.currentModel);let t=document.getElementById(`enableToolsBtn`);t&&(t.checked=C.useTools);let n=document.getElementById(`tempIconValue`);n&&C.temperature!==void 0&&(n.textContent=C.temperature.toFixed(2))}var hc=new WeakSet;function gc(e){hc.has(e)||(hc.add(e),e.addEventListener(`wheel`,t=>{e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY)},{passive:!1}))}function _c(e){let t=document.getElementById(`sessionRenameModal`),n=document.getElementById(`sessionRenameInput`),r=document.getElementById(`sessionRenameConfirmBtn`),i=document.getElementById(`sessionRenameCancelBtn`),a=document.getElementById(`sessionRenameCloseBtn`);if(!t||!n)return;n.value=e.title;let o=()=>{t.classList.remove(`show`),r.removeEventListener(`click`,s),i.removeEventListener(`click`,c),a.removeEventListener(`click`,c)},s=async()=>{let t=n.value.trim();if(t&&t!==e.title){await Ti(e.id,t),Io();let n=await vi();C.sessions=n.list,C.activeSessionId=n.activeSessionId,cs(document.getElementById(`sessionDropdownSearch`)?.value||``)}o()},c=()=>{o()};r.addEventListener(`click`,s),i.addEventListener(`click`,c),a.addEventListener(`click`,c),n.onkeydown=e=>{e.key===`Enter`?s():e.key===`Escape`&&c()},t.classList.add(`show`),setTimeout(()=>{n.focus(),n.select()},50)}function vc(e,t){let n=document.getElementById(`sessionDeleteModal`),i=document.getElementById(`sessionDeleteMessage`),a=document.getElementById(`sessionDeleteConfirmBtn`),o=document.getElementById(`sessionDeleteCancelBtn`),s=document.getElementById(`sessionDeleteCloseBtn`);if(!n||!i)return;i.textContent=r(`session.confirmCloseMessageWithTitle`,{title:e.title});let c=()=>{n.classList.remove(`show`),a.removeEventListener(`click`,l),o.removeEventListener(`click`,u),s.removeEventListener(`click`,u)},l=async()=>{ds(await us(e.id)),t&&await t(),c()},u=()=>{c()};a.addEventListener(`click`,l),o.addEventListener(`click`,u),s.addEventListener(`click`,u),n.classList.add(`show`),requestAnimationFrame(()=>a.focus())}function yc(e,t){let n=document.querySelector(`.session-context-menu`);n&&n.remove();let i=document.createElement(`div`);i.className=`session-context-menu`,i.style.left=e.clientX+`px`,i.style.top=e.clientY+`px`;let a=bc(r(`session.rename`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,()=>{i.remove(),_c(t)});i.appendChild(a);let o=bc(r(`session.duplicate`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="6" r="2.5"/><path d="M6 8.5v7"/><path d="M18 8.5c0 4-6 3.5-6 3.5"/></svg>`,()=>{i.remove(),pc(t.id)});i.appendChild(o);let s=bc(r(`session.archive`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,async()=>{i.remove(),await Zs(t.id)});i.appendChild(s);let c=bc(r(`session.closeSession`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,async()=>{if(i.remove(),(t.id===C.activeSessionId?C.messageHistory?.length||0:t.messageCount??t.messageHistory?.length??0)===0){ds(await us(t.id)),await xc();return}vc(t,async()=>{await xc()})},`danger`);i.appendChild(c),document.body.appendChild(i);let l=e=>{i.contains(e.target)||(i.remove(),document.removeEventListener(`click`,l))};setTimeout(()=>document.addEventListener(`click`,l),0)}function bc(e,t=``,n,r=``){let i=document.createElement(`div`);return i.className=`session-context-menu-item `+r,t?i.innerHTML=`${t}<span>${e}</span>`:i.textContent=e,i.addEventListener(`click`,n),i}async function xc(){let e=C.activeSessionId,t=await vi();t.activeSessionId||(await Si(),t=await vi()),C.activeSessionId=t.activeSessionId,C.sessions=t.list;let n=t.list.find(e=>e.id===t.activeSessionId);if(C.messageHistory=n&&n.messageHistory||[],C.activeCompaction=n?.contextCompaction||null,bi(n),C.activeAgentId=n&&n.agentId||null,C.activeAgentId){let e=await pt(C.activeAgentId);C.activeAgentToolIds=e?e.toolIds:null,C.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null}else C.activeAgentToolIds=null,C.activeAgentMcpExcludedServerIds=null;document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:C.activeSessionId,previousSessionId:e}})),Io(),await ND()}async function Sc(){let e=C.activeSessionId;if(!e)return;let t=C.sessions?.find(t=>t.id===e);if(t){if((C.messageHistory?.length||0)===0){ds(await us(e)),await xc();return}vc(t,async()=>{await xc()})}}document.addEventListener(`generating-state-changed`,()=>{Io()}),document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{Go(),qs()}):(Go(),qs()),[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`].join(``),[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M12.146.146a.5.5 0 0 1 .708 0l2.5 2.5a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207 11.207 2.5zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293l6.5-6.5zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12h.5a.5.5 0 0 1 .5.5v.5a.5.5 0 0 1-.5.5h-.5a.5.5 0 0 1-.468-.325z"/>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<circle cx="12" cy="12" r="10"></circle>`,`<polyline points="12 6 12 12 16 14"></polyline>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<line x1="18" y1="6" x2="6" y2="18"></line>`,`<line x1="6" y1="6" x2="18" y2="18"></line>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<polyline points="7 13 12 18 17 13"></polyline>`,`<polyline points="7 6 12 11 17 6"></polyline>`,`</svg>`].join(``);var Cc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>`,wc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`,Tc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>`,Ec=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,Dc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,Oc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>`;[`<svg class="tool-call-icon exec" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>`,`<polyline points="14 2 14 8 20 8"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>`,`</svg>`].join(``),n(`zh`,{uiProto:{defaultTitle:`原型`,optimizePrompt:`请帮我优化这个UI原型界面 {id}({title}),`,loadFailed:`加载失败`,noDescription:`暂无描述`,previewInPanel:`面板内预览`,continueOptimizeTitle:`继续优化`,downloadPrototype:`下载原型`,confirmDeleteTitle:`确认删除`,confirmDeleteMessage:`确定删除原型 "{title}" 吗?此操作不可撤销。`,deleteFailed:`删除失败: {message}`,justNow:`刚刚`,minutesAgo:`{count} 分钟前`,hoursAgo:`{count} 小时前`}}),n(`en`,{uiProto:{defaultTitle:`Prototype`,optimizePrompt:`Please help me optimize this UI prototype {id} ({title}), `,loadFailed:`Load failed`,noDescription:`No description`,previewInPanel:`Preview in panel`,continueOptimizeTitle:`Continue optimizing`,downloadPrototype:`Download prototype`,confirmDeleteTitle:`Confirm delete`,confirmDeleteMessage:`Are you sure you want to delete prototype "{title}"? This action cannot be undone.`,deleteFailed:`Delete failed: {message}`,justNow:`Just now`,minutesAgo:`{count} minutes ago`,hoursAgo:`{count} hours ago`}});var kc=null,Ac=1,jc=.25,Mc=2,Nc=.1;function Pc(e){let t=e.trim();return/^\s*<!DOCTYPE\s/i.test(t)||/^\s*<html[\s>]/i.test(t)?/<\/head>/i.test(t)?t.replace(/<\/head>/i,`<style>html,body{overflow:auto!important;height:auto!important;}</style></head>`):/<body[\s>]/i.test(t)?t.replace(/<body([\s>])/i,`<body$1<style>html,body{overflow:auto!important;height:auto!important;}</style>`):t:`<!DOCTYPE html>
|
|
62
|
+
`,e.addEventListener(`click`,()=>co(-1)),g.appendChild(e);let t=document.getElementById(`clarifyCustomInput`);t&&g.appendChild(t)}let _=document.getElementById(`clarifyCustomInput`);_&&_.classList.remove(`show`);let v=document.getElementById(`clarifyAdditionalInfo`);v&&v.classList.toggle(`show`,o);let y=document.getElementById(`clarifyCustomTextarea`);y&&(y.value=``);let b=document.getElementById(`clarifyAdditionalTextarea`);b&&(b.value=``),l.classList.add(`show`);let x=document.querySelector(`#clarifyContainer .clarify-content`),S=document.querySelector(`#clarifyContainer .clarify-header`);return x&&(x.scrollTop=0),S&&S.classList.remove(`scrolled`),Va=null,Ha=!1,Ja(),Ka(s),i.debug(`[SidePanel] clarification dialogshown:`,e.toolCallId,t),!0}function eo(){if(z)return!0;if(Ba.length===0)return!1;let e=Ba.shift();return $a(e)?(z=e,Ra(za,e),!0):(i.error(`[SidePanel] clarify overlay missing, settle as unanswered:`,e.toolCallId),to(e),F(r(`clarify.dropped`),`warning`),!1)}function to(e){Promise.resolve(chrome.runtime.sendMessage({type:`CLARIFY_RESPONSE`,toolCallId:e.toolCallId,selectedOption:-1,customInput:``,additionalInfo:``})).catch(e=>{i.debug(`[SidePanel] send unanswered clarify response failed:`,e?.message)})}function no(){if(Ba.length>0){Ma(za);return}ro(),Na(za)}function ro(){let e=document.getElementById(`clarifyOverlay`);e&&e.classList.remove(`show`),C.currentClarifyToolCallId=null,C.currentClarifySessionId=null,qa()}function io(){z=null,no()}function ao(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&e.question===t.question}function oo(e){let t={...e,sessionId:e.sessionId||null};if(i.debug(`[SidePanel] showclarification dialog:`,t.toolCallId,e),z&&ao(z,t)){i.debug(`[SidePanel] duplicate clarify request, ignored:`,t.toolCallId);return}if(Ba.some(e=>ao(e,t))){i.debug(`[SidePanel] queued duplicate clarify, ignored:`,t.toolCallId);return}Ba.push(t),Ma(za),Qa(),Ia(za)}function so(){if(z){io();return}ro()}function co(e){document.querySelectorAll(`.clarify-option-item`).forEach(e=>{e.classList.remove(`selected`),e.setAttribute(`aria-checked`,`false`),e.setAttribute(`tabindex`,`-1`)});let t=document.querySelector(`.clarify-option-item[data-index="${e}"]`);t&&(t.classList.add(`selected`),t.setAttribute(`aria-checked`,`true`),t.setAttribute(`tabindex`,`0`));let n=document.getElementById(`clarifyCustomInput`);if(n)if(e===-1){n.classList.add(`show`);let e=document.getElementById(`clarifyCustomTextarea`);e&&e.focus()}else n.classList.remove(`show`);i.debug(`[SidePanel] selectclarificationselect :`,e)}function lo(){if(!z){i.error(`[SidePanel] no has currenttool callID`);return}let e=z.toolCallId,t=z.sessionId,n=-1;document.querySelectorAll(`.clarify-option-item`).forEach((e,t)=>{e.classList.contains(`selected`)&&(n=parseInt(e.dataset.index))});let r=document.getElementById(`clarifyCustomTextarea`),a=r?r.value.trim():``,o=document.getElementById(`clarifyAdditionalTextarea`),s=o?o.value.trim():``,c={type:`CLARIFY_RESPONSE`,toolCallId:e,sessionId:t,selectedOption:n,customInput:a,additionalInfo:s};i.debug(`[SidePanel] send clarificationresponse:`,c),chrome.runtime.sendMessage(c),io()}function uo(){if(z){let e={type:`CLARIFY_RESPONSE`,toolCallId:z.toolCallId,sessionId:z.sessionId,selectedOption:-1,customInput:``,additionalInfo:``};chrome.runtime.sendMessage(e)}so()}function fo(e){return e?.reason===`timeout`&&e?.defaultOption||null}function po(e){i.debug(`[SidePanel] received clarificationtimeoutnotification:`,e);let t=e?.toolCallId;if(!t){if(e?.sessionId&&C.currentClarifySessionId&&e.sessionId!==C.currentClarifySessionId){i.debug(`[SidePanel] clarificationtimeoutfrom othersession,ignore`);return}if(!z)return;mo(fo(e));return}if(z&&z.toolCallId===t){mo(fo(e));return}let n=Ba.findIndex(e=>e.toolCallId===t);n>=0&&(i.debug(`[SidePanel] drop queued clarify (already settled by background):`,t),Ba.splice(n,1),Qa(),Ia(za))}function mo(e=null){let t=z?.question;io(),F(e?r(`clarify.timedOutDefaulted`,{option:e}):`${r(`clarify.timedOut`)}${t?`:${t}`:``}`,`warning`),Wa(`error`)}ja(za,{present:eo,pendingCount:()=>Ba.length,refresh:Qa});function ho(){let e=document.getElementById(`clarifyConfirmBtn`);e&&e.addEventListener(`click`,lo);let t=document.getElementById(`clarifyCancelBtn`);t&&t.addEventListener(`click`,uo);let n=document.getElementById(`clarifyExtendBtn`);n&&n.addEventListener(`click`,Ya);let r=document.querySelector(`#clarifyContainer .clarify-content`),a=document.querySelector(`#clarifyContainer .clarify-header`);r&&a&&r.addEventListener(`scroll`,()=>{a.classList.toggle(`scrolled`,r.scrollTop>2)}),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_CLARIFY_DIALOG`?(i.debug(`[SidePanel] received clarificationrequested :`,e,`currently activesession:`,C.activeSessionId),oo(e.data),n({success:!0})):e.type===`PLAY_NOTIFICATION_SOUND`?(i.debug(`[SidePanel] recei to play soundrequested :`,e),Wa(e.soundType),n({success:!0})):e.type===`CLARIFY_TIMEOUT`?po(e):e.type===`CLARIFY_EXTENDED`&&Xa(e)}),i.debug(`[SidePanel] clarification dialogeventinitializing`)}var go=Da.CONFIRM,_o=[],vo=null,yo=null,bo=null;function xo(e){let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`}function So(){yo&&=(clearInterval(yo),null),bo&&=(clearTimeout(bo),null)}function Co(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&JSON.stringify(e.args??null)===JSON.stringify(t.args??null)}function wo(e){let t=e.message||r(`dialog.confirmAction`,{name:e.toolLabel||e.toolName}),n=_o.length,i=La(go),a=t;return n>0&&(a+=` ${r(`dialog.pendingQueue`,{count:n})}`),i>0&&(a+=` ${r(`dialog.otherPending`,{count:i})}`),a}function To(e){let{toolName:t,toolLabel:n,args:a,timeout:o=3e5}=e;C.currentConfirmToolCallId=e.toolCallId,C.currentConfirmSessionId=e.sessionId||null;let s=document.getElementById(`confirmOverlay`);if(!s)return!1;document.getElementById(`confirmToolName`).textContent=n||t;let c=e.variant===`network`,l=document.getElementById(`confirmTitle`);l&&(l.textContent=r(c?`dialog.networkTitle`:`dialog.operationConfirm`));let u=document.getElementById(`confirmApproveLoopBtn`);u&&(u.textContent=r(c?`dialog.approveWhitelist`:`dialog.approveLoop`));let d=document.getElementById(`confirmArgsSummary`);if(d&&a){let e=Object.entries(a).filter(([e,t])=>t!=null&&t!==``).slice(0,5);e.length>0?(d.textContent=``,e.forEach(([e,t],n)=>{n>0&&d.appendChild(document.createTextNode(`、 `));let r=typeof t==`string`?t:JSON.stringify(t),i=r.length>80?r.substring(0,80)+`...`:r,a=document.createElement(`span`);a.className=`confirm-arg`,a.style.marginRight=`8px`,r.length>80&&(a.title=r);let o=document.createElement(`strong`);o.textContent=`${e}:`,a.appendChild(o),a.appendChild(document.createTextNode(` ${i}`)),d.appendChild(a)}),d.style.display=`block`):d.style.display=`none`}let f=document.getElementById(`confirmMessage`);f&&(f.textContent=wo(e)),So();let p=Math.floor(o/1e3),m=document.getElementById(`confirmCountdownText`),h=document.getElementById(`confirmCountdown`);return m&&h&&(h.classList.remove(`warning`),h.style.display=`flex`,m.textContent=r(`dialog.remainingTime`,{time:xo(p)}),yo=setInterval(()=>{if(p--,p<=0){clearInterval(yo),yo=null,m.textContent=r(`dialog.remainingTime`,{time:`0:00`});return}m.textContent=r(`dialog.remainingTime`,{time:xo(p)}),p<=30&&h.classList.add(`warning`)},1e3)),s.style.display=`flex`,bo=setTimeout(()=>{i.debug(`[SidePanel] confirm dialogtimeout,autodeny`),jo(!1,`single`)},o),!0}function Eo(){if(vo)return!0;if(_o.length===0)return!1;let e=_o.shift();return To(e)?(vo=e,Ra(go,e),!0):(e.resolve&&e.resolve(!1),!1)}function Do(){let e=document.getElementById(`confirmOverlay`);e&&(e.style.display=`none`);let t=document.getElementById(`confirmCountdown`);t&&(t.classList.remove(`warning`),t.style.display=`none`),C.currentConfirmToolCallId=null,C.currentConfirmSessionId=null}function Oo(){if(_o.length>0){Ma(go);return}Do(),Na(go)}function ko(e){let t=vo?.resolve;vo=null,So(),t&&t(e),Oo()}function Ao(e){let t={...e,sessionId:e.sessionId||null};return i.debug(`[SidePanel] showconfirm dialog:`,t.toolName,e),vo&&Co(vo,t)?(i.debug(`[SidePanel] duplicate confirm request, ignored:`,t.toolCallId),Promise.resolve(!1)):_o.some(e=>Co(e,t))?(i.debug(`[SidePanel] queued duplicate confirm, ignored:`,t.toolCallId),Promise.resolve(!1)):new Promise(e=>{_o.push({...t,resolve:e}),Ma(go),vo&&Mo(),Ia(go)})}function jo(e,t=`single`){if(!vo)return;let n=vo.toolCallId,r=vo.sessionId;So(),chrome.runtime.sendMessage({type:`TOOL_CONFIRMATION_RESPONSE`,toolCallId:n,confirmed:e,scope:t,sessionId:r}).catch(e=>{i.debug(`[SidePanel] send confirmationresponse failed:`,e.message)}),ko(e)}function Mo(){if(!vo)return;let e=document.getElementById(`confirmMessage`);e&&(e.textContent=wo(vo))}function No(e){let t=e?.toolCallId;if(!t)return;if(vo&&vo.toolCallId===t){i.debug(`[SidePanel] dismiss active confirm dialog (already settled by background):`,t),ko(!1);return}let n=_o.findIndex(e=>e.toolCallId===t);if(n>=0){i.debug(`[SidePanel] drop queued confirm dialog (already settled by background):`,t);let[e]=_o.splice(n,1);e.resolve&&e.resolve(!1),Mo(),Ia(go)}}ja(go,{present:Eo,pendingCount:()=>_o.length,refresh:()=>{vo&&Mo()}});function Po(){let e=document.getElementById(`confirmApproveOnceBtn`),t=document.getElementById(`confirmApproveLoopBtn`),n=document.getElementById(`confirmDenyBtn`);e&&e.addEventListener(`click`,()=>jo(!0,`single`)),t&&t.addEventListener(`click`,()=>{jo(!0,vo?.variant===`network`?`whitelist`:`loop`)}),n&&n.addEventListener(`click`,()=>jo(!1,`single`)),chrome.runtime.onMessage.addListener((e,t,n)=>e.type===`SHOW_CONFIRM_DIALOG`?(Ao(e.data),n({received:!0}),!1):e.type===`DISMISS_CONFIRM_DIALOG`?(No(e.data),n({received:!0}),!1):!1)}var Fo=t({closeCurrentSession:()=>Ec,handleDuplicateSession:()=>_c,handleSessionSwitch:()=>gc,newSession:()=>Ho,renderSessionTabs:()=>Bo});n(`zh`,{session:{newSession:`新会话`,closeSession:`关闭会话`,taskCompleted:`任务已完成`,noMatch:`未找到匹配的会话`,rename:`重命名`,duplicate:`复制会话`,confirmCloseMessageWithTitle:`确定要关闭会话 "{title}" 吗?`,confirmCloseAllMessage:`确定要关闭所有 {count} 个会话吗?`,confirmCloseAllTitle:`关闭全部会话`,forkedFrom:`已从 "{title}" 分叉`,forkedSession:`已复制会话 "{title}"`,operationFailed:`操作失败:{message}`,sessionListTitle:`会话列表`,closeGroupAll:`全部关闭`,confirmCloseGroupMessage:`确定要关闭“{group}”下的 {count} 个会话吗?`,today:`今天`,yesterday:`昨天`,last7Days:`近 7 天`,earlier:`更早`,todayFormat:`{hour}:{minute}`,yesterdayFormat:`昨天 {hour}:{minute}`,daysAgo:`{count} 天前`,archive:`归档会话`,archiveEntry:`归档区`,archiveEntryTitle:`查看归档会话`,archivePanelTitle:`归档区`,archiveSearchPlaceholder:`搜索归档会话...`,archiveEmpty:`暂无归档会话`,archiveNoMatch:`未找到匹配的归档会话`,archiveHint:`归档只是移出视野,随时可以恢复`,archiveBusyRunning:`该会话任务还在执行,完成后再归档`,archiveBusyQueued:`该会话还有排队任务,先清空队列再归档`,archived:`已归档到归档区`,archivedRestored:`已恢复会话「{title}」`,archivedAt:`归档于 {time}`,restore:`恢复`,restoreTitle:`恢复到会话列表`,deleteForever:`彻底删除`,confirmDeleteForeverTitle:`彻底删除会话`,confirmDeleteForeverMessage:`「{title}」将被彻底删除,消息与执行记录都无法恢复。确定继续吗?`,archiveDeleted:`已彻底删除会话「{title}」`,backToSessionList:`返回会话列表`,expandSidebar:`展开会话列表`,collapseSidebar:`收起会话列表`,searchSessions:`搜索会话`,sortModeTitle:`会话排序`,sortManual:`手动排序(拖拽调整,与标签栏一致)`,sortRecent:`最近更新优先(按时间倒序,带时间分组)`}}),n(`en`,{session:{newSession:`New Session`,closeSession:`Close Session`,taskCompleted:`Task completed`,noMatch:`No matching sessions found`,rename:`Rename`,duplicate:`Duplicate`,confirmCloseMessageWithTitle:`Are you sure you want to close session "{title}"?`,confirmCloseAllMessage:`Are you sure you want to close all {count} sessions?`,confirmCloseAllTitle:`Close All Sessions`,forkedFrom:`Forked from "{title}"`,forkedSession:`Duplicated session "{title}"`,operationFailed:`Operation failed: {message}`,sessionListTitle:`Sessions`,closeGroupAll:`Close all`,confirmCloseGroupMessage:`Are you sure you want to close {count} sessions in "{group}"?`,today:`Today`,yesterday:`Yesterday`,last7Days:`Last 7 days`,earlier:`Earlier`,todayFormat:`{hour}:{minute}`,yesterdayFormat:`Yesterday {hour}:{minute}`,daysAgo:`{count}d ago`,archive:`Archive session`,archiveEntry:`Archived`,archiveEntryTitle:`View archived sessions`,archivePanelTitle:`Archived sessions`,archiveSearchPlaceholder:`Search archived sessions...`,archiveEmpty:`No archived sessions`,archiveNoMatch:`No archived sessions found`,archiveHint:`Archiving only hides a session — you can restore it anytime`,archiveBusyRunning:`This session is still running. Archive it when it finishes`,archiveBusyQueued:`This session still has queued tasks. Clear the queue first`,archived:`Moved to archive`,archivedRestored:`Session "{title}" restored`,archivedAt:`Archived {time}`,restore:`Restore`,restoreTitle:`Restore to session list`,deleteForever:`Delete permanently`,confirmDeleteForeverTitle:`Delete session permanently`,confirmDeleteForeverMessage:`"{title}" will be permanently deleted. Messages and execution logs cannot be recovered. Continue?`,archiveDeleted:`Session "{title}" permanently deleted`,backToSessionList:`Back to sessions`,expandSidebar:`Expand session list`,collapseSidebar:`Collapse session list`,searchSessions:`Search sessions`,sortModeTitle:`Session order`,sortManual:`Manual order (drag to arrange, same as tabs)`,sortRecent:`Most recent first (time order with day groups)`}});var B={visible:!1,highlightIndex:-1,filteredSessions:[]},Io={draggedId:null,sourceType:null};function Lo(e){if(!e)return``;let t=new Date(e),n=new Date,i=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),a=t.getTime();if(a>=i)return r(`session.todayFormat`,{hour:String(t.getHours()).padStart(2,`0`),minute:String(t.getMinutes()).padStart(2,`0`)});if(a>=i-864e5)return r(`session.yesterdayFormat`,{hour:String(t.getHours()).padStart(2,`0`),minute:String(t.getMinutes()).padStart(2,`0`)});let o=Math.floor((i-a)/864e5);return o<=7?r(`session.daysAgo`,{count:o}):t.getFullYear()===n.getFullYear()?`${t.getMonth()+1}/${t.getDate()}`:`${t.getFullYear()}/${t.getMonth()+1}/${t.getDate()}`}function Ro(e){return e.sort((e,t)=>{let n=e.updatedAt?new Date(e.updatedAt).getTime():0;return(t.updatedAt?new Date(t.updatedAt).getTime():0)-n})}function zo(e){if(!e)return`earlier`;let t=new Date(e),n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate()).getTime(),i=t.getTime();return i>=r?`today`:i>=r-864e5?`yesterday`:Math.floor((r-i)/864e5)<=7?`last7Days`:`earlier`}async function Bo(e=null){let t=e||await vi({withActiveHistory:!1});C.sessions=t.list,C.activeSessionId=t.activeSessionId;let n=document.getElementById(`sessionTabs`),i=document.getElementById(`sessionTabsScroll`),a=document.getElementById(`sessionTabsActions`);!n||!i||!a||(i.style.opacity=``,i.innerHTML=``,t.list.forEach(e=>{let t=document.createElement(`div`);t.className=`session-tab`,t.dataset.sessionId=e.id,e.id===C.activeSessionId&&t.classList.add(`active`),t.title=e.title;let n=document.createElement(`span`);n.className=`session-tab-title`,n.textContent=e.title||r(`session.newSession`),t.appendChild(n);let a=document.createElement(`span`);if(a.className=`session-tab-close`,a.innerHTML=`✕`,a.title=r(`session.closeSession`),a.addEventListener(`click`,async t=>{if(t.stopPropagation(),(e.id===C.activeSessionId?C.messageHistory?.length||0:e.messageCount??e.messageHistory?.length??0)===0){hs(await ms(e.id)),await Tc();return}Sc(e,async()=>{await Tc()})}),t.appendChild(a),e.isGenerating||C.generatingSessionIds.has(e.id)){let e=document.createElement(`span`);e.className=`session-tab-indicator`,t.appendChild(e)}else if(C.completedSessionIds.has(e.id)&&e.id!==C.activeSessionId){let e=document.createElement(`span`);e.className=`session-tab-completed-indicator`,e.title=r(`session.taskCompleted`),t.appendChild(e)}let o=kr(e.id);if(o>0){let e=document.createElement(`span`);e.className=`session-tab-queue-badge`,e.textContent=String(o>99?`99+`:o),e.title=r(`queue.badgeTitle`,{count:o}),t.appendChild(e)}t.addEventListener(`click`,async n=>{if(n.preventDefault(),e.id!==C.activeSessionId&&!fc){fc=!0,i.querySelectorAll(`.session-tab.active`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`);try{await gc(e.id)}finally{fc=!1,C.activeSessionId!==e.id&&Bo({list:C.sessions,activeSessionId:C.activeSessionId})}}}),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),Cc(t,e)}),t.addEventListener(`mousedown`,async t=>{t.button===1&&(t.preventDefault(),t.stopPropagation(),hs(await ms(e.id)),await Tc())}),t.draggable=!0,t.addEventListener(`dragstart`,t=>Zo(t,e.id)),t.addEventListener(`dragover`,e=>Qo(e)),t.addEventListener(`dragleave`,e=>$o(e)),t.addEventListener(`drop`,t=>es(t,e.id)),t.addEventListener(`dragend`,e=>ts(e)),i.appendChild(t)}),Vo(),Uo(),ys(),dc(),bc(i),Ko(i),qo(i),Xo(i),Ws(),Zs())}function Vo(){let e=document.getElementById(`sessionTabsMore`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,e=>{e.stopPropagation(),zs()})}async function Ho(){let e=C.activeSessionId;await yi();let t=await Si();C.activeSessionId=t.id,C.messageHistory=[],C.activeCompaction=null,bi(t),document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:t.id,previousSessionId:e}})),Bo()}function Uo(){let e=document.getElementById(`sessionTabsAdd`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,()=>Ho())}var Wo=0,Go=0;function Ko(e){let t=document.getElementById(`sessionTabsMore`);if(!t)return;if(!Ns()){t.style.display=`none`;return}let n=e.scrollWidth>e.clientWidth;t.style.display=n||Wo>0?`flex`:`none`}async function qo(e){let t=++Go,n;try{n=await Oi()}catch{return}t===Go&&(Wo=n.length,Ko(e))}var Jo=null;function Yo(){if(Jo)return;let e=document.getElementById(`sessionTabsScroll`);e&&(Jo=new ResizeObserver(()=>{requestAnimationFrame(()=>{Ko(e)})}),Jo.observe(e))}function Xo(e){let t=e.querySelector(`.session-tab.active`);if(t){let n=t.offsetLeft,r=t.offsetWidth;e.scrollLeft=n-(e.clientWidth-r)/2}e.style.opacity=`1`}function Zo(e,t){Io.draggedId=t,Io.sourceType=`tab`,e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,t),e.currentTarget.classList.add(`dragging`)}function Qo(e){e.preventDefault(),e.dataTransfer.dropEffect=`move`,e.currentTarget.classList.add(`drag-over`)}function $o(e){e.currentTarget.classList.remove(`drag-over`)}async function es(e,t){e.preventDefault(),e.currentTarget.classList.remove(`drag-over`);let n=Io.draggedId;if(!n||n===t)return;let r=C.sessions||[],i=r.findIndex(e=>e.id===n),a=r.findIndex(e=>e.id===t);if(i===-1||a===-1)return;let o=[...r],[s]=o.splice(i,1);o.splice(a,0,s),C.sessions=o,await Ei(o.map(e=>e.id)),Bo()}function ts(e){e.currentTarget.classList.remove(`dragging`),document.querySelectorAll(`.session-tab.drag-over`).forEach(e=>e.classList.remove(`drag-over`)),Io.draggedId=null,Io.sourceType=null}function ns(){B.visible?is():rs()}async function rs(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);if(!e||!t)return;let n=await vi();C.sessions=n.list,C.activeSessionId=n.activeSessionId,B.filteredSessions=Ro([...n.list]),B.highlightIndex=-1,B.visible=!0,rc(),os(),t.classList.add(`show`);let r=document.getElementById(`sessionDropdownCloseBtn`);r&&(r.onclick=()=>is());let i=document.getElementById(`sessionDropdownSearch`),a=document.getElementById(`sessionDropdownSearchClear`);i&&(i.value=B.lastSearchText||``,as(),B.lastSearchText&&fs(B.lastSearchText),setTimeout(()=>i.focus(),50),i.oninput=()=>{B.lastSearchText=i.value,as(),fs(i.value)},i.onkeydown=e=>{bs(e)}),a&&(a.onclick=()=>{i&&(i.value=``,B.lastSearchText=``,as(),fs(``),i.focus())}),e.classList.add(`active`)}function is(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);t&&t.classList.remove(`show`),e&&e.classList.remove(`active`);let n=document.getElementById(`sessionDropdownSearch`);n&&(B.lastSearchText=n.value,n.oninput=null,n.onkeydown=null);let r=document.getElementById(`sessionDropdownSearchClear`);r&&(r.onclick=null),B.visible=!1,B.highlightIndex=-1,B.filteredSessions=[]}function as(){let e=document.getElementById(`sessionDropdownSearch`),t=document.getElementById(`sessionDropdownSearchClear`);t&&e&&(t.style.display=e.value?`flex`:`none`)}function os(){ss({listEl:document.getElementById(`sessionDropdownList`),filteredSessions:B.filteredSessions,highlightIndex:B.highlightIndex,onSelect:e=>ps(e)})}function ss({listEl:e,filteredSessions:t,highlightIndex:n,onSelect:i,grouped:a=!0,draggable:o=!1}){if(!e)return;if(e.innerHTML=``,t.length===0){let t=document.createElement(`div`);t.className=`session-dropdown-empty`,t.textContent=r(`session.noMatch`),e.appendChild(t);return}let s={today:r(`session.today`),yesterday:r(`session.yesterday`),last7Days:r(`session.last7Days`),earlier:r(`session.earlier`)},c={};a&&t.forEach(e=>{let t=zo(e.updatedAt);c[t]=(c[t]||0)+1});let l=null;t.forEach((t,u)=>{if(a){let n=zo(t.updatedAt);if(n!==l){l=n;let t=document.createElement(`div`);t.className=`session-dropdown-group-header`;let i=document.createElement(`span`);if(i.textContent=s[n]||n,t.appendChild(i),(c[n]||0)>0){let e=document.createElement(`button`);e.className=`session-dropdown-group-close`,e.textContent=r(`session.closeGroupAll`),e.onclick=e=>{e.stopPropagation(),vs(n,s[n]||n)},t.appendChild(e)}e.appendChild(t)}}let d=ds(t,{index:u,highlightIndex:n,onSelect:i});o&&ls(d,t.id),e.appendChild(d)})}var cs=null;function ls(e,t){e.draggable=!0,e.classList.add(`draggable`),e.addEventListener(`dragstart`,n=>{cs=t,n.dataTransfer.effectAllowed=`move`,n.dataTransfer.setData(`text/plain`,t),e.classList.add(`dragging`)}),e.addEventListener(`dragover`,n=>{!cs||cs===t||(n.preventDefault(),n.dataTransfer.dropEffect=`move`,e.classList.add(`drag-over`))}),e.addEventListener(`dragleave`,()=>e.classList.remove(`drag-over`)),e.addEventListener(`drop`,n=>{n.preventDefault(),n.stopPropagation(),e.classList.remove(`drag-over`),us(cs,t)}),e.addEventListener(`dragend`,()=>{e.classList.remove(`dragging`),document.querySelectorAll(`.session-dropdown-item.drag-over`).forEach(e=>e.classList.remove(`drag-over`)),cs=null})}async function us(e,t){let n=e;if(cs=null,!n||n===t)return;let r=C.sessions||[],i=r.findIndex(e=>e.id===n),a=r.findIndex(e=>e.id===t);if(i===-1||a===-1)return;let o=[...r],[s]=o.splice(i,1);o.splice(a,0,s),C.sessions=o,await Ei(o.map(e=>e.id)),await Bo()}function ds(e,{index:t,highlightIndex:n,onSelect:i}){let a=document.createElement(`div`);a.className=`session-dropdown-item`,a.dataset.sessionId=e.id,a.dataset.index=t,e.id===C.activeSessionId&&a.classList.add(`active`),t===n&&a.classList.add(`highlighted`);let o=e.isGenerating||C.generatingSessionIds.has(e.id);if(C.completedSessionIds.has(e.id)&&e.id!==C.activeSessionId&&!o){let e=document.createElement(`span`);e.className=`session-dropdown-item-completed`,e.title=r(`session.taskCompleted`),a.appendChild(e)}let s=kr(e.id);if(s>0){let e=document.createElement(`span`);e.className=`session-dropdown-item-queue`,e.textContent=String(s>99?`99+`:s),e.title=r(`queue.badgeTitle`,{count:s}),a.appendChild(e)}let c=document.createElement(`span`);if(c.className=`session-dropdown-item-icon`,o){let e=document.createElement(`span`);e.className=`session-dropdown-item-running`,c.appendChild(e)}else c.innerHTML=`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>`;a.appendChild(c);let l=document.createElement(`span`);if(l.className=`session-dropdown-item-title`,l.textContent=e.title||r(`session.newSession`),l.title=e.title||r(`session.newSession`),a.appendChild(l),e.id===C.activeSessionId){let e=document.createElement(`span`);e.className=`session-dropdown-item-check`,e.innerHTML=`<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>`,a.appendChild(e)}let u=document.createElement(`span`);u.className=`session-dropdown-item-time`,u.textContent=Lo(e.updatedAt),a.appendChild(u);let d=document.createElement(`span`);d.className=`session-dropdown-item-actions`;let f=document.createElement(`span`);f.className=`session-dropdown-item-rename`,f.title=r(`session.rename`),f.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,f.addEventListener(`click`,t=>{t.stopPropagation(),t.preventDefault(),xc(e)}),d.appendChild(f);let p=document.createElement(`span`);p.className=`session-dropdown-item-duplicate`,p.title=r(`session.duplicate`),p.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="6" r="2.5"/><path d="M6 8.5v7"/><path d="M18 8.5c0 4-6 3.5-6 3.5"/></svg>`,p.addEventListener(`click`,async t=>{t.stopPropagation(),t.preventDefault(),await _c(e.id);let n=await vi({withActiveHistory:!1});C.sessions=n.list,C.activeSessionId=n.activeSessionId,fs(document.getElementById(`sessionDropdownSearch`)?.value||``)}),d.appendChild(p);let m=document.createElement(`span`);m.className=`session-dropdown-item-archive`,m.title=r(`session.archive`),m.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,m.addEventListener(`click`,async t=>{t.stopPropagation(),t.preventDefault(),await tc(e.id),fs(document.getElementById(`sessionDropdownSearch`)?.value||``)}),d.appendChild(m);let h=document.createElement(`span`);return h.className=`session-dropdown-item-close`,h.innerHTML=`✕`,h.title=r(`session.closeSession`),h.addEventListener(`click`,async t=>{t.stopPropagation(),t.preventDefault(),await gs(e.id)}),d.appendChild(h),a.appendChild(d),a.addEventListener(`click`,async t=>{t.preventDefault(),await i(e.id)}),a}function fs(e){let t=C.sessions||[],n;if(!e.trim())n=[...t];else{let i=e.trim().toLowerCase();n=t.filter(e=>(e.title||r(`session.newSession`)).toLowerCase().includes(i))}B.filteredSessions=Ro(n),B.highlightIndex=-1,os()}async function ps(e){is(),e!==C.activeSessionId&&await gc(e)}async function ms(e){let t=kr(e)+Dr(e).length;return await wi(e),t}function hs(e){e<=0||F(r(`queue.sessionDropped`,{count:e}),`info`,3e3)}async function gs(e){let t=(C.sessions||[]).find(t=>t.id===e);t&&((e===C.activeSessionId?C.messageHistory?.length||0:t.messageCount??t.messageHistory?.length??0)>0&&!await Qs(r(`session.confirmCloseMessageWithTitle`,{title:t.title}),r(`session.closeSession`))||(hs(await ms(e)),await Tc(),fs(document.getElementById(`sessionDropdownSearch`)?.value||``)))}async function _s(){let e=C.sessions||[];if(e.length===0||!await Qs(r(`session.confirmCloseAllMessage`,{count:e.length}),r(`session.confirmCloseAllTitle`)))return;let t=0;for(let n of e)t+=await ms(n.id);hs(t),await Tc(),fs(document.getElementById(`sessionDropdownSearch`)?.value||``)}async function vs(e,t){let n=(C.sessions||[]).filter(t=>zo(t.updatedAt)===e);if(n.length===0||!await Qs(r(`session.confirmCloseGroupMessage`,{group:t,count:n.length}),r(`session.closeSession`)))return;let i=0;for(let e of n)i+=await ms(e.id);hs(i),await Tc(),fs(document.getElementById(`sessionDropdownSearch`)?.value||``)}function ys(){let e=document.getElementById(`sessionDropdownCloseAll`),t=document.getElementById(`sessionDropdown`);if(t){if(e){let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,async e=>{e.stopPropagation(),await _s()})}t.addEventListener(`click`,e=>{e.stopPropagation()})}}function bs(e){if(!B.visible)return;let t=B.filteredSessions.length;if(t===0){e.key===`Escape`&&is();return}switch(e.key){case`ArrowDown`:e.preventDefault(),B.highlightIndex=Math.min(B.highlightIndex+1,t-1),os(),xs(document.getElementById(`sessionDropdownList`));break;case`ArrowUp`:e.preventDefault(),B.highlightIndex=Math.max(B.highlightIndex-1,0),os(),xs(document.getElementById(`sessionDropdownList`));break;case`Enter`:if(e.preventDefault(),B.highlightIndex>=0&&B.highlightIndex<t){let e=B.filteredSessions[B.highlightIndex];ps(e.id)}break;case`Escape`:e.preventDefault(),is();break}}function xs(e){let t=(e||document).querySelector(`.session-dropdown-item.highlighted`);t&&t.scrollIntoView({block:`nearest`})}var Ss=560,Cs=200,ws=480,Ts=360,Es=240,Ds=`sessionSidebarExpanded`,Os=`sessionSidebarWidth`,ks=`sessionSidebarSortMode`,As=`manual`,js=`recent`,V={expanded:!1,width:Es,sortMode:As,narrow:!1,pendingRestore:!1,highlightIndex:-1,filteredSessions:[],inited:!1,lastActiveId:null};function Ms(e){let t=document.getElementById(`mainRow`),n=t?Math.max(Cs,t.clientWidth-Ts):ws;return Math.max(Cs,Math.min(e,ws,n))}function Ns(){let e=document.getElementById(`mainRow`);return e?e.clientWidth<Ss:!0}function Ps(){let e=document.getElementById(`sessionSidebar`);if(!e)return;V.narrow=Ns(),e.classList.toggle(`sidebar-hidden`,V.narrow),e.classList.toggle(`expanded`,!V.narrow&&V.expanded),e.style.setProperty(`--session-sidebar-width`,`${V.width}px`),Fs();let t=document.getElementById(`sessionSidebarToggle`);t&&t.classList.toggle(`sidebar-hidden`,V.narrow||V.expanded);let n=document.getElementById(`sessionTabs`);if(n){let e=!V.narrow&&V.expanded;if(n.classList.toggle(`tabs-hidden`,e),!e){let e=document.getElementById(`sessionTabsScroll`);e&&Xo(e)}}}function Fs(){let e=!V.narrow&&V.expanded?V.width:0;document.body.style.setProperty(`--session-sidebar-offset`,`${e}px`)}async function Is(){try{await chrome.storage.local.set({[Ds]:V.expanded,[Os]:V.width,[ks]:V.sortMode})}catch{}}function Ls(){Ns()||(V.expanded=!0,Ps(),Is(),Ws())}function Rs(){V.expanded=!1,Ps(),Is()}function zs(){if(Ns()){ns();return}V.expanded?Rs():Ls()}function Bs(){let e=document.getElementById(`sessionSidebarList`),t=V.sortMode===js,n=!!(document.getElementById(`sessionSidebarSearch`)?.value||``).trim();ss({listEl:e,filteredSessions:V.filteredSessions,highlightIndex:V.highlightIndex,onSelect:e=>Gs(e),grouped:t,draggable:!t&&!n});let r=C.activeSessionId;r&&V.lastActiveId!==r&&(V.lastActiveId=r,e?.querySelector(`.session-dropdown-item.active`)?.scrollIntoView({block:`nearest`}))}function Vs(e){let t=C.sessions||[],n;if(!e.trim())n=[...t];else{let i=e.trim().toLowerCase();n=t.filter(e=>(e.title||r(`session.newSession`)).toLowerCase().includes(i))}V.filteredSessions=V.sortMode===js?Ro(n):n.reverse(),V.highlightIndex=-1,Bs()}function Hs(){document.querySelectorAll(`.session-sidebar-sort-btn`).forEach(e=>{let t=e.dataset.mode===V.sortMode;e.classList.toggle(`active`,t),e.setAttribute(`aria-pressed`,t?`true`:`false`)})}function Us(e){e!==As&&e!==js||V.sortMode!==e&&(V.sortMode=e,Hs(),V.lastActiveId=null,Vs(document.getElementById(`sessionSidebarSearch`)?.value||``),Is())}function Ws(){let e=document.getElementById(`sessionSidebar`);!e||!e.classList.contains(`expanded`)||Vs(document.getElementById(`sessionSidebarSearch`)?.value||``)}async function Gs(e){e!==C.activeSessionId&&await gc(e)}function Ks(e){let t=V.filteredSessions,n=t.length;if(n===0){e.key===`Escape`&&Rs();return}switch(e.key){case`ArrowDown`:e.preventDefault(),V.highlightIndex=Math.min(V.highlightIndex+1,n-1),Bs(),xs(document.getElementById(`sessionSidebarList`));break;case`ArrowUp`:e.preventDefault(),V.highlightIndex=Math.max(V.highlightIndex-1,0),Bs(),xs(document.getElementById(`sessionSidebarList`));break;case`Enter`:e.preventDefault(),V.highlightIndex>=0&&V.highlightIndex<n&&Gs(t[V.highlightIndex].id);break;case`Escape`:e.preventDefault(),Rs();break}}function qs(){let e=document.getElementById(`sessionSidebarSearch`),t=document.getElementById(`sessionSidebarSearchClear`);t&&e&&(t.style.display=e.value?`flex`:`none`)}function Js(){let e=document.getElementById(`sessionSidebar`),t=document.getElementById(`sessionSidebarGrip`);!e||!t||t.addEventListener(`mousedown`,t=>{t.preventDefault();let n=t.clientX,r=V.width;e.classList.add(`resizing`);function i(t){let i=Ms(r+(t.clientX-n));V.width=i,e.style.setProperty(`--session-sidebar-width`,`${i}px`),Fs()}function a(){document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),e.classList.remove(`resizing`),Is()}document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)})}function Ys(){let e=document.getElementById(`mainRow`);!e||typeof ResizeObserver>`u`||new ResizeObserver(()=>{requestAnimationFrame(()=>{let e=Ns();e!==V.narrow&&(e&&V.expanded?V.pendingRestore=!0:!e&&V.pendingRestore&&(V.pendingRestore=!1),Ps(),!e&&V.expanded&&Ws())})}).observe(e)}function Xs(){Ns()?rs():Ls()}async function Zs(){if(V.inited||!document.getElementById(`sessionSidebar`))return;V.inited=!0;try{let e=await chrome.storage.local.get([Ds,Os,ks]);V.expanded=e[Ds]===!0,typeof e[Os]==`number`&&(V.width=Ms(e[Os])),(e[ks]===js||e[ks]===As)&&(V.sortMode=e[ks])}catch{}Hs(),Ns()&&V.expanded&&(V.pendingRestore=!0),Ps(),Ws(),document.getElementById(`sessionSidebarToggle`)?.addEventListener(`click`,()=>zs()),document.getElementById(`sessionSidebarAdd`)?.addEventListener(`click`,()=>{Ho()}),document.getElementById(`sessionSidebarCollapse`)?.addEventListener(`click`,()=>Rs()),document.querySelectorAll(`.session-sidebar-sort-btn`).forEach(e=>{e.addEventListener(`click`,()=>Us(e.dataset.mode))}),document.getElementById(`sessionSidebarArchiveEntry`)?.addEventListener(`click`,()=>{ic()}),document.getElementById(`sessionSidebarCloseAll`)?.addEventListener(`click`,async e=>{e.stopPropagation(),await _s()});let e=document.getElementById(`sessionSidebarSearch`),t=document.getElementById(`sessionSidebarSearchClear`);e&&(e.addEventListener(`input`,()=>{qs(),Vs(e.value)}),e.addEventListener(`keydown`,e=>{Ks(e)})),t&&t.addEventListener(`click`,()=>{e&&(e.value=``,qs(),Vs(``),e.focus())}),Js(),Ys(),rc()}function Qs(e,t){return new Promise(t=>{let n=document.getElementById(`sessionDeleteModal`),r=document.getElementById(`sessionDeleteMessage`),i=document.getElementById(`sessionDeleteConfirmBtn`),a=document.getElementById(`sessionDeleteCancelBtn`),o=document.getElementById(`sessionDeleteCloseBtn`);if(!n||!r){t(!1);return}r.textContent=e;let s=()=>{n.classList.remove(`show`),i.removeEventListener(`click`,c),a.removeEventListener(`click`,l),o.removeEventListener(`click`,l)},c=()=>{s(),t(!0)},l=()=>{s(),t(!1)};i.addEventListener(`click`,c),a.addEventListener(`click`,l),o.addEventListener(`click`,l),n.classList.add(`show`)})}var $s=``,ec=!1;async function tc(e){if(!e)return;let t=ki(e);if(!t.ok){t.reason===`running`?F(r(`session.archiveBusyRunning`),`warning`):t.reason===`queued`&&F(r(`session.archiveBusyQueued`),`warning`);return}let n=e===C.activeSessionId,i=await Ai(e);if(!i?.ok){i?.reason===`running`?F(r(`session.archiveBusyRunning`),`warning`):i?.reason===`queued`?F(r(`session.archiveBusyQueued`),`warning`):F(r(`session.operationFailed`,{message:i?.reason||`unknown`}),`error`);return}if(document.dispatchEvent(new CustomEvent(`session-archived`,{detail:{sessionId:e}})),n)await nc(e);else{let e=await vi();C.sessions=e.list,Bo(e)}await rc(),F(r(`session.archived`),`info`)}async function nc(e){let t=Ro([...(await vi()).list]).filter(t=>t.id!==e);if(t.length>0){await gc(t[0].id);return}await Si(),await Tc()}async function rc(){let e=[`sessionArchiveEntryLabel`,`sessionSidebarArchiveLabel`].map(e=>document.getElementById(e));if(!e.some(Boolean))return;Wo=(await Oi()).length;let t=document.getElementById(`sessionTabsScroll`);t&&Ko(t);let n=r(`session.archiveEntry`);e.forEach(e=>{e&&(e.textContent=n)})}async function ic(){let e=document.getElementById(`sessionArchivePanel`);if(!e)return;dc(),$s=``;let t=document.getElementById(`sessionArchiveSearch`);t&&(t.value=``),oc(),await sc(),e.classList.add(`show`),is()}function ac(){let e=document.getElementById(`sessionArchivePanel`);e&&e.classList.remove(`show`)}function oc(){let e=document.getElementById(`sessionArchiveSearchClear`);e&&(e.style.display=$s?`flex`:`none`)}async function sc(){let e=document.getElementById(`sessionArchiveList`);if(!e)return;let t=await Oi(),n=$s.trim().toLowerCase(),i=n?t.filter(e=>(e.title||``).toLowerCase().includes(n)):t;if(e.innerHTML=``,i.length===0){let t=document.createElement(`div`);t.className=`session-dropdown-empty`,t.textContent=r(n?`session.archiveNoMatch`:`session.archiveEmpty`),e.appendChild(t);return}let a={today:r(`session.today`),yesterday:r(`session.yesterday`),last7Days:r(`session.last7Days`),earlier:r(`session.earlier`)},o=null;i.forEach(t=>{let n=zo(t.archivedAt);if(n!==o){o=n;let t=document.createElement(`div`);t.className=`session-dropdown-group-header`;let r=document.createElement(`span`);r.textContent=a[n]||n,t.appendChild(r),e.appendChild(t)}e.appendChild(cc(t))})}function cc(e){let t=document.createElement(`div`);t.className=`session-dropdown-item session-archive-item`,t.dataset.sessionId=e.id,t.title=e.title||r(`session.newSession`);let n=document.createElement(`span`);n.className=`session-dropdown-item-icon`,n.innerHTML=`<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,t.appendChild(n);let i=document.createElement(`span`);i.className=`session-dropdown-item-title`,i.textContent=e.title||r(`session.newSession`),t.appendChild(i);let a=document.createElement(`span`);a.className=`session-dropdown-item-time`,a.textContent=r(`session.archivedAt`,{time:Lo(e.archivedAt)}),t.appendChild(a);let o=document.createElement(`span`);o.className=`session-dropdown-item-actions`;let s=document.createElement(`span`);s.className=`session-dropdown-item-restore`,s.title=r(`session.restoreTitle`),s.innerHTML=`<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 14 4 9 9 4"/><path d="M20 20v-7a4 4 0 0 0-4-4H4"/></svg>`,s.addEventListener(`click`,async t=>{t.stopPropagation(),await lc(e.id)}),o.appendChild(s);let c=document.createElement(`span`);return c.className=`session-dropdown-item-delete`,c.title=r(`session.deleteForever`),c.innerHTML=`✕`,c.addEventListener(`click`,async t=>{t.stopPropagation(),await uc(e)}),o.appendChild(c),t.appendChild(o),t.addEventListener(`click`,async()=>{await lc(e.id,{enter:!0})}),t}async function lc(e,{enter:t=!1}={}){if(!await ji(e)){F(r(`session.operationFailed`,{message:`not found`}),`error`),await sc();return}let n=await vi();C.sessions=n.list;let i=n.list.find(t=>t.id===e)?.title||r(`session.newSession`);ac(),await sc(),await rc(),t?await gc(e):Bo(n),F(r(`session.archivedRestored`,{title:i}),`success`)}async function uc(e){let t=e.title||r(`session.newSession`);await Qs(r(`session.confirmDeleteForeverMessage`,{title:t}),r(`session.confirmDeleteForeverTitle`))&&(await Mi(e.id),await sc(),await rc(),document.dispatchEvent(new CustomEvent(`session-deleted`,{detail:{sessionId:e.id}})),F(r(`session.archiveDeleted`,{title:t}),`success`))}function dc(){if(ec)return;let e=document.getElementById(`sessionArchivePanel`),t=document.getElementById(`sessionArchiveEntry`);if(!e||!t)return;ec=!0,t.addEventListener(`click`,()=>{ic()});let n=document.getElementById(`sessionArchiveBackBtn`);n&&n.addEventListener(`click`,()=>{ac(),Xs()});let r=document.getElementById(`sessionArchiveCloseBtn`);r&&r.addEventListener(`click`,()=>ac());let i=document.getElementById(`sessionArchiveSearch`),a=document.getElementById(`sessionArchiveSearchClear`);i&&(i.addEventListener(`input`,()=>{$s=i.value,oc(),sc()}),i.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.stopPropagation(),ac(),Xs())})),a&&a.addEventListener(`click`,()=>{i&&(i.value=``,$s=``,oc(),sc(),i.focus())}),document.addEventListener(`session-archived`,()=>{e.classList.contains(`show`)&&sc()}),document.addEventListener(`session-deleted`,()=>{e.classList.contains(`show`)&&sc()})}var fc=!1,pc=500;function mc(e){let t=`scrollPosition_${e||`default`}`;chrome.storage.local.get([t],e=>{let n=document.getElementById(`chatContainer`);n&&e[t]!==void 0&&(n.scrollTop=e[t]),A(async()=>{let{updateScrollButtonState:e}=await Promise.resolve().then(()=>XS);return{updateScrollButtonState:e}},void 0).then(({updateScrollButtonState:e})=>e()).catch(()=>{})})}function hc(e,t){setTimeout(()=>{C.activeSessionId===e&&(Ue(t)||mc(e))},pc)}async function gc(e,{focusMessageId:t=null}={}){let n=C.activeSessionId;if(!await Ci(e))return;let r=`agentEnabledTools_${C.activeAgentId||`default`}`,i=`agentMcpClosedServers_${C.activeAgentId||`default`}`,[a,o,s,c]=await Promise.all([vi(),chrome.storage.local.get([i,`ragTools`,`ragToolsIntroduced`]),chrome.storage.local.get([r,`enabledTools`]),C.activeAgentId?pt(C.activeAgentId):Promise.resolve(null)]);C.sessions=a.list,C.activeSessionId=e;let l=o.ragTools||[];C.mcpClosedServers=o[i]||[];let u=!!s[r],d=s[r]||s.enabledTools;if(u||d&&d.length>0){let e=va(l),t=d.filter(t=>e.has(t));if(u)C.enabledTools=t;else{let e=f.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);C.enabledTools=[...t,...e]}let n=_a(C.enabledTools,l,o.ragToolsIntroduced);C.enabledTools=n.tools,C.enabledTools.length!==d.length&&chrome.storage.local.set({[r]:C.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{C.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let e=_a(C.enabledTools,l,o.ragToolsIntroduced);C.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[r]:C.enabledTools})}C.activeAgentToolIds=c?c.toolIds:null,C.activeAgentMcpExcludedServerIds=c?c.mcpExcludedServerIds??null:null,document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,...t?{skipScrollRestore:!0}:{}}})),_i(e),Bo(a),vc(),VD();try{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await A(async()=>{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await Promise.resolve().then(()=>uh);return{refreshBookmarkPanel:e,updateBookmarkButtons:t}},void 0);e(),setTimeout(()=>t(),100)}catch{}let p=document.getElementById(`toolsPopupOverlay`);p&&p.classList.contains(`show`)&&(ra(),da(),fa()),ha(),t&&hc(e,t)}async function _c(e,t=null){if(e)try{let n=await Fi(e,t);await gc(n.id),F(r(t?`session.forkedFrom`:`session.forkedSession`,{title:n.title}),`success`)}catch(e){i.error(`[SessionUI] copy/forksession failed:`,e),F(r(`session.operationFailed`,{message:e.message}),`error`)}}function vc(){let e=document.querySelector(`.model-display`);e&&C.currentModel&&(e.textContent=C.currentModel);let t=document.getElementById(`enableToolsBtn`);t&&(t.checked=C.useTools);let n=document.getElementById(`tempIconValue`);n&&C.temperature!==void 0&&(n.textContent=C.temperature.toFixed(2))}var yc=new WeakSet;function bc(e){yc.has(e)||(yc.add(e),e.addEventListener(`wheel`,t=>{e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY)},{passive:!1}))}function xc(e){let t=document.getElementById(`sessionRenameModal`),n=document.getElementById(`sessionRenameInput`),r=document.getElementById(`sessionRenameConfirmBtn`),i=document.getElementById(`sessionRenameCancelBtn`),a=document.getElementById(`sessionRenameCloseBtn`);if(!t||!n)return;n.value=e.title;let o=()=>{t.classList.remove(`show`),r.removeEventListener(`click`,s),i.removeEventListener(`click`,c),a.removeEventListener(`click`,c)},s=async()=>{let t=n.value.trim();if(t&&t!==e.title){await Ti(e.id,t),Bo();let n=await vi();C.sessions=n.list,C.activeSessionId=n.activeSessionId,fs(document.getElementById(`sessionDropdownSearch`)?.value||``)}o()},c=()=>{o()};r.addEventListener(`click`,s),i.addEventListener(`click`,c),a.addEventListener(`click`,c),n.onkeydown=e=>{e.key===`Enter`?s():e.key===`Escape`&&c()},t.classList.add(`show`),setTimeout(()=>{n.focus(),n.select()},50)}function Sc(e,t){let n=document.getElementById(`sessionDeleteModal`),i=document.getElementById(`sessionDeleteMessage`),a=document.getElementById(`sessionDeleteConfirmBtn`),o=document.getElementById(`sessionDeleteCancelBtn`),s=document.getElementById(`sessionDeleteCloseBtn`);if(!n||!i)return;i.textContent=r(`session.confirmCloseMessageWithTitle`,{title:e.title});let c=()=>{n.classList.remove(`show`),a.removeEventListener(`click`,l),o.removeEventListener(`click`,u),s.removeEventListener(`click`,u)},l=async()=>{hs(await ms(e.id)),t&&await t(),c()},u=()=>{c()};a.addEventListener(`click`,l),o.addEventListener(`click`,u),s.addEventListener(`click`,u),n.classList.add(`show`),requestAnimationFrame(()=>a.focus())}function Cc(e,t){let n=document.querySelector(`.session-context-menu`);n&&n.remove();let i=document.createElement(`div`);i.className=`session-context-menu`,i.style.left=e.clientX+`px`,i.style.top=e.clientY+`px`;let a=wc(r(`session.rename`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,()=>{i.remove(),xc(t)});i.appendChild(a);let o=wc(r(`session.duplicate`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="6" r="2.5"/><path d="M6 8.5v7"/><path d="M18 8.5c0 4-6 3.5-6 3.5"/></svg>`,()=>{i.remove(),_c(t.id)});i.appendChild(o);let s=wc(r(`session.archive`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 8v13H3V8"/><rect x="1" y="3" width="22" height="5"/><line x1="10" y1="12" x2="14" y2="12"/></svg>`,async()=>{i.remove(),await tc(t.id)});i.appendChild(s);let c=wc(r(`session.closeSession`),`<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,async()=>{if(i.remove(),(t.id===C.activeSessionId?C.messageHistory?.length||0:t.messageCount??t.messageHistory?.length??0)===0){hs(await ms(t.id)),await Tc();return}Sc(t,async()=>{await Tc()})},`danger`);i.appendChild(c),document.body.appendChild(i);let l=e=>{i.contains(e.target)||(i.remove(),document.removeEventListener(`click`,l))};setTimeout(()=>document.addEventListener(`click`,l),0)}function wc(e,t=``,n,r=``){let i=document.createElement(`div`);return i.className=`session-context-menu-item `+r,t?i.innerHTML=`${t}<span>${e}</span>`:i.textContent=e,i.addEventListener(`click`,n),i}async function Tc(){let e=C.activeSessionId,t=await vi();t.activeSessionId||(await Si(),t=await vi()),C.activeSessionId=t.activeSessionId,C.sessions=t.list;let n=t.list.find(e=>e.id===t.activeSessionId);if(C.messageHistory=n&&n.messageHistory||[],C.activeCompaction=n?.contextCompaction||null,bi(n),C.activeAgentId=n&&n.agentId||null,C.activeAgentId){let e=await pt(C.activeAgentId);C.activeAgentToolIds=e?e.toolIds:null,C.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null}else C.activeAgentToolIds=null,C.activeAgentMcpExcludedServerIds=null;document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:C.activeSessionId,previousSessionId:e}})),Bo(),await VD()}async function Ec(){let e=C.activeSessionId;if(!e)return;let t=C.sessions?.find(t=>t.id===e);if(t){if((C.messageHistory?.length||0)===0){hs(await ms(e)),await Tc();return}Sc(t,async()=>{await Tc()})}}document.addEventListener(`generating-state-changed`,()=>{Bo()}),document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{Yo(),Zs()}):(Yo(),Zs()),[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`].join(``),[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M12.146.146a.5.5 0 0 1 .708 0l2.5 2.5a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207 11.207 2.5zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293l6.5-6.5zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12h.5a.5.5 0 0 1 .5.5v.5a.5.5 0 0 1-.5.5h-.5a.5.5 0 0 1-.468-.325z"/>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<circle cx="12" cy="12" r="10"></circle>`,`<polyline points="12 6 12 12 16 14"></polyline>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<line x1="18" y1="6" x2="6" y2="18"></line>`,`<line x1="6" y1="6" x2="18" y2="18"></line>`,`</svg>`].join(``),[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<polyline points="7 13 12 18 17 13"></polyline>`,`<polyline points="7 6 12 11 17 6"></polyline>`,`</svg>`].join(``);var Dc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>`,Oc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>`,kc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/></svg>`,Ac=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/></svg>`,jc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg>`,Mc=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>`;[`<svg class="tool-call-icon exec" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>`,`<polyline points="14 2 14 8 20 8"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>`,`</svg>`].join(``),[`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/>`,`</svg>`].join(``),n(`zh`,{uiProto:{defaultTitle:`原型`,optimizePrompt:`请帮我优化这个UI原型界面 {id}({title}),`,loadFailed:`加载失败`,noDescription:`暂无描述`,previewInPanel:`面板内预览`,continueOptimizeTitle:`继续优化`,downloadPrototype:`下载原型`,confirmDeleteTitle:`确认删除`,confirmDeleteMessage:`确定删除原型 "{title}" 吗?此操作不可撤销。`,deleteFailed:`删除失败: {message}`,justNow:`刚刚`,minutesAgo:`{count} 分钟前`,hoursAgo:`{count} 小时前`}}),n(`en`,{uiProto:{defaultTitle:`Prototype`,optimizePrompt:`Please help me optimize this UI prototype {id} ({title}), `,loadFailed:`Load failed`,noDescription:`No description`,previewInPanel:`Preview in panel`,continueOptimizeTitle:`Continue optimizing`,downloadPrototype:`Download prototype`,confirmDeleteTitle:`Confirm delete`,confirmDeleteMessage:`Are you sure you want to delete prototype "{title}"? This action cannot be undone.`,deleteFailed:`Delete failed: {message}`,justNow:`Just now`,minutesAgo:`{count} minutes ago`,hoursAgo:`{count} hours ago`}});var Nc=null,Pc=1,Fc=.25,Ic=2,Lc=.1;function Rc(e){let t=e.trim();return/^\s*<!DOCTYPE\s/i.test(t)||/^\s*<html[\s>]/i.test(t)?/<\/head>/i.test(t)?t.replace(/<\/head>/i,`<style>html,body{overflow:auto!important;height:auto!important;}</style></head>`):/<body[\s>]/i.test(t)?t.replace(/<body([\s>])/i,`<body$1<style>html,body{overflow:auto!important;height:auto!important;}</style>`):t:`<!DOCTYPE html>
|
|
61
63
|
<html>
|
|
62
64
|
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
|
|
63
65
|
<body style="margin:0;padding:0;overflow:auto;">${t}</body>
|
|
64
|
-
</html>`}function
|
|
66
|
+
</html>`}function zc(e){i.debug(`[SidePanel] show UI prototype preview:`,e),Nc=e,al();let t=document.getElementById(`prototypeTitle`),n=document.getElementById(`prototypeDescription`),a=document.getElementById(`prototypeIframe`),o=document.getElementById(`prototypeLocalOpenBtn`);t&&(t.textContent=e.title||r(`prototype.previewTitle`)),n&&(n.textContent=e.description||``,n.style.display=e.description?`block`:`none`),a&&e.html&&(a.srcdoc=Rc(e.html)),o&&(e.localPath?(o.style.display=``,o.dataset.path=e.localPath):o.style.display=`none`);let s=document.getElementById(`prototypeOverlay`);s&&s.classList.add(`show`),i.debug(`[SidePanel] UI prototype previewpopupshown`)}function Bc(){let e=document.getElementById(`prototypeOverlay`);e&&e.classList.remove(`show`);let t=document.getElementById(`prototypeIframe`);t&&(t.srcdoc=``),Nc=null,i.debug(`[SidePanel] UI prototype previewpopuphidden`)}function Vc(){if(!Nc)return;let e=Nc.id,t=Nc.title||r(`uiProto.defaultTitle`);Bc();let n=document.getElementById(`userInput`);n&&(n.value=r(`uiProto.optimizePrompt`,{id:e,title:t}),n.focus(),n.style.height=`auto`,n.style.height=n.scrollHeight+`px`),i.debug(`[SidePanel] continue optimizeprototype:`,e)}function Hc(){if(!Nc||!Nc.html){i.error(`[SidePanel] no downloadable prototype`);return}let e=Rc(Nc.html),t=new Blob([e],{type:`text/html`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=(Nc.title||`prototype`).replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)+`.html`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n),i.debug(`[SidePanel] prototype down loaded:`,r.download)}function Uc(){if(!Nc||!Nc.html){i.error(`[SidePanel] no has can open prototype`);return}let e=Rc(Nc.html),t=`data:text/html;base64,`+btoa(unescape(encodeURIComponent(e)));chrome.tabs.create({url:t,active:!0}),i.debug(`[SidePanel] prototype in newlabelpageopen`)}async function Wc(e){try{let t=await D(e);if(!t){i.error(`[SidePanel] not foundprototype:`,e);return}zc(t)}catch(e){i.error(`[SidePanel] load prototype failed:`,e)}}async function Gc(e){try{let t=await D(e);if(!t){i.error(`[SidePanel] not foundprototype (autoopen):`,e);return}Nc=t,Uc(),i.debug(`[SidePanel] prototype inbrowserlabelpageautoopen:`,t.title)}catch(e){i.error(`[SidePanel] autoopenprototype failed:`,e)}}async function Kc(){let e=document.getElementById(`prototypeLibraryList`),t=document.getElementById(`prototypeLibraryModal`);if(!(!e||!t)){e.innerHTML=`<div class="prototype-library-empty">${r(`common.loading`)}</div>`;try{let e=await O();qc(e),Jc(e)}catch(t){i.error(`[SidePanel] loadprototype page library failed:`,t),e.innerHTML=`<div class="prototype-library-empty">${r(`uiProto.loadFailed`)}</div>`}t.classList.add(`show`),i.debug(`[SidePanel] prototype page libraryshown`)}}function qc(e){let t=document.getElementById(`prototypeLibraryList`);t&&(e.length===0?t.innerHTML=`<div class="prototype-library-empty">${r(`prototype.empty`)}</div>`:(t.innerHTML=e.map(e=>{let t=e.id.replace(`proto_`,``).slice(-6);return`
|
|
65
67
|
<div class="prototype-library-item" data-id="${e.id}">
|
|
66
68
|
<div class="prototype-library-item-info">
|
|
67
|
-
<div class="prototype-library-item-title" title="${
|
|
68
|
-
${e.description?`<div class="prototype-library-item-desc" title="${
|
|
69
|
+
<div class="prototype-library-item-title" title="${el(e.title)}">${el(e.title)}</div>
|
|
70
|
+
${e.description?`<div class="prototype-library-item-desc" title="${el(e.description)}">${el(e.description)}</div>`:`<div class="prototype-library-item-desc prototype-library-item-desc-empty">${r(`uiProto.noDescription`)}</div>`}
|
|
69
71
|
<div class="prototype-library-item-meta">
|
|
70
72
|
<span class="prototype-library-item-id">ID: ${t}</span>
|
|
71
|
-
<span class="prototype-library-item-time">${
|
|
73
|
+
<span class="prototype-library-item-time">${tl(e.createdAt)}</span>
|
|
72
74
|
</div>
|
|
73
75
|
</div>
|
|
74
76
|
<div class="prototype-library-item-actions">
|
|
75
77
|
<button class="prototype-library-item-open" title="${r(`uiProto.previewInPanel`)}">
|
|
76
|
-
${
|
|
78
|
+
${Oc}
|
|
77
79
|
</button>
|
|
78
80
|
${e.localPath?`
|
|
79
|
-
<button class="prototype-library-item-local-open" data-path="${
|
|
80
|
-
${
|
|
81
|
+
<button class="prototype-library-item-local-open" data-path="${el(e.localPath)}" title="${r(`prototype.openLocal`)}">
|
|
82
|
+
${kc}
|
|
81
83
|
</button>
|
|
82
84
|
`:``}
|
|
83
85
|
<button class="prototype-library-item-optimize" data-id="${e.id}" title="${r(`uiProto.continueOptimizeTitle`)}">
|
|
84
|
-
${
|
|
86
|
+
${Ac}
|
|
85
87
|
</button>
|
|
86
88
|
<button class="prototype-library-item-delete" data-id="${e.id}" title="${r(`common.delete`)}">
|
|
87
|
-
${
|
|
89
|
+
${jc}
|
|
88
90
|
</button>
|
|
89
91
|
<button class="prototype-library-item-download" data-id="${e.id}" title="${r(`uiProto.downloadPrototype`)}">
|
|
90
|
-
${
|
|
92
|
+
${Mc}
|
|
91
93
|
</button>
|
|
92
94
|
</div>
|
|
93
95
|
</div>
|
|
94
|
-
`}).join(``),t.querySelectorAll(`.prototype-library-item`).forEach(e=>{let t=e.querySelector(`.prototype-library-item-info`),n=e.querySelector(`.prototype-library-item-open`),a=e.querySelector(`.prototype-library-item-local-open`),o=e.querySelector(`.prototype-library-item-optimize`),s=e.querySelector(`.prototype-library-item-delete`),c=e.querySelector(`.prototype-library-item-download`);t&&t.addEventListener(`click`,()=>{let t=e.dataset.id;Bc(t)}),n&&n.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.id;Bc(n)}),a&&a.addEventListener(`click`,e=>{e.stopPropagation();let t=a.dataset.path;chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:t},e=>{e?.success||i.error(`[SidePanel] local browseropen failed:`,e?.error)})}),o&&o.addEventListener(`click`,t=>{t.stopPropagation();let n=o.dataset.id;Kc(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`)),Gc()}),s&&s.addEventListener(`click`,t=>{t.stopPropagation();let n=s.dataset.id;Jc(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`))}),c&&c.addEventListener(`click`,e=>{e.stopPropagation();let t=c.dataset.id;qc(t)})})))}function Wc(e){let t=()=>{let t=document.getElementById(`prototypeLibrarySearch`),n=document.getElementById(`prototypeLibrarySort`),r=(t?.value||``).trim().toLowerCase(),i=n?.value||`createdAt_desc`,a=e;r&&(a=e.filter(e=>(e.title||``).toLowerCase().includes(r)||(e.description||``).toLowerCase().includes(r)));let[o,s]=i.split(`_`);a=[...a].sort((e,t)=>{let n;return n=o===`title`?(e.title||``).localeCompare(t.title||``,`zh-CN`):(e.createdAt||0)-(t.createdAt||0),s===`desc`?-n:n}),Uc(a)},n=document.getElementById(`prototypeLibrarySearch`),r=document.getElementById(`prototypeLibrarySort`);if(n){let e=n.cloneNode(!0);n.parentNode.replaceChild(e,n),e.addEventListener(`input`,t)}if(r){let e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener(`change`,t)}}function Gc(){let e=document.getElementById(`prototypeLibraryModal`);e&&e.classList.remove(`show`),i.debug(`[SidePanel] prototype page libraryhidden`)}function Kc(e,t){let n=document.getElementById(`userInput`);n&&(n.value=r(`uiProto.optimizePrompt`,{id:e,title:t}),n.focus(),n.style.height=`auto`,n.style.height=n.scrollHeight+`px`),i.debug(`[SidePanel] from prototype page librarycontinue optimizeprototype:`,e)}async function qc(e){try{let t=await D(e);if(!t||!t.html){i.error(`[SidePanel] download prototype failed:not foundprototype`,e);return}let n=Pc(t.html),r=new Blob([n],{type:`text/html`}),a=URL.createObjectURL(r),o=document.createElement(`a`);o.href=a,o.download=(t.title||`prototype`).replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)+`.html`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(a),i.debug(`[SidePanel] prototype fromprototypelibrarydownload:`,o.download)}catch(e){i.error(`[SidePanel] download prototype failed:`,e)}}async function Jc(e,t){if(await Yc(r(`uiProto.confirmDeleteTitle`),r(`uiProto.confirmDeleteMessage`,{title:t}),r(`common.delete`)))try{let t=await D(e);await x(e),i.debug(`[SidePanel] prototype deleted:`,e),t?.localPath&&chrome.runtime.sendMessage({type:`DELETE_LOCAL_PROTOTYPE`,path:t.localPath},e=>{e?.success?i.debug(`[SidePanel] local prototypefile deleted:`,t.localPath):i.warn(`[SidePanel] local prototypefiledelete failed:`,e?.error)}),Hc()}catch(e){i.error(`[SidePanel] delete prototype failed:`,e),alert(r(`uiProto.deleteFailed`,{message:e.message}))}}function Yc(e,t,n=r(`common.confirm`)){return new Promise(r=>{let i=document.getElementById(`genericConfirmModal`),a=document.getElementById(`genericConfirmTitle`),o=document.getElementById(`genericConfirmMessage`),s=document.getElementById(`genericConfirmOkBtn`),c=document.getElementById(`genericConfirmCancelBtn`);if(!i){r(confirm(t));return}a.textContent=e,o.textContent=t,s.textContent=n;let l=()=>{i.classList.remove(`show`),s.removeEventListener(`click`,u),c.removeEventListener(`click`,d)},u=()=>{l(),r(!0)},d=()=>{l(),r(!1)};s.addEventListener(`click`,u),c.addEventListener(`click`,d),i.classList.add(`show`)})}function Xc(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function Zc(e){if(!e)return``;let t=new Date(e),n=new Date-t;return n<6e4?r(`uiProto.justNow`):n<36e5?r(`uiProto.minutesAgo`,{count:Math.floor(n/6e4)}):n<864e5?r(`uiProto.hoursAgo`,{count:Math.floor(n/36e5)}):t.toLocaleDateString(`zh-CN`)}function Qc(e){Ac=Math.max(jc,Math.min(Mc,e)),Ac=Math.round(Ac*100)/100;let t=document.getElementById(`prototypeIframe`),n=document.getElementById(`prototypeZoomLevel`);t&&(t.style.zoom=Ac),n&&(n.textContent=Math.round(Ac*100)+`%`,Ac===1?n.classList.remove(`zoomed`):n.classList.add(`zoomed`))}function $c(){Qc(Ac+Nc),nl()}function el(){Qc(Ac-Nc),nl()}function tl(){Qc(1)}function nl(){let e=document.getElementById(`prototypeZoomLevel`);e&&(e.classList.add(`flash`),setTimeout(()=>e.classList.remove(`flash`),150))}function rl(e){!e.ctrlKey&&!e.metaKey||(e.preventDefault(),e.deltaY<0?$c():el())}function il(e){(e.ctrlKey||e.metaKey)&&e.key===`0`&&(e.preventDefault(),tl())}function al(){let e=document.getElementById(`prototypeCloseBtn`);e&&e.addEventListener(`click`,Ic);let t=document.getElementById(`prototypeDownloadBtn`);t&&t.addEventListener(`click`,Rc);let n=document.getElementById(`prototypeOpenTabBtn`);n&&n.addEventListener(`click`,zc);let r=document.getElementById(`prototypeLocalOpenBtn`);r&&r.addEventListener(`click`,()=>{let e=r.dataset.path;e&&chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:e},e=>{e?.success||i.error(`[SidePanel] local browseropen failed:`,e?.error)})});let a=document.getElementById(`prototypeContinueBtn`);a&&a.addEventListener(`click`,Lc);let o=document.getElementById(`prototypeZoomInBtn`);o&&o.addEventListener(`click`,$c);let s=document.getElementById(`prototypeZoomOutBtn`);s&&s.addEventListener(`click`,el);let c=document.getElementById(`prototypeZoomLevel`);c&&c.addEventListener(`click`,tl);let l=document.getElementById(`prototypeContent`);l&&l.addEventListener(`wheel`,rl,{passive:!1}),document.addEventListener(`keydown`,il);let u=document.getElementById(`prototypeLibraryCloseBtn`);u&&u.addEventListener(`click`,Gc),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_UI_PROTOTYPE`&&(i.debug(`[SidePanel] received showprototyperequested :`,e),e.data.localOpened?i.debug(`[SidePanel] prototype inagent-side browseropen,skip popup`):e.data.isRemoteAgent?(i.debug(`[SidePanel] remoteagent,will use browserlabelpageautoopenprototype`),Vc(e.data.prototypeId)):Bc(e.data.prototypeId),n({success:!0}))}),i.debug(`[SidePanel] UI prototype moduleeventinitializing`)}var ol={enabled:!1,thresholdRatio:.85,minPending:4,maxFailures:2};function sl(e,t){let n=Number(e);return Number.isFinite(n)&&n>0&&n<=1?n:t}function cl(e,t){let n=Number(e);return Number.isFinite(n)&&n>=0?Math.floor(n):t}function ll({enabled:e,ratio:t,thresholdRatio:n,pendingCount:r,minPending:i,isGenerating:a,isolateChat:o}={}){if(!e||a||!o)return!1;let s=sl(n,ol.thresholdRatio),c=cl(i,ol.minPending);return!Number.isFinite(t)||t<s?!1:cl(r,0)>=c}function ul(e){let t=e?.messageHistory||[],n=e?.activeCompaction?.upToMessageId;if(!n)return t.length;let r=t.findIndex(e=>e.messageId===n);return r===-1?t.length:t.length-r-1}var dl=0;function fl(){dl=0}async function pl({state:e,getRatio:t,compact:n}={}){let r=e?.chatConfig||{},a=r.autoCompaction===!0;if(!a)return{attempted:!1,success:!1,reason:`disabled`};if(dl>=ol.maxFailures)return{attempted:!1,success:!1,reason:`backoff`};let o;try{o=Number(t?t():NaN)}catch(e){return i.warn(`[AutoCompaction] usage compute failed, send continues:`,e?.message),{attempted:!1,success:!1,reason:`usage_unavailable`}}let s=ul(e);if(!ll({enabled:a,ratio:o,thresholdRatio:r.autoCompactionThreshold,pendingCount:s,isGenerating:!!e?.isGenerating,isolateChat:!!e?.isolateChat}))return{attempted:!1,success:!1,reason:`not_needed`};i.debug(`[AutoCompaction] triggered`,{ratio:o,pendingCount:s});let c=null;try{c=await n({silent:!0})}catch(e){return i.warn(`[AutoCompaction] compact threw, send continues:`,e?.message),dl++,{attempted:!0,success:!1,reason:`exception`}}return c?.success?(fl(),{attempted:!0,success:!0}):(dl++,i.debug(`[AutoCompaction] skipped send:`,c?.reason),{attempted:!0,success:!1,reason:c?.reason||`failed`})}var ml=null,hl=`global`,gl=new Map;function _l(){try{chrome.windows?.getCurrent?.().then?.(e=>{e?.id!=null&&(ml=e.id)}).catch?.(e=>{i.debug(`[PanelContext] query current window failed:`,e?.message)})}catch(e){i.debug(`[PanelContext] init window query failed:`,e?.message)}try{chrome.storage?.local?.get?.([`sidePanelScope`],e=>{hl=e?.sidePanelScope===`tab-specific`?`tab-specific`:`global`}),chrome.storage?.onChanged?.addListener?.((e,t)=>{t!==`local`||!e?.sidePanelScope||(hl=e.sidePanelScope.newValue===`tab-specific`?`tab-specific`:`global`)})}catch(e){i.debug(`[PanelContext] init scope mirror failed:`,e?.message)}}function vl(){return ml}function yl(e){e&&typeof C.currentTabId==`number`&&gl.set(e,C.currentTabId)}function bl(e,t){e&&(typeof t==`number`?gl.set(e,t):gl.delete(e))}function xl(e){if(!e)return null;let t=gl.get(e);return typeof t==`number`?t:null}function Sl(e){let t=null;try{t=typeof document<`u`?!!document.hidden:null}catch{}return{windowId:ml,hostTabId:xl(e),scope:hl,panelHidden:t}}var Cl=0,wl=500,Tl=[{frequency:523.25,startTime:0,duration:.12,type:`sine`,gain:.3},{frequency:659.25,startTime:.09,duration:.12,type:`sine`,gain:.3},{frequency:783.99,startTime:.18,duration:.22,type:`sine`,gain:.35}],El=[{frequency:440,startTime:0,duration:.16,type:`square`,gain:.22},{frequency:349.23,startTime:.14,duration:.3,type:`square`,gain:.22}],Dl=[`#FF3B30`,`#FF9500`,`#FFCC00`,`#34C759`,`#00C7BE`,`#007AFF`,`#AF52DE`,`#FF2D55`],Ol=120,kl=4e3,Al=600,jl=1e3,Ml=.25,Nl=.99,Pl=.3,Fl=.6,Il=9999;function Ll(){return new Promise(e=>{try{chrome.storage.local.get([`completionSoundEnabled`,`completionConfettiEnabled`],t=>{e({soundEnabled:t?.completionSoundEnabled!==!1,confettiEnabled:t?.completionConfettiEnabled!==!1})})}catch(t){i.debug(`[CompletionFeedback] read config failed, use defaults:`,t?.message),e({soundEnabled:!0,confettiEnabled:!0})}})}function Rl(e){try{let t=window.AudioContext||window.webkitAudioContext;if(!t){i.debug(`[CompletionFeedback] AudioContext unavailable`);return}let n=new t;n.state===`suspended`&&typeof n.resume==`function`&&n.resume().catch(()=>{});let r=n.currentTime,a=0;for(let t of e){let e=n.createOscillator(),i=n.createGain();e.type=t.type||`sine`,e.frequency.value=t.frequency;let o=r+t.startTime,s=o+t.duration;i.gain.setValueAtTime(1e-4,o),i.gain.exponentialRampToValueAtTime(t.gain,o+.012),i.gain.exponentialRampToValueAtTime(1e-4,s),e.connect(i),i.connect(n.destination),e.start(o),e.stop(s+.02),s>a&&(a=s)}let o=Math.max(0,(a-r)*1e3)+200;setTimeout(()=>{try{n.close()}catch{}},o)}catch(e){i.debug(`[CompletionFeedback] play tone failed:`,e?.message)}}function zl(){Rl(Tl),i.debug(`[CompletionFeedback] success sound played`)}function Bl(){Rl(El),i.debug(`[CompletionFeedback] failure sound played`)}function Vl(){try{return typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{return!1}}function Hl(){try{if(!document.body)return;let e=window.innerWidth,t=window.innerHeight;if(e<=0||t<=0)return;let n=document.createElement(`canvas`);n.style.cssText=`position:fixed;inset:0;pointer-events:none;z-index:${Il};`;let r=window.devicePixelRatio||1;n.width=Math.floor(e*r),n.height=Math.floor(t*r),n.style.width=e+`px`,n.style.height=t+`px`,document.body.appendChild(n);let a=n.getContext(`2d`);if(!a){n.remove();return}a.scale(r,r);let o=[{x:e*.15,y:t+10,baseAngle:-Math.PI/2+Pl},{x:e*.85,y:t+10,baseAngle:-Math.PI/2-Pl}],s=[],c=0,l=0,u=performance.now(),d=e=>{let t=Math.min(Ol,Math.floor(Math.min(e,Al)/Al*Ol));for(;c<t;){let e=o[c%o.length],t=e.baseAngle+(Math.random()-.5)*Fl,n=12+Math.random()*8,r=4+Math.random()*4;s.push({x:e.x+(Math.random()-.5)*20,y:e.y,vx:Math.cos(t)*n,vy:Math.sin(t)*n,size:r,color:Dl[Math.floor(Math.random()*Dl.length)],rotation:Math.random()*Math.PI*2,rotationSpeed:(Math.random()-.5)*.3,shape:Math.random()<.5?`rect`:`circle`}),c++}},f=r=>{let i=r-u;if(i>=kl){cancelAnimationFrame(l),n.remove();return}d(i),a.clearRect(0,0,e,t);let o=kl-jl,c=i>o?Math.max(0,1-(i-o)/jl):1;for(let n=s.length-1;n>=0;n--){let r=s[n];if(r.vy+=Ml,r.vx*=Nl,r.vy*=Nl,r.x+=r.vx,r.y+=r.vy,r.rotation+=r.rotationSpeed,r.y-r.size>t||r.x+r.size<0||r.x-r.size>e){s.splice(n,1);continue}a.save(),a.globalAlpha=c,a.translate(r.x,r.y),a.rotate(r.rotation),a.fillStyle=r.color,r.shape===`rect`?a.fillRect(-r.size/2,-r.size/2,r.size,r.size*.6):(a.beginPath(),a.arc(0,0,r.size/2,0,Math.PI*2),a.fill()),a.restore()}l=requestAnimationFrame(f)};l=requestAnimationFrame(f),i.debug(`[CompletionFeedback] confetti launched`)}catch(e){i.debug(`[CompletionFeedback] launch confetti failed:`,e?.message)}}function Ul(e,t,n,r){try{chrome.runtime.sendMessage({type:`TASK_FEEDBACK_NOTIFY`,success:e,sessionId:t||null,error:n||``,question:r||``,panel:Sl(t)})?.catch?.(()=>{})}catch(e){i.debug(`[CompletionFeedback] desktop notify failed:`,e?.message)}}async function Wl(e=null,t=``){try{let n=Date.now();if(n-Cl<wl){i.debug(`[CompletionFeedback] throttled, skip`);return}Cl=n;let{soundEnabled:r,confettiEnabled:a}=await Ll();r&&zl(),a&&!Vl()&&Hl(),Ul(!0,e,``,t)}catch(e){i.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}async function Gl(e=null,t=``,n=``){try{let r=Date.now();if(r-Cl<wl){i.debug(`[CompletionFeedback] throttled, skip`);return}Cl=r;let{soundEnabled:a}=await Ll();a&&Bl(),Ul(!1,e,t,n)}catch(e){i.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}var Kl=new Set;function ql(e){return typeof e==`function`?(Kl.add(e),()=>Kl.delete(e)):()=>{}}function Jl(e){let t=e||C.activeSessionId;if(t){C.generatingSessionIds.delete(t);try{gi(t)}catch(e){i.warn(`[GenerationLifecycle] markSessionCompleted failed:`,e?.message)}typeof document<`u`&&typeof CustomEvent==`function`&&(document.dispatchEvent(new CustomEvent(`generating-state-changed`)),document.dispatchEvent(new CustomEvent(`generation-ended`,{detail:{sessionId:t}})));for(let e of Kl)try{e(t)}catch(e){i.error(`[GenerationLifecycle] end handler failed:`,e?.message)}}}function Yl(e){let t=Number(e);return!Number.isFinite(t)||t<=0?3:Math.min(20,Math.max(1,Math.round(t)))}function Xl(){return{callId:null,carried:0,lastIteration:null}}function Zl(e){let t=0;for(let n of e||[]){let e=Number(n&&n.iteration);Number.isFinite(e)&&e>t&&(t=e)}return t}function Ql(e){let{tracker:t,callId:n=null,iteration:r,everyN:i,enabled:a=!0,hasCandidate:o=!0}=e||{},s=t&&typeof t==`object`?{callId:t.callId??null,carried:Number(t.carried)||0,lastIteration:t.lastIteration??null}:Xl(),c=Number(r);if(!Number.isFinite(c)||c<=0)return{carry:!1,reason:`invalid_iteration`,tracker:s};let l=!!n&&!!s.callId&&n!==s.callId,u=s.lastIteration!=null&&c<s.lastIteration;if((l||u)&&(s=Xl()),n&&!s.callId&&(s={...s,callId:n}),!a)return{carry:!1,reason:`disabled`,tracker:s};if(c<2)return{carry:!1,reason:`too_early`,tracker:s};if(!o)return{carry:!1,reason:`no_candidate`,tracker:s};if(s.carried>=3)return{carry:!1,reason:`call_limit`,tracker:s};let d=Yl(i);return s.lastIteration!=null&&c-s.lastIteration<d?{carry:!1,reason:`interval_not_reached`,tracker:s}:{carry:!0,reason:`carry`,tracker:{callId:s.callId||n||null,carried:s.carried,lastIteration:c}}}function $l(e,{callId:t=null}={}){let n=e&&typeof e==`object`?e:Xl();return t&&n.callId&&t!==n.callId?n:{...n,carried:(Number(n.carried)||0)+1}}var eu=/[\p{P}\p{S}]/gu;function tu(e){return Array.isArray(e)?e.map(e=>e&&e.text||``).join(``):``}function nu(e){return String(e||``).replace(/[\s\u3000]/g,``).replace(eu,``)}function ru(e,t){if(!Array.isArray(e))return e;let n=t&&t.id,r=t&&typeof t.text==`string`?t.text:null;if(r===null||typeof n!=`number`)return e;let i=!1,a=e.map(e=>!e||e.id!==n||e.state===`locked`?e:(i=!0,{...e,text:r}));return i?a:e}function iu(e,t,n){let r=String(t||``),i=String(n||``),a={lockedIds:[],shift:0,items:e,len:r.length};if(r===i||!Array.isArray(e)||e.length===0)return a;let o=0,s=Math.min(r.length,i.length);for(;o<s&&r[o]===i[o];)o++;let c=0,l=Math.min(r.length-o,i.length-o);for(;c<l&&r[r.length-1-c]===i[i.length-1-c];)c++;let u=o,d=r.length-c;if(u>=r.length&&d>=r.length){let t=e[e.length-1],n=t&&t.text?t.text.length:0,a=i.slice(Math.max(0,r.length-n)),o=e.map((t,n)=>n===e.length-1?{...t,text:a}:t);return{lockedIds:[t.id],shift:0,items:o,len:i.length}}let f=[],p=0;for(let t of e){let e=(t&&t.text?t.text:``).length;u<p+e&&d>p&&f.push(t.id),p+=e}if(f.length===0)return{lockedIds:[],shift:u===0?i.length-r.length:0,items:e,len:r.length};let m=i.length-r.length,h=d+m,g=e=>e<=u?e:e>=d?e+m:u+Math.min(e-u,Math.max(0,h-u)),_=0;return{lockedIds:f,shift:0,items:e.map(e=>{let t=(e&&e.text?e.text:``).length,n=g(_),r=g(_+t);return _+=t,{...e,text:i.slice(n,r)}}),len:i.length}}function au(e,t){if(!Array.isArray(e)||e.length===0)return{items:Array.isArray(e)?e:[],changed:0,takeAll:!1};let n=tu(e),r=String(t||``);if(!r)return{items:e,changed:0,takeAll:!1};let i=nu(n),a=nu(r);if(i===a)return{items:e,changed:0,takeAll:!1};if(Math.abs(i.length-a.length)+ou(i,a)>2||i.length!==a.length)return e.some(e=>e&&e.state===`locked`)?{items:e,changed:0,takeAll:!1}:{items:[{id:e[0]&&typeof e[0].id==`number`?e[0].id:null,text:r,state:`refined`}],changed:1,takeAll:!0};let o=n.split(``),s=0,c=0;for(let e=0;e<o.length;e++)nu(o[e])!==``&&(s<a.length&&o[e]!==a[s]&&(o[e]=a[s],c+=1),s+=1);if(c===0)return{items:e,changed:0,takeAll:!1};let l=o.join(``),u=0;return{items:e.map(e=>{let t=(e&&e.text?e.text:``).length,n=e&&e.state===`locked`?e.text:l.slice(u,u+t);return u+=t,e&&e.state===`locked`?e:{...e,text:n}}),changed:c,takeAll:!1}}function ou(e,t){if(e.length!==t.length)return 2**53-1;let n=0;for(let r=0;r<e.length;r++)e[r]!==t[r]&&(n+=1);return n}n(`zh`,{voice:{start:`语音输入(开始录音)`,stop:`结束录音并转写`,recording:`正在录音`,listening:`正在聆听…`,transcribing:`正在转写…`,cancel:`取消录音`,done:`完成`,noSpeech:`没有听到声音`,noResult:`未识别到语音`,micDenied:`麦克风未授权`,micDeniedHelp:`侧边栏里浏览器不会弹授权框,请到配置页「语音输入 → 麦克风权限」授权一次`,micDeniedAction:`去授权`,micDeniedActionTitle:`打开配置页授权麦克风(侧边栏内无法弹出授权框)`,unavailable:`语音功能不可用`,modelMissing:`缺少语音模型`,modelMissingHelp:`请在配置页「语音」Tab 中导入模型包`,busy:`有语音任务正在进行`,failed:`语音识别失败`,connectionLost:`连接中断`,tooShort:`录音太短`,maxDuration:`已达单次录音时长上限,正在转写…`,unsupported:`当前浏览器不支持录音`,keyRightAlt:`右侧 Alt`,keyRightCtrl:`右侧 Ctrl`,btnTitle:`语音输入({keys})`,deviceFallback:`原麦克风不可用,已改用系统默认`,refineListening:`正在听…(已定稿 {n} 句)`,refineCorrecting:`正在校正…`,refineCorrected:`已校正 {n} 处`,refineDegraded:`本机性能有限,已关闭逐句精修(松手后仍会整体校正)`}}),n(`en`,{voice:{start:`Voice input (start recording)`,stop:`Stop and transcribe`,recording:`Recording`,listening:`Listening…`,transcribing:`Transcribing…`,cancel:`Cancel recording`,done:`Done`,noSpeech:`No sound detected`,noResult:`No speech recognised`,micDenied:`Microphone not granted`,micDeniedHelp:`The browser cannot prompt inside the side panel — grant it once in Options → Voice Input → Microphone permission`,micDeniedAction:`Grant access`,micDeniedActionTitle:`Open options to grant microphone access (the side panel cannot show the prompt)`,unavailable:`Voice input unavailable`,modelMissing:`Speech model missing`,modelMissingHelp:`Import a model pack in the Options "Voice" tab`,busy:`Another voice task is running`,failed:`Speech recognition failed`,connectionLost:`Connection lost`,tooShort:`Recording too short`,maxDuration:`Recording length limit reached, transcribing…`,unsupported:`Recording is not supported in this browser`,keyRightAlt:`Right Alt`,keyRightCtrl:`Right Ctrl`,btnTitle:`Voice input ({keys})`,deviceFallback:`Selected microphone unavailable — using the system default`,refineListening:`Listening… ({n} sentences finalized)`,refineCorrecting:`Refining…`,refineCorrected:`{n} correction(s) applied`,refineDegraded:`This machine is too slow for per-sentence refinement (the final pass still runs)`}});var su=15e3,cu=16e3,lu=2500,uu=.008,du=350,fu=24,H={input:null,btn:null,bar:null,wave:null,timerEl:null,statusEl:null,permBtn:null,barEls:[],status:null,armed:!1,phase:`idle`,port:null,stream:null,ctx:null,node:null,source:null,startedAt:0,timer:null,silentSince:0,silenceWarned:!1,draft:null,lastText:``,appliedText:``,appliedValue:``,openText:``,mute:null,programmatic:!1,draftSupported:!0,finishWaitTimer:null,adjustInputHeight:null,shortcutCfg:{...Ne},shortcutTrigger:null,shortcutBound:!1,deviceFellBack:!1};function pu(e){return typeof e==`string`?e:``}function mu(e){let t=Math.max(0,Math.floor(e/1e3));return`${String(Math.floor(t/60)).padStart(2,`0`)}:${String(t%60).padStart(2,`0`)}`}function hu(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode.apply(null,t.subarray(e,e+r));return btoa(n)}function gu(e,t,n){if(t===n)return e;let r=t/n,i=Math.floor(e.length/r),a=new Float32Array(i);for(let t=0;t<i;t++){let n=t*r,i=Math.floor(n),o=n-i,s=e[i]||0;a[t]=s+((e[i+1]===void 0?s:e[i+1])-s)*o}return a}function _u(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++){let r=e[n]<-1?-1:e[n]>1?1:e[n];t[n]=r<0?r*32768:r*32767}return t}async function vu(e=!1){try{let t=await chrome.runtime.sendMessage({type:`ASR_GET_STATUS`,force:e});if(t&&t.success&&t.status)return H.status=t.status,H.status}catch(e){i.debug(`[Voice] status fetch failed:`,e?.message||e)}return H.status=null,null}function yu(e){return!e||e.success===!1?!1:typeof e.available==`boolean`?e.available:e.deps?.ready===!0&&e.modelsReady===!0&&e.enabled===!0}function bu({value:e,draft:t,text:n,caret:r,canReplace:i=!0}){let a=typeof e==`string`?e:``;if(!t)return{value:a,caret:a.length,len:0};if(!i){let e=typeof r==`number`?Math.min(Math.max(0,r),a.length):a.length;return{value:a.slice(0,e)+n+a.slice(e),caret:e+n.length,len:0}}let o=Math.min(Math.max(0,t.start),a.length),s=Math.min(Math.max(o,t.start+t.len),a.length);return{value:a.slice(0,o)+n+a.slice(s),caret:o+n.length,len:n.length}}function xu({value:e,draft:t,canReplace:n=!0}){let r=typeof e==`string`?e:``;if(!t||!n||t.len<=0)return{value:r,caret:r.length};let i=Math.min(Math.max(0,t.start),r.length),a=Math.min(Math.max(i,t.start+t.len),r.length);return{value:r.slice(0,i)+r.slice(a),caret:i}}function Su(e){return!e||e.isComposing||e.repeat?!1:e.altKey===!0&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyV`}async function Cu(){return H.armed=yu(await vu()),H.btn&&(H.btn.style.display=H.armed?``:`none`),!H.armed&&H.phase!==`idle`&&ed({rollback:!0}),H.armed}function wu(){if(!H.draft||!H.input)return;let e=tu(H.draft.items),t=H.input.value,n=pu(H.appliedValue),r=H.draft.start,i=r+e.length,a=0;for(;a<n.length&&a<t.length&&n[a]===t[a];)a+=1;let o=0,s=Math.min(n.length-a,t.length-a);for(;o<s&&n[n.length-1-o]===t[t.length-1-o];)o+=1;let c=a;if(n.length-o<=r){H.draft.start=Math.max(0,r+(t.length-n.length));return}if(c>i)return;let l=Math.max(0,n.length-i),u=t.slice(r,Math.max(r,t.length-l)),d=iu(H.draft.items,e,u);d.shift&&(H.draft.start+=d.shift),d.lockedIds.length!==0&&(H.draft.items=d.items.map(e=>d.lockedIds.includes(e.id)?{...e,state:`locked`}:e),H.draft.len=d.len)}function Tu(){let e=H.input;if(!e)return{start:0,len:0,items:[]};let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length,n=typeof e.selectionEnd==`number`?e.selectionEnd:t;return t!==n&&e.setRangeText(``,t,n,`end`),{start:t,len:0,items:[]}}function Eu(e,t){let n=pu(e),r=pu(t);return r?n?r.startsWith(n)?r.slice(n.length):null:r:``}function Du(e,t){let n=H.input;if(n){H.programmatic=!0,H.appliedValue=e,n.value=e;try{n.setSelectionRange(t,t)}catch{}H.programmatic=!1;try{document.dispatchEvent(new CustomEvent(`voice-draft-written`))}catch{}try{H.adjustInputHeight?.()}catch{}try{n.focus()}catch{}}}function Ou(e=!1){let t=H.input;if(!t||!H.draft)return;let n=tu(H.draft.items);if(!e&&n===pu(H.appliedText))return;let r=typeof t.selectionStart==`number`?t.selectionStart:void 0,i=H.draft.start,a=i+H.draft.len,o=bu({value:t.value,draft:{start:i,len:H.draft.len},text:n,caret:r,canReplace:H.draftSupported});typeof r==`number`&&r>i&&r<a&&(o.caret=i+Math.min(r-i,n.length)),H.draft.len=n.length,H.appliedText=n,Du(o.value,o.caret)}function ku(e){if(!H.input||!H.draft)return;let t=Array.isArray(H.draft.items)?H.draft.items:[],n=t.findIndex(e=>e.id===null),r=pu(e);if(n>=0&&t[n].state===`locked`){let e=Eu(H.openText,r);if(H.openText=r,!e)return;H.draft.items=t.map((t,r)=>r===n?{...t,text:t.text+e}:t)}else H.openText=r,H.draft.items=n>=0?t.map((e,t)=>t===n?{...e,text:r}:e):t.concat([{id:null,text:r,state:`draft`}]);Ou()}function Au(){let e=H.input;if(!e||!H.draft)return;let t=Array.isArray(H.draft.items)&&H.draft.items.some(e=>e.state===`locked`)?{value:e.value,caret:e.value.length}:xu({value:e.value,draft:H.draft,canReplace:H.draftSupported});if(t.value!==e.value){H.programmatic=!0,H.appliedValue=t.value,e.value=t.value;let n=Math.min(t.caret,e.value.length);try{e.setSelectionRange(n,n)}catch{}H.programmatic=!1;try{H.adjustInputHeight?.()}catch{}}H.draft=null,H.lastText=``,H.appliedText=``,H.openText=``}function ju(){if(H.wave){H.wave.textContent=``,H.barEls=[];for(let e=0;e<fu;e++){let e=document.createElement(`i`);H.wave.appendChild(e),H.barEls.push(e)}}}function Mu(e,t=``){H.statusEl&&(H.statusEl.textContent=e,H.statusEl.className=`voice-recorder-status`+(t?` is-${t}`:``))}function Nu(){H.bar&&(H.bar.classList.add(`show`),H.bar.removeAttribute(`aria-hidden`))}function Pu(e){H.permBtn&&(H.permBtn.style.display=e?``:`none`)}function Fu(){let e=document.activeElement;if(!(!H.bar||!e||!H.bar.contains(e))){if(H.input&&typeof H.input.focus==`function`)try{H.input.focus({preventScroll:!0});return}catch{}try{e.blur()}catch{}}}function Iu(){H.bar&&(typeof document>`u`||!document.body||(Fu(),Pu(!1),H.bar.classList.remove(`show`),H.bar.setAttribute(`aria-hidden`,`true`),H.barEls.forEach(e=>{e.style.height=``,e.style.opacity=``}),H.timerEl&&(H.timerEl.textContent=`00:00`)))}function Lu(e){if(!H.barEls.length)return;let t=Math.min(1,Math.sqrt(Math.max(0,e))*6);for(let e=0;e<H.barEls.length-1;e++)H.barEls[e].style.height=H.barEls[e+1].style.height,H.barEls[e].style.opacity=H.barEls[e+1].style.opacity;let n=H.barEls[H.barEls.length-1];n.style.height=`${Math.max(2,Math.round(t*18))}px`,n.style.opacity=t>.06?`1`:`0.35`}function Ru(e){H.btn&&(H.btn.classList.toggle(`recording`,e),H.btn.setAttribute(`aria-pressed`,e?`true`:`false`),H.btn.setAttribute(`aria-label`,r(e?`voice.stop`:`voice.start`)),H.btn.title=r(e?`voice.stop`:`voice.start`))}function zu(e){document.body?.classList.toggle(`voice-recording-active`,!!e)}function Bu(){if(H.port)return H.port;try{let e=chrome.runtime.connect({name:`asr`});return e.onMessage.addListener(nd),e.onDisconnect.addListener(()=>{H.port=null,(H.phase===`recording`||H.phase===`finalizing`)&&(Yu(),Xu(),H.draft=null,H.lastText=``,Ru(!1),zu(!1),Mu(r(`voice.connectionLost`),`warn`),setTimeout(()=>{H.phase===`idle`&&Iu()},3500))}),H.port=e,e}catch(e){return i.warn(`[Voice] connect port failed:`,e?.message||e),null}}function Vu(e,t){if(Lu(t),Hu(t),H.port)try{H.port.postMessage({type:`audio`,data:hu(e)})}catch(e){i.debug(`[Voice] post audio failed:`,e?.message||e)}}function Hu(e){if(H.phase!==`recording`&&H.phase!==`starting`)return;if(e>=uu){H.silentSince=0,H.silenceWarned&&(H.silenceWarned=!1,Mu(r(`voice.listening`)));return}let t=Date.now();if(!H.silentSince){H.silentSince=t;return}H.silenceWarned||t-H.silentSince>=lu&&(H.silenceWarned=!0,Mu(r(`voice.noSpeech`),`warn`))}var Uu=[`voice-capture-worklet.js`,`dist/voice-capture-worklet.js`],Wu;async function Gu(){if(Wu!==void 0)return Wu;for(let e of Uu){let t=``;try{t=chrome.runtime.getURL(e)}catch{continue}try{let e=await fetch(t);if(e&&e.ok)return Wu=t,t}catch{}}return Wu=null,null}async function Ku(e,t){let n=await Gu();if(!n)throw Error(`worklet not found in extension`);await e.audioWorklet.addModule(n);let r=new AudioWorkletNode(e,`voice-capture`),i=Math.abs(e.sampleRate-cu)>1;r.port.onmessage=t=>{let n=t.data;if(!n||n.type!==`chunk`||!n.pcm)return;let r=new Int16Array(n.pcm);if(i){let t=new Float32Array(r.length);for(let e=0;e<r.length;e++)t[e]=r[e]/32768;r=_u(gu(t,e.sampleRate,cu))}Vu(r,n.rms||0)},t.connect(r),H.node=r}function qu(e,t){let n=e.createScriptProcessor(4096,1,1),r=Math.abs(e.sampleRate-cu)>1;n.onaudioprocess=t=>{let n=t.inputBuffer.getChannelData(0),i=new Float32Array(n);r&&(i=gu(i,e.sampleRate,cu));let a=0;for(let e=0;e<i.length;e++)a+=i[e]*i[e];Vu(_u(i),Math.sqrt(a/Math.max(1,i.length)))},t.connect(n);let i=e.createGain();i.gain.value=0,n.connect(i),i.connect(e.destination),H.mute=i,H.node=n}async function Ju(){if(!navigator.mediaDevices?.getUserMedia)throw Mu(r(`voice.unsupported`),`warn`),Error(`unsupported`);let e=await ot(await nt());H.stream=e.stream,H.deviceFellBack=e.fellBack===!0;let t=window.AudioContext||window.webkitAudioContext,n;try{n=new t({sampleRate:cu})}catch{n=new t}if(n.state===`suspended`)try{await n.resume()}catch{}H.ctx=n;let a=n.createMediaStreamSource(e.stream);H.source=a;try{await Ku(n,a)}catch(e){i.warn(`[Voice] worklet unavailable, fallback to ScriptProcessor:`,e?.message||e),qu(n,a)}}function Yu(){H.timer&&=(clearInterval(H.timer),null);try{H.node?.port?.close?.()}catch{}try{H.node?.disconnect?.()}catch{}try{H.mute?.disconnect?.()}catch{}try{H.source?.disconnect?.()}catch{}try{H.stream?.getTracks?.().forEach(e=>e.stop())}catch{}try{H.ctx?.close?.()}catch{}H.node=null,H.mute=null,H.source=null,H.stream=null,H.ctx=null}function Xu(){H.finishWaitTimer&&=(clearTimeout(H.finishWaitTimer),null),H.phase=`idle`}function Zu(){let e=()=>{let e=Date.now()-H.startedAt;H.timerEl&&(H.timerEl.textContent=mu(e));let t=H.status;e>=(t&&t.maxRecordingMs||300*1e3)&&$u(`stop`)};H.timer&&clearInterval(H.timer),H.timer=setInterval(e,200),e()}async function Qu(e={}){if(H.phase!==`idle`||!H.armed&&!e.force&&(await Cu(),!H.armed||H.phase!==`idle`))return!1;H.phase=`starting`,H.lastText=``,H.appliedText=``,H.openText=``,H.draft=Tu(),H.appliedValue=H.input?H.input.value:``,H.draftSupported=!0,H.silentSince=0,H.silenceWarned=!1,Nu(),Mu(r(`voice.listening`)),Ru(!0),zu(!0);let t=Bu();if(!t)return Mu(r(`voice.failed`),`warn`),Xu(),Ru(!1),zu(!1),!1;try{await Ju()}catch(e){if(H.phase!==`starting`)return Yu(),!1;let n=e?.name||``,i=n===`NotAllowedError`||n===`SecurityError`;i?(Mu(r(`voice.micDenied`),`warn`),Pu(!0)):Mu(r(`voice.failed`),`warn`),Yu(),Xu(),Ru(!1),zu(!1);try{t.postMessage({type:`cancel`})}catch{}return setTimeout(()=>{H.phase===`idle`&&Iu()},i?12e3:4e3),!1}if(H.phase!==`starting`)return Yu(),!1;H.startedAt=Date.now(),H.phase=`recording`,Mu(r(`voice.listening`)),H.deviceFellBack&&(H.deviceFellBack=!1,Mu(r(`voice.deviceFallback`),`warn`),setTimeout(()=>{H.phase===`recording`&&Mu(r(`voice.listening`))},4e3)),Zu();try{t.postMessage({type:`start`,language:H.status&&H.status.language||`auto`})}catch(e){i.debug(`[Voice] post start failed:`,e?.message||e)}return!0}function $u(e){if(H.phase!==`recording`)return;H.phase=`finalizing`;let t=Date.now()-H.startedAt;if(Yu(),Ru(!1),zu(!1),e===`cancel`){try{H.port?.postMessage({type:`cancel`})}catch{}Au(),Xu(),Iu();return}if(t<du&&!H.lastText){try{H.port?.postMessage({type:`cancel`})}catch{}Au(),Mu(r(`voice.tooShort`),`warn`),Xu(),setTimeout(()=>{H.phase===`idle`&&Iu()},2200);return}Mu(r(`voice.transcribing`));try{H.port?.postMessage({type:`stop`})}catch{}H.finishWaitTimer&&clearTimeout(H.finishWaitTimer),H.finishWaitTimer=setTimeout(()=>{H.phase===`finalizing`&&td(H.lastText,{fallback:!0})},6e4)}function ed({rollback:e=!0}={}){if(H.phase===`idle`)return!1;let t=H.phase===`recording`||H.phase===`finalizing`;if(H.phase=`finalizing`,Yu(),t)try{H.port?.postMessage({type:`cancel`})}catch{}return e&&Au(),Xu(),Ru(!1),zu(!1),Iu(),!0}function td(e,t={}){let n=pu(e).trim();if(!n){Au(),Mu(r(`voice.noResult`),`warn`),Xu(),setTimeout(()=>{H.phase===`idle`&&Iu()},2200);return}if(!H.draft){let e=H.input;if(e){let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length;Du(e.value.slice(0,t)+n+e.value.slice(t),t+n.length)}Mu(r(`voice.done`)),Xu(),setTimeout(()=>{H.phase===`idle`&&Iu()},1200);return}let a=Array.isArray(t.texts)?t.texts.filter(e=>typeof e==`string`&&e.trim()):[];a.length>1&&!H.draft.items.some(e=>e.id!==null||e.state===`locked`)&&(H.draft.items=a.map((e,t)=>({id:t+1,text:e,state:`refined`}))),H.draft.items.length===0&&(H.draft.items=[{id:null,text:n,state:`refined`}]);let{items:o,changed:s,takeAll:c}=au(H.draft.items,n);H.draft.items=o,Ou(!0),c&&i.debug(`[Voice] final text took over the whole draft`),H.draft=null,H.lastText=``,H.appliedText=``,H.openText=``,Xu(),Mu(s>0?r(`voice.refineCorrected`,{n:s}):r(`voice.done`)),setTimeout(()=>{H.phase===`idle`&&Iu()},s>0?1800:1200)}function nd(e){if(!(!e||typeof e.type!=`string`)){if(e.type===`ready`){e.draft===!1&&H.phase===`recording`&&i.debug(`[Voice] online model missing, draft disabled`);return}if(e.type===`partial`){if(H.phase!==`recording`&&H.phase!==`finalizing`)return;H.lastText=pu(e.text),ku(typeof e.open==`string`?e.open:H.lastText);return}if(e.type===`endpoint`)return H.phase!==`recording`&&H.phase,void 0;if(e.type===`sentence`){if(H.phase!==`recording`&&H.phase!==`finalizing`||!H.draft||typeof e.id!=`number`)return;let t=typeof e.refined==`string`&&e.refined?e.refined:null,n=Array.isArray(H.draft.items)?H.draft.items:[],i=n.findIndex(e=>e.id===null),a=n;if(!t&&i>=0){let t=n[i];a=n.map((n,r)=>r===i?t.state===`locked`?{...n,id:e.id}:{id:e.id,text:pu(e.draft)||n.text,state:`draft`}:n),H.openText=``}if(t&&(a.some(t=>t.id===e.id)?a=ru(a,{id:e.id,text:t}).map(t=>t.id===e.id&&t.state!==`locked`?{...t,state:`refined`}:t):a.some(e=>e.id===null)||(a=a.concat([{id:e.id,text:t,state:`refined`}]))),a!==n&&(H.draft.items=a,Ou()),t&&H.phase===`recording`){let e=H.draft.items.filter(e=>e.id!==null&&e.state===`refined`).length;Mu(r(`voice.refineListening`,{n:e}))}return}if(e.type===`refine`){e.enabled===!1&&(H.phase===`recording`||H.phase===`finalizing`)&&Mu(r(`voice.refineDegraded`),`warn`);return}if(e.type===`final`){if(H.phase!==`recording`&&H.phase!==`finalizing`)return;td(e.text||H.lastText,{fallback:e.fallback===!0,texts:e.texts});return}if(e.type===`closed`){H.phase===`finalizing`&&td(H.lastText,{fallback:!0});return}if(e.type===`error`){let t=e.code||`internal`;if(t===`max_duration`){H.phase===`recording`&&$u(`stop`),Mu(r(`voice.maxDuration`),`warn`);return}Mu(t===`busy`?r(`voice.busy`):t===`model_missing`?`${r(`voice.modelMissing`)} — ${r(`voice.modelMissingHelp`)}`:r(`voice.failed`),`warn`),Yu(),(H.phase===`recording`||H.phase===`finalizing`)&&Au(),Xu(),Ru(!1),zu(!1),t===`model_missing`&&Cu(),setTimeout(()=>{H.phase===`idle`&&Iu()},3500)}}}async function rd(){return H.phase===`recording`?($u(`stop`),!0):H.phase===`starting`||H.phase===`finalizing`?!1:Qu()}function id(){return H.phase===`recording`||H.phase===`starting`||H.phase===`finalizing`}function ad(){return id()?ed({rollback:!0}):!1}function od(){return H.phase===`idle`?!1:ed({rollback:!1})}async function sd(){try{let e=(await chrome.storage.session?.get?.(`pendingVoiceStart`))?.pendingVoiceStart;return!(!e||(await chrome.storage.session.remove(`pendingVoiceStart`),typeof e!=`number`||Date.now()-e>su))}catch{return!1}}function cd(){if(!H.btn)return;let e=[`Alt+V`];H.shortcutCfg.rightAlt&&e.push(r(`voice.keyRightAlt`)),H.shortcutCfg.rightCtrl&&e.push(r(`voice.keyRightCtrl`));let t=r(`voice.btnTitle`,{keys:e.join(` / `)});H.btn.title=t,H.btn.setAttribute(`aria-label`,t)}async function ld(){if(H.shortcutCfg=await Me(),H.shortcutTrigger||=Ae(()=>H.shortcutCfg),cd(),H.shortcutBound)return;H.shortcutBound=!0,document.addEventListener(`keydown`,e=>{H.shortcutTrigger?.onKeyDown(e)===`cancel`&&e.preventDefault()},!0),document.addEventListener(`keyup`,e=>{H.shortcutTrigger?.onKeyUp(e)===`trigger`&&(!H.armed&&H.phase===`idle`||(e.preventDefault(),rd()))},!0),window.addEventListener(`blur`,()=>{H.shortcutTrigger?.reset()}),ke(e=>{H.shortcutCfg=e,cd()});let e=async()=>{try{let e=await Me();if(e.rightAlt===H.shortcutCfg.rightAlt&&e.rightCtrl===H.shortcutCfg.rightCtrl)return;H.shortcutCfg=e,cd()}catch{}};window.addEventListener(`focus`,()=>{e()}),document.addEventListener(`visibilitychange`,()=>{document.hidden||e()})}async function ud(e={}){if(H.input=document.getElementById(`userInput`),H.btn=document.getElementById(`voiceInputBtn`),H.bar=document.getElementById(`voiceRecorderBar`),H.wave=document.getElementById(`voiceWave`),H.timerEl=document.getElementById(`voiceTimer`),H.statusEl=document.getElementById(`voiceStatusText`),H.permBtn=document.getElementById(`voicePermBtn`),H.adjustInputHeight=typeof e.adjustInputHeight==`function`?e.adjustInputHeight:null,!H.input||!H.btn){i.debug(`[Voice] input or button missing, skip init`);return}ju(),Ru(!1),Mu(r(`voice.listening`)),await ld(),H.btn.addEventListener(`click`,e=>{e.preventDefault(),rd()}),document.getElementById(`voiceCancelBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),ed({rollback:!0})}),document.getElementById(`voiceDoneBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),$u(`stop`)}),H.permBtn?.addEventListener(`click`,e=>{e.preventDefault();try{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`asr`}).catch?.(()=>{})}catch{}Mu(r(`voice.micDeniedHelp`),`warn`),Pu(!1)}),H.input.addEventListener(`input`,()=>{H.programmatic||(H.phase===`recording`||H.phase===`finalizing`)&&wu()}),chrome.runtime.onMessage.addListener((e,t,n)=>e?.type===`VOICE_TOGGLE`?(rd(),n?.({success:!0}),!1):(e?.type===`ASR_STATUS_CHANGED`&&Cu(),!1)),window.addEventListener(`pagehide`,()=>{od()}),document.addEventListener(`visibilitychange`,()=>{document.hidden&&H.phase===`recording`&&od()}),await Cu()&&await sd()&&setTimeout(()=>{rd()},220)}var dd=`panel_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8),fd=new Set,pd=new Set,md=null,hd=new Map,gd=`queue-context-cleared`,_d=`queue-context-restored`;function vd(e){md=e}function yd(e){return C.generatingSessionIds.has(e||C.activeSessionId)}function bd(){return{quotedContextText:C.quotedContextText||``,selectedContextText:C.selectedContextText||``,selectedSkills:(C.selectedSkills||[]).slice(),selectedMcpServices:(C.selectedMcpServices||[]).slice(),knowledgeRefs:(C.knowledgeRefs||[]).slice(),selectedPage:C.selectedPage?{...C.selectedPage}:null,attachedImages:(C.attachedImages||[]).slice(),attachedFiles:(C.attachedFiles||[]).slice()}}function xd(e){return e?e.attachmentSummary||(e.attachedImages||[]).length||(e.attachedFiles||[]).length?!0:!!(e.quotedContextText&&e.quotedContextText.trim()||e.selectedContextText&&e.selectedContextText.trim()||(e.selectedSkills||[]).length||(e.selectedMcpServices||[]).length||(e.knowledgeRefs||[]).length||e.selectedPage):!1}function Sd(){return xd(bd())}function Cd(e){let t=e||{},n=(t.attachedImages||[]).length>0,i=(t.attachedFiles||[]).length>0;return n&&i?r(`sidePanel.defaultPromptAttachments`):n?r(`sidePanel.defaultPromptImage`):i?r(`sidePanel.defaultPromptFile`):(t.knowledgeRefs||[]).length>0?r(`sidePanel.defaultPromptKnowledge`):t.selectedPage?r(`sidePanel.defaultPromptPage`):t.quotedContextText&&t.quotedContextText.trim()||t.selectedContextText&&t.selectedContextText.trim()?r(`sidePanel.defaultPromptSelection`):(t.selectedSkills||[]).length>0||(t.selectedMcpServices||[]).length>0?r(`sidePanel.defaultPromptContext`):``}function wd(){let e=bd();return xd(e)&&Ed(),e}function Td(e){e&&(e.quotedContextText&&(C.quotedContextText=e.quotedContextText),e.selectedContextText&&(C.selectedContextText=e.selectedContextText),(e.selectedSkills||[]).length&&(C.selectedSkills=e.selectedSkills.slice()),(e.selectedMcpServices||[]).length&&(C.selectedMcpServices=e.selectedMcpServices.slice()),(e.knowledgeRefs||[]).length&&(C.knowledgeRefs=e.knowledgeRefs.slice()),e.selectedPage&&(C.selectedPage={...e.selectedPage}),(e.attachedImages||[]).length&&(C.attachedImages=e.attachedImages.slice()),(e.attachedFiles||[]).length&&(C.attachedFiles=e.attachedFiles.slice()))}function Ed(){let e=(C.attachedImages||[]).length>0;if(C.quotedContextText=``,C.selectedContextText=``,C.selectedSkills=[],C.selectedMcpServices=[],C.knowledgeRefs=[],C.selectedPage=null,C.attachedImages=[],C.attachedFiles=[],e){let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}document.dispatchEvent(new CustomEvent(gd))}var Dd=new Set([`pending`,`extracting`]);function Od(){return(C.attachedFiles||[]).some(e=>Dd.has(e&&e.status))}function kd(e){let t=e&&e.attachedImages||[],n=(e&&e.attachedFiles||[]).map(e=>{if(!e||typeof e.dataUrl!=`string`||!e.dataUrl.startsWith(`blob:`))return e;let t={...e};return delete t.dataUrl,t}),r={...e||{}};return delete r.attachedImages,delete r.attachedFiles,r.attachmentSummary=oi({attachedImages:t,attachedFiles:n}),{light:r,heavy:t.length||n.length?{images:t,files:n}:null}}async function Ad(e){if(!e)return{ok:!1,attachments:!1,wantsAttachments:!1};let t=await ci(e.id)||hd.get(e.id)||null,n=!!(e.attachmentSummary||e.contextSnapshot&&e.contextSnapshot.attachmentSummary);return Td({...e.contextSnapshot||{},attachedImages:t&&t.images||[],attachedFiles:t&&t.files||[]}),document.dispatchEvent(new CustomEvent(_d,{detail:{snapshot:e.contextSnapshot||{}}})),{ok:!0,attachments:!!t,wantsAttachments:n}}async function jd(e){return e?(hd.delete(e),li(e)):!1}async function Md({autoDrain:e=!0}={}){let t=document.getElementById(`userInput`),n=(t?.value||``).trim()||Cd(bd());if(!n)return{ok:!1,error:`empty`};od();let i=C.activeSessionId;if(!i)return F(r(`queue.noSession`),`error`),{ok:!1,error:`missing_session`};if(Od())return F(r(`queue.filesStillExtracting`),`warning`,4e3),{ok:!1,error:`files_extracting`};let a=wd(),{light:o,heavy:s}=kd(a),c=await Fr({sessionId:i,text:n,contextSnapshot:o,hasContext:xd(o),attachmentSummary:o.attachmentSummary,source:`manual`});return c.ok?(s&&((await si(c.item.id,i,s)).ok||(hd.set(c.item.id,s),F(r(`queue.attachmentsVolatile`),`warning`,5e3))),t&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`)),t.focus()),F(r(`queue.enqueued`,{position:c.position}),`success`),document.dispatchEvent(new CustomEvent(`queue-enqueued`,{detail:{sessionId:i,item:c.item}})),e&&!yd(i)&&!Pr(i)&&Pd(i),c):(Td(a),document.dispatchEvent(new CustomEvent(_d,{detail:{snapshot:a}})),c.error===`queue_full`?F(r(`queue.queueFull`,{limit:c.limit}),`warning`):F(r(`queue.enqueueFailed`),`error`),c)}async function Nd(e){try{let{list:t}=await vi(),n=(t||[]).find(t=>t.id===e);return n?{messageHistory:Array.isArray(n.messageHistory)?n.messageHistory.slice():[],model:n.model,useTools:n.useTools,enabledTools:Array.isArray(n.enabledTools)?n.enabledTools.slice():n.enabledTools,agentId:n.agentId,temperature:n.temperature,topP:n.topP,contextCompaction:n.contextCompaction,workdir:n.workdir||null,workdirAgentId:n.workdirAgentId||null}:null}catch(e){return i.warn(`[QueueRunner] load session state failed:`,e?.message||e),null}}async function Pd(e){let t=e||C.activeSessionId;if(!(!t||!md)){if(fd.has(t)){pd.add(t);return}fd.add(t);try{do pd.delete(t),await Fd(t);while(pd.has(t)&&!Pr(t))}finally{fd.delete(t)}}}async function Fd(e){if(yd(e)||Pr(e))return;let t=Ar(e);if(!t)return;if((t.attempts||0)>=5){await Vr(e,t.id,{status:tr.FAILED,note:`too_many_attempts`}),F(r(`queue.tooManyAttempts`,{count:5}),`error`,5e3);return}if(!await qr(e,t.id,dd)){i.debug(`[QueueRunner] lease held by another panel, skip:`,t.id);return}await Rr(e,t.id,tr.DISPATCHING,{attempts:(t.attempts||0)+1,lastError:null});let n=await ci(t.id)||hd.get(t.id)||null;hd.delete(t.id);let a=!!t.attachmentSummary&&!n;a&&F(r(`queue.attachmentsMissing`),`warning`,5e3);let o={quotedContextText:``,selectedContextText:``,selectedSkills:[],selectedMcpServices:[],knowledgeRefs:[],selectedPage:null,...t.contextSnapshot||{},attachedImages:n&&n.images||[],attachedFiles:n&&n.files||[]},s=e===C.activeSessionId,c=null;if(!s&&(c=await Nd(e),!c)){let t=await Jr(e);t&&i.warn(`[QueueRunner] dropped queue of deleted session:`,e,t);return}let l={ok:!0};try{let n={text:t.text,fromQueue:!0,sessionId:e,context:o};s||(n.sessionState=c),l=await md(n)||{ok:!0}}catch(e){l={ok:!1,reason:e?.message||`dispatch_error`},i.error(`[QueueRunner] dispatch failed:`,e?.message||e)}Mr(e,t.id)?l.ok===!1?l.delivered?(await Vr(e,t.id,{status:tr.FAILED,note:l.reason||`failed`}),await li(t.id)):(await Br(e,t.id,`dispatch_failed`,l.reason||`dispatch_failed`),pd.delete(e)):(await Vr(e,t.id,{status:tr.DONE,note:a?`relayed_no_attachments`:`relayed`}),await li(t.id)):i.debug(`[QueueRunner] item removed during dispatch, drop result:`,t.id)}var Id=new Set;function Ld(e){let t=e||C.activeSessionId;return t?(Id.add(t),t):null}function Rd(e){let t=e||C.activeSessionId;return!!(t&&Ar(t))}async function zd(e){let t=e||C.activeSessionId;t&&(Id.delete(t),await Kr(t),await Pd(t))}function Bd(e){Pr(e)||Pd(e)}var Vd=new Map,Hd=new Set,Ud=new Map,Wd=new Map;function Gd(e){let t=e&&e.attachmentSummary;return t?(t.imageCount||0)>0||(t.fileCount||0)>0:!1}function Kd(e,t){return`${e}\u0000${t}`}function qd(e,t){let n=Kd(e,t),r=Vd.get(n);r&&(clearTimeout(r),Vd.delete(n))}async function Jd(e,t,n,r){qd(e,t);let i=Mr(e,t);!i||i.status!==tr.INJECTING||(await Br(e,t,n,n),r&&F(r,`warning`,4e3))}function Yd(e,t,n){return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,r(e))},o=setTimeout(()=>a(null),2e3);try{chrome.runtime.sendMessage({type:`INJECT_MESSAGE`,sessionId:e,itemId:t,text:n},e=>{if(clearTimeout(o),chrome.runtime.lastError){a(null);return}a(e||null)})}catch{clearTimeout(o),a(null)}})}async function Xd(e,t,n={}){let i=t||C.activeSessionId,a=n.auto===!0;if(!i||!e)return{ok:!1,error:`missing_session`};let o=Mr(i,e);if(!o)return{ok:!1,error:`not_found`};if(o.status!==tr.QUEUED)return{ok:!1,error:`not_queued`};if(Gd(o))return a||F(r(`queue.injectNoAttachments`),`warning`,4e3),{ok:!1,error:`has_attachments`};let s=Kd(i,e);if(Hd.has(s))return{ok:!1,error:`in_flight`};Hd.add(s);try{await zr(i,e),Vd.set(s,setTimeout(()=>{Jd(i,e,`timeout`,r(`queue.injectTimeout`))},$n));let t=await Yd(i,e,o.text);if(!t)return{ok:!0,pending:!0};if(!t.accepted){let n=t.reason||`rejected`;return await Jd(i,e,n,r(n===`no_running_task`?`queue.injectNoTask`:`queue.injectFailed`)),{ok:!1,error:n}}return a?i===C.activeSessionId&&F(r(`queue.autoCarried`,{iteration:n.iteration??`?`}),`success`,2500):F(r(`queue.injectAccepted`),`success`,2500),{ok:!0,pending:!0}}finally{Hd.delete(s)}}function Zd(e){let t=document.getElementById(`userInput`);t&&t.value.trim()===e&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`)),t.focus())}async function Qd(e){let t=C.activeSessionId,n=String(e||``).trim();if(!t||!n)return{ok:!1,error:`empty`};if(od(),!yd(t))return F(r(`queue.injectNoTask`),`warning`,3e3),{ok:!1,error:`no_running_task`};let i=`adhoc_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,7),a=setTimeout(()=>{Ud.has(i)&&(Ud.delete(i),F(r(`queue.injectTimeoutAdhoc`),`warning`,4e3))},$n);Ud.set(i,{text:n,timer:a});let o=await Yd(t,i,n);return o&&!o.accepted?(clearTimeout(a),Ud.delete(i),F(o.reason===`no_running_task`?r(`queue.injectNoTask`):r(`queue.injectFailed`),`warning`,4e3),{ok:!1,error:o.reason}):(o&&o.accepted&&F(r(`queue.injectAccepted`),`success`,2500),{ok:!0,pending:!0})}function $d(e){let t=e?.sessionId,n=Array.isArray(e?.items)?e.items:[];if(!t||n.length===0)return;let i=0;for(let r of n){let n=Ud.get(r);if(n){clearTimeout(n.timer),Ud.delete(r),Zd(n.text);continue}qd(t,r),Mr(t,r)&&(i++,Vr(t,r,{status:tr.INJECTED,note:`injected`,callId:e.callId||null,iteration:e.iteration??null}))}i>0&&t===C.activeSessionId&&F(r(`queue.injected`),`success`,2500),document.dispatchEvent(new CustomEvent(`queue-injected`,{detail:{sessionId:t,items:n,iteration:e.iteration??null}}))}function ef(e){let t=e?.sessionId,n=Array.isArray(e?.items)?e.items:[];if(!t||n.length===0)return;let i=e.reason||`rejected`,a=r(i===`task_ended`?`queue.injectNoTask`:`queue.injectFailed`);for(let e of n){let r=Ud.get(e);if(r){clearTimeout(r.timer),Ud.delete(e);continue}Jd(t,e,i,e===n[0]?a:null)}}function tf(e){let t=e?.sessionId;if(!t||e.isSubtask===!0||Pr(t))return;let n=Zl(e.executionLog);if(!n)return;let r=Ar(t),a=r&&!Gd(r)?r:null,o=C.chatConfig||{},s=Ql({tracker:Wd.get(t),callId:e.callId||null,iteration:n,everyN:o.queueAutoCarryEveryNIterations,enabled:o.queueAutoCarry!==!1,hasCandidate:!!a});if(Wd.set(t,s.tracker),!s.carry)return;i.debug(`[QueueRunner] auto carry item`,a.id,`at iteration`,n,`session`,t);let c=e.callId||null;Xd(a.id,t,{auto:!0,iteration:n}).then(e=>{!e||e.ok!==!0||Wd.set(t,$l(Wd.get(t),{callId:c}))})}function nf(e){!e||typeof e!=`object`||(e.type===`INJECT_ABSORBED`?$d(e):e.type===`INJECT_REJECTED`?ef(e):e.type===`EXECUTION_STATUS_UPDATE`&&tf(e))}async function rf(){try{if(Sr()){i.warn(`[QueueRunner] skip attachment prune in degraded mode`);return}let e=new Set;for(let t of Nr())for(let n of Er(t))e.add(n.id);let t=await di(e);t&&i.debug(`[QueueRunner] pruned orphan attachments:`,t)}catch(e){i.warn(`[QueueRunner] prune orphan attachments failed:`,e?.message||e)}}var af=!1,of=null,sf=[];function cf(e,t){document.addEventListener(e,t),sf.push([e,t])}var lf=1500;function uf(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,t(e))},i=setTimeout(()=>r(null),lf);try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`,sessionId:e},e=>{if(clearTimeout(i),chrome.runtime.lastError){r(null);return}r(!!(e&&e.running))})}catch{clearTimeout(i),r(null)}})}async function df(){if(!C.activeSessionId)return!1;let e=Nr();if(e.length===0)return!0;let t=!1;for(let n of e){if(Pr(n)||yd(n)||!Ar(n))continue;let e=await uf(n);if(e===null){t=!0;continue}if(!e&&!(Pr(n)||yd(n)))return await Pd(n),!0}return!t}function ff(){if(of)return;let e=0,t=async()=>{if(of=null,++e>25)return;let n=!1;try{n=await df()}catch(e){i.warn(`[QueueRunner] auto-resume attempt failed:`,e?.message||e)}n||(of=setTimeout(t,800))};of=setTimeout(t,300)}async function pf({autoResume:e=!0}={}){af||(af=!0,await Cr(),wr(),rf(),ql(Bd),typeof chrome<`u`&&chrome.runtime?.onMessage?.addListener&&chrome.runtime.onMessage.addListener(nf),cf(`task-stop-requested`,e=>{let t=e?.detail?.sessionId||C.activeSessionId;if(t){if(Id.delete(t)){Kr(t).then(()=>Pd(t));return}Gr(t,`user_stopped`)}}),cf(`generating-state-changed`,()=>{let e=C.activeSessionId;if(e){if(C.isGenerating&&Pr(e)){Kr(e);return}for(let e of Nr())if(!(Pr(e)||yd(e))&&Ar(e)){Pd(e);break}}}),cf(`session-switched`,()=>ff()),cf(`visibilitychange`,()=>{document.visibilityState===`visible`&&ff()}),e&&ff())}async function mf(e){let t=e||C.activeSessionId;t&&(await Kr(t),await Pd(t))}var hf=[/(?:按|按照|以|用|走|使用|开启|启用|切换?到)\s*(?:goal|目标)\s*模式/i,/(?:进入|改成|改为|设为|设置为|切换到)\s*(?:goal|目标)\s*模式/i,/\b(?:in|use|using|enable|enter|switch\s+to|with)\s+(?:the\s+)?goal\s+mode\b/i,/(?:无人值守|不用管我|别停下来|不要停|直到(?:我|你)(?:叫停|喊停))/,/\bunattended\b|\bwithout\s+(?:me|supervision)\b|\bdon'?t\s+stop\s+until\b/i,/(?:持续|一直|连续)(?:执行|跑|做|干|尝试|迭代)\s*(?:到|直到)/,/(?:跑到|做到|干到|做到)(?:完成|通过|结束|成功)/,/\bkeep\s+(?:working|going|trying|iterating)\s+until\b/i,/\brun\s+until\s+(?:done|complete|passing|it\s+passes)\b/i],gf=[/直到\s*[^。;;\n]{1,40}?(?:全部|都)?(?:通过|完成|跑通|变绿)/,/(?:确保|保证)\s*[^。;;\n]{1,40}?(?:通过|跑通|可用)/,/\buntil\s+[^.;\n]{1,40}?(?:pass|passes|green|works)\b/i],_f=/(?:不要|不用|不必|无需|取消|关闭|停用|停止|退出|不按|不以|别|不)\s*$/,vf=/\b(?:do\s+not|don'?t|does\s+not|doesn'?t|never|avoid|without|no\s+need\s+to)\s+(?:(?:use|using|enable|enabling|enter|entering|switch(?:ing)?\s+to|turn\s+on|activate|run(?:\s+in)?|go(?:\s+with)?)\s*)?$/i,yf=2e3,bf=40;function xf(e,t,n){let r=[];for(let i of t){let t=i.flags.includes(`g`)?i.flags:`${i.flags}g`,a=new RegExp(i.source,t),o;for(;(o=a.exec(e))!==null&&o[0].length!==0;){let t=e.slice(Math.max(0,o.index-bf),o.index);if(!(n&&(_f.test(t)||vf.test(t)))&&(r.push(o[0].trim()),o[0].length===0))break}}return r}function Sf(e){let t={detected:!1,strength:`none`,matches:[]};if(typeof e!=`string`)return t;let n=e.trim();if(!n)return t;let r=n.slice(0,yf),i=xf(r,hf,!0);if(i.length>0)return{detected:!0,strength:`strong`,matches:Cf(i).slice(0,3)};let a=xf(r,gf,!0);return a.length>0?{detected:!1,strength:`weak`,matches:Cf(a).slice(0,3)}:t}function Cf(e){let t=new Set,n=[];for(let r of e){let e=r.toLowerCase();t.has(e)||(t.add(e),n.push(r))}return n}function wf(e){if(typeof e!=`string`)return``;let t=e,n=xf(e.slice(0,yf),hf,!0);for(let e of n)e&&(t=t.replace(e,` `));return t=t.replace(/^[\s,,。.、::;;-]+/,``).trim(),t||e.trim()}var Tf={active:`goal.statusActive`,paused:`goal.statusPaused`,achieved:`goal.statusAchieved`,unmet:`goal.statusUnmet`,budget_limited:`goal.statusBudgetLimited`,cleared:`goal.statusCleared`},Ef=new Set([`achieved`,`unmet`,`cleared`]),U=null;function Df(e){return document.getElementById(e)}function Of(e){let t=Tf[e];return t?r(t):String(e||``)}function kf(e){return!!e&&Ef.has(e.status)}function Af(e){return new Promise(t=>{try{chrome.runtime.sendMessage(e,e=>{if(chrome.runtime.lastError){i.debug(`[GoalPanel] message failed:`,chrome.runtime.lastError.message),t(null);return}t(e||null)})}catch(e){i.debug(`[GoalPanel] message threw:`,e?.message),t(null)}})}function jf(e){return Af({type:`SET_GOAL`,...e})}function Mf(){if(!U)return;let e=C.goalSnapshot,t=C.goalMode;U.toggle.checked=t;let n=t&&!!e&&(e.status===`paused`||e.status===`budget_limited`);U.group&&(U.group.dataset.goalIdle=n?`1`:``);let i=t||e&&!kf(e);if(U.bar.style.display=i?``:`none`,!i)return;if(U.bar.dataset.status=e?e.status:`none`,U.status.textContent=e?Of(e.status):``,U.status.style.display=e?``:`none`,e){U.objective.textContent=e.objective||``,U.objective.title=e.objective||``;let t=M(e,r);n&&e.status===`paused`&&t.push(r(`goal.pausedHintInline`)),U.meta.textContent=t.join(` · `)}else U.objective.textContent=r(`goal.startHint`),U.objective.title=``,U.meta.textContent=``;let a=!!e&&e.status===`active`&&e.autoApprove===!0;U.approve.style.display=a?``:`none`;let o=!!e&&e.status===`active`,s=!!e&&(e.status===`paused`||e.status===`budget_limited`);U.pause.style.display=o?``:`none`,U.resume.style.display=s?``:`none`,U.edit.style.display=e?``:`none`,U.clear.style.display=e?``:`none`}function Nf(){return C.activeSessionId||null}async function Pf(e=Nf()){if(!e)return C.goalSnapshot=null,Mf(),null;let t=await Af({type:`GET_GOAL`,sessionId:e});return e===Nf()?(C.goalSnapshot=t?.goal||null,Mf(),C.goalSnapshot):null}var Ff=null;async function If(){return Ff||(Ff=await new Promise(e=>{try{chrome.storage.local.get([`goalConfig`],t=>e(t?.goalConfig||{}))}catch(t){i.debug(`[GoalPanel] read goalConfig failed:`,t?.message),e({})}}),Ff)}async function Lf(){let e=Df(`goalGroup`);if(!e)return;let t=await If();e.style.display=t.enabled===!1?`none`:``}async function Rf({sessionId:e=Nf(),text:t=``,attachments:n=[]}={}){if(!e||!String(t||``).trim())return null;let i=await If(),a=!!C.goalMode;if(i.enabled===!1)return a&&F(r(`goal.disabledHint`),`warning`),null;let o=t;if(!a){if(i.intentDetection===!1)return null;let e=Sf(t);if(!e.detected)return e.strength===`weak`&&F(r(`goal.intentHint`),`info`,6e3),null;o=String(wf(t)||``).trim()||t}let s=await jf({sessionId:e,action:`set`,objective:o,attachments:Array.isArray(n)?n:[],createdBy:a?`toggle`:`intent`,autoApprove:a});return!s||s.success===!1?(s?.disabled&&F(r(`goal.disabledHint`),`warning`),null):(a||F(r(`goal.intentDetected`),`info`,6e3),e===Nf()?(C.goalSnapshot=s.goal||null,Mf(),s.goal||null):s.goal||null)}function zf(e={}){let t=[],n=Array.isArray(e.attachedImages)?e.attachedImages.length:0;n>0&&t.push({kind:`image`,name:r(`goal.attachmentImage`,{count:n})});for(let n of Array.isArray(e.attachedFiles)?e.attachedFiles:[])!n||n.status!==`done`||!n.name||t.push({kind:`file`,name:String(n.name),detail:n.agentPath?`workspace file`:`inline text`});let i=e.selectedPage;i&&(i.title||i.url)&&t.push({kind:`page`,name:String(i.title||i.url),detail:i.id==null?``:`tab ${i.id}`});for(let n of Array.isArray(e.knowledgeRefs)?e.knowledgeRefs:[])n&&n.name&&t.push({kind:`knowledge`,name:String(n.name)});return t}function Bf(){C.goalSnapshot=null,Mf()}function Vf(){return Mf(),Pf()}function Hf(e=``){return new Promise(t=>{let n=document.createElement(`div`);n.className=`modal-overlay show`,n.innerHTML=`
|
|
96
|
+
`}).join(``),t.querySelectorAll(`.prototype-library-item`).forEach(e=>{let t=e.querySelector(`.prototype-library-item-info`),n=e.querySelector(`.prototype-library-item-open`),a=e.querySelector(`.prototype-library-item-local-open`),o=e.querySelector(`.prototype-library-item-optimize`),s=e.querySelector(`.prototype-library-item-delete`),c=e.querySelector(`.prototype-library-item-download`);t&&t.addEventListener(`click`,()=>{let t=e.dataset.id;Wc(t)}),n&&n.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.id;Wc(n)}),a&&a.addEventListener(`click`,e=>{e.stopPropagation();let t=a.dataset.path;chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:t},e=>{e?.success||i.error(`[SidePanel] local browseropen failed:`,e?.error)})}),o&&o.addEventListener(`click`,t=>{t.stopPropagation();let n=o.dataset.id;Xc(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`)),Yc()}),s&&s.addEventListener(`click`,t=>{t.stopPropagation();let n=s.dataset.id;Qc(n,e.querySelector(`.prototype-library-item-title`)?.textContent||r(`uiProto.defaultTitle`))}),c&&c.addEventListener(`click`,e=>{e.stopPropagation();let t=c.dataset.id;Zc(t)})})))}function Jc(e){let t=()=>{let t=document.getElementById(`prototypeLibrarySearch`),n=document.getElementById(`prototypeLibrarySort`),r=(t?.value||``).trim().toLowerCase(),i=n?.value||`createdAt_desc`,a=e;r&&(a=e.filter(e=>(e.title||``).toLowerCase().includes(r)||(e.description||``).toLowerCase().includes(r)));let[o,s]=i.split(`_`);a=[...a].sort((e,t)=>{let n;return n=o===`title`?(e.title||``).localeCompare(t.title||``,`zh-CN`):(e.createdAt||0)-(t.createdAt||0),s===`desc`?-n:n}),qc(a)},n=document.getElementById(`prototypeLibrarySearch`),r=document.getElementById(`prototypeLibrarySort`);if(n){let e=n.cloneNode(!0);n.parentNode.replaceChild(e,n),e.addEventListener(`input`,t)}if(r){let e=r.cloneNode(!0);r.parentNode.replaceChild(e,r),e.addEventListener(`change`,t)}}function Yc(){let e=document.getElementById(`prototypeLibraryModal`);e&&e.classList.remove(`show`),i.debug(`[SidePanel] prototype page libraryhidden`)}function Xc(e,t){let n=document.getElementById(`userInput`);n&&(n.value=r(`uiProto.optimizePrompt`,{id:e,title:t}),n.focus(),n.style.height=`auto`,n.style.height=n.scrollHeight+`px`),i.debug(`[SidePanel] from prototype page librarycontinue optimizeprototype:`,e)}async function Zc(e){try{let t=await D(e);if(!t||!t.html){i.error(`[SidePanel] download prototype failed:not foundprototype`,e);return}let n=Rc(t.html),r=new Blob([n],{type:`text/html`}),a=URL.createObjectURL(r),o=document.createElement(`a`);o.href=a,o.download=(t.title||`prototype`).replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)+`.html`,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(a),i.debug(`[SidePanel] prototype fromprototypelibrarydownload:`,o.download)}catch(e){i.error(`[SidePanel] download prototype failed:`,e)}}async function Qc(e,t){if(await $c(r(`uiProto.confirmDeleteTitle`),r(`uiProto.confirmDeleteMessage`,{title:t}),r(`common.delete`)))try{let t=await D(e);await x(e),i.debug(`[SidePanel] prototype deleted:`,e),t?.localPath&&chrome.runtime.sendMessage({type:`DELETE_LOCAL_PROTOTYPE`,path:t.localPath},e=>{e?.success?i.debug(`[SidePanel] local prototypefile deleted:`,t.localPath):i.warn(`[SidePanel] local prototypefiledelete failed:`,e?.error)}),Kc()}catch(e){i.error(`[SidePanel] delete prototype failed:`,e),alert(r(`uiProto.deleteFailed`,{message:e.message}))}}function $c(e,t,n=r(`common.confirm`)){return new Promise(r=>{let i=document.getElementById(`genericConfirmModal`),a=document.getElementById(`genericConfirmTitle`),o=document.getElementById(`genericConfirmMessage`),s=document.getElementById(`genericConfirmOkBtn`),c=document.getElementById(`genericConfirmCancelBtn`);if(!i){r(confirm(t));return}a.textContent=e,o.textContent=t,s.textContent=n;let l=()=>{i.classList.remove(`show`),s.removeEventListener(`click`,u),c.removeEventListener(`click`,d)},u=()=>{l(),r(!0)},d=()=>{l(),r(!1)};s.addEventListener(`click`,u),c.addEventListener(`click`,d),i.classList.add(`show`)})}function el(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function tl(e){if(!e)return``;let t=new Date(e),n=new Date-t;return n<6e4?r(`uiProto.justNow`):n<36e5?r(`uiProto.minutesAgo`,{count:Math.floor(n/6e4)}):n<864e5?r(`uiProto.hoursAgo`,{count:Math.floor(n/36e5)}):t.toLocaleDateString(`zh-CN`)}function nl(e){Pc=Math.max(Fc,Math.min(Ic,e)),Pc=Math.round(Pc*100)/100;let t=document.getElementById(`prototypeIframe`),n=document.getElementById(`prototypeZoomLevel`);t&&(t.style.zoom=Pc),n&&(n.textContent=Math.round(Pc*100)+`%`,Pc===1?n.classList.remove(`zoomed`):n.classList.add(`zoomed`))}function rl(){nl(Pc+Lc),ol()}function il(){nl(Pc-Lc),ol()}function al(){nl(1)}function ol(){let e=document.getElementById(`prototypeZoomLevel`);e&&(e.classList.add(`flash`),setTimeout(()=>e.classList.remove(`flash`),150))}function sl(e){!e.ctrlKey&&!e.metaKey||(e.preventDefault(),e.deltaY<0?rl():il())}function cl(e){(e.ctrlKey||e.metaKey)&&e.key===`0`&&(e.preventDefault(),al())}function ll(){let e=document.getElementById(`prototypeCloseBtn`);e&&e.addEventListener(`click`,Bc);let t=document.getElementById(`prototypeDownloadBtn`);t&&t.addEventListener(`click`,Hc);let n=document.getElementById(`prototypeOpenTabBtn`);n&&n.addEventListener(`click`,Uc);let r=document.getElementById(`prototypeLocalOpenBtn`);r&&r.addEventListener(`click`,()=>{let e=r.dataset.path;e&&chrome.runtime.sendMessage({type:`OPEN_LOCAL_PROTOTYPE`,path:e},e=>{e?.success||i.error(`[SidePanel] local browseropen failed:`,e?.error)})});let a=document.getElementById(`prototypeContinueBtn`);a&&a.addEventListener(`click`,Vc);let o=document.getElementById(`prototypeZoomInBtn`);o&&o.addEventListener(`click`,rl);let s=document.getElementById(`prototypeZoomOutBtn`);s&&s.addEventListener(`click`,il);let c=document.getElementById(`prototypeZoomLevel`);c&&c.addEventListener(`click`,al);let l=document.getElementById(`prototypeContent`);l&&l.addEventListener(`wheel`,sl,{passive:!1}),document.addEventListener(`keydown`,cl);let u=document.getElementById(`prototypeLibraryCloseBtn`);u&&u.addEventListener(`click`,Yc),chrome.runtime.onMessage.addListener((e,t,n)=>{e.type===`SHOW_UI_PROTOTYPE`&&(i.debug(`[SidePanel] received showprototyperequested :`,e),e.data.localOpened?i.debug(`[SidePanel] prototype inagent-side browseropen,skip popup`):e.data.isRemoteAgent?(i.debug(`[SidePanel] remoteagent,will use browserlabelpageautoopenprototype`),Gc(e.data.prototypeId)):Wc(e.data.prototypeId),n({success:!0}))}),i.debug(`[SidePanel] UI prototype moduleeventinitializing`)}var ul={enabled:!1,thresholdRatio:.85,minPending:4,maxFailures:2};function dl(e,t){let n=Number(e);return Number.isFinite(n)&&n>0&&n<=1?n:t}function fl(e,t){let n=Number(e);return Number.isFinite(n)&&n>=0?Math.floor(n):t}function pl({enabled:e,ratio:t,thresholdRatio:n,pendingCount:r,minPending:i,isGenerating:a,isolateChat:o}={}){if(!e||a||!o)return!1;let s=dl(n,ul.thresholdRatio),c=fl(i,ul.minPending);return!Number.isFinite(t)||t<s?!1:fl(r,0)>=c}function ml(e){let t=e?.messageHistory||[],n=e?.activeCompaction?.upToMessageId;if(!n)return t.length;let r=t.findIndex(e=>e.messageId===n);return r===-1?t.length:t.length-r-1}var hl=0;function gl(){hl=0}async function _l({state:e,getRatio:t,compact:n}={}){let r=e?.chatConfig||{},a=r.autoCompaction===!0;if(!a)return{attempted:!1,success:!1,reason:`disabled`};if(hl>=ul.maxFailures)return{attempted:!1,success:!1,reason:`backoff`};let o;try{o=Number(t?t():NaN)}catch(e){return i.warn(`[AutoCompaction] usage compute failed, send continues:`,e?.message),{attempted:!1,success:!1,reason:`usage_unavailable`}}let s=ml(e);if(!pl({enabled:a,ratio:o,thresholdRatio:r.autoCompactionThreshold,pendingCount:s,isGenerating:!!e?.isGenerating,isolateChat:!!e?.isolateChat}))return{attempted:!1,success:!1,reason:`not_needed`};i.debug(`[AutoCompaction] triggered`,{ratio:o,pendingCount:s});let c=null;try{c=await n({silent:!0})}catch(e){return i.warn(`[AutoCompaction] compact threw, send continues:`,e?.message),hl++,{attempted:!0,success:!1,reason:`exception`}}return c?.success?(gl(),{attempted:!0,success:!0}):(hl++,i.debug(`[AutoCompaction] skipped send:`,c?.reason),{attempted:!0,success:!1,reason:c?.reason||`failed`})}var vl=null,yl=`global`,bl=new Map;function xl(){try{chrome.windows?.getCurrent?.().then?.(e=>{e?.id!=null&&(vl=e.id)}).catch?.(e=>{i.debug(`[PanelContext] query current window failed:`,e?.message)})}catch(e){i.debug(`[PanelContext] init window query failed:`,e?.message)}try{chrome.storage?.local?.get?.([`sidePanelScope`],e=>{yl=e?.sidePanelScope===`tab-specific`?`tab-specific`:`global`}),chrome.storage?.onChanged?.addListener?.((e,t)=>{t!==`local`||!e?.sidePanelScope||(yl=e.sidePanelScope.newValue===`tab-specific`?`tab-specific`:`global`)})}catch(e){i.debug(`[PanelContext] init scope mirror failed:`,e?.message)}}function Sl(){return vl}function Cl(e){e&&typeof C.currentTabId==`number`&&bl.set(e,C.currentTabId)}function wl(e,t){e&&(typeof t==`number`?bl.set(e,t):bl.delete(e))}function Tl(e){if(!e)return null;let t=bl.get(e);return typeof t==`number`?t:null}function El(e){let t=null;try{t=typeof document<`u`?!!document.hidden:null}catch{}return{windowId:vl,hostTabId:Tl(e),scope:yl,panelHidden:t}}var Dl=0,Ol=500,kl=[{frequency:523.25,startTime:0,duration:.12,type:`sine`,gain:.3},{frequency:659.25,startTime:.09,duration:.12,type:`sine`,gain:.3},{frequency:783.99,startTime:.18,duration:.22,type:`sine`,gain:.35}],Al=[{frequency:440,startTime:0,duration:.16,type:`square`,gain:.22},{frequency:349.23,startTime:.14,duration:.3,type:`square`,gain:.22}],jl=[`#FF3B30`,`#FF9500`,`#FFCC00`,`#34C759`,`#00C7BE`,`#007AFF`,`#AF52DE`,`#FF2D55`],Ml=120,Nl=4e3,Pl=600,Fl=1e3,Il=.25,Ll=.99,Rl=.3,zl=.6,Bl=9999;function Vl(){return new Promise(e=>{try{chrome.storage.local.get([`completionSoundEnabled`,`completionConfettiEnabled`],t=>{e({soundEnabled:t?.completionSoundEnabled!==!1,confettiEnabled:t?.completionConfettiEnabled!==!1})})}catch(t){i.debug(`[CompletionFeedback] read config failed, use defaults:`,t?.message),e({soundEnabled:!0,confettiEnabled:!0})}})}function Hl(e){try{let t=window.AudioContext||window.webkitAudioContext;if(!t){i.debug(`[CompletionFeedback] AudioContext unavailable`);return}let n=new t;n.state===`suspended`&&typeof n.resume==`function`&&n.resume().catch(()=>{});let r=n.currentTime,a=0;for(let t of e){let e=n.createOscillator(),i=n.createGain();e.type=t.type||`sine`,e.frequency.value=t.frequency;let o=r+t.startTime,s=o+t.duration;i.gain.setValueAtTime(1e-4,o),i.gain.exponentialRampToValueAtTime(t.gain,o+.012),i.gain.exponentialRampToValueAtTime(1e-4,s),e.connect(i),i.connect(n.destination),e.start(o),e.stop(s+.02),s>a&&(a=s)}let o=Math.max(0,(a-r)*1e3)+200;setTimeout(()=>{try{n.close()}catch{}},o)}catch(e){i.debug(`[CompletionFeedback] play tone failed:`,e?.message)}}function Ul(){Hl(kl),i.debug(`[CompletionFeedback] success sound played`)}function Wl(){Hl(Al),i.debug(`[CompletionFeedback] failure sound played`)}function Gl(){try{return typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{return!1}}function Kl(){try{if(!document.body)return;let e=window.innerWidth,t=window.innerHeight;if(e<=0||t<=0)return;let n=document.createElement(`canvas`);n.style.cssText=`position:fixed;inset:0;pointer-events:none;z-index:${Bl};`;let r=window.devicePixelRatio||1;n.width=Math.floor(e*r),n.height=Math.floor(t*r),n.style.width=e+`px`,n.style.height=t+`px`,document.body.appendChild(n);let a=n.getContext(`2d`);if(!a){n.remove();return}a.scale(r,r);let o=[{x:e*.15,y:t+10,baseAngle:-Math.PI/2+Rl},{x:e*.85,y:t+10,baseAngle:-Math.PI/2-Rl}],s=[],c=0,l=0,u=performance.now(),d=e=>{let t=Math.min(Ml,Math.floor(Math.min(e,Pl)/Pl*Ml));for(;c<t;){let e=o[c%o.length],t=e.baseAngle+(Math.random()-.5)*zl,n=12+Math.random()*8,r=4+Math.random()*4;s.push({x:e.x+(Math.random()-.5)*20,y:e.y,vx:Math.cos(t)*n,vy:Math.sin(t)*n,size:r,color:jl[Math.floor(Math.random()*jl.length)],rotation:Math.random()*Math.PI*2,rotationSpeed:(Math.random()-.5)*.3,shape:Math.random()<.5?`rect`:`circle`}),c++}},f=r=>{let i=r-u;if(i>=Nl){cancelAnimationFrame(l),n.remove();return}d(i),a.clearRect(0,0,e,t);let o=Nl-Fl,c=i>o?Math.max(0,1-(i-o)/Fl):1;for(let n=s.length-1;n>=0;n--){let r=s[n];if(r.vy+=Il,r.vx*=Ll,r.vy*=Ll,r.x+=r.vx,r.y+=r.vy,r.rotation+=r.rotationSpeed,r.y-r.size>t||r.x+r.size<0||r.x-r.size>e){s.splice(n,1);continue}a.save(),a.globalAlpha=c,a.translate(r.x,r.y),a.rotate(r.rotation),a.fillStyle=r.color,r.shape===`rect`?a.fillRect(-r.size/2,-r.size/2,r.size,r.size*.6):(a.beginPath(),a.arc(0,0,r.size/2,0,Math.PI*2),a.fill()),a.restore()}l=requestAnimationFrame(f)};l=requestAnimationFrame(f),i.debug(`[CompletionFeedback] confetti launched`)}catch(e){i.debug(`[CompletionFeedback] launch confetti failed:`,e?.message)}}function ql(e,t,n,r){try{chrome.runtime.sendMessage({type:`TASK_FEEDBACK_NOTIFY`,success:e,sessionId:t||null,error:n||``,question:r||``,panel:El(t)})?.catch?.(()=>{})}catch(e){i.debug(`[CompletionFeedback] desktop notify failed:`,e?.message)}}async function Jl(e=null,t=``){try{let n=Date.now();if(n-Dl<Ol){i.debug(`[CompletionFeedback] throttled, skip`);return}Dl=n;let{soundEnabled:r,confettiEnabled:a}=await Vl();r&&Ul(),a&&!Gl()&&Kl(),ql(!0,e,``,t)}catch(e){i.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}async function Yl(e=null,t=``,n=``){try{let r=Date.now();if(r-Dl<Ol){i.debug(`[CompletionFeedback] throttled, skip`);return}Dl=r;let{soundEnabled:a}=await Vl();a&&Wl(),ql(!1,e,t,n)}catch(e){i.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}var Xl=new Set;function Zl(e){return typeof e==`function`?(Xl.add(e),()=>Xl.delete(e)):()=>{}}function Ql(e){let t=e||C.activeSessionId;if(t){C.generatingSessionIds.delete(t);try{gi(t)}catch(e){i.warn(`[GenerationLifecycle] markSessionCompleted failed:`,e?.message)}typeof document<`u`&&typeof CustomEvent==`function`&&(document.dispatchEvent(new CustomEvent(`generating-state-changed`)),document.dispatchEvent(new CustomEvent(`generation-ended`,{detail:{sessionId:t}})));for(let e of Xl)try{e(t)}catch(e){i.error(`[GenerationLifecycle] end handler failed:`,e?.message)}}}function $l(e){let t=Number(e);return!Number.isFinite(t)||t<=0?3:Math.min(20,Math.max(1,Math.round(t)))}function eu(){return{callId:null,carried:0,lastIteration:null}}function tu(e){let t=0;for(let n of e||[]){let e=Number(n&&n.iteration);Number.isFinite(e)&&e>t&&(t=e)}return t}function nu(e){let{tracker:t,callId:n=null,iteration:r,everyN:i,enabled:a=!0,hasCandidate:o=!0}=e||{},s=t&&typeof t==`object`?{callId:t.callId??null,carried:Number(t.carried)||0,lastIteration:t.lastIteration??null}:eu(),c=Number(r);if(!Number.isFinite(c)||c<=0)return{carry:!1,reason:`invalid_iteration`,tracker:s};let l=!!n&&!!s.callId&&n!==s.callId,u=s.lastIteration!=null&&c<s.lastIteration;if((l||u)&&(s=eu()),n&&!s.callId&&(s={...s,callId:n}),!a)return{carry:!1,reason:`disabled`,tracker:s};if(c<2)return{carry:!1,reason:`too_early`,tracker:s};if(!o)return{carry:!1,reason:`no_candidate`,tracker:s};if(s.carried>=3)return{carry:!1,reason:`call_limit`,tracker:s};let d=$l(i);return s.lastIteration!=null&&c-s.lastIteration<d?{carry:!1,reason:`interval_not_reached`,tracker:s}:{carry:!0,reason:`carry`,tracker:{callId:s.callId||n||null,carried:s.carried,lastIteration:c}}}function ru(e,{callId:t=null}={}){let n=e&&typeof e==`object`?e:eu();return t&&n.callId&&t!==n.callId?n:{...n,carried:(Number(n.carried)||0)+1}}var iu=/[\p{P}\p{S}]/gu;function au(e){return Array.isArray(e)?e.map(e=>e&&e.text||``).join(``):``}function ou(e){return String(e||``).replace(/[\s\u3000]/g,``).replace(iu,``)}function su(e,t){if(!Array.isArray(e))return e;let n=t&&t.id,r=t&&typeof t.text==`string`?t.text:null;if(r===null||typeof n!=`number`)return e;let i=!1,a=e.map(e=>!e||e.id!==n||e.state===`locked`?e:(i=!0,{...e,text:r}));return i?a:e}function cu(e,t,n){let r=String(t||``),i=String(n||``),a={lockedIds:[],shift:0,items:e,len:r.length};if(r===i||!Array.isArray(e)||e.length===0)return a;let o=0,s=Math.min(r.length,i.length);for(;o<s&&r[o]===i[o];)o++;let c=0,l=Math.min(r.length-o,i.length-o);for(;c<l&&r[r.length-1-c]===i[i.length-1-c];)c++;let u=o,d=r.length-c;if(u>=r.length&&d>=r.length){let t=e[e.length-1],n=t&&t.text?t.text.length:0,a=i.slice(Math.max(0,r.length-n)),o=e.map((t,n)=>n===e.length-1?{...t,text:a}:t);return{lockedIds:[t.id],shift:0,items:o,len:i.length}}let f=[],p=0;for(let t of e){let e=(t&&t.text?t.text:``).length;u<p+e&&d>p&&f.push(t.id),p+=e}if(f.length===0)return{lockedIds:[],shift:u===0?i.length-r.length:0,items:e,len:r.length};let m=i.length-r.length,h=d+m,g=e=>e<=u?e:e>=d?e+m:u+Math.min(e-u,Math.max(0,h-u)),_=0;return{lockedIds:f,shift:0,items:e.map(e=>{let t=(e&&e.text?e.text:``).length,n=g(_),r=g(_+t);return _+=t,{...e,text:i.slice(n,r)}}),len:i.length}}function lu(e,t){if(!Array.isArray(e)||e.length===0)return{items:Array.isArray(e)?e:[],changed:0,takeAll:!1};let n=au(e),r=String(t||``);if(!r)return{items:e,changed:0,takeAll:!1};let i=ou(n),a=ou(r);if(i===a)return{items:e,changed:0,takeAll:!1};if(Math.abs(i.length-a.length)+uu(i,a)>2||i.length!==a.length)return e.some(e=>e&&e.state===`locked`)?{items:e,changed:0,takeAll:!1}:{items:[{id:e[0]&&typeof e[0].id==`number`?e[0].id:null,text:r,state:`refined`}],changed:1,takeAll:!0};let o=n.split(``),s=0,c=0;for(let e=0;e<o.length;e++)ou(o[e])!==``&&(s<a.length&&o[e]!==a[s]&&(o[e]=a[s],c+=1),s+=1);if(c===0)return{items:e,changed:0,takeAll:!1};let l=o.join(``),u=0;return{items:e.map(e=>{let t=(e&&e.text?e.text:``).length,n=e&&e.state===`locked`?e.text:l.slice(u,u+t);return u+=t,e&&e.state===`locked`?e:{...e,text:n}}),changed:c,takeAll:!1}}function uu(e,t){if(e.length!==t.length)return 2**53-1;let n=0;for(let r=0;r<e.length;r++)e[r]!==t[r]&&(n+=1);return n}n(`zh`,{voice:{start:`语音输入(开始录音)`,stop:`结束录音并转写`,recording:`正在录音`,listening:`正在聆听…`,transcribing:`正在转写…`,cancel:`取消录音`,done:`完成`,noSpeech:`没有听到声音`,noResult:`未识别到语音`,micDenied:`麦克风未授权`,micDeniedHelp:`侧边栏里浏览器不会弹授权框,请到配置页「语音输入 → 麦克风权限」授权一次`,micDeniedAction:`去授权`,micDeniedActionTitle:`打开配置页授权麦克风(侧边栏内无法弹出授权框)`,unavailable:`语音功能不可用`,modelMissing:`缺少语音模型`,modelMissingHelp:`请在配置页「语音」Tab 中导入模型包`,busy:`有语音任务正在进行`,failed:`语音识别失败`,connectionLost:`连接中断`,tooShort:`录音太短`,maxDuration:`已达单次录音时长上限,正在转写…`,unsupported:`当前浏览器不支持录音`,keyRightAlt:`右侧 Alt`,keyRightCtrl:`右侧 Ctrl`,btnTitle:`语音输入({keys})`,deviceFallback:`原麦克风不可用,已改用系统默认`,refineListening:`正在听…(已定稿 {n} 句)`,refineCorrecting:`正在校正…`,refineCorrected:`已校正 {n} 处`,refineDegraded:`本机性能有限,已关闭逐句精修(松手后仍会整体校正)`}}),n(`en`,{voice:{start:`Voice input (start recording)`,stop:`Stop and transcribe`,recording:`Recording`,listening:`Listening…`,transcribing:`Transcribing…`,cancel:`Cancel recording`,done:`Done`,noSpeech:`No sound detected`,noResult:`No speech recognised`,micDenied:`Microphone not granted`,micDeniedHelp:`The browser cannot prompt inside the side panel — grant it once in Options → Voice Input → Microphone permission`,micDeniedAction:`Grant access`,micDeniedActionTitle:`Open options to grant microphone access (the side panel cannot show the prompt)`,unavailable:`Voice input unavailable`,modelMissing:`Speech model missing`,modelMissingHelp:`Import a model pack in the Options "Voice" tab`,busy:`Another voice task is running`,failed:`Speech recognition failed`,connectionLost:`Connection lost`,tooShort:`Recording too short`,maxDuration:`Recording length limit reached, transcribing…`,unsupported:`Recording is not supported in this browser`,keyRightAlt:`Right Alt`,keyRightCtrl:`Right Ctrl`,btnTitle:`Voice input ({keys})`,deviceFallback:`Selected microphone unavailable — using the system default`,refineListening:`Listening… ({n} sentences finalized)`,refineCorrecting:`Refining…`,refineCorrected:`{n} correction(s) applied`,refineDegraded:`This machine is too slow for per-sentence refinement (the final pass still runs)`}});var du=15e3,fu=16e3,pu=2500,mu=.008,hu=350,gu=24,H={input:null,btn:null,bar:null,wave:null,timerEl:null,statusEl:null,permBtn:null,barEls:[],status:null,armed:!1,phase:`idle`,port:null,stream:null,ctx:null,node:null,source:null,startedAt:0,timer:null,silentSince:0,silenceWarned:!1,draft:null,lastText:``,appliedText:``,appliedValue:``,openText:``,mute:null,programmatic:!1,draftSupported:!0,finishWaitTimer:null,adjustInputHeight:null,shortcutCfg:{...Ne},shortcutTrigger:null,shortcutBound:!1,deviceFellBack:!1};function _u(e){return typeof e==`string`?e:``}function vu(e){let t=Math.max(0,Math.floor(e/1e3));return`${String(Math.floor(t/60)).padStart(2,`0`)}:${String(t%60).padStart(2,`0`)}`}function yu(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode.apply(null,t.subarray(e,e+r));return btoa(n)}function bu(e,t,n){if(t===n)return e;let r=t/n,i=Math.floor(e.length/r),a=new Float32Array(i);for(let t=0;t<i;t++){let n=t*r,i=Math.floor(n),o=n-i,s=e[i]||0;a[t]=s+((e[i+1]===void 0?s:e[i+1])-s)*o}return a}function xu(e){let t=new Int16Array(e.length);for(let n=0;n<e.length;n++){let r=e[n]<-1?-1:e[n]>1?1:e[n];t[n]=r<0?r*32768:r*32767}return t}async function Su(e=!1){try{let t=await chrome.runtime.sendMessage({type:`ASR_GET_STATUS`,force:e});if(t&&t.success&&t.status)return H.status=t.status,H.status}catch(e){i.debug(`[Voice] status fetch failed:`,e?.message||e)}return H.status=null,null}function Cu(e){return!e||e.success===!1?!1:typeof e.available==`boolean`?e.available:e.deps?.ready===!0&&e.modelsReady===!0&&e.enabled===!0}function wu({value:e,draft:t,text:n,caret:r,canReplace:i=!0}){let a=typeof e==`string`?e:``;if(!t)return{value:a,caret:a.length,len:0};if(!i){let e=typeof r==`number`?Math.min(Math.max(0,r),a.length):a.length;return{value:a.slice(0,e)+n+a.slice(e),caret:e+n.length,len:0}}let o=Math.min(Math.max(0,t.start),a.length),s=Math.min(Math.max(o,t.start+t.len),a.length);return{value:a.slice(0,o)+n+a.slice(s),caret:o+n.length,len:n.length}}function Tu({value:e,draft:t,canReplace:n=!0}){let r=typeof e==`string`?e:``;if(!t||!n||t.len<=0)return{value:r,caret:r.length};let i=Math.min(Math.max(0,t.start),r.length),a=Math.min(Math.max(i,t.start+t.len),r.length);return{value:r.slice(0,i)+r.slice(a),caret:i}}function Eu(e){return!e||e.isComposing||e.repeat?!1:e.altKey===!0&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyV`}async function Du(){return H.armed=Cu(await Su()),H.btn&&(H.btn.style.display=H.armed?``:`none`),!H.armed&&H.phase!==`idle`&&id({rollback:!0}),H.armed}function Ou(){if(!H.draft||!H.input)return;let e=au(H.draft.items),t=H.input.value,n=_u(H.appliedValue),r=H.draft.start,i=r+e.length,a=0;for(;a<n.length&&a<t.length&&n[a]===t[a];)a+=1;let o=0,s=Math.min(n.length-a,t.length-a);for(;o<s&&n[n.length-1-o]===t[t.length-1-o];)o+=1;let c=a;if(n.length-o<=r){H.draft.start=Math.max(0,r+(t.length-n.length));return}if(c>i)return;let l=Math.max(0,n.length-i),u=t.slice(r,Math.max(r,t.length-l)),d=cu(H.draft.items,e,u);d.shift&&(H.draft.start+=d.shift),d.lockedIds.length!==0&&(H.draft.items=d.items.map(e=>d.lockedIds.includes(e.id)?{...e,state:`locked`}:e),H.draft.len=d.len)}function ku(){let e=H.input;if(!e)return{start:0,len:0,items:[]};let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length,n=typeof e.selectionEnd==`number`?e.selectionEnd:t;return t!==n&&e.setRangeText(``,t,n,`end`),{start:t,len:0,items:[]}}function Au(e,t){let n=_u(e),r=_u(t);return r?n?r.startsWith(n)?r.slice(n.length):null:r:``}function ju(e,t){let n=H.input;if(n){H.programmatic=!0,H.appliedValue=e,n.value=e;try{n.setSelectionRange(t,t)}catch{}H.programmatic=!1;try{document.dispatchEvent(new CustomEvent(`voice-draft-written`))}catch{}try{H.adjustInputHeight?.()}catch{}try{n.focus()}catch{}}}function Mu(e=!1){let t=H.input;if(!t||!H.draft)return;let n=au(H.draft.items);if(!e&&n===_u(H.appliedText))return;let r=typeof t.selectionStart==`number`?t.selectionStart:void 0,i=H.draft.start,a=i+H.draft.len,o=wu({value:t.value,draft:{start:i,len:H.draft.len},text:n,caret:r,canReplace:H.draftSupported});typeof r==`number`&&r>i&&r<a&&(o.caret=i+Math.min(r-i,n.length)),H.draft.len=n.length,H.appliedText=n,ju(o.value,o.caret)}function Nu(e){if(!H.input||!H.draft)return;let t=Array.isArray(H.draft.items)?H.draft.items:[],n=t.findIndex(e=>e.id===null),r=_u(e);if(n>=0&&t[n].state===`locked`){let e=Au(H.openText,r);if(H.openText=r,!e)return;H.draft.items=t.map((t,r)=>r===n?{...t,text:t.text+e}:t)}else H.openText=r,H.draft.items=n>=0?t.map((e,t)=>t===n?{...e,text:r}:e):t.concat([{id:null,text:r,state:`draft`}]);Mu()}function Pu(){let e=H.input;if(!e||!H.draft)return;let t=Array.isArray(H.draft.items)&&H.draft.items.some(e=>e.state===`locked`)?{value:e.value,caret:e.value.length}:Tu({value:e.value,draft:H.draft,canReplace:H.draftSupported});if(t.value!==e.value){H.programmatic=!0,H.appliedValue=t.value,e.value=t.value;let n=Math.min(t.caret,e.value.length);try{e.setSelectionRange(n,n)}catch{}H.programmatic=!1;try{H.adjustInputHeight?.()}catch{}}H.draft=null,H.lastText=``,H.appliedText=``,H.openText=``}function Fu(){if(H.wave){H.wave.textContent=``,H.barEls=[];for(let e=0;e<gu;e++){let e=document.createElement(`i`);H.wave.appendChild(e),H.barEls.push(e)}}}function Iu(e,t=``){H.statusEl&&(H.statusEl.textContent=e,H.statusEl.className=`voice-recorder-status`+(t?` is-${t}`:``))}function Lu(){H.bar&&(H.bar.classList.add(`show`),H.bar.removeAttribute(`aria-hidden`))}function Ru(e){H.permBtn&&(H.permBtn.style.display=e?``:`none`)}function zu(){let e=document.activeElement;if(!(!H.bar||!e||!H.bar.contains(e))){if(H.input&&typeof H.input.focus==`function`)try{H.input.focus({preventScroll:!0});return}catch{}try{e.blur()}catch{}}}function Bu(){H.bar&&(typeof document>`u`||!document.body||(zu(),Ru(!1),H.bar.classList.remove(`show`),H.bar.setAttribute(`aria-hidden`,`true`),H.barEls.forEach(e=>{e.style.height=``,e.style.opacity=``}),H.timerEl&&(H.timerEl.textContent=`00:00`)))}function Vu(e){if(!H.barEls.length)return;let t=Math.min(1,Math.sqrt(Math.max(0,e))*6);for(let e=0;e<H.barEls.length-1;e++)H.barEls[e].style.height=H.barEls[e+1].style.height,H.barEls[e].style.opacity=H.barEls[e+1].style.opacity;let n=H.barEls[H.barEls.length-1];n.style.height=`${Math.max(2,Math.round(t*18))}px`,n.style.opacity=t>.06?`1`:`0.35`}function Hu(e){H.btn&&(H.btn.classList.toggle(`recording`,e),H.btn.setAttribute(`aria-pressed`,e?`true`:`false`),H.btn.setAttribute(`aria-label`,r(e?`voice.stop`:`voice.start`)),H.btn.title=r(e?`voice.stop`:`voice.start`))}function Uu(e){document.body?.classList.toggle(`voice-recording-active`,!!e)}function Wu(){if(H.port)return H.port;try{let e=chrome.runtime.connect({name:`asr`});return e.onMessage.addListener(od),e.onDisconnect.addListener(()=>{H.port=null,(H.phase===`recording`||H.phase===`finalizing`)&&($u(),ed(),H.draft=null,H.lastText=``,Hu(!1),Uu(!1),Iu(r(`voice.connectionLost`),`warn`),setTimeout(()=>{H.phase===`idle`&&Bu()},3500))}),H.port=e,e}catch(e){return i.warn(`[Voice] connect port failed:`,e?.message||e),null}}function Gu(e,t){if(Vu(t),Ku(t),H.port)try{H.port.postMessage({type:`audio`,data:yu(e)})}catch(e){i.debug(`[Voice] post audio failed:`,e?.message||e)}}function Ku(e){if(H.phase!==`recording`&&H.phase!==`starting`)return;if(e>=mu){H.silentSince=0,H.silenceWarned&&(H.silenceWarned=!1,Iu(r(`voice.listening`)));return}let t=Date.now();if(!H.silentSince){H.silentSince=t;return}H.silenceWarned||t-H.silentSince>=pu&&(H.silenceWarned=!0,Iu(r(`voice.noSpeech`),`warn`))}var qu=[`voice-capture-worklet.js`,`dist/voice-capture-worklet.js`],Ju;async function Yu(){if(Ju!==void 0)return Ju;for(let e of qu){let t=``;try{t=chrome.runtime.getURL(e)}catch{continue}try{let e=await fetch(t);if(e&&e.ok)return Ju=t,t}catch{}}return Ju=null,null}async function Xu(e,t){let n=await Yu();if(!n)throw Error(`worklet not found in extension`);await e.audioWorklet.addModule(n);let r=new AudioWorkletNode(e,`voice-capture`),i=Math.abs(e.sampleRate-fu)>1;r.port.onmessage=t=>{let n=t.data;if(!n||n.type!==`chunk`||!n.pcm)return;let r=new Int16Array(n.pcm);if(i){let t=new Float32Array(r.length);for(let e=0;e<r.length;e++)t[e]=r[e]/32768;r=xu(bu(t,e.sampleRate,fu))}Gu(r,n.rms||0)},t.connect(r),H.node=r}function Zu(e,t){let n=e.createScriptProcessor(4096,1,1),r=Math.abs(e.sampleRate-fu)>1;n.onaudioprocess=t=>{let n=t.inputBuffer.getChannelData(0),i=new Float32Array(n);r&&(i=bu(i,e.sampleRate,fu));let a=0;for(let e=0;e<i.length;e++)a+=i[e]*i[e];Gu(xu(i),Math.sqrt(a/Math.max(1,i.length)))},t.connect(n);let i=e.createGain();i.gain.value=0,n.connect(i),i.connect(e.destination),H.mute=i,H.node=n}async function Qu(){if(!navigator.mediaDevices?.getUserMedia)throw Iu(r(`voice.unsupported`),`warn`),Error(`unsupported`);let e=await ot(await nt());H.stream=e.stream,H.deviceFellBack=e.fellBack===!0;let t=window.AudioContext||window.webkitAudioContext,n;try{n=new t({sampleRate:fu})}catch{n=new t}if(n.state===`suspended`)try{await n.resume()}catch{}H.ctx=n;let a=n.createMediaStreamSource(e.stream);H.source=a;try{await Xu(n,a)}catch(e){i.warn(`[Voice] worklet unavailable, fallback to ScriptProcessor:`,e?.message||e),Zu(n,a)}}function $u(){H.timer&&=(clearInterval(H.timer),null);try{H.node?.port?.close?.()}catch{}try{H.node?.disconnect?.()}catch{}try{H.mute?.disconnect?.()}catch{}try{H.source?.disconnect?.()}catch{}try{H.stream?.getTracks?.().forEach(e=>e.stop())}catch{}try{H.ctx?.close?.()}catch{}H.node=null,H.mute=null,H.source=null,H.stream=null,H.ctx=null}function ed(){H.finishWaitTimer&&=(clearTimeout(H.finishWaitTimer),null),H.phase=`idle`}function td(){let e=()=>{let e=Date.now()-H.startedAt;H.timerEl&&(H.timerEl.textContent=vu(e));let t=H.status;e>=(t&&t.maxRecordingMs||300*1e3)&&rd(`stop`)};H.timer&&clearInterval(H.timer),H.timer=setInterval(e,200),e()}async function nd(e={}){if(H.phase!==`idle`||!H.armed&&!e.force&&(await Du(),!H.armed||H.phase!==`idle`))return!1;H.phase=`starting`,H.lastText=``,H.appliedText=``,H.openText=``,H.draft=ku(),H.appliedValue=H.input?H.input.value:``,H.draftSupported=!0,H.silentSince=0,H.silenceWarned=!1,Lu(),Iu(r(`voice.listening`)),Hu(!0),Uu(!0);let t=Wu();if(!t)return Iu(r(`voice.failed`),`warn`),ed(),Hu(!1),Uu(!1),!1;try{await Qu()}catch(e){if(H.phase!==`starting`)return $u(),!1;let n=e?.name||``,i=n===`NotAllowedError`||n===`SecurityError`;i?(Iu(r(`voice.micDenied`),`warn`),Ru(!0)):Iu(r(`voice.failed`),`warn`),$u(),ed(),Hu(!1),Uu(!1);try{t.postMessage({type:`cancel`})}catch{}return setTimeout(()=>{H.phase===`idle`&&Bu()},i?12e3:4e3),!1}if(H.phase!==`starting`)return $u(),!1;H.startedAt=Date.now(),H.phase=`recording`,Iu(r(`voice.listening`)),H.deviceFellBack&&(H.deviceFellBack=!1,Iu(r(`voice.deviceFallback`),`warn`),setTimeout(()=>{H.phase===`recording`&&Iu(r(`voice.listening`))},4e3)),td();try{t.postMessage({type:`start`,language:H.status&&H.status.language||`auto`})}catch(e){i.debug(`[Voice] post start failed:`,e?.message||e)}return!0}function rd(e){if(H.phase!==`recording`)return;H.phase=`finalizing`;let t=Date.now()-H.startedAt;if($u(),Hu(!1),Uu(!1),e===`cancel`){try{H.port?.postMessage({type:`cancel`})}catch{}Pu(),ed(),Bu();return}if(t<hu&&!H.lastText){try{H.port?.postMessage({type:`cancel`})}catch{}Pu(),Iu(r(`voice.tooShort`),`warn`),ed(),setTimeout(()=>{H.phase===`idle`&&Bu()},2200);return}Iu(r(`voice.transcribing`));try{H.port?.postMessage({type:`stop`})}catch{}H.finishWaitTimer&&clearTimeout(H.finishWaitTimer),H.finishWaitTimer=setTimeout(()=>{H.phase===`finalizing`&&ad(H.lastText,{fallback:!0})},6e4)}function id({rollback:e=!0}={}){if(H.phase===`idle`)return!1;let t=H.phase===`recording`||H.phase===`finalizing`;if(H.phase=`finalizing`,$u(),t)try{H.port?.postMessage({type:`cancel`})}catch{}return e&&Pu(),ed(),Hu(!1),Uu(!1),Bu(),!0}function ad(e,t={}){let n=_u(e).trim();if(!n){Pu(),Iu(r(`voice.noResult`),`warn`),ed(),setTimeout(()=>{H.phase===`idle`&&Bu()},2200);return}if(!H.draft){let e=H.input;if(e){let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length;ju(e.value.slice(0,t)+n+e.value.slice(t),t+n.length)}Iu(r(`voice.done`)),ed(),setTimeout(()=>{H.phase===`idle`&&Bu()},1200);return}let a=Array.isArray(t.texts)?t.texts.filter(e=>typeof e==`string`&&e.trim()):[];a.length>1&&!H.draft.items.some(e=>e.id!==null||e.state===`locked`)&&(H.draft.items=a.map((e,t)=>({id:t+1,text:e,state:`refined`}))),H.draft.items.length===0&&(H.draft.items=[{id:null,text:n,state:`refined`}]);let{items:o,changed:s,takeAll:c}=lu(H.draft.items,n);H.draft.items=o,Mu(!0),c&&i.debug(`[Voice] final text took over the whole draft`),H.draft=null,H.lastText=``,H.appliedText=``,H.openText=``,ed(),Iu(s>0?r(`voice.refineCorrected`,{n:s}):r(`voice.done`)),setTimeout(()=>{H.phase===`idle`&&Bu()},s>0?1800:1200)}function od(e){if(!(!e||typeof e.type!=`string`)){if(e.type===`ready`){e.draft===!1&&H.phase===`recording`&&i.debug(`[Voice] online model missing, draft disabled`);return}if(e.type===`partial`){if(H.phase!==`recording`&&H.phase!==`finalizing`)return;H.lastText=_u(e.text),Nu(typeof e.open==`string`?e.open:H.lastText);return}if(e.type===`endpoint`)return H.phase!==`recording`&&H.phase,void 0;if(e.type===`sentence`){if(H.phase!==`recording`&&H.phase!==`finalizing`||!H.draft||typeof e.id!=`number`)return;let t=typeof e.refined==`string`&&e.refined?e.refined:null,n=Array.isArray(H.draft.items)?H.draft.items:[],i=n.findIndex(e=>e.id===null),a=n;if(!t&&i>=0){let t=n[i];a=n.map((n,r)=>r===i?t.state===`locked`?{...n,id:e.id}:{id:e.id,text:_u(e.draft)||n.text,state:`draft`}:n),H.openText=``}if(t&&(a.some(t=>t.id===e.id)?a=su(a,{id:e.id,text:t}).map(t=>t.id===e.id&&t.state!==`locked`?{...t,state:`refined`}:t):a.some(e=>e.id===null)||(a=a.concat([{id:e.id,text:t,state:`refined`}]))),a!==n&&(H.draft.items=a,Mu()),t&&H.phase===`recording`){let e=H.draft.items.filter(e=>e.id!==null&&e.state===`refined`).length;Iu(r(`voice.refineListening`,{n:e}))}return}if(e.type===`refine`){e.enabled===!1&&(H.phase===`recording`||H.phase===`finalizing`)&&Iu(r(`voice.refineDegraded`),`warn`);return}if(e.type===`final`){if(H.phase!==`recording`&&H.phase!==`finalizing`)return;ad(e.text||H.lastText,{fallback:e.fallback===!0,texts:e.texts});return}if(e.type===`closed`){H.phase===`finalizing`&&ad(H.lastText,{fallback:!0});return}if(e.type===`error`){let t=e.code||`internal`;if(t===`max_duration`){H.phase===`recording`&&rd(`stop`),Iu(r(`voice.maxDuration`),`warn`);return}Iu(t===`busy`?r(`voice.busy`):t===`model_missing`?`${r(`voice.modelMissing`)} — ${r(`voice.modelMissingHelp`)}`:r(`voice.failed`),`warn`),$u(),(H.phase===`recording`||H.phase===`finalizing`)&&Pu(),ed(),Hu(!1),Uu(!1),t===`model_missing`&&Du(),setTimeout(()=>{H.phase===`idle`&&Bu()},3500)}}}async function sd(){return H.phase===`recording`?(rd(`stop`),!0):H.phase===`starting`||H.phase===`finalizing`?!1:nd()}function cd(){return H.phase===`recording`||H.phase===`starting`||H.phase===`finalizing`}function ld(){return cd()?id({rollback:!0}):!1}function ud(){return H.phase===`idle`?!1:id({rollback:!1})}async function dd(){try{let e=(await chrome.storage.session?.get?.(`pendingVoiceStart`))?.pendingVoiceStart;return!(!e||(await chrome.storage.session.remove(`pendingVoiceStart`),typeof e!=`number`||Date.now()-e>du))}catch{return!1}}function fd(){if(!H.btn)return;let e=[`Alt+V`];H.shortcutCfg.rightAlt&&e.push(r(`voice.keyRightAlt`)),H.shortcutCfg.rightCtrl&&e.push(r(`voice.keyRightCtrl`));let t=r(`voice.btnTitle`,{keys:e.join(` / `)});H.btn.title=t,H.btn.setAttribute(`aria-label`,t)}async function pd(){if(H.shortcutCfg=await Me(),H.shortcutTrigger||=Ae(()=>H.shortcutCfg),fd(),H.shortcutBound)return;H.shortcutBound=!0,document.addEventListener(`keydown`,e=>{H.shortcutTrigger?.onKeyDown(e)===`cancel`&&e.preventDefault()},!0),document.addEventListener(`keyup`,e=>{H.shortcutTrigger?.onKeyUp(e)===`trigger`&&(!H.armed&&H.phase===`idle`||(e.preventDefault(),sd()))},!0),window.addEventListener(`blur`,()=>{H.shortcutTrigger?.reset()}),ke(e=>{H.shortcutCfg=e,fd()});let e=async()=>{try{let e=await Me();if(e.rightAlt===H.shortcutCfg.rightAlt&&e.rightCtrl===H.shortcutCfg.rightCtrl)return;H.shortcutCfg=e,fd()}catch{}};window.addEventListener(`focus`,()=>{e()}),document.addEventListener(`visibilitychange`,()=>{document.hidden||e()})}async function md(e={}){if(H.input=document.getElementById(`userInput`),H.btn=document.getElementById(`voiceInputBtn`),H.bar=document.getElementById(`voiceRecorderBar`),H.wave=document.getElementById(`voiceWave`),H.timerEl=document.getElementById(`voiceTimer`),H.statusEl=document.getElementById(`voiceStatusText`),H.permBtn=document.getElementById(`voicePermBtn`),H.adjustInputHeight=typeof e.adjustInputHeight==`function`?e.adjustInputHeight:null,!H.input||!H.btn){i.debug(`[Voice] input or button missing, skip init`);return}Fu(),Hu(!1),Iu(r(`voice.listening`)),await pd(),H.btn.addEventListener(`click`,e=>{e.preventDefault(),sd()}),document.getElementById(`voiceCancelBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),id({rollback:!0})}),document.getElementById(`voiceDoneBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),rd(`stop`)}),H.permBtn?.addEventListener(`click`,e=>{e.preventDefault();try{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`asr`}).catch?.(()=>{})}catch{}Iu(r(`voice.micDeniedHelp`),`warn`),Ru(!1)}),H.input.addEventListener(`input`,()=>{H.programmatic||(H.phase===`recording`||H.phase===`finalizing`)&&Ou()}),chrome.runtime.onMessage.addListener((e,t,n)=>e?.type===`VOICE_TOGGLE`?(sd(),n?.({success:!0}),!1):(e?.type===`ASR_STATUS_CHANGED`&&Du(),!1)),window.addEventListener(`pagehide`,()=>{ud()}),document.addEventListener(`visibilitychange`,()=>{document.hidden&&H.phase===`recording`&&ud()}),await Du()&&await dd()&&setTimeout(()=>{sd()},220)}var hd=`panel_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8),gd=new Set,_d=new Set,vd=null,yd=new Map,bd=`queue-context-cleared`,xd=`queue-context-restored`;function Sd(e){vd=e}function Cd(e){return C.generatingSessionIds.has(e||C.activeSessionId)}function wd(){return{quotedContextText:C.quotedContextText||``,selectedContextText:C.selectedContextText||``,selectedSkills:(C.selectedSkills||[]).slice(),selectedMcpServices:(C.selectedMcpServices||[]).slice(),knowledgeRefs:(C.knowledgeRefs||[]).slice(),selectedPage:C.selectedPage?{...C.selectedPage}:null,attachedImages:(C.attachedImages||[]).slice(),attachedFiles:(C.attachedFiles||[]).slice()}}function Td(e){return e?e.attachmentSummary||(e.attachedImages||[]).length||(e.attachedFiles||[]).length?!0:!!(e.quotedContextText&&e.quotedContextText.trim()||e.selectedContextText&&e.selectedContextText.trim()||(e.selectedSkills||[]).length||(e.selectedMcpServices||[]).length||(e.knowledgeRefs||[]).length||e.selectedPage):!1}function Ed(){return Td(wd())}function Dd(e){let t=e||{},n=(t.attachedImages||[]).length>0,i=(t.attachedFiles||[]).length>0;return n&&i?r(`sidePanel.defaultPromptAttachments`):n?r(`sidePanel.defaultPromptImage`):i?r(`sidePanel.defaultPromptFile`):(t.knowledgeRefs||[]).length>0?r(`sidePanel.defaultPromptKnowledge`):t.selectedPage?r(`sidePanel.defaultPromptPage`):t.quotedContextText&&t.quotedContextText.trim()||t.selectedContextText&&t.selectedContextText.trim()?r(`sidePanel.defaultPromptSelection`):(t.selectedSkills||[]).length>0||(t.selectedMcpServices||[]).length>0?r(`sidePanel.defaultPromptContext`):``}function Od(){let e=wd();return Td(e)&&Ad(),e}function kd(e){e&&(e.quotedContextText&&(C.quotedContextText=e.quotedContextText),e.selectedContextText&&(C.selectedContextText=e.selectedContextText),(e.selectedSkills||[]).length&&(C.selectedSkills=e.selectedSkills.slice()),(e.selectedMcpServices||[]).length&&(C.selectedMcpServices=e.selectedMcpServices.slice()),(e.knowledgeRefs||[]).length&&(C.knowledgeRefs=e.knowledgeRefs.slice()),e.selectedPage&&(C.selectedPage={...e.selectedPage}),(e.attachedImages||[]).length&&(C.attachedImages=e.attachedImages.slice()),(e.attachedFiles||[]).length&&(C.attachedFiles=e.attachedFiles.slice()))}function Ad(){let e=(C.attachedImages||[]).length>0;if(C.quotedContextText=``,C.selectedContextText=``,C.selectedSkills=[],C.selectedMcpServices=[],C.knowledgeRefs=[],C.selectedPage=null,C.attachedImages=[],C.attachedFiles=[],e){let e=document.getElementById(`imagePreviewBar`);e&&(e.innerHTML=``,e.style.display=`none`)}document.dispatchEvent(new CustomEvent(bd))}var jd=new Set([`pending`,`extracting`]);function Md(){return(C.attachedFiles||[]).some(e=>jd.has(e&&e.status))}function Nd(e){let t=e&&e.attachedImages||[],n=(e&&e.attachedFiles||[]).map(e=>{if(!e||typeof e.dataUrl!=`string`||!e.dataUrl.startsWith(`blob:`))return e;let t={...e};return delete t.dataUrl,t}),r={...e||{}};return delete r.attachedImages,delete r.attachedFiles,r.attachmentSummary=oi({attachedImages:t,attachedFiles:n}),{light:r,heavy:t.length||n.length?{images:t,files:n}:null}}async function Pd(e){if(!e)return{ok:!1,attachments:!1,wantsAttachments:!1};let t=await ci(e.id)||yd.get(e.id)||null,n=!!(e.attachmentSummary||e.contextSnapshot&&e.contextSnapshot.attachmentSummary);return kd({...e.contextSnapshot||{},attachedImages:t&&t.images||[],attachedFiles:t&&t.files||[]}),document.dispatchEvent(new CustomEvent(xd,{detail:{snapshot:e.contextSnapshot||{}}})),{ok:!0,attachments:!!t,wantsAttachments:n}}async function Fd(e){return e?(yd.delete(e),li(e)):!1}async function Id({autoDrain:e=!0}={}){let t=document.getElementById(`userInput`),n=(t?.value||``).trim()||Dd(wd());if(!n)return{ok:!1,error:`empty`};ud();let i=C.activeSessionId;if(!i)return F(r(`queue.noSession`),`error`),{ok:!1,error:`missing_session`};if(Md())return F(r(`queue.filesStillExtracting`),`warning`,4e3),{ok:!1,error:`files_extracting`};let a=Od(),{light:o,heavy:s}=Nd(a),c=await Fr({sessionId:i,text:n,contextSnapshot:o,hasContext:Td(o),attachmentSummary:o.attachmentSummary,source:`manual`});return c.ok?(s&&((await si(c.item.id,i,s)).ok||(yd.set(c.item.id,s),F(r(`queue.attachmentsVolatile`),`warning`,5e3))),t&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`)),t.focus()),F(r(`queue.enqueued`,{position:c.position}),`success`),document.dispatchEvent(new CustomEvent(`queue-enqueued`,{detail:{sessionId:i,item:c.item}})),e&&!Cd(i)&&!Pr(i)&&Rd(i),c):(kd(a),document.dispatchEvent(new CustomEvent(xd,{detail:{snapshot:a}})),c.error===`queue_full`?F(r(`queue.queueFull`,{limit:c.limit}),`warning`):F(r(`queue.enqueueFailed`),`error`),c)}async function Ld(e){try{let{list:t}=await vi(),n=(t||[]).find(t=>t.id===e);return n?{messageHistory:Array.isArray(n.messageHistory)?n.messageHistory.slice():[],model:n.model,useTools:n.useTools,enabledTools:Array.isArray(n.enabledTools)?n.enabledTools.slice():n.enabledTools,agentId:n.agentId,temperature:n.temperature,topP:n.topP,contextCompaction:n.contextCompaction,workdir:n.workdir||null,workdirAgentId:n.workdirAgentId||null}:null}catch(e){return i.warn(`[QueueRunner] load session state failed:`,e?.message||e),null}}async function Rd(e){let t=e||C.activeSessionId;if(!(!t||!vd)){if(gd.has(t)){_d.add(t);return}gd.add(t);try{do _d.delete(t),await zd(t);while(_d.has(t)&&!Pr(t))}finally{gd.delete(t)}}}async function zd(e){if(Cd(e)||Pr(e))return;let t=Ar(e);if(!t)return;if((t.attempts||0)>=5){await Vr(e,t.id,{status:tr.FAILED,note:`too_many_attempts`}),F(r(`queue.tooManyAttempts`,{count:5}),`error`,5e3);return}if(!await qr(e,t.id,hd)){i.debug(`[QueueRunner] lease held by another panel, skip:`,t.id);return}await Rr(e,t.id,tr.DISPATCHING,{attempts:(t.attempts||0)+1,lastError:null});let n=await ci(t.id)||yd.get(t.id)||null;yd.delete(t.id);let a=!!t.attachmentSummary&&!n;a&&F(r(`queue.attachmentsMissing`),`warning`,5e3);let o={quotedContextText:``,selectedContextText:``,selectedSkills:[],selectedMcpServices:[],knowledgeRefs:[],selectedPage:null,...t.contextSnapshot||{},attachedImages:n&&n.images||[],attachedFiles:n&&n.files||[]},s=e===C.activeSessionId,c=null;if(!s&&(c=await Ld(e),!c)){let t=await Jr(e);t&&i.warn(`[QueueRunner] dropped queue of deleted session:`,e,t);return}let l={ok:!0};try{let n={text:t.text,fromQueue:!0,sessionId:e,context:o};s||(n.sessionState=c),l=await vd(n)||{ok:!0}}catch(e){l={ok:!1,reason:e?.message||`dispatch_error`},i.error(`[QueueRunner] dispatch failed:`,e?.message||e)}Mr(e,t.id)?l.ok===!1?l.delivered?(await Vr(e,t.id,{status:tr.FAILED,note:l.reason||`failed`}),await li(t.id)):(await Br(e,t.id,`dispatch_failed`,l.reason||`dispatch_failed`),_d.delete(e)):(await Vr(e,t.id,{status:tr.DONE,note:a?`relayed_no_attachments`:`relayed`}),await li(t.id)):i.debug(`[QueueRunner] item removed during dispatch, drop result:`,t.id)}var Bd=new Set;function Vd(e){let t=e||C.activeSessionId;return t?(Bd.add(t),t):null}function Hd(e){let t=e||C.activeSessionId;return!!(t&&Ar(t))}async function Ud(e){let t=e||C.activeSessionId;t&&(Bd.delete(t),await Kr(t),await Rd(t))}function Wd(e){Pr(e)||Rd(e)}var Gd=new Map,Kd=new Set,qd=new Map,Jd=new Map;function Yd(e){let t=e&&e.attachmentSummary;return t?(t.imageCount||0)>0||(t.fileCount||0)>0:!1}function Xd(e,t){return`${e}\u0000${t}`}function Zd(e,t){let n=Xd(e,t),r=Gd.get(n);r&&(clearTimeout(r),Gd.delete(n))}async function Qd(e,t,n,r){Zd(e,t);let i=Mr(e,t);!i||i.status!==tr.INJECTING||(await Br(e,t,n,n),r&&F(r,`warning`,4e3))}function $d(e,t,n){return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,r(e))},o=setTimeout(()=>a(null),2e3);try{chrome.runtime.sendMessage({type:`INJECT_MESSAGE`,sessionId:e,itemId:t,text:n},e=>{if(clearTimeout(o),chrome.runtime.lastError){a(null);return}a(e||null)})}catch{clearTimeout(o),a(null)}})}async function ef(e,t,n={}){let i=t||C.activeSessionId,a=n.auto===!0;if(!i||!e)return{ok:!1,error:`missing_session`};let o=Mr(i,e);if(!o)return{ok:!1,error:`not_found`};if(o.status!==tr.QUEUED)return{ok:!1,error:`not_queued`};if(Yd(o))return a||F(r(`queue.injectNoAttachments`),`warning`,4e3),{ok:!1,error:`has_attachments`};let s=Xd(i,e);if(Kd.has(s))return{ok:!1,error:`in_flight`};Kd.add(s);try{await zr(i,e),Gd.set(s,setTimeout(()=>{Qd(i,e,`timeout`,r(`queue.injectTimeout`))},$n));let t=await $d(i,e,o.text);if(!t)return{ok:!0,pending:!0};if(!t.accepted){let n=t.reason||`rejected`;return await Qd(i,e,n,r(n===`no_running_task`?`queue.injectNoTask`:`queue.injectFailed`)),{ok:!1,error:n}}return a?i===C.activeSessionId&&F(r(`queue.autoCarried`,{iteration:n.iteration??`?`}),`success`,2500):F(r(`queue.injectAccepted`),`success`,2500),{ok:!0,pending:!0}}finally{Kd.delete(s)}}function tf(e){let t=document.getElementById(`userInput`);t&&t.value.trim()===e&&(t.value=``,t.style.height=`auto`,t.dispatchEvent(new Event(`input`)),t.focus())}async function nf(e){let t=C.activeSessionId,n=String(e||``).trim();if(!t||!n)return{ok:!1,error:`empty`};if(ud(),!Cd(t))return F(r(`queue.injectNoTask`),`warning`,3e3),{ok:!1,error:`no_running_task`};let i=`adhoc_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,7),a=setTimeout(()=>{qd.has(i)&&(qd.delete(i),F(r(`queue.injectTimeoutAdhoc`),`warning`,4e3))},$n);qd.set(i,{text:n,timer:a});let o=await $d(t,i,n);return o&&!o.accepted?(clearTimeout(a),qd.delete(i),F(o.reason===`no_running_task`?r(`queue.injectNoTask`):r(`queue.injectFailed`),`warning`,4e3),{ok:!1,error:o.reason}):(o&&o.accepted&&F(r(`queue.injectAccepted`),`success`,2500),{ok:!0,pending:!0})}function rf(e){let t=e?.sessionId,n=Array.isArray(e?.items)?e.items:[];if(!t||n.length===0)return;let i=0;for(let r of n){let n=qd.get(r);if(n){clearTimeout(n.timer),qd.delete(r),tf(n.text);continue}Zd(t,r),Mr(t,r)&&(i++,Vr(t,r,{status:tr.INJECTED,note:`injected`,callId:e.callId||null,iteration:e.iteration??null}))}i>0&&t===C.activeSessionId&&F(r(`queue.injected`),`success`,2500),document.dispatchEvent(new CustomEvent(`queue-injected`,{detail:{sessionId:t,items:n,iteration:e.iteration??null}}))}function af(e){let t=e?.sessionId,n=Array.isArray(e?.items)?e.items:[];if(!t||n.length===0)return;let i=e.reason||`rejected`,a=r(i===`task_ended`?`queue.injectNoTask`:`queue.injectFailed`);for(let e of n){let r=qd.get(e);if(r){clearTimeout(r.timer),qd.delete(e);continue}Qd(t,e,i,e===n[0]?a:null)}}function of(e){let t=e?.sessionId;if(!t||e.isSubtask===!0||Pr(t))return;let n=tu(e.executionLog);if(!n)return;let r=Ar(t),a=r&&!Yd(r)?r:null,o=C.chatConfig||{},s=nu({tracker:Jd.get(t),callId:e.callId||null,iteration:n,everyN:o.queueAutoCarryEveryNIterations,enabled:o.queueAutoCarry!==!1,hasCandidate:!!a});if(Jd.set(t,s.tracker),!s.carry)return;i.debug(`[QueueRunner] auto carry item`,a.id,`at iteration`,n,`session`,t);let c=e.callId||null;ef(a.id,t,{auto:!0,iteration:n}).then(e=>{!e||e.ok!==!0||Jd.set(t,ru(Jd.get(t),{callId:c}))})}function sf(e){!e||typeof e!=`object`||(e.type===`INJECT_ABSORBED`?rf(e):e.type===`INJECT_REJECTED`?af(e):e.type===`EXECUTION_STATUS_UPDATE`&&of(e))}async function cf(){try{if(Sr()){i.warn(`[QueueRunner] skip attachment prune in degraded mode`);return}let e=new Set;for(let t of Nr())for(let n of Er(t))e.add(n.id);let t=await di(e);t&&i.debug(`[QueueRunner] pruned orphan attachments:`,t)}catch(e){i.warn(`[QueueRunner] prune orphan attachments failed:`,e?.message||e)}}var lf=!1,uf=null,df=[];function ff(e,t){document.addEventListener(e,t),df.push([e,t])}var pf=1500;function mf(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,t(e))},i=setTimeout(()=>r(null),pf);try{chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`,sessionId:e},e=>{if(clearTimeout(i),chrome.runtime.lastError){r(null);return}r(!!(e&&e.running))})}catch{clearTimeout(i),r(null)}})}async function hf(){if(!C.activeSessionId)return!1;let e=Nr();if(e.length===0)return!0;let t=!1;for(let n of e){if(Pr(n)||Cd(n)||!Ar(n))continue;let e=await mf(n);if(e===null){t=!0;continue}if(!e&&!(Pr(n)||Cd(n)))return await Rd(n),!0}return!t}function gf(){if(uf)return;let e=0,t=async()=>{if(uf=null,++e>25)return;let n=!1;try{n=await hf()}catch(e){i.warn(`[QueueRunner] auto-resume attempt failed:`,e?.message||e)}n||(uf=setTimeout(t,800))};uf=setTimeout(t,300)}async function _f({autoResume:e=!0}={}){lf||(lf=!0,await Cr(),wr(),cf(),Zl(Wd),typeof chrome<`u`&&chrome.runtime?.onMessage?.addListener&&chrome.runtime.onMessage.addListener(sf),ff(`task-stop-requested`,e=>{let t=e?.detail?.sessionId||C.activeSessionId;if(t){if(Bd.delete(t)){Kr(t).then(()=>Rd(t));return}Gr(t,`user_stopped`)}}),ff(`generating-state-changed`,()=>{let e=C.activeSessionId;if(e){if(C.isGenerating&&Pr(e)){Kr(e);return}for(let e of Nr())if(!(Pr(e)||Cd(e))&&Ar(e)){Rd(e);break}}}),ff(`session-switched`,()=>gf()),ff(`visibilitychange`,()=>{document.visibilityState===`visible`&&gf()}),e&&gf())}async function vf(e){let t=e||C.activeSessionId;t&&(await Kr(t),await Rd(t))}var yf=[/(?:按|按照|以|用|走|使用|开启|启用|切换?到)\s*(?:goal|目标)\s*模式/i,/(?:进入|改成|改为|设为|设置为|切换到)\s*(?:goal|目标)\s*模式/i,/\b(?:in|use|using|enable|enter|switch\s+to|with)\s+(?:the\s+)?goal\s+mode\b/i,/(?:无人值守|不用管我|别停下来|不要停|直到(?:我|你)(?:叫停|喊停))/,/\bunattended\b|\bwithout\s+(?:me|supervision)\b|\bdon'?t\s+stop\s+until\b/i,/(?:持续|一直|连续)(?:执行|跑|做|干|尝试|迭代)\s*(?:到|直到)/,/(?:跑到|做到|干到|做到)(?:完成|通过|结束|成功)/,/\bkeep\s+(?:working|going|trying|iterating)\s+until\b/i,/\brun\s+until\s+(?:done|complete|passing|it\s+passes)\b/i],bf=[/直到\s*[^。;;\n]{1,40}?(?:全部|都)?(?:通过|完成|跑通|变绿)/,/(?:确保|保证)\s*[^。;;\n]{1,40}?(?:通过|跑通|可用)/,/\buntil\s+[^.;\n]{1,40}?(?:pass|passes|green|works)\b/i],xf=/(?:不要|不用|不必|无需|取消|关闭|停用|停止|退出|不按|不以|别|不)\s*$/,Sf=/\b(?:do\s+not|don'?t|does\s+not|doesn'?t|never|avoid|without|no\s+need\s+to)\s+(?:(?:use|using|enable|enabling|enter|entering|switch(?:ing)?\s+to|turn\s+on|activate|run(?:\s+in)?|go(?:\s+with)?)\s*)?$/i,Cf=2e3,wf=40;function Tf(e,t,n){let r=[];for(let i of t){let t=i.flags.includes(`g`)?i.flags:`${i.flags}g`,a=new RegExp(i.source,t),o;for(;(o=a.exec(e))!==null&&o[0].length!==0;){let t=e.slice(Math.max(0,o.index-wf),o.index);if(!(n&&(xf.test(t)||Sf.test(t)))&&(r.push(o[0].trim()),o[0].length===0))break}}return r}function Ef(e){let t={detected:!1,strength:`none`,matches:[]};if(typeof e!=`string`)return t;let n=e.trim();if(!n)return t;let r=n.slice(0,Cf),i=Tf(r,yf,!0);if(i.length>0)return{detected:!0,strength:`strong`,matches:Df(i).slice(0,3)};let a=Tf(r,bf,!0);return a.length>0?{detected:!1,strength:`weak`,matches:Df(a).slice(0,3)}:t}function Df(e){let t=new Set,n=[];for(let r of e){let e=r.toLowerCase();t.has(e)||(t.add(e),n.push(r))}return n}function Of(e){if(typeof e!=`string`)return``;let t=e,n=Tf(e.slice(0,Cf),yf,!0);for(let e of n)e&&(t=t.replace(e,` `));return t=t.replace(/^[\s,,。.、::;;-]+/,``).trim(),t||e.trim()}var kf={active:`goal.statusActive`,paused:`goal.statusPaused`,achieved:`goal.statusAchieved`,unmet:`goal.statusUnmet`,budget_limited:`goal.statusBudgetLimited`,cleared:`goal.statusCleared`},Af=new Set([`achieved`,`unmet`,`cleared`]),U=null;function jf(e){return document.getElementById(e)}function Mf(e){let t=kf[e];return t?r(t):String(e||``)}function Nf(e){return!!e&&Af.has(e.status)}function Pf(e){return new Promise(t=>{try{chrome.runtime.sendMessage(e,e=>{if(chrome.runtime.lastError){i.debug(`[GoalPanel] message failed:`,chrome.runtime.lastError.message),t(null);return}t(e||null)})}catch(e){i.debug(`[GoalPanel] message threw:`,e?.message),t(null)}})}function Ff(e){return Pf({type:`SET_GOAL`,...e})}function If(){if(!U)return;let e=C.goalSnapshot,t=C.goalMode;U.toggle.checked=t;let n=t&&!!e&&(e.status===`paused`||e.status===`budget_limited`);U.group&&(U.group.dataset.goalIdle=n?`1`:``);let i=t||e&&!Nf(e);if(U.bar.style.display=i?``:`none`,!i)return;if(U.bar.dataset.status=e?e.status:`none`,U.status.textContent=e?Mf(e.status):``,U.status.style.display=e?``:`none`,e){U.objective.textContent=e.objective||``,U.objective.title=e.objective||``;let t=M(e,r);n&&e.status===`paused`&&t.push(r(`goal.pausedHintInline`)),U.meta.textContent=t.join(` · `)}else U.objective.textContent=r(`goal.startHint`),U.objective.title=``,U.meta.textContent=``;let a=!!e&&e.status===`active`&&e.autoApprove===!0;U.approve.style.display=a?``:`none`;let o=!!e&&e.status===`active`,s=!!e&&(e.status===`paused`||e.status===`budget_limited`);U.pause.style.display=o?``:`none`,U.resume.style.display=s?``:`none`,U.edit.style.display=e?``:`none`,U.clear.style.display=e?``:`none`}function Lf(){return C.activeSessionId||null}async function Rf(e=Lf()){if(!e)return C.goalSnapshot=null,If(),null;let t=await Pf({type:`GET_GOAL`,sessionId:e});return e===Lf()?(C.goalSnapshot=t?.goal||null,If(),C.goalSnapshot):null}var zf=null;async function Bf(){return zf||(zf=await new Promise(e=>{try{chrome.storage.local.get([`goalConfig`],t=>e(t?.goalConfig||{}))}catch(t){i.debug(`[GoalPanel] read goalConfig failed:`,t?.message),e({})}}),zf)}async function Vf(){let e=jf(`goalGroup`);if(!e)return;let t=await Bf();e.style.display=t.enabled===!1?`none`:``}async function Hf({sessionId:e=Lf(),text:t=``,attachments:n=[]}={}){if(!e||!String(t||``).trim())return null;let i=await Bf(),a=!!C.goalMode;if(i.enabled===!1)return a&&F(r(`goal.disabledHint`),`warning`),null;let o=t;if(!a){if(i.intentDetection===!1)return null;let e=Ef(t);if(!e.detected)return e.strength===`weak`&&F(r(`goal.intentHint`),`info`,6e3),null;o=String(Of(t)||``).trim()||t}let s=await Ff({sessionId:e,action:`set`,objective:o,attachments:Array.isArray(n)?n:[],createdBy:a?`toggle`:`intent`,autoApprove:a});return!s||s.success===!1?(s?.disabled&&F(r(`goal.disabledHint`),`warning`),null):(a||F(r(`goal.intentDetected`),`info`,6e3),e===Lf()?(C.goalSnapshot=s.goal||null,If(),s.goal||null):s.goal||null)}function Uf(e={}){let t=[],n=Array.isArray(e.attachedImages)?e.attachedImages.length:0;n>0&&t.push({kind:`image`,name:r(`goal.attachmentImage`,{count:n})});for(let n of Array.isArray(e.attachedFiles)?e.attachedFiles:[])!n||n.status!==`done`||!n.name||t.push({kind:`file`,name:String(n.name),detail:n.agentPath?`workspace file`:`inline text`});let i=e.selectedPage;i&&(i.title||i.url)&&t.push({kind:`page`,name:String(i.title||i.url),detail:i.id==null?``:`tab ${i.id}`});for(let n of Array.isArray(e.knowledgeRefs)?e.knowledgeRefs:[])n&&n.name&&t.push({kind:`knowledge`,name:String(n.name)});return t}function Wf(){C.goalSnapshot=null,If()}function Gf(){return If(),Rf()}function Kf(e=``){return new Promise(t=>{let n=document.createElement(`div`);n.className=`modal-overlay show`,n.innerHTML=`
|
|
95
97
|
<div class="modal-container" style="min-width:320px;">
|
|
96
98
|
<div class="modal-title">${L(r(`goal.editTitle`))}</div>
|
|
97
99
|
<input type="text" class="goal-edit-input" value="${L(e)}"
|
|
@@ -101,7 +103,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
101
103
|
<button class="goal-edit-cancel" style="padding:6px 16px;border:1px solid var(--border-default);border-radius:6px;background:var(--bg-surface);color:var(--text-secondary);cursor:pointer;">${L(r(`common.cancel`))}</button>
|
|
102
104
|
<button class="goal-edit-confirm" style="padding:6px 16px;border:none;border-radius:6px;background:var(--brand-500);color:var(--text-inverse);cursor:pointer;">${L(r(`common.confirm`))}</button>
|
|
103
105
|
</div>
|
|
104
|
-
</div>`,document.body.appendChild(n);let i=n.querySelector(`.goal-edit-input`),a=e=>{n.remove(),t(e)};n.querySelector(`.goal-edit-confirm`).addEventListener(`click`,()=>{a(i.value.trim()||null)}),n.querySelector(`.goal-edit-cancel`).addEventListener(`click`,()=>a(null)),i.addEventListener(`keydown`,e=>{e.key===`Enter`&&a(i.value.trim()||null),e.key===`Escape`&&a(null)}),setTimeout(()=>i.select(),50)})}function Uf(e){!e||e.status===`active`||F(r(`goal.resumeBlocked`,{turns:e.turnBudget}),`warning`,6e3)}function Wf(){if(U)return;let e=Df(`goalModeBtn`),t=Df(`goalBar`);if(!e||!t){i.warn(`[GoalPanel] init skipped: DOM not ready`);return}U={toggle:e,group:Df(`goalGroup`),bar:t,status:Df(`goalBarStatus`),objective:Df(`goalBarObjective`),meta:Df(`goalBarMeta`),approve:Df(`goalBarApprove`),edit:Df(`goalBarEditBtn`),pause:Df(`goalBarPauseBtn`),resume:Df(`goalBarResumeBtn`),clear:Df(`goalBarClearBtn`)},U.toggle.checked=!!C.goalMode,U.toggle.addEventListener(`change`,async()=>{if(C.goalMode=U.toggle.checked,Mf(),i.debug(`[GoalPanel] goal mode:`,C.goalMode?`enabled`:`disabled`),C.goalMode){let e=Nf(),t=C.goalSnapshot;if(e&&t&&(t.status===`paused`||t.status===`budget_limited`)){let t=await jf({sessionId:e,action:`resume`,autoApprove:!0});t?.goal&&e===Nf()&&(C.goalSnapshot=t.goal,Mf(),Uf(t.goal))}}else{let e=Nf();if(e&&!kf(C.goalSnapshot)){let t=await jf({sessionId:e,action:`pause`});t?.goal&&e===Nf()&&(C.goalSnapshot=t.goal,Mf())}}}),U.edit.addEventListener(`click`,async()=>{let e=Nf();if(!e)return;let t=await Hf(C.goalSnapshot?.objective||``);if(!t)return;let n=await jf({sessionId:e,action:`replace`,objective:t,autoApprove:!!C.goalMode});n?.goal&&e===Nf()&&(C.goalSnapshot=n.goal,Mf(),F(r(`goal.updated`),`success`))}),U.pause.addEventListener(`click`,async()=>{let e=Nf();if(!e)return;let t=await jf({sessionId:e,action:`pause`});t?.goal&&e===Nf()&&(C.goalSnapshot=t.goal,Mf(),t.goal.status===`paused`&&F(r(C.goalMode?`goal.pausedToast`:`goal.pausedToastChipOff`),`info`,6e3))}),U.resume.addEventListener(`click`,async()=>{let e=Nf();if(!e)return;let t=await jf({sessionId:e,action:`resume`,autoApprove:!!C.goalMode});t?.goal&&e===Nf()&&(C.goalSnapshot=t.goal,Mf(),Uf(t.goal))}),U.clear.addEventListener(`click`,async()=>{let e=Nf();e&&(!window.showCustomConfirm||await window.showCustomConfirm(r(`goal.clearConfirm`),r(`goal.label`)))&&(await jf({sessionId:e,action:`clear`}),e===Nf()&&(C.goalSnapshot=null,Mf()))}),U.approve.addEventListener(`click`,async()=>{let e=Nf();if(!e)return;let t=await jf({sessionId:e,action:`pause`});C.goalMode=!1,t?.goal&&e===Nf()&&(C.goalSnapshot=t.goal),Mf(),F(r(`goal.approvalRevoked`),`info`,6e3)}),chrome.runtime.onMessage.addListener(e=>{e?.type===`GOAL_UPDATE`&&(e.sessionId&&e.sessionId!==Nf()||(C.goalSnapshot=e.goal||null,Mf()))});try{chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!(`goalConfig`in e)||(Ff=null,Lf())})}catch(e){i.debug(`[GoalPanel] storage.onChanged unavailable:`,e?.message)}Lf(),document.addEventListener(`session-switched`,()=>{Vf()}),document.addEventListener(`session-hydrated`,()=>{Vf()}),document.addEventListener(`session-deleted`,()=>{Bf()}),document.addEventListener(`session-archived`,()=>{Bf()}),Mf()}var Gf=`combo-collapsed`,Kf=`summary-collapsed`,qf=`summary-wrapped`,Jf=[Gf,Kf,qf];function Yf(e){if(!e)return;let t=e.querySelector(`.log-summary`);t&&(t.classList.remove(...Jf),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(Gf),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(Kf),!(t.scrollWidth<=t.clientWidth)&&t.classList.add(qf))))}var Xf=null,Zf=0,Qf=!1;function $f(e){e&&(Xf=e,ep(),!Zf&&(Zf=(typeof requestAnimationFrame==`function`?requestAnimationFrame:e=>setTimeout(e,0))(()=>{Zf=0;let e=Xf;Xf=null,e&&Yf(e)})))}function ep(){Qf||typeof window>`u`||(Qf=!0,window.addEventListener(`resize`,()=>{let e=document.querySelector(`.execution-log-panel`);e&&$f(e)}))}n(`zh`,{execLog:{statusSuccess:`成功`,statusFailed:`失败`,statusProcessing:`处理中`,unknownNode:`未知节点`,sequentialExecution:`顺序执行`,parallelExecution:`并行执行`,subtaskCountStrategy:`{count}个子任务, {strategy}`,messageCountTitle:`本次模型API调用携带的消息数`,toolCountTitle:`本次模型API调用携带的工具定义数`,messageCount:`{count}条`,toolCount:`{count}个`,durationTitle:`耗时`,sectionThought:`💡 思考`,sectionToolCall:`⚡ 工具调用`,labelTool:`工具:`,labelParams:`参数:`,sectionFilterResult:`🔍 筛选结果`,labelSelectedTools:`选中工具:`,labelCount:`数量:`,unitItems:`个`,sectionObservation:`📝 观察结果`,sectionApiRequest:`📡 API 请求`,labelModel:`模型:`,labelTemperature:`温度:`,labelTopP:`top_p:`,labelMessageCount:`消息数:`,labelToolCount:`工具数:`,sectionApiResponse:`📤 API 响应`,labelFinishReason:`完成原因:`,labelFilteredToolCount:`筛选后工具数:`,labelTokenUsage:`Token 使用:`,sectionError:`❌ 错误信息`,sectionSubtaskResult:`✅ 子任务结果`,sectionSubtaskDesc:`📝 任务描述`,subtaskPendingNode:`(待执行)`,sectionReflectionPrompt:`📊 评估提示词`,sectionReflectionRaw:`📤 评估结果(原始响应)`,sectionTokenUsage:`📊 Token 使用`,overallScore:`⭐ 综合评分: {score}/10`,sectionIssues:`📋 发现的问题`,sectionSuggestions:`💡 改进建议`,labelDecision:`🎯 决策: {decision}`,decisionPassed:`✅ 通过`,decisionRevised:`🔧 已修订`,decisionNeedsImprovement:`⚠️ 需改进`,resultUseful:`✅ 结果有用`,resultInvalid:`⚠️ 结果无效`,labelSuggestion:`建议: {suggestion}`,mainTask:`主任务`,stepCount:`({count} 步骤)`,processingDots:`处理中...`,waitingExecution:`等待执行中...`,realtimeLogTitle:`实时执行日志`,executingLabel:`执行中:`,preparing:`准备中...`,totalNodes:`总节点`,labelSuccess:`成功`,labelFailed:`失败`,labelSubtask:`子任务`,expandAll:`展开全部节点`,collapseAll:`收起全部节点`,sectionUserInjection:`💬 插话内容`}}),n(`en`,{execLog:{statusSuccess:`Success`,statusFailed:`Failed`,statusProcessing:`Processing`,unknownNode:`Unknown node`,sequentialExecution:`sequential`,parallelExecution:`parallel`,subtaskCountStrategy:`{count} subtasks, {strategy}`,messageCountTitle:`Number of messages carried in this model API call`,toolCountTitle:`Number of tool definitions carried in this model API call`,messageCount:`{count} msgs`,toolCount:`{count} tools`,durationTitle:`Duration`,sectionThought:`💡 Thought`,sectionToolCall:`⚡ Tool Call`,labelTool:`Tool:`,labelParams:`Params:`,sectionFilterResult:`🔍 Filter Result`,labelSelectedTools:`Selected tools:`,labelCount:`Count:`,unitItems:``,sectionObservation:`📝 Observation`,sectionApiRequest:`📡 API Request`,labelModel:`Model:`,labelTemperature:`Temperature:`,labelTopP:`top_p:`,labelMessageCount:`Messages:`,labelToolCount:`Tools:`,sectionApiResponse:`📤 API Response`,labelFinishReason:`Finish reason:`,labelFilteredToolCount:`Filtered tool count:`,labelTokenUsage:`Token Usage:`,sectionError:`❌ Error`,sectionSubtaskResult:`✅ Subtask Result`,sectionSubtaskDesc:`📝 Task Description`,subtaskPendingNode:`(pending)`,sectionReflectionPrompt:`📊 Reflection Prompt`,sectionReflectionRaw:`📤 Reflection Result (raw)`,sectionTokenUsage:`📊 Token Usage`,overallScore:`⭐ Overall Score: {score}/10`,sectionIssues:`📋 Issues Found`,sectionSuggestions:`💡 Suggestions`,labelDecision:`🎯 Decision: {decision}`,decisionPassed:`✅ Passed`,decisionRevised:`🔧 Revised`,decisionNeedsImprovement:`⚠️ Needs Improvement`,resultUseful:`✅ Useful`,resultInvalid:`⚠️ Invalid`,labelSuggestion:`Suggestion: {suggestion}`,mainTask:`Main Task`,stepCount:`({count} steps)`,processingDots:`Processing...`,waitingExecution:`Waiting for execution...`,realtimeLogTitle:`Real-time Execution Log`,executingLabel:`Executing:`,preparing:`Preparing...`,totalNodes:`Total nodes`,labelSuccess:`Success`,labelFailed:`Failed`,labelSubtask:`Subtask`,expandAll:`Expand all nodes`,collapseAll:`Collapse all nodes`,sectionUserInjection:`💬 Your interjection`}});function tp(e){if(e?.nodeType!==`tool_exec`||!e?.action)return``;let t=e.action.name||``,n=e.action.params;if(n==null)return``;if(typeof n==`string`&&(n=(()=>{try{return JSON.parse(n)}catch{return{raw:n}}})()),typeof n!=`object`)return String(n).trim();if(t===`execute_command`||t===`agent_exec`)return(n.command||n.cmd||``).toString().trim();if(t===`agent_file`||t===`file_upload`||t===`download_file`){let e=(n.file_path||n.filePath||n.path||n.filename||n.fileName||n.url||``).toString().trim();if(e)return e}if(t===`fetch_url`||t===`interact_element`||t===`fill_form`||t===`manage_tab`||t===`preview_ui`){let e=(n.url||n.href||n.selector||``).toString().trim();if(e)return e}if(t===`search_browser_data`||t===`search_in_page`||t===`exec_log`){let e=(n.query||n.keyword||n.text||``).toString().trim();if(e)return e}if(t===`dispatch_task`){let e=(n.task||``).toString().trim();if(e)return e}if(t===`agent_memory`){let e=(n.action||n.subAction||``).toString().trim();if(e)return e}let r=[`content`,`text`,`prompt`,`description`,`markdown`,`html`,`css`,`js`,`code`,`script`,`data`],i=Object.keys(n).filter(e=>n[e]!=null&&n[e]!==``&&!r.includes(e));if(i.length===0)return``;if(i.length===1){let e=String(n[i[0]]);return`${i[0]}: ${e}`}return i.slice(0,2).map(e=>`${e}=${JSON.stringify(n[e])}`).join(`, `)}function np(e){return tp(e)}function rp(e){let t=Array.isArray(e)?e:[],n=t.filter(e=>e&&e.nodeType===`subtask_plan`&&Array.isArray(e.items));if(n.length===0)return t;let i=t.filter(e=>e&&e.nodeType!==`subtask_plan`),a=new Set(i.filter(e=>e.nodeType===`subtask`&&typeof e.subtaskIndex==`number`).map(e=>e.subtaskIndex)),o=new Map;n.forEach(e=>{e.items.forEach(t=>{!t||typeof t.index!=`number`||o.set(t.index,{item:t,plan:e})})});let s=[];return Array.from(o.keys()).sort((e,t)=>e-t).forEach(e=>{if(a.has(e))return;let{item:t,plan:n}=o.get(e),i=r(`execLog.subtaskPendingNode`);s.push({id:`plan_pending_${n.id||`x`}_${e}`,nodeType:`subtask`,status:`pending`,iteration:0,timestamp:n.timestamp,subtaskIndex:e,subtaskId:t.id,subtaskName:t.name,description:t.description||``,nodeName:t.name?`${t.name} ${i}`:i,taskGroup:`subtask_group_${e}`,taskGroupIndex:e+1,taskGroupName:t.name,isSubtask:!0})}),i.concat(s)}function ip(e,t){let n=e=>e.status===`pending`?2**53-1:new Date(e.timestamp).getTime();return n(e)-n(t)}function ap(e){let t=rp(e).sort(ip),n=t.length,i=``,a=null;return t.forEach((e,t)=>{let o=e.nodeType===`subtask`,s=e.nodeType===`tool_exec`,c=e.nodeType===`api_call`,l=e.nodeType===`preselect`,u=e.nodeType===`reflection`,d=e.nodeType===`user_injection`,f=s&&e.action?.name===`plan_task`;o&&(a=e.subtaskIndex);let p=``,m=``;d?m=`💬`:u?m=`🎯`:l?m=`🔍`:f?(p=`plan-task-level`,m=`📋`):o?(p=`subtask-level`,m=`🔀`):s&&a!==null?(p=`tool-level`,m=`🔧`):c&&a!==null?(p=`api-level`,m=`📡`):s?m=`⚡`:c&&(m=`📡`);let h=`○`,g=e.status||`processing`;e.status===`success`?h=`✓`:e.status===`failed`&&(h=`✗`),u&&(g=`reflection ${g}`);let _=L(e.nodeName||r(`execLog.unknownNode`));if(e.subtaskIndex!==null&&e.subtaskIndex>=0&&(_=`<span class="subtask-badge">${e.subtaskIndex+1}</span> ${_}`),e.subtaskCount&&(_+=` <span class="plan-badge">(${r(`execLog.subtaskCountStrategy`,{count:e.subtaskCount,strategy:e.strategy===`sequential`?r(`execLog.sequentialExecution`):r(`execLog.parallelExecution`)})})</span>`),(c||l||u)&&e.apiRequest){let t=[];e.apiRequest.messageCount!==void 0&&e.apiRequest.messageCount!==null&&t.push(`💬<span title="${r(`execLog.messageCountTitle`)}">${r(`execLog.messageCount`,{count:e.apiRequest.messageCount})}</span>`),!l&&e.apiRequest.toolCount!==void 0&&e.apiRequest.toolCount!==null&&t.push(`🔧<span title="${r(`execLog.toolCountTitle`)}">${r(`execLog.toolCount`,{count:e.apiRequest.toolCount})}</span>`),t.length>0&&(_+=` <span class="api-info-badge">(${t.join(` `)})</span>`)}if(s){let t=np(e);t&&(_+=` <span class="node-cmd-preview" title="${P(t)}">${L(t)}</span>`)}i+=`
|
|
106
|
+
</div>`,document.body.appendChild(n);let i=n.querySelector(`.goal-edit-input`),a=e=>{n.remove(),t(e)};n.querySelector(`.goal-edit-confirm`).addEventListener(`click`,()=>{a(i.value.trim()||null)}),n.querySelector(`.goal-edit-cancel`).addEventListener(`click`,()=>a(null)),i.addEventListener(`keydown`,e=>{e.key===`Enter`&&a(i.value.trim()||null),e.key===`Escape`&&a(null)}),setTimeout(()=>i.select(),50)})}function qf(e){!e||e.status===`active`||F(r(`goal.resumeBlocked`,{turns:e.turnBudget}),`warning`,6e3)}function Jf(){if(U)return;let e=jf(`goalModeBtn`),t=jf(`goalBar`);if(!e||!t){i.warn(`[GoalPanel] init skipped: DOM not ready`);return}U={toggle:e,group:jf(`goalGroup`),bar:t,status:jf(`goalBarStatus`),objective:jf(`goalBarObjective`),meta:jf(`goalBarMeta`),approve:jf(`goalBarApprove`),edit:jf(`goalBarEditBtn`),pause:jf(`goalBarPauseBtn`),resume:jf(`goalBarResumeBtn`),clear:jf(`goalBarClearBtn`)},U.toggle.checked=!!C.goalMode,U.toggle.addEventListener(`change`,async()=>{if(C.goalMode=U.toggle.checked,If(),i.debug(`[GoalPanel] goal mode:`,C.goalMode?`enabled`:`disabled`),C.goalMode){let e=Lf(),t=C.goalSnapshot;if(e&&t&&(t.status===`paused`||t.status===`budget_limited`)){let t=await Ff({sessionId:e,action:`resume`,autoApprove:!0});t?.goal&&e===Lf()&&(C.goalSnapshot=t.goal,If(),qf(t.goal))}}else{let e=Lf();if(e&&!Nf(C.goalSnapshot)){let t=await Ff({sessionId:e,action:`pause`});t?.goal&&e===Lf()&&(C.goalSnapshot=t.goal,If())}}}),U.edit.addEventListener(`click`,async()=>{let e=Lf();if(!e)return;let t=await Kf(C.goalSnapshot?.objective||``);if(!t)return;let n=await Ff({sessionId:e,action:`replace`,objective:t,autoApprove:!!C.goalMode});n?.goal&&e===Lf()&&(C.goalSnapshot=n.goal,If(),F(r(`goal.updated`),`success`))}),U.pause.addEventListener(`click`,async()=>{let e=Lf();if(!e)return;let t=await Ff({sessionId:e,action:`pause`});t?.goal&&e===Lf()&&(C.goalSnapshot=t.goal,If(),t.goal.status===`paused`&&F(r(C.goalMode?`goal.pausedToast`:`goal.pausedToastChipOff`),`info`,6e3))}),U.resume.addEventListener(`click`,async()=>{let e=Lf();if(!e)return;let t=await Ff({sessionId:e,action:`resume`,autoApprove:!!C.goalMode});t?.goal&&e===Lf()&&(C.goalSnapshot=t.goal,If(),qf(t.goal))}),U.clear.addEventListener(`click`,async()=>{let e=Lf();e&&(!window.showCustomConfirm||await window.showCustomConfirm(r(`goal.clearConfirm`),r(`goal.label`)))&&(await Ff({sessionId:e,action:`clear`}),e===Lf()&&(C.goalSnapshot=null,If()))}),U.approve.addEventListener(`click`,async()=>{let e=Lf();if(!e)return;let t=await Ff({sessionId:e,action:`pause`});C.goalMode=!1,t?.goal&&e===Lf()&&(C.goalSnapshot=t.goal),If(),F(r(`goal.approvalRevoked`),`info`,6e3)}),chrome.runtime.onMessage.addListener(e=>{e?.type===`GOAL_UPDATE`&&(e.sessionId&&e.sessionId!==Lf()||(C.goalSnapshot=e.goal||null,If()))});try{chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!(`goalConfig`in e)||(zf=null,Vf())})}catch(e){i.debug(`[GoalPanel] storage.onChanged unavailable:`,e?.message)}Vf(),document.addEventListener(`session-switched`,()=>{Gf()}),document.addEventListener(`session-hydrated`,()=>{Gf()}),document.addEventListener(`session-deleted`,()=>{Wf()}),document.addEventListener(`session-archived`,()=>{Wf()}),If()}var Yf=`combo-collapsed`,Xf=`summary-collapsed`,Zf=`summary-wrapped`,Qf=[Yf,Xf,Zf];function $f(e){if(!e)return;let t=e.querySelector(`.log-summary`);t&&(t.classList.remove(...Qf),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(Yf),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(Xf),!(t.scrollWidth<=t.clientWidth)&&t.classList.add(Zf))))}var ep=null,tp=0,np=!1;function rp(e){e&&(ep=e,ip(),!tp&&(tp=(typeof requestAnimationFrame==`function`?requestAnimationFrame:e=>setTimeout(e,0))(()=>{tp=0;let e=ep;ep=null,e&&$f(e)})))}function ip(){np||typeof window>`u`||(np=!0,window.addEventListener(`resize`,()=>{let e=document.querySelector(`.execution-log-panel`);e&&rp(e)}))}n(`zh`,{execLog:{statusSuccess:`成功`,statusFailed:`失败`,statusProcessing:`处理中`,unknownNode:`未知节点`,sequentialExecution:`顺序执行`,parallelExecution:`并行执行`,subtaskCountStrategy:`{count}个子任务, {strategy}`,messageCountTitle:`本次模型API调用携带的消息数`,toolCountTitle:`本次模型API调用携带的工具定义数`,messageCount:`{count}条`,toolCount:`{count}个`,durationTitle:`耗时`,sectionThought:`💡 思考`,sectionToolCall:`⚡ 工具调用`,labelTool:`工具:`,labelParams:`参数:`,sectionFilterResult:`🔍 筛选结果`,labelSelectedTools:`选中工具:`,labelCount:`数量:`,unitItems:`个`,sectionObservation:`📝 观察结果`,sectionApiRequest:`📡 API 请求`,labelModel:`模型:`,labelTemperature:`温度:`,labelTopP:`top_p:`,labelMessageCount:`消息数:`,labelToolCount:`工具数:`,sectionApiResponse:`📤 API 响应`,labelFinishReason:`完成原因:`,labelFilteredToolCount:`筛选后工具数:`,labelTokenUsage:`Token 使用:`,sectionError:`❌ 错误信息`,sectionSubtaskResult:`✅ 子任务结果`,sectionSubtaskDesc:`📝 任务描述`,subtaskPendingNode:`(待执行)`,sectionReflectionPrompt:`📊 评估提示词`,sectionReflectionRaw:`📤 评估结果(原始响应)`,sectionTokenUsage:`📊 Token 使用`,overallScore:`⭐ 综合评分: {score}/10`,sectionIssues:`📋 发现的问题`,sectionSuggestions:`💡 改进建议`,labelDecision:`🎯 决策: {decision}`,decisionPassed:`✅ 通过`,decisionRevised:`🔧 已修订`,decisionNeedsImprovement:`⚠️ 需改进`,resultUseful:`✅ 结果有用`,resultInvalid:`⚠️ 结果无效`,labelSuggestion:`建议: {suggestion}`,mainTask:`主任务`,stepCount:`({count} 步骤)`,processingDots:`处理中...`,waitingExecution:`等待执行中...`,realtimeLogTitle:`实时执行日志`,executingLabel:`执行中:`,preparing:`准备中...`,totalNodes:`总节点`,labelSuccess:`成功`,labelFailed:`失败`,labelSubtask:`子任务`,expandAll:`展开全部节点`,collapseAll:`收起全部节点`,sectionUserInjection:`💬 插话内容`}}),n(`en`,{execLog:{statusSuccess:`Success`,statusFailed:`Failed`,statusProcessing:`Processing`,unknownNode:`Unknown node`,sequentialExecution:`sequential`,parallelExecution:`parallel`,subtaskCountStrategy:`{count} subtasks, {strategy}`,messageCountTitle:`Number of messages carried in this model API call`,toolCountTitle:`Number of tool definitions carried in this model API call`,messageCount:`{count} msgs`,toolCount:`{count} tools`,durationTitle:`Duration`,sectionThought:`💡 Thought`,sectionToolCall:`⚡ Tool Call`,labelTool:`Tool:`,labelParams:`Params:`,sectionFilterResult:`🔍 Filter Result`,labelSelectedTools:`Selected tools:`,labelCount:`Count:`,unitItems:``,sectionObservation:`📝 Observation`,sectionApiRequest:`📡 API Request`,labelModel:`Model:`,labelTemperature:`Temperature:`,labelTopP:`top_p:`,labelMessageCount:`Messages:`,labelToolCount:`Tools:`,sectionApiResponse:`📤 API Response`,labelFinishReason:`Finish reason:`,labelFilteredToolCount:`Filtered tool count:`,labelTokenUsage:`Token Usage:`,sectionError:`❌ Error`,sectionSubtaskResult:`✅ Subtask Result`,sectionSubtaskDesc:`📝 Task Description`,subtaskPendingNode:`(pending)`,sectionReflectionPrompt:`📊 Reflection Prompt`,sectionReflectionRaw:`📤 Reflection Result (raw)`,sectionTokenUsage:`📊 Token Usage`,overallScore:`⭐ Overall Score: {score}/10`,sectionIssues:`📋 Issues Found`,sectionSuggestions:`💡 Suggestions`,labelDecision:`🎯 Decision: {decision}`,decisionPassed:`✅ Passed`,decisionRevised:`🔧 Revised`,decisionNeedsImprovement:`⚠️ Needs Improvement`,resultUseful:`✅ Useful`,resultInvalid:`⚠️ Invalid`,labelSuggestion:`Suggestion: {suggestion}`,mainTask:`Main Task`,stepCount:`({count} steps)`,processingDots:`Processing...`,waitingExecution:`Waiting for execution...`,realtimeLogTitle:`Real-time Execution Log`,executingLabel:`Executing:`,preparing:`Preparing...`,totalNodes:`Total nodes`,labelSuccess:`Success`,labelFailed:`Failed`,labelSubtask:`Subtask`,expandAll:`Expand all nodes`,collapseAll:`Collapse all nodes`,sectionUserInjection:`💬 Your interjection`}});function ap(e){if(e?.nodeType!==`tool_exec`||!e?.action)return``;let t=e.action.name||``,n=e.action.params;if(n==null)return``;if(typeof n==`string`&&(n=(()=>{try{return JSON.parse(n)}catch{return{raw:n}}})()),typeof n!=`object`)return String(n).trim();if(t===`execute_command`||t===`agent_exec`)return(n.command||n.cmd||``).toString().trim();if(t===`agent_file`||t===`file_upload`||t===`download_file`){let e=(n.file_path||n.filePath||n.path||n.filename||n.fileName||n.url||``).toString().trim();if(e)return e}if(t===`fetch_url`||t===`interact_element`||t===`fill_form`||t===`manage_tab`||t===`preview_ui`){let e=(n.url||n.href||n.selector||``).toString().trim();if(e)return e}if(t===`search_browser_data`||t===`search_in_page`||t===`exec_log`){let e=(n.query||n.keyword||n.text||``).toString().trim();if(e)return e}if(t===`dispatch_task`){let e=(n.task||``).toString().trim();if(e)return e}if(t===`agent_memory`){let e=(n.action||n.subAction||``).toString().trim();if(e)return e}let r=[`content`,`text`,`prompt`,`description`,`markdown`,`html`,`css`,`js`,`code`,`script`,`data`],i=Object.keys(n).filter(e=>n[e]!=null&&n[e]!==``&&!r.includes(e));if(i.length===0)return``;if(i.length===1){let e=String(n[i[0]]);return`${i[0]}: ${e}`}return i.slice(0,2).map(e=>`${e}=${JSON.stringify(n[e])}`).join(`, `)}function op(e){return ap(e)}function sp(e){let t=Array.isArray(e)?e:[],n=t.filter(e=>e&&e.nodeType===`subtask_plan`&&Array.isArray(e.items));if(n.length===0)return t;let i=t.filter(e=>e&&e.nodeType!==`subtask_plan`),a=new Set(i.filter(e=>e.nodeType===`subtask`&&typeof e.subtaskIndex==`number`).map(e=>e.subtaskIndex)),o=new Map;n.forEach(e=>{e.items.forEach(t=>{!t||typeof t.index!=`number`||o.set(t.index,{item:t,plan:e})})});let s=[];return Array.from(o.keys()).sort((e,t)=>e-t).forEach(e=>{if(a.has(e))return;let{item:t,plan:n}=o.get(e),i=r(`execLog.subtaskPendingNode`);s.push({id:`plan_pending_${n.id||`x`}_${e}`,nodeType:`subtask`,status:`pending`,iteration:0,timestamp:n.timestamp,subtaskIndex:e,subtaskId:t.id,subtaskName:t.name,description:t.description||``,nodeName:t.name?`${t.name} ${i}`:i,taskGroup:`subtask_group_${e}`,taskGroupIndex:e+1,taskGroupName:t.name,isSubtask:!0})}),i.concat(s)}function cp(e,t){let n=e=>e.status===`pending`?2**53-1:new Date(e.timestamp).getTime();return n(e)-n(t)}function lp(e){let t=sp(e).sort(cp),n=t.length,i=``,a=null;return t.forEach((e,t)=>{let o=e.nodeType===`subtask`,s=e.nodeType===`tool_exec`,c=e.nodeType===`api_call`,l=e.nodeType===`preselect`,u=e.nodeType===`reflection`,d=e.nodeType===`user_injection`,f=s&&e.action?.name===`plan_task`;o&&(a=e.subtaskIndex);let p=``,m=``;d?m=`💬`:u?m=`🎯`:l?m=`🔍`:f?(p=`plan-task-level`,m=`📋`):o?(p=`subtask-level`,m=`🔀`):s&&a!==null?(p=`tool-level`,m=`🔧`):c&&a!==null?(p=`api-level`,m=`📡`):s?m=`⚡`:c&&(m=`📡`);let h=`○`,g=e.status||`processing`;e.status===`success`?h=`✓`:e.status===`failed`&&(h=`✗`),u&&(g=`reflection ${g}`);let _=L(e.nodeName||r(`execLog.unknownNode`));if(e.subtaskIndex!==null&&e.subtaskIndex>=0&&(_=`<span class="subtask-badge">${e.subtaskIndex+1}</span> ${_}`),e.subtaskCount&&(_+=` <span class="plan-badge">(${r(`execLog.subtaskCountStrategy`,{count:e.subtaskCount,strategy:e.strategy===`sequential`?r(`execLog.sequentialExecution`):r(`execLog.parallelExecution`)})})</span>`),(c||l||u)&&e.apiRequest){let t=[];e.apiRequest.messageCount!==void 0&&e.apiRequest.messageCount!==null&&t.push(`💬<span title="${r(`execLog.messageCountTitle`)}">${r(`execLog.messageCount`,{count:e.apiRequest.messageCount})}</span>`),!l&&e.apiRequest.toolCount!==void 0&&e.apiRequest.toolCount!==null&&t.push(`🔧<span title="${r(`execLog.toolCountTitle`)}">${r(`execLog.toolCount`,{count:e.apiRequest.toolCount})}</span>`),t.length>0&&(_+=` <span class="api-info-badge">(${t.join(` `)})</span>`)}if(s){let t=op(e);t&&(_+=` <span class="node-cmd-preview" title="${P(t)}">${L(t)}</span>`)}i+=`
|
|
105
107
|
<div class="timeline-item ${p}" data-status="${e.status||`processing`}" data-node-type="${e.nodeType||``}">
|
|
106
108
|
<div class="timeline-line"></div>
|
|
107
109
|
<div class="timeline-dot ${g}">
|
|
@@ -267,7 +269,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
267
269
|
</div>
|
|
268
270
|
</div>
|
|
269
271
|
</div>
|
|
270
|
-
`}),i}function
|
|
272
|
+
`}),i}function up(e){let t=sp(e).sort(cp);if(!t.some(e=>e.taskGroup))return mp(t);let n=new Map,i=[];t.forEach(e=>{e.taskGroup?(n.has(e.taskGroup)||n.set(e.taskGroup,{groupId:e.taskGroup,groupIndex:e.taskGroupIndex,groupName:e.taskGroupName,entries:[],status:e.status}),n.get(e.taskGroup).entries.push(e),e.status&&(n.get(e.taskGroup).status=e.status)):i.push(e)});let a=dp(i,t.length);return n.forEach((e,n)=>{let i=e.status||`processing`;a+=`
|
|
271
273
|
<div class="task-group-container" data-group-id="${n}">
|
|
272
274
|
<div class="task-group-header">
|
|
273
275
|
<div class="task-group-line"></div>
|
|
@@ -285,10 +287,10 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
285
287
|
</div>
|
|
286
288
|
</div>
|
|
287
289
|
<div class="task-group-timeline">
|
|
288
|
-
${
|
|
290
|
+
${fp(e.entries,t.length)}
|
|
289
291
|
</div>
|
|
290
292
|
</div>
|
|
291
|
-
`}),a}function
|
|
293
|
+
`}),a}function dp(e,t){if(e.length===0)return``;let n=``;return n+=`
|
|
292
294
|
<div class="main-tasks-container">
|
|
293
295
|
<div class="main-tasks-header">
|
|
294
296
|
<div class="main-tasks-line"></div>
|
|
@@ -304,10 +306,10 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
304
306
|
</div>
|
|
305
307
|
</div>
|
|
306
308
|
<div class="main-tasks-timeline">
|
|
307
|
-
`,e.forEach((e,r)=>{n+=
|
|
309
|
+
`,e.forEach((e,r)=>{n+=pp(e,r,t)}),n+=`
|
|
308
310
|
</div>
|
|
309
311
|
</div>
|
|
310
|
-
`,n}function
|
|
312
|
+
`,n}function fp(e,t){let n=``;return e.forEach((e,r)=>{n+=pp(e,r,t)}),n}function pp(e,t,n){let i=e.nodeType===`subtask`,a=e.nodeType===`tool_exec`,o=e.nodeType===`api_call`,s=e.nodeType===`preselect`,c=e.nodeType===`reflection`,l=e.nodeType===`user_injection`,u=a&&e.action?.name===`plan_task`,d=``,f=``;l?f=`💬`:c?(d=`reflection-level`,f=`🎯`):s?f=`📡`:u?(d=`plan-task-level`,f=`📋`):i?(d=`subtask-level`,f=`🔀`):a?(d=`tool-level`,f=`🔧`):o?(d=`api-level`,f=`📡`):a?f=`⚡`:o&&(f=`📡`);let p=`○`,m=e.status||`processing`;e.status===`success`?p=`✓`:e.status===`failed`&&(p=`✗`),c&&(m=`reflection ${m}`);let h=L(e.nodeName||r(`execLog.unknownNode`));if(e.subtaskCount&&(h+=` <span class="plan-badge">(${r(`execLog.subtaskCountStrategy`,{count:e.subtaskCount,strategy:e.strategy===`sequential`?r(`execLog.sequentialExecution`):r(`execLog.parallelExecution`)})})</span>`),(o||s)&&e.apiRequest){let t=[];e.apiRequest.messageCount!==void 0&&e.apiRequest.messageCount!==null&&t.push(`💬<span title="${r(`execLog.messageCountTitle`)}">${r(`execLog.messageCount`,{count:e.apiRequest.messageCount})}</span>`),!s&&e.apiRequest.toolCount!==void 0&&e.apiRequest.toolCount!==null&&t.push(`🔧<span title="${r(`execLog.toolCountTitle`)}">${r(`execLog.toolCount`,{count:e.apiRequest.toolCount})}</span>`),t.length>0&&(h+=` <span class="api-info-badge">(${t.join(` `)})</span>`)}if(a){let t=op(e);t&&(h+=` <span class="node-cmd-preview" title="${P(t)}">${L(t)}</span>`)}return`
|
|
311
313
|
<div class="timeline-item ${d}">
|
|
312
314
|
<div class="timeline-line"></div>
|
|
313
315
|
<div class="timeline-dot ${m}">
|
|
@@ -451,7 +453,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
451
453
|
</div>
|
|
452
454
|
</div>
|
|
453
455
|
</div>
|
|
454
|
-
`}function
|
|
456
|
+
`}function mp(e){let t=``,n=null;return e.forEach((i,a)=>{let o=i.nodeType===`subtask`,s=i.nodeType===`tool_exec`,c=i.nodeType===`api_call`,l=i.nodeType===`preselect`,u=i.nodeType===`reflection`,d=i.nodeType===`user_injection`,f=s&&i.action?.name===`plan_task`;o&&(n=i.subtaskIndex);let p=``,m=``;d?m=`💬`:u?m=`🎯`:l?m=`🔍`:f?(p=`plan-task-level`,m=`📋`):o?(p=`subtask-level`,m=`🔀`):s&&n!==null?(p=`tool-level`,m=`🔧`):c&&n!==null?(p=`api-level`,m=`📡`):s?m=`⚡`:c&&(m=`📡`);let h=`○`,g=i.status||`processing`;i.status===`success`?h=`✓`:i.status===`failed`&&(h=`✗`);let _=L(i.nodeName||r(`execLog.unknownNode`));if(i.subtaskId&&(_=`<span class="subtask-badge">${n===null?``:n+1}</span> ${_}`),i.subtaskCount&&(_+=` <span class="plan-badge">(${r(`execLog.subtaskCountStrategy`,{count:i.subtaskCount,strategy:i.strategy===`sequential`?r(`execLog.sequentialExecution`):r(`execLog.parallelExecution`)})})</span>`),(c||l||u)&&i.apiRequest){let e=[];i.apiRequest.messageCount!==void 0&&i.apiRequest.messageCount!==null&&e.push(`💬<span title="${r(`execLog.messageCountTitle`)}">${r(`execLog.messageCount`,{count:i.apiRequest.messageCount})}</span>`),!l&&i.apiRequest.toolCount!==void 0&&i.apiRequest.toolCount!==null&&e.push(`🔧<span title="${r(`execLog.toolCountTitle`)}">${r(`execLog.toolCount`,{count:i.apiRequest.toolCount})}</span>`),e.length>0&&(_+=` <span class="api-info-badge">(${e.join(` `)})</span>`)}if(s){let e=op(i);e&&(_+=` <span class="node-cmd-preview" title="${P(e)}">${L(e)}</span>`)}t+=`
|
|
455
457
|
<div class="timeline-item ${p}">
|
|
456
458
|
<div class="timeline-line"></div>
|
|
457
459
|
<div class="timeline-dot ${g}">
|
|
@@ -617,7 +619,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
617
619
|
</div>
|
|
618
620
|
</div>
|
|
619
621
|
</div>
|
|
620
|
-
`}),t}var
|
|
622
|
+
`}),t}var hp=null,gp=!1;function _p(e){if(!e||(hp=e,gp))return;gp=!0;let t=()=>{gp=!1;let e=hp;hp=null,e&&vp(e)};typeof requestAnimationFrame==`function`?requestAnimationFrame(t):t()}function vp(e){let t=document.querySelector(`.execution-log-panel.realtime-mode`);if(!t)return;let n=t.querySelector(`.realtime-executing-node`);n&&(n.textContent=e.nodeName||r(`execLog.processingDots`));let i=e.executionLog||[],a=i.length,o=0,s=0,c=0,l=0;for(let e of i)e&&(e.status===`success`?o++:e.status===`failed`&&s++,e.nodeType===`subtask`&&(c++,e.status===`success`&&l++));let u=t.querySelector(`.combo-value`),d=t.querySelector(`.combo-stat.success .stat-value`),f=t.querySelector(`.combo-stat.failed .stat-value`),p=t.querySelector(`.combo-stat.subtask`);u&&(u.textContent=a),d&&(d.textContent=o),f&&(f.textContent=s),p&&(c>0?(p.style.display=``,p.querySelector(`.stat-value`).textContent=`${l}/${c}`):p.style.display=`none`);let m=t.querySelector(`.timeline`);m.innerHTML=i.length>0?lp(i):`<div class="realtime-waiting-message">${r(`execLog.waitingExecution`)}</div>`,rp(t),m.scrollTop=m.scrollHeight}function yp(e){let t=document.querySelector(`.execution-log-panel.realtime-mode`);t&&t.remove();let n=document.createElement(`div`);n.className=`execution-log-panel realtime-mode`,n.innerHTML=`
|
|
621
623
|
<div class="log-container">
|
|
622
624
|
<div class="log-header">
|
|
623
625
|
<div class="log-title">
|
|
@@ -679,18 +681,18 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
679
681
|
<div class="realtime-waiting-message">${r(`execLog.waitingExecution`)}</div>
|
|
680
682
|
</div>
|
|
681
683
|
</div>
|
|
682
|
-
`,document.body.appendChild(n)
|
|
684
|
+
`,document.body.appendChild(n),rp(n),n.querySelector(`.log-close`).addEventListener(`click`,()=>{n.remove()}),n.addEventListener(`click`,e=>{e.target===n&&n.remove()});let i=n.querySelector(`.toggle-expand-btn`),a=!1;i.addEventListener(`click`,()=>{a=!a,n.querySelectorAll(`.timeline-content`).forEach(e=>{a?e.classList.add(`expanded`):e.classList.remove(`expanded`)});let e=i.querySelector(`svg`);a?(e.innerHTML=`<polyline points="17 11 12 6 7 11"></polyline><polyline points="17 18 12 13 7 18"></polyline>`,i.setAttribute(`title`,r(`execLog.collapseAll`))):(e.innerHTML=`<polyline points="7 13 12 18 17 13"></polyline><polyline points="7 6 12 11 17 6"></polyline>`,i.setAttribute(`title`,r(`execLog.expandAll`)))}),n.addEventListener(`click`,e=>{let t=e.target.closest(`.timeline-header`);if(t){if(e.ctrlKey||e.metaKey)return;t.parentElement.classList.toggle(`expanded`)}}),n.addEventListener(`click`,e=>{let t=e.target.closest(`.combo-stat[data-status]`);if(!t)return;let r=t.dataset.status,i=t.classList.contains(`active`);n.querySelectorAll(`.combo-stat[data-status]`).forEach(e=>{e.classList.remove(`active`)});let a=n.querySelectorAll(`.timeline-item`);i?a.forEach(e=>{e.style.display=``}):(t.classList.add(`active`),a.forEach(e=>{if(r===`subtask`)e.dataset.nodeType===`subtask`?e.style.display=``:e.style.display=`none`;else{let t=e.querySelector(`.timeline-dot`);t&&t.classList.contains(r)?e.style.display=``:e.style.display=`none`}}))}),C.currentExecutionStatus&&_p(C.currentExecutionStatus)}function bp(e){let t=document.querySelector(`.execution-log-panel.realtime-mode`);if(t){t.remove();return}yp(e)}function xp(e,t){let n=!!(t.observationTruncated&&e.observation),r={...e,...t,observation:n?e.observation:t.observation??e.observation,subtaskIndex:t.subtaskIndex??e.subtaskIndex,subtaskId:t.subtaskId??e.subtaskId,subtaskName:t.subtaskName??e.subtaskName};return delete r.observationTruncated,r}function Sp(e,t,n,a){let o=document.getElementById(e);if(!o)return;i.debug(`[SidePanel] updateExecutionStatus called:`,t,n,`log count:`,a?.length);let s=o.querySelector(`.current-node-name`);s&&(s.textContent=t||r(`execLog.processingDots`),s.title=t||``),C.currentExecutionStatus?(C.currentExecutionStatus.executionLog||(C.currentExecutionStatus.executionLog=[]),a&&a.length>0&&a.forEach(e=>{let t=C.currentExecutionStatus.executionLog.findIndex(t=>t.id===e.id);t===-1?C.currentExecutionStatus.executionLog.push(e):C.currentExecutionStatus.executionLog[t]=xp(C.currentExecutionStatus.executionLog[t],e)}),C.currentExecutionStatus.nodeName=t,C.currentExecutionStatus.status=n):C.currentExecutionStatus={nodeName:t,status:n,executionLog:[]},document.querySelector(`.execution-log-panel.realtime-mode`)&&_p(C.currentExecutionStatus)}n(`zh`,{exportImport:{noSessionsToExport:`暂无会话可导出`,unnamedSession:`未命名会话`,currentBadge:`当前`,messageCount:`{count} 条消息`,loadFailed:`加载失败`,exportSelectedCount:`导出选中 ({count})`,selectAtLeastOne:`请至少选择一个会话`,exportSuccess:`已导出 {count} 个会话`,exportFailed:`导出失败: {message}`,importedConversation:`导入的对话`,unrecognizedFormat:`无法识别的文件格式`,noImportableData:`文件中没有可导入的会话数据`,importSuccess:`成功导入 {count} 个会话`,importFailed:`导入失败: {message}`}}),n(`en`,{exportImport:{noSessionsToExport:`No sessions to export`,unnamedSession:`Unnamed session`,currentBadge:`Current`,messageCount:`{count} messages`,loadFailed:`Load failed`,exportSelectedCount:`Export selected ({count})`,selectAtLeastOne:`Please select at least one session`,exportSuccess:`Exported {count} sessions`,exportFailed:`Export failed: {message}`,importedConversation:`Imported conversation`,unrecognizedFormat:`Unrecognized file format`,noImportableData:`No importable session data in the file`,importSuccess:`Successfully imported {count} sessions`,importFailed:`Import failed: {message}`}});async function Cp(){let e=document.getElementById(`exportSessionsModal`),t=document.getElementById(`exportSessionsList`);if(!(!e||!t)){t.innerHTML=`<div class="export-sessions-empty">${r(`common.loading`)}</div>`;try{let{list:e,activeSessionId:n}=await vi({withActiveHistory:!1});if(e.length===0)t.innerHTML=`<div class="export-sessions-empty">${r(`exportImport.noSessionsToExport`)}</div>`;else{let i=n||C.activeSessionId;t.innerHTML=e.map((e,t)=>{let n=e.id===i,a=e.messageCount??(e.messageHistory||[]).length,o=e.createdAt?new Date(e.createdAt).toLocaleDateString(`zh-CN`):``;return`
|
|
683
685
|
<div class="export-session-item" data-id="${e.id}">
|
|
684
686
|
<input type="checkbox" class="export-session-checkbox" data-session-id="${e.id}" ${n?`checked`:``}>
|
|
685
687
|
<div class="export-session-info">
|
|
686
688
|
<div class="export-session-title">${L(e.title||r(`exportImport.unnamedSession`))}${n?`<span class="current-badge">${r(`exportImport.currentBadge`)}</span>`:``}</div>
|
|
687
689
|
<div class="export-session-meta">${r(`exportImport.messageCount`,{count:a})}${o?` · `+o:``}</div>
|
|
688
690
|
</div>
|
|
689
|
-
</div>`}).join(``),t.querySelectorAll(`.export-session-item`).forEach(e=>{let t=e.querySelector(`.export-session-checkbox`);e.addEventListener(`click`,e=>{e.target!==t&&(t.checked=!t.checked),bp()})});let a=document.getElementById(`exportSelectAllBtn`),o=document.getElementById(`exportDeselectAllBtn`),s=document.getElementById(`exportSelectCurrentBtn`);a&&(a.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=!0}),bp()}),o&&(o.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=!1}),bp()}),s&&(s.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=e.dataset.sessionId===i}),bp()}),bp()}}catch(e){i.error(`[SidePanel] loadsession column table failed:`,e),t.innerHTML=`<div class="export-sessions-empty">${r(`exportImport.loadFailed`)}</div>`}e.classList.add(`show`)}}function bp(){document.querySelectorAll(`#exportSessionsList .export-session-checkbox`);let e=document.querySelectorAll(`#exportSessionsList .export-session-checkbox:checked`),t=document.getElementById(`exportSelectedCount`);t&&(t.textContent=r(`chatExport.selectedCount`,{count:e.length}));let n=document.getElementById(`exportSessionsOkBtn`);n&&(n.textContent=r(`exportImport.exportSelectedCount`,{count:e.length}),n.disabled=e.length===0,n.style.opacity=e.length===0?`0.5`:`1`)}function xp(){let e=document.getElementById(`exportSessionsModal`);e&&e.classList.remove(`show`)}async function Sp(){let e=document.querySelectorAll(`#exportSessionsList .export-session-checkbox:checked`),t=Array.from(e).map(e=>e.dataset.sessionId);if(t.length===0){F(r(`exportImport.selectAtLeastOne`),`warning`);return}try{let{list:e}=await vi({withActiveHistory:!1}),n=await Promise.all(e.filter(e=>t.includes(e.id)).map(async e=>await w(e.id)||e)),a={version:1,exportedAt:new Date().toISOString(),sessions:n.map(e=>({title:e.title||r(`exportImport.unnamedSession`),model:e.model,useTools:e.useTools,enabledTools:e.enabledTools,temperature:e.temperature,topP:e.topP,createdAt:e.createdAt,messageHistory:(e.messageHistory||[]).map(e=>({role:e.role,content:e.content||``,executionLog:e.executionLog||[],htmlContent:e.htmlContent||``,reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,messageId:e.messageId||``,timestamp:e.timestamp||``}))}))},o=new Date,s=o.getFullYear()+String(o.getMonth()+1).padStart(2,`0`)+String(o.getDate()).padStart(2,`0`)+`-`+String(o.getHours()).padStart(2,`0`)+String(o.getMinutes()).padStart(2,`0`)+String(o.getSeconds()).padStart(2,`0`),c=n.length,l=c===1?`ai-helper-${n[0].title.replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)}-${s}.aihelper.json`:`ai-helper-${c}sessions-${s}.aihelper.json`,u=JSON.stringify(a,null,2),d=new Blob([u],{type:`application/json;charset=utf-8;`}),f=URL.createObjectURL(d),p=document.createElement(`a`);p.href=f,p.download=l,document.body.appendChild(p),p.click(),document.body.removeChild(p),URL.revokeObjectURL(f),xp(),i.debug(`[SidePanel] sessionexported:`,l,`total `,c,`session`),F(r(`exportImport.exportSuccess`,{count:c}),`success`)}catch(e){i.error(`[SidePanel] export failed:`,e),F(r(`exportImport.exportFailed`,{message:e.message}),`error`)}}function Cp(){let e=document.getElementById(`exportSessionsCloseBtn`),t=document.getElementById(`exportSessionsCancelBtn`),n=document.getElementById(`exportSessionsOkBtn`),r=document.getElementById(`exportSessionsModal`);e&&e.addEventListener(`click`,xp),t&&t.addEventListener(`click`,xp),n&&n.addEventListener(`click`,Sp),r&&r.addEventListener(`click`,e=>{e.target===r&&xp()})}function wp(){let e=document.getElementById(`importSessionsFile`);e&&(e.value=``,e.click())}async function Tp(e){try{let t=await e.text(),n=JSON.parse(t),a=[];if(n.version&&n.sessions&&Array.isArray(n.sessions))a=n.sessions;else if(Array.isArray(n))a=n.length>0&&n[0].role?[{title:r(`exportImport.importedConversation`),messageHistory:n.map(e=>({role:e.role||`user`,content:e.content||``}))}]:(n.length>0&&n[0].title,n);else throw Error(r(`exportImport.unrecognizedFormat`));if(a.length===0){F(r(`exportImport.noImportableData`),`warning`);return}let o=await Ni(a);await Io(),i.debug(`[SidePanel] import complete:`,o.length,`session`),F(r(`exportImport.importSuccess`,{count:o.length}),`success`)}catch(e){i.error(`[SidePanel] import failed:`,e),F(r(`exportImport.importFailed`,{message:e.message}),`error`)}}n(`zh`,{imagePreview:{clickToEnlarge:`点击查看大图`,removeImage:`移除图片`}}),n(`en`,{imagePreview:{clickToEnlarge:`Click to enlarge`,removeImage:`Remove image`}});var Ep=1,Dp=0,Op=0,kp=!1,Ap=0,jp=0,Mp=0,Np=0,Pp=[],Fp=0,Ip=!1,Lp=`brush`,Rp=`#ff4757`,zp=4,Bp=1,Vp=!1,Hp=0,Up=0,Wp=0,Gp=0,Kp=0,qp=0,Jp=[],W=null,G=null,Yp=null,K=null;function Xp(e){let t=document.createElement(`a`);t.href=e,t.download=`image_${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.jpg`,document.body.appendChild(t),t.click(),document.body.removeChild(t)}function Zp(){let e=document.getElementById(`imagePreviewLarge`);e&&(e.style.transform=`translate(${Dp}px, ${Op}px) scale(${Ep})`,Ep>1?(e.classList.add(`zoomable`),kp?e.classList.add(`dragging`):e.classList.remove(`dragging`)):e.classList.remove(`zoomable`,`dragging`))}function Qp(){Ep=1,Dp=0,Op=0,kp=!1,Zp()}function $p(e,t){let n=document.getElementById(`imagePreviewOverlay`),r=document.getElementById(`imagePreviewLarge`),i=document.getElementById(`imagePreviewEdit`);if(!n||!r)return;let a=t&&t.closest(`.user-message-images`);i&&(i.style.display=a?`none`:``),em(e,t),tm(),rm(e),n.classList.add(`show`)}function em(e,t){Pp=[],t&&(t.closest(`.image-preview-bar`)||t.classList.contains(`image-preview-thumb`)?document.querySelectorAll(`.image-preview-thumb`).forEach(e=>{e.src&&Pp.push(e.src)}):t.closest(`.user-message-images`)&&t.closest(`.user-message-images`).querySelectorAll(`.user-message-image`).forEach(e=>{e.src&&Pp.push(e.src)})),Pp.length===0&&document.querySelectorAll(`.image-preview-thumb, .user-message-image`).forEach(e=>{e.src&&Pp.push(e.src)}),Fp=Pp.indexOf(e),Fp===-1&&(Pp.push(e),Fp=Pp.length-1)}function tm(){let e=document.getElementById(`imagePreviewPrev`),t=document.getElementById(`imagePreviewNext`),n=document.getElementById(`imagePreviewCounter`);Pp.length<=1?(e&&(e.style.display=`none`),t&&(t.style.display=`none`),n&&(n.style.display=`none`)):(e&&(e.style.display=``),t&&(t.style.display=``),n&&(n.style.display=``),nm())}function nm(){let e=document.getElementById(`imagePreviewPrev`),t=document.getElementById(`imagePreviewNext`),n=document.getElementById(`imagePreviewCounter`);e&&(e.disabled=!1),t&&(t.disabled=!1),n&&(n.textContent=`${Fp+1} / ${Pp.length}`)}function rm(e){let t=document.getElementById(`imagePreviewLarge`);t&&(Qp(),t.src=e)}function im(e){let t=Pp.length;t!==0&&(Fp=(Fp+e+t)%t,rm(Pp[Fp]),nm())}function am(){let e=document.getElementById(`imagePreviewOverlay`);if(!e||e.dataset.initialized)return;e.dataset.initialized=`true`;let t=document.getElementById(`imagePreviewLarge`),n=()=>{e.classList.remove(`show`),Qp()},r=e.querySelector(`.image-preview-close`);r&&r.addEventListener(`click`,n);let i=document.getElementById(`imagePreviewDownload`);i&&i.addEventListener(`click`,e=>{e.stopPropagation();let t=document.getElementById(`imagePreviewLarge`);t&&t.src&&Xp(t.src)});let a=document.getElementById(`imagePreviewEdit`);a&&a.addEventListener(`click`,e=>{e.stopPropagation(),pm()});let o=document.getElementById(`imagePreviewPrev`),s=document.getElementById(`imagePreviewNext`);o&&o.addEventListener(`click`,e=>{e.stopPropagation(),im(-1)}),s&&s.addEventListener(`click`,e=>{e.stopPropagation(),im(1)}),document.addEventListener(`keydown`,t=>{e.classList.contains(`show`)&&(t.key===`Escape`?n():t.key===`ArrowLeft`?im(-1):t.key===`ArrowRight`&&im(1))}),e.addEventListener(`wheel`,n=>{if(!e.classList.contains(`show`)||Ip)return;n.preventDefault();let r=t.getBoundingClientRect(),i=n.clientX-r.left-r.width/2,a=n.clientY-r.top-r.height/2,o=n.deltaY>0?-.15:.15,s=Ep,c=Math.max(.3,Math.min(5,Ep+o)),l=c/s;Ep=c,Dp=i-l*(i-Dp),Op=a-l*(a-Op),Zp()},{passive:!1}),t.addEventListener(`mousedown`,t=>{Ip||!e.classList.contains(`show`)||Ep<=1||(t.preventDefault(),kp=!0,Ap=t.clientX,jp=t.clientY,Mp=Dp,Np=Op,Zp())}),document.addEventListener(`mousemove`,e=>{kp&&(Dp=Mp+(e.clientX-Ap),Op=Np+(e.clientY-jp),Zp())}),document.addEventListener(`mouseup`,()=>{kp&&(kp=!1,Zp())}),t.addEventListener(`dblclick`,()=>{Ip||e.classList.contains(`show`)&&(Ep>1?Qp():(Ep=2,Dp=0,Op=0,Zp()))}),dm()}function om(e,t){let n=Math.max(e,t),r,i;n<=768?(r=n,i=.75):n<=1280?(r=768,i=.7):n<=2560?(r=1024,i=.65):n<=3840?(r=1280,i=.6):(r=1280,i=.55);let a=e,o=t;return n>r&&(e>t?(o=Math.round(r/e*t),a=r):(a=Math.round(r/t*e),o=r)),{targetWidth:a,targetHeight:o,quality:i}}function sm(e){let t=new Image,n=URL.createObjectURL(e);t.onload=()=>{URL.revokeObjectURL(n);let r=new FileReader;r.onloadend=()=>{let e=r.result,{width:n,height:i}=t,{targetWidth:a,targetHeight:o,quality:s}=om(n,i),c=document.createElement(`canvas`);c.width=a,c.height=o;let l=c.getContext(`2d`,{willReadFrequently:!0});l.imageSmoothingEnabled=!0,l.imageSmoothingQuality=`high`,l.drawImage(t,0,0,a,o);let u=c.toDataURL(`image/jpeg`,s);C.attachedImages.push({originalUrl:e,compressedUrl:u,width:a,height:o});let d=document.getElementById(`imagePreviewBar`),f=document.getElementById(`userInput`);d&&(d.style.display=``),cm(),f&&f.focus()},r.readAsDataURL(e)},t.onerror=()=>{URL.revokeObjectURL(n),i.error(`[ChatManager] imageload failed`)},t.src=n}function cm(){document.dispatchEvent(new CustomEvent(`input-attachments-changed`));let e=document.getElementById(`imagePreviewBar`);if(e){if(e.innerHTML=``,C.attachedImages.length===0){e.style.display=`none`;return}e.style.display=``,C.attachedImages.forEach((t,n)=>{let i=document.createElement(`div`);i.className=`image-preview-item`;let a=document.createElement(`img`);a.src=t.originalUrl||t.dataUrl,a.className=`image-preview-thumb`,a.title=r(`imagePreview.clickToEnlarge`),a.style.cursor=`zoom-in`,a.addEventListener(`click`,()=>{$p(t.originalUrl||t.dataUrl,a)});let o=document.createElement(`button`);o.className=`image-preview-remove`,o.innerHTML=`×`,o.title=r(`imagePreview.removeImage`),o.addEventListener(`click`,e=>{e.stopPropagation(),C.attachedImages.splice(n,1),cm()}),i.appendChild(a),i.appendChild(o),e.appendChild(i)})}}function lm(e,t=null){let n=t||C.attachedImages;if(!C.enableImageInput||n.length===0)return e;let r=[{type:`text`,text:e}];for(let e of n)r.push({type:`image_url`,image_url:{url:e.compressedUrl||e.dataUrl,original_url:e.originalUrl||e.compressedUrl||e.dataUrl,width:e.width,height:e.height}});return r}function um(e){if(typeof e==`string`)return e;if(Array.isArray(e)){let t=e.filter(e=>e.type===`text`);return t.length===1?t[0].text:t}return e}function dm(){W=document.getElementById(`imagePreviewEditCanvas`),Yp=document.getElementById(`imagePreviewPreviewCanvas`),W&&(G=W.getContext(`2d`,{willReadFrequently:!0}),G.lineCap=`round`,G.lineJoin=`round`),Yp&&(K=Yp.getContext(`2d`,{willReadFrequently:!0}),K.lineCap=`round`,K.lineJoin=`round`),fm();let e=document.getElementById(`imagePreviewLarge`);e&&e.addEventListener(`load`,_m)}function fm(){let e=document.getElementById(`imagePreviewEditorToolbar`);if(!e)return;e.querySelectorAll(`[data-tool]`).forEach(t=>{t.addEventListener(`click`,()=>{e.querySelectorAll(`[data-tool]`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`),Lp=t.dataset.tool,W&&(W.style.cursor=Lp===`eraser`?`cell`:`crosshair`)})});let t=document.getElementById(`editorColorPicker`);t&&t.addEventListener(`input`,e=>{Rp=e.target.value});let n=document.getElementById(`editorBrushSize`);n&&n.addEventListener(`input`,e=>{zp=parseInt(e.target.value)});let r=document.getElementById(`editorUndoBtn`);r&&r.addEventListener(`click`,Em);let i=document.getElementById(`editorConfirmBtn`);i&&i.addEventListener(`click`,Dm);let a=document.getElementById(`editorCancelBtn`);a&&a.addEventListener(`click`,km),document.addEventListener(`keydown`,t=>{if(!Ip)return;let n={b:`brush`,r:`rectangle`,e:`ellipse`,a:`arrow`,l:`line`};n[t.key.toLowerCase()]&&!t.ctrlKey&&!t.metaKey&&(t.preventDefault(),Lp=n[t.key.toLowerCase()],e.querySelectorAll(`[data-tool]`).forEach(e=>{e.classList.toggle(`active`,e.dataset.tool===Lp)})),(t.ctrlKey||t.metaKey)&&t.key===`z`&&(t.preventDefault(),Em()),t.key===`Enter`&&(t.preventDefault(),Dm()),t.key===`Escape`&&(t.preventDefault(),km())})}function pm(){Ip?gm():mm()}function mm(){Ip=!0,Jp=[];let e=document.getElementById(`imagePreviewLarge`);if(!e||!e.src)return;Qp(),e.style.transform=`none`,Ep=1,Dp=0,Op=0,e.style.pointerEvents=`none`,e.style.zIndex=`1`,W&&(W.style.display=`block`,W.style.pointerEvents=`auto`,W.style.zIndex=`5`),Yp&&(Yp.style.display=`block`,Yp.style.pointerEvents=`none`,Yp.style.zIndex=`6`);let t=document.getElementById(`imagePreviewEditorToolbar`);t&&(t.style.display=`flex`);let n=document.getElementById(`imagePreviewEdit`);n&&(n.style.display=`none`);let r=document.getElementById(`imagePreviewDownload`);r&&(r.style.display=`none`);let i=document.getElementById(`imagePreviewViewport`);i&&i.addEventListener(`contextmenu`,hm),setTimeout(()=>{_m()},50),Jp=[],W&&W.addEventListener(`mousedown`,ym),document.addEventListener(`mousemove`,bm),document.addEventListener(`mouseup`,xm)}function hm(e){e.preventDefault()}function gm(){Ip=!1,Vp=!1;let e=document.getElementById(`imagePreviewLarge`);e&&(e.style.pointerEvents=``,e.style.zIndex=``),W&&(W.style.display=`none`,W.removeEventListener(`mousedown`,ym)),Yp&&(Yp.style.display=`none`,K.clearRect(0,0,Yp.width,Yp.height));let t=document.getElementById(`imagePreviewEditorToolbar`);t&&(t.style.display=`none`);let n=document.getElementById(`imagePreviewEdit`);n&&(n.style.display=``);let r=document.getElementById(`imagePreviewDownload`);r&&(r.style.display=``);let i=document.getElementById(`imagePreviewViewport`);i&&i.removeEventListener(`contextmenu`,hm),document.removeEventListener(`mousemove`,bm),document.removeEventListener(`mouseup`,xm)}function _m(){let e=document.getElementById(`imagePreviewLarge`),t=document.getElementById(`imagePreviewViewport`);if(!e||!t||!W||!Yp)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=Math.round(n.width),a=Math.round(n.height);W.width=i,W.height=a,W.style.width=i+`px`,W.style.height=a+`px`,W.style.left=(r.width-i)/2+`px`,W.style.top=(r.height-a)/2+`px`,Yp.width=i,Yp.height=a,Yp.style.width=i+`px`,Yp.style.height=a+`px`,Yp.style.left=(r.width-i)/2+`px`,Yp.style.top=(r.height-a)/2+`px`}function vm(e){if(!W)return{x:0,y:0};let t=W.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}function ym(e){if(!Ip)return;e.preventDefault(),Vp=!0;let t=vm(e);Hp=t.x,Up=t.y,Wp=t.x,Gp=t.y,Kp=t.x,qp=t.y,Jp.push(W.toDataURL()),Jp.length>20&&Jp.shift()}function bm(e){if(!Vp||!Ip)return;e.preventDefault();let t=vm(e);if(Kp=t.x,qp=t.y,Lp===`brush`){G.save(),G.beginPath(),G.strokeStyle=Rp,G.lineWidth=zp,G.globalAlpha=Bp,G.lineCap=`round`,G.lineJoin=`round`;let e=Kp-Wp,t=qp-Gp,n=Math.sqrt(e*e+t*t);if(n>2){let r=Math.ceil(n);for(let n=1;n<=r;n++){let i=n/r,a=Wp+e*i,o=Gp+t*i;n===1&&G.moveTo(Wp,Gp),G.lineTo(a,o)}}else G.moveTo(Wp,Gp),G.lineTo(Kp,qp);G.stroke(),G.restore(),Wp=Kp,Gp=qp}else if(Lp===`eraser`){G.save(),G.beginPath(),G.lineWidth=zp*2,G.lineCap=`round`,G.lineJoin=`round`,G.globalCompositeOperation=`destination-out`;let e=Kp-Wp,t=qp-Gp,n=Math.sqrt(e*e+t*t);if(n>2){let r=Math.ceil(n);for(let n=1;n<=r;n++){let i=n/r,a=Wp+e*i,o=Gp+t*i;n===1&&G.moveTo(Wp,Gp),G.lineTo(a,o)}}else G.moveTo(Wp,Gp),G.lineTo(Kp,qp);G.stroke(),G.restore(),Wp=Kp,Gp=qp}else{if(!K)return;switch(K.clearRect(0,0,Yp.width,Yp.height),K.strokeStyle=Rp,K.lineWidth=zp,K.globalAlpha=Bp,K.lineCap=`round`,K.lineJoin=`round`,Lp){case`rectangle`:Sm();break;case`ellipse`:Cm();break;case`arrow`:wm();break;case`line`:Tm();break}}}function xm(){Vp&&(Vp=!1,Lp!==`brush`&&Lp!==`eraser`&&K&&(G.drawImage(Yp,0,0),K.clearRect(0,0,Yp.width,Yp.height)))}function Sm(){let e=Math.min(Hp,Kp),t=Math.min(Up,qp),n=Math.abs(Kp-Hp),r=Math.abs(qp-Up);if(event.shiftKey){let e=Math.max(n,r),t=Kp>Hp?Hp:Hp-e,i=qp>Up?Up:Up-e;K.strokeRect(t,i,e,e)}else K.strokeRect(e,t,n,r)}function Cm(){let e=Math.min(Hp,Kp),t=Math.min(Up,qp),n=Math.abs(Kp-Hp),r=Math.abs(qp-Up);if(event.shiftKey){let e=Math.max(n,r),t=Kp>Hp?Hp:Hp-e,i=qp>Up?Up:Up-e;K.beginPath(),K.ellipse(t+e/2,i+e/2,e/2,e/2,0,0,Math.PI*2),K.stroke()}else K.beginPath(),K.ellipse(e+n/2,t+r/2,n/2,r/2,0,0,Math.PI*2),K.stroke()}function wm(){let e=Math.atan2(qp-Up,Kp-Hp);K.beginPath(),K.moveTo(Hp,Up),K.lineTo(Kp,qp),K.stroke(),K.beginPath(),K.moveTo(Kp,qp),K.lineTo(Kp-12*Math.cos(e-Math.PI/6),qp-12*Math.sin(e-Math.PI/6)),K.moveTo(Kp,qp),K.lineTo(Kp-12*Math.cos(e+Math.PI/6),qp-12*Math.sin(e+Math.PI/6)),K.stroke()}function Tm(){K.beginPath(),K.moveTo(Hp,Up),K.lineTo(Kp,qp),K.stroke()}function Em(){if(Jp.length===0)return;let e=Jp.pop(),t=new Image;t.onload=()=>{try{G.clearRect(0,0,W.width,W.height),G.drawImage(t,0,0,W.width,W.height)}catch(e){i.error(`Undo failed:`,e)}},t.onerror=()=>{i.error(`Failed to load undo image`),Jp.length>0&&Em()},t.src=e}function Dm(){let e=document.getElementById(`imagePreviewLarge`),t=document.getElementById(`imagePreviewOverlay`);if(!e||!W)return;let n=document.createElement(`canvas`);n.width=e.naturalWidth,n.height=e.naturalHeight;let r=n.getContext(`2d`,{willReadFrequently:!0});r.drawImage(e,0,0);let i=e.naturalWidth/W.width,a=e.naturalHeight/W.height;r.save(),r.scale(i,a),r.drawImage(W,0,0),r.restore(),Om(n.toDataURL(`image/jpeg`,.85)),gm(),t.classList.remove(`show`),Qp()}function Om(e){let t=document.getElementById(`imagePreviewLarge`).src,n=document.getElementById(`imagePreviewLarge`),r=C.attachedImages.findIndex(e=>e.originalUrl===t||e.compressedUrl===t);if(r!==-1){let t=n?.naturalWidth||C.attachedImages[r].width,i=n?.naturalHeight||C.attachedImages[r].height;C.attachedImages[r]={originalUrl:e,compressedUrl:e,width:t,height:i},cm()}let i=document.getElementById(`imagePreviewLarge`);i&&(i.src=e)}function km(){G&&G.clearRect(0,0,W.width,W.height),Jp=[],gm()}var Am=t({attachFiles:()=>Jm,buildFileContentText:()=>Qm,clearFiles:()=>Xm,extractFileContent:()=>zm,formatFileSize:()=>Pm,getAgentConnectionInfo:()=>Bm,getFileCategory:()=>Mm,getFileIcon:()=>Nm,processFile:()=>qm,removeFile:()=>Ym,renderFilePreviews:()=>Zm,runImagePipeline:()=>Km,uploadFileToAgent:()=>Hm});n(`zh`,{fileExtract:{fileReadFailed:`文件读取失败`,oldDocNotSupported:`旧版 .doc 格式不支持,请用 Word 另存为 .docx 格式后再试`,agentNotPaired:`Agent 未配对`,agentUploadFailed:`Agent 上传失败 ({status}): {error}`,unsupportedFormat:`暂不支持 "{name}" 格式的浏览器端提取,请连接 Agent 后再试`,oldDocNotSupportedBrowser:`旧版 .doc 格式浏览器不支持,请用 Word 另存为 .docx 格式后再试`,extracting:`提取中...`,failed:`失败`,extractFailed:`提取失败`,removeFile:`移除文件`,workspaceFileMarker:`[工作目录文件: {path} (原名: {name})]`,truncated:`...(内容已截断)`,fileContentMarker:`[文件内容: {name}]`}}),n(`en`,{fileExtract:{fileReadFailed:`File read failed`,oldDocNotSupported:`Legacy .doc format is not supported. Please save as .docx in Word and try again.`,agentNotPaired:`Agent not paired`,agentUploadFailed:`Agent upload failed ({status}): {error}`,unsupportedFormat:`Browser-side extraction for "{name}" is not supported. Please connect an Agent and try again.`,oldDocNotSupportedBrowser:`Legacy .doc format is not supported in the browser. Please save as .docx in Word and try again.`,extracting:`Extracting...`,failed:`Failed`,extractFailed:`Extraction failed`,removeFile:`Remove file`,workspaceFileMarker:`[Workspace file: {path} (original name: {name})]`,truncated:`...(content truncated)`,fileContentMarker:`[File content: {name}]`}});var jm=`.txt,.md,.json,.js,.jsx,.ts,.tsx,.html,.css,.scss,.less,.xml,.yaml,.yml,.py,.java,.c,.cpp,.h,.go,.rs,.rb,.php,.sql,.sh,.bash,.zsh,.cfg,.ini,.toml,.conf,.log,.csv,.tsv,.env,.gitignore,.vue,.svelte,.astro,.rtf,.svg,.bat,.ps1,.makefile,.cmake,.gradle,.properties`.split(`,`);function Mm(e){let t=e.toLowerCase();return t.endsWith(`.pdf`)?`pdf`:t.endsWith(`.docx`)?`docx`:t.endsWith(`.doc`)?`doc`:t.endsWith(`.xlsx`)||t.endsWith(`.xls`)?`xlsx`:jm.some(e=>t.endsWith(e))?`text`:`unknown`}function Nm(e){switch(Mm(e)){case`pdf`:return`📄`;case`docx`:case`doc`:return`📝`;case`xlsx`:return`📊`;case`text`:return`📃`;default:return`📎`}}function Pm(e){return e<1024?e+` B`:e<1024*1024?(e/1024).toFixed(1)+` KB`:(e/(1024*1024)).toFixed(1)+` MB`}async function Fm(e){return new Promise((t,n)=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>n(Error(r(`fileExtract.fileReadFailed`))),i.readAsText(e,`UTF-8`)})}async function Im(t){let n=await A(()=>import(`./pdf-DnVqBaAN.js`).then(t=>e(t.default,1)),__vite__mapDeps([4,1,5]));n.GlobalWorkerOptions.workerSrc=`libs/pdf.worker.min.js`;let r=await t.arrayBuffer(),i=await n.getDocument({data:r}).promise,a=[];for(let e=1;e<=i.numPages;e++){let t=(await(await i.getPage(e)).getTextContent()).items.map(e=>e.str).join(` `);a.push(t)}return a.join(`
|
|
691
|
+
</div>`}).join(``),t.querySelectorAll(`.export-session-item`).forEach(e=>{let t=e.querySelector(`.export-session-checkbox`);e.addEventListener(`click`,e=>{e.target!==t&&(t.checked=!t.checked),wp()})});let a=document.getElementById(`exportSelectAllBtn`),o=document.getElementById(`exportDeselectAllBtn`),s=document.getElementById(`exportSelectCurrentBtn`);a&&(a.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=!0}),wp()}),o&&(o.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=!1}),wp()}),s&&(s.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=e.dataset.sessionId===i}),wp()}),wp()}}catch(e){i.error(`[SidePanel] loadsession column table failed:`,e),t.innerHTML=`<div class="export-sessions-empty">${r(`exportImport.loadFailed`)}</div>`}e.classList.add(`show`)}}function wp(){document.querySelectorAll(`#exportSessionsList .export-session-checkbox`);let e=document.querySelectorAll(`#exportSessionsList .export-session-checkbox:checked`),t=document.getElementById(`exportSelectedCount`);t&&(t.textContent=r(`chatExport.selectedCount`,{count:e.length}));let n=document.getElementById(`exportSessionsOkBtn`);n&&(n.textContent=r(`exportImport.exportSelectedCount`,{count:e.length}),n.disabled=e.length===0,n.style.opacity=e.length===0?`0.5`:`1`)}function Tp(){let e=document.getElementById(`exportSessionsModal`);e&&e.classList.remove(`show`)}async function Ep(){let e=document.querySelectorAll(`#exportSessionsList .export-session-checkbox:checked`),t=Array.from(e).map(e=>e.dataset.sessionId);if(t.length===0){F(r(`exportImport.selectAtLeastOne`),`warning`);return}try{let{list:e}=await vi({withActiveHistory:!1}),n=await Promise.all(e.filter(e=>t.includes(e.id)).map(async e=>await w(e.id)||e)),a={version:1,exportedAt:new Date().toISOString(),sessions:n.map(e=>({title:e.title||r(`exportImport.unnamedSession`),model:e.model,useTools:e.useTools,enabledTools:e.enabledTools,temperature:e.temperature,topP:e.topP,createdAt:e.createdAt,messageHistory:(e.messageHistory||[]).map(e=>({role:e.role,content:e.content||``,executionLog:e.executionLog||[],htmlContent:e.htmlContent||``,reflectionScore:e.reflectionScore,wasRevised:e.wasRevised||!1,messageId:e.messageId||``,timestamp:e.timestamp||``}))}))},o=new Date,s=o.getFullYear()+String(o.getMonth()+1).padStart(2,`0`)+String(o.getDate()).padStart(2,`0`)+`-`+String(o.getHours()).padStart(2,`0`)+String(o.getMinutes()).padStart(2,`0`)+String(o.getSeconds()).padStart(2,`0`),c=n.length,l=c===1?`ai-helper-${n[0].title.replace(/[^a-zA-Z0-9\u4e00-\u9fa5_-]/g,`_`)}-${s}.aihelper.json`:`ai-helper-${c}sessions-${s}.aihelper.json`,u=JSON.stringify(a,null,2),d=new Blob([u],{type:`application/json;charset=utf-8;`}),f=URL.createObjectURL(d),p=document.createElement(`a`);p.href=f,p.download=l,document.body.appendChild(p),p.click(),document.body.removeChild(p),URL.revokeObjectURL(f),Tp(),i.debug(`[SidePanel] sessionexported:`,l,`total `,c,`session`),F(r(`exportImport.exportSuccess`,{count:c}),`success`)}catch(e){i.error(`[SidePanel] export failed:`,e),F(r(`exportImport.exportFailed`,{message:e.message}),`error`)}}function Dp(){let e=document.getElementById(`exportSessionsCloseBtn`),t=document.getElementById(`exportSessionsCancelBtn`),n=document.getElementById(`exportSessionsOkBtn`),r=document.getElementById(`exportSessionsModal`);e&&e.addEventListener(`click`,Tp),t&&t.addEventListener(`click`,Tp),n&&n.addEventListener(`click`,Ep),r&&r.addEventListener(`click`,e=>{e.target===r&&Tp()})}function Op(){let e=document.getElementById(`importSessionsFile`);e&&(e.value=``,e.click())}async function kp(e){try{let t=await e.text(),n=JSON.parse(t),a=[];if(n.version&&n.sessions&&Array.isArray(n.sessions))a=n.sessions;else if(Array.isArray(n))a=n.length>0&&n[0].role?[{title:r(`exportImport.importedConversation`),messageHistory:n.map(e=>({role:e.role||`user`,content:e.content||``}))}]:(n.length>0&&n[0].title,n);else throw Error(r(`exportImport.unrecognizedFormat`));if(a.length===0){F(r(`exportImport.noImportableData`),`warning`);return}let o=await Ni(a);await Bo(),i.debug(`[SidePanel] import complete:`,o.length,`session`),F(r(`exportImport.importSuccess`,{count:o.length}),`success`)}catch(e){i.error(`[SidePanel] import failed:`,e),F(r(`exportImport.importFailed`,{message:e.message}),`error`)}}n(`zh`,{imagePreview:{clickToEnlarge:`点击查看大图`,removeImage:`移除图片`}}),n(`en`,{imagePreview:{clickToEnlarge:`Click to enlarge`,removeImage:`Remove image`}});var Ap=1,jp=0,Mp=0,Np=!1,Pp=0,Fp=0,Ip=0,Lp=0,Rp=[],zp=0,Bp=!1,Vp=`brush`,Hp=`#ff4757`,Up=4,Wp=1,Gp=!1,Kp=0,qp=0,Jp=0,Yp=0,Xp=0,Zp=0,Qp=[],W=null,G=null,$p=null,K=null;function em(e){let t=document.createElement(`a`);t.href=e,t.download=`image_${new Date().toISOString().replace(/[:.]/g,`-`).slice(0,19)}.jpg`,document.body.appendChild(t),t.click(),document.body.removeChild(t)}function tm(){let e=document.getElementById(`imagePreviewLarge`);e&&(e.style.transform=`translate(${jp}px, ${Mp}px) scale(${Ap})`,Ap>1?(e.classList.add(`zoomable`),Np?e.classList.add(`dragging`):e.classList.remove(`dragging`)):e.classList.remove(`zoomable`,`dragging`))}function nm(){Ap=1,jp=0,Mp=0,Np=!1,tm()}function rm(e,t){let n=document.getElementById(`imagePreviewOverlay`),r=document.getElementById(`imagePreviewLarge`),i=document.getElementById(`imagePreviewEdit`);if(!n||!r)return;let a=t&&t.closest(`.user-message-images`);i&&(i.style.display=a?`none`:``),im(e,t),am(),sm(e),n.classList.add(`show`)}function im(e,t){Rp=[],t&&(t.closest(`.image-preview-bar`)||t.classList.contains(`image-preview-thumb`)?document.querySelectorAll(`.image-preview-thumb`).forEach(e=>{e.src&&Rp.push(e.src)}):t.closest(`.user-message-images`)&&t.closest(`.user-message-images`).querySelectorAll(`.user-message-image`).forEach(e=>{e.src&&Rp.push(e.src)})),Rp.length===0&&document.querySelectorAll(`.image-preview-thumb, .user-message-image`).forEach(e=>{e.src&&Rp.push(e.src)}),zp=Rp.indexOf(e),zp===-1&&(Rp.push(e),zp=Rp.length-1)}function am(){let e=document.getElementById(`imagePreviewPrev`),t=document.getElementById(`imagePreviewNext`),n=document.getElementById(`imagePreviewCounter`);Rp.length<=1?(e&&(e.style.display=`none`),t&&(t.style.display=`none`),n&&(n.style.display=`none`)):(e&&(e.style.display=``),t&&(t.style.display=``),n&&(n.style.display=``),om())}function om(){let e=document.getElementById(`imagePreviewPrev`),t=document.getElementById(`imagePreviewNext`),n=document.getElementById(`imagePreviewCounter`);e&&(e.disabled=!1),t&&(t.disabled=!1),n&&(n.textContent=`${zp+1} / ${Rp.length}`)}function sm(e){let t=document.getElementById(`imagePreviewLarge`);t&&(nm(),t.src=e)}function cm(e){let t=Rp.length;t!==0&&(zp=(zp+e+t)%t,sm(Rp[zp]),om())}function lm(){let e=document.getElementById(`imagePreviewOverlay`);if(!e||e.dataset.initialized)return;e.dataset.initialized=`true`;let t=document.getElementById(`imagePreviewLarge`),n=()=>{e.classList.remove(`show`),nm()},r=e.querySelector(`.image-preview-close`);r&&r.addEventListener(`click`,n);let i=document.getElementById(`imagePreviewDownload`);i&&i.addEventListener(`click`,e=>{e.stopPropagation();let t=document.getElementById(`imagePreviewLarge`);t&&t.src&&em(t.src)});let a=document.getElementById(`imagePreviewEdit`);a&&a.addEventListener(`click`,e=>{e.stopPropagation(),_m()});let o=document.getElementById(`imagePreviewPrev`),s=document.getElementById(`imagePreviewNext`);o&&o.addEventListener(`click`,e=>{e.stopPropagation(),cm(-1)}),s&&s.addEventListener(`click`,e=>{e.stopPropagation(),cm(1)}),document.addEventListener(`keydown`,t=>{e.classList.contains(`show`)&&(t.key===`Escape`?n():t.key===`ArrowLeft`?cm(-1):t.key===`ArrowRight`&&cm(1))}),e.addEventListener(`wheel`,n=>{if(!e.classList.contains(`show`)||Bp)return;n.preventDefault();let r=t.getBoundingClientRect(),i=n.clientX-r.left-r.width/2,a=n.clientY-r.top-r.height/2,o=n.deltaY>0?-.15:.15,s=Ap,c=Math.max(.3,Math.min(5,Ap+o)),l=c/s;Ap=c,jp=i-l*(i-jp),Mp=a-l*(a-Mp),tm()},{passive:!1}),t.addEventListener(`mousedown`,t=>{Bp||!e.classList.contains(`show`)||Ap<=1||(t.preventDefault(),Np=!0,Pp=t.clientX,Fp=t.clientY,Ip=jp,Lp=Mp,tm())}),document.addEventListener(`mousemove`,e=>{Np&&(jp=Ip+(e.clientX-Pp),Mp=Lp+(e.clientY-Fp),tm())}),document.addEventListener(`mouseup`,()=>{Np&&(Np=!1,tm())}),t.addEventListener(`dblclick`,()=>{Bp||e.classList.contains(`show`)&&(Ap>1?nm():(Ap=2,jp=0,Mp=0,tm()))}),hm()}function um(e,t){let n=Math.max(e,t),r,i;n<=768?(r=n,i=.75):n<=1280?(r=768,i=.7):n<=2560?(r=1024,i=.65):n<=3840?(r=1280,i=.6):(r=1280,i=.55);let a=e,o=t;return n>r&&(e>t?(o=Math.round(r/e*t),a=r):(a=Math.round(r/t*e),o=r)),{targetWidth:a,targetHeight:o,quality:i}}function dm(e){let t=new Image,n=URL.createObjectURL(e);t.onload=()=>{URL.revokeObjectURL(n);let r=new FileReader;r.onloadend=()=>{let e=r.result,{width:n,height:i}=t,{targetWidth:a,targetHeight:o,quality:s}=um(n,i),c=document.createElement(`canvas`);c.width=a,c.height=o;let l=c.getContext(`2d`,{willReadFrequently:!0});l.imageSmoothingEnabled=!0,l.imageSmoothingQuality=`high`,l.drawImage(t,0,0,a,o);let u=c.toDataURL(`image/jpeg`,s);C.attachedImages.push({originalUrl:e,compressedUrl:u,width:a,height:o});let d=document.getElementById(`imagePreviewBar`),f=document.getElementById(`userInput`);d&&(d.style.display=``),fm(),f&&f.focus()},r.readAsDataURL(e)},t.onerror=()=>{URL.revokeObjectURL(n),i.error(`[ChatManager] imageload failed`)},t.src=n}function fm(){document.dispatchEvent(new CustomEvent(`input-attachments-changed`));let e=document.getElementById(`imagePreviewBar`);if(e){if(e.innerHTML=``,C.attachedImages.length===0){e.style.display=`none`;return}e.style.display=``,C.attachedImages.forEach((t,n)=>{let i=document.createElement(`div`);i.className=`image-preview-item`;let a=document.createElement(`img`);a.src=t.originalUrl||t.dataUrl,a.className=`image-preview-thumb`,a.title=r(`imagePreview.clickToEnlarge`),a.style.cursor=`zoom-in`,a.addEventListener(`click`,()=>{rm(t.originalUrl||t.dataUrl,a)});let o=document.createElement(`button`);o.className=`image-preview-remove`,o.innerHTML=`×`,o.title=r(`imagePreview.removeImage`),o.addEventListener(`click`,e=>{e.stopPropagation(),C.attachedImages.splice(n,1),fm()}),i.appendChild(a),i.appendChild(o),e.appendChild(i)})}}function pm(e,t=null){let n=t||C.attachedImages;if(!C.enableImageInput||n.length===0)return e;let r=[{type:`text`,text:e}];for(let e of n)r.push({type:`image_url`,image_url:{url:e.compressedUrl||e.dataUrl,original_url:e.originalUrl||e.compressedUrl||e.dataUrl,width:e.width,height:e.height}});return r}function mm(e){if(typeof e==`string`)return e;if(Array.isArray(e)){let t=e.filter(e=>e.type===`text`);return t.length===1?t[0].text:t}return e}function hm(){W=document.getElementById(`imagePreviewEditCanvas`),$p=document.getElementById(`imagePreviewPreviewCanvas`),W&&(G=W.getContext(`2d`,{willReadFrequently:!0}),G.lineCap=`round`,G.lineJoin=`round`),$p&&(K=$p.getContext(`2d`,{willReadFrequently:!0}),K.lineCap=`round`,K.lineJoin=`round`),gm();let e=document.getElementById(`imagePreviewLarge`);e&&e.addEventListener(`load`,xm)}function gm(){let e=document.getElementById(`imagePreviewEditorToolbar`);if(!e)return;e.querySelectorAll(`[data-tool]`).forEach(t=>{t.addEventListener(`click`,()=>{e.querySelectorAll(`[data-tool]`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`),Vp=t.dataset.tool,W&&(W.style.cursor=Vp===`eraser`?`cell`:`crosshair`)})});let t=document.getElementById(`editorColorPicker`);t&&t.addEventListener(`input`,e=>{Hp=e.target.value});let n=document.getElementById(`editorBrushSize`);n&&n.addEventListener(`input`,e=>{Up=parseInt(e.target.value)});let r=document.getElementById(`editorUndoBtn`);r&&r.addEventListener(`click`,Am);let i=document.getElementById(`editorConfirmBtn`);i&&i.addEventListener(`click`,jm);let a=document.getElementById(`editorCancelBtn`);a&&a.addEventListener(`click`,Nm),document.addEventListener(`keydown`,t=>{if(!Bp)return;let n={b:`brush`,r:`rectangle`,e:`ellipse`,a:`arrow`,l:`line`};n[t.key.toLowerCase()]&&!t.ctrlKey&&!t.metaKey&&(t.preventDefault(),Vp=n[t.key.toLowerCase()],e.querySelectorAll(`[data-tool]`).forEach(e=>{e.classList.toggle(`active`,e.dataset.tool===Vp)})),(t.ctrlKey||t.metaKey)&&t.key===`z`&&(t.preventDefault(),Am()),t.key===`Enter`&&(t.preventDefault(),jm()),t.key===`Escape`&&(t.preventDefault(),Nm())})}function _m(){Bp?bm():vm()}function vm(){Bp=!0,Qp=[];let e=document.getElementById(`imagePreviewLarge`);if(!e||!e.src)return;nm(),e.style.transform=`none`,Ap=1,jp=0,Mp=0,e.style.pointerEvents=`none`,e.style.zIndex=`1`,W&&(W.style.display=`block`,W.style.pointerEvents=`auto`,W.style.zIndex=`5`),$p&&($p.style.display=`block`,$p.style.pointerEvents=`none`,$p.style.zIndex=`6`);let t=document.getElementById(`imagePreviewEditorToolbar`);t&&(t.style.display=`flex`);let n=document.getElementById(`imagePreviewEdit`);n&&(n.style.display=`none`);let r=document.getElementById(`imagePreviewDownload`);r&&(r.style.display=`none`);let i=document.getElementById(`imagePreviewViewport`);i&&i.addEventListener(`contextmenu`,ym),setTimeout(()=>{xm()},50),Qp=[],W&&W.addEventListener(`mousedown`,Cm),document.addEventListener(`mousemove`,wm),document.addEventListener(`mouseup`,Tm)}function ym(e){e.preventDefault()}function bm(){Bp=!1,Gp=!1;let e=document.getElementById(`imagePreviewLarge`);e&&(e.style.pointerEvents=``,e.style.zIndex=``),W&&(W.style.display=`none`,W.removeEventListener(`mousedown`,Cm)),$p&&($p.style.display=`none`,K.clearRect(0,0,$p.width,$p.height));let t=document.getElementById(`imagePreviewEditorToolbar`);t&&(t.style.display=`none`);let n=document.getElementById(`imagePreviewEdit`);n&&(n.style.display=``);let r=document.getElementById(`imagePreviewDownload`);r&&(r.style.display=``);let i=document.getElementById(`imagePreviewViewport`);i&&i.removeEventListener(`contextmenu`,ym),document.removeEventListener(`mousemove`,wm),document.removeEventListener(`mouseup`,Tm)}function xm(){let e=document.getElementById(`imagePreviewLarge`),t=document.getElementById(`imagePreviewViewport`);if(!e||!t||!W||!$p)return;let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=Math.round(n.width),a=Math.round(n.height);W.width=i,W.height=a,W.style.width=i+`px`,W.style.height=a+`px`,W.style.left=(r.width-i)/2+`px`,W.style.top=(r.height-a)/2+`px`,$p.width=i,$p.height=a,$p.style.width=i+`px`,$p.style.height=a+`px`,$p.style.left=(r.width-i)/2+`px`,$p.style.top=(r.height-a)/2+`px`}function Sm(e){if(!W)return{x:0,y:0};let t=W.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}function Cm(e){if(!Bp)return;e.preventDefault(),Gp=!0;let t=Sm(e);Kp=t.x,qp=t.y,Jp=t.x,Yp=t.y,Xp=t.x,Zp=t.y,Qp.push(W.toDataURL()),Qp.length>20&&Qp.shift()}function wm(e){if(!Gp||!Bp)return;e.preventDefault();let t=Sm(e);if(Xp=t.x,Zp=t.y,Vp===`brush`){G.save(),G.beginPath(),G.strokeStyle=Hp,G.lineWidth=Up,G.globalAlpha=Wp,G.lineCap=`round`,G.lineJoin=`round`;let e=Xp-Jp,t=Zp-Yp,n=Math.sqrt(e*e+t*t);if(n>2){let r=Math.ceil(n);for(let n=1;n<=r;n++){let i=n/r,a=Jp+e*i,o=Yp+t*i;n===1&&G.moveTo(Jp,Yp),G.lineTo(a,o)}}else G.moveTo(Jp,Yp),G.lineTo(Xp,Zp);G.stroke(),G.restore(),Jp=Xp,Yp=Zp}else if(Vp===`eraser`){G.save(),G.beginPath(),G.lineWidth=Up*2,G.lineCap=`round`,G.lineJoin=`round`,G.globalCompositeOperation=`destination-out`;let e=Xp-Jp,t=Zp-Yp,n=Math.sqrt(e*e+t*t);if(n>2){let r=Math.ceil(n);for(let n=1;n<=r;n++){let i=n/r,a=Jp+e*i,o=Yp+t*i;n===1&&G.moveTo(Jp,Yp),G.lineTo(a,o)}}else G.moveTo(Jp,Yp),G.lineTo(Xp,Zp);G.stroke(),G.restore(),Jp=Xp,Yp=Zp}else{if(!K)return;switch(K.clearRect(0,0,$p.width,$p.height),K.strokeStyle=Hp,K.lineWidth=Up,K.globalAlpha=Wp,K.lineCap=`round`,K.lineJoin=`round`,Vp){case`rectangle`:Em();break;case`ellipse`:Dm();break;case`arrow`:Om();break;case`line`:km();break}}}function Tm(){Gp&&(Gp=!1,Vp!==`brush`&&Vp!==`eraser`&&K&&(G.drawImage($p,0,0),K.clearRect(0,0,$p.width,$p.height)))}function Em(){let e=Math.min(Kp,Xp),t=Math.min(qp,Zp),n=Math.abs(Xp-Kp),r=Math.abs(Zp-qp);if(event.shiftKey){let e=Math.max(n,r),t=Xp>Kp?Kp:Kp-e,i=Zp>qp?qp:qp-e;K.strokeRect(t,i,e,e)}else K.strokeRect(e,t,n,r)}function Dm(){let e=Math.min(Kp,Xp),t=Math.min(qp,Zp),n=Math.abs(Xp-Kp),r=Math.abs(Zp-qp);if(event.shiftKey){let e=Math.max(n,r),t=Xp>Kp?Kp:Kp-e,i=Zp>qp?qp:qp-e;K.beginPath(),K.ellipse(t+e/2,i+e/2,e/2,e/2,0,0,Math.PI*2),K.stroke()}else K.beginPath(),K.ellipse(e+n/2,t+r/2,n/2,r/2,0,0,Math.PI*2),K.stroke()}function Om(){let e=Math.atan2(Zp-qp,Xp-Kp);K.beginPath(),K.moveTo(Kp,qp),K.lineTo(Xp,Zp),K.stroke(),K.beginPath(),K.moveTo(Xp,Zp),K.lineTo(Xp-12*Math.cos(e-Math.PI/6),Zp-12*Math.sin(e-Math.PI/6)),K.moveTo(Xp,Zp),K.lineTo(Xp-12*Math.cos(e+Math.PI/6),Zp-12*Math.sin(e+Math.PI/6)),K.stroke()}function km(){K.beginPath(),K.moveTo(Kp,qp),K.lineTo(Xp,Zp),K.stroke()}function Am(){if(Qp.length===0)return;let e=Qp.pop(),t=new Image;t.onload=()=>{try{G.clearRect(0,0,W.width,W.height),G.drawImage(t,0,0,W.width,W.height)}catch(e){i.error(`Undo failed:`,e)}},t.onerror=()=>{i.error(`Failed to load undo image`),Qp.length>0&&Am()},t.src=e}function jm(){let e=document.getElementById(`imagePreviewLarge`),t=document.getElementById(`imagePreviewOverlay`);if(!e||!W)return;let n=document.createElement(`canvas`);n.width=e.naturalWidth,n.height=e.naturalHeight;let r=n.getContext(`2d`,{willReadFrequently:!0});r.drawImage(e,0,0);let i=e.naturalWidth/W.width,a=e.naturalHeight/W.height;r.save(),r.scale(i,a),r.drawImage(W,0,0),r.restore(),Mm(n.toDataURL(`image/jpeg`,.85)),bm(),t.classList.remove(`show`),nm()}function Mm(e){let t=document.getElementById(`imagePreviewLarge`).src,n=document.getElementById(`imagePreviewLarge`),r=C.attachedImages.findIndex(e=>e.originalUrl===t||e.compressedUrl===t);if(r!==-1){let t=n?.naturalWidth||C.attachedImages[r].width,i=n?.naturalHeight||C.attachedImages[r].height;C.attachedImages[r]={originalUrl:e,compressedUrl:e,width:t,height:i},fm()}let i=document.getElementById(`imagePreviewLarge`);i&&(i.src=e)}function Nm(){G&&G.clearRect(0,0,W.width,W.height),Qp=[],bm()}var Pm=t({attachFiles:()=>Qm,buildFileContentText:()=>nh,clearFiles:()=>eh,extractFileContent:()=>Um,formatFileSize:()=>Rm,getAgentConnectionInfo:()=>Wm,getFileCategory:()=>Im,getFileIcon:()=>Lm,processFile:()=>Zm,removeFile:()=>$m,renderFilePreviews:()=>th,runImagePipeline:()=>Xm,uploadFileToAgent:()=>Km});n(`zh`,{fileExtract:{fileReadFailed:`文件读取失败`,oldDocNotSupported:`旧版 .doc 格式不支持,请用 Word 另存为 .docx 格式后再试`,agentNotPaired:`Agent 未配对`,agentUploadFailed:`Agent 上传失败 ({status}): {error}`,unsupportedFormat:`暂不支持 "{name}" 格式的浏览器端提取,请连接 Agent 后再试`,oldDocNotSupportedBrowser:`旧版 .doc 格式浏览器不支持,请用 Word 另存为 .docx 格式后再试`,extracting:`提取中...`,failed:`失败`,extractFailed:`提取失败`,removeFile:`移除文件`,workspaceFileMarker:`[工作目录文件: {path} (原名: {name})]`,truncated:`...(内容已截断)`,fileContentMarker:`[文件内容: {name}]`}}),n(`en`,{fileExtract:{fileReadFailed:`File read failed`,oldDocNotSupported:`Legacy .doc format is not supported. Please save as .docx in Word and try again.`,agentNotPaired:`Agent not paired`,agentUploadFailed:`Agent upload failed ({status}): {error}`,unsupportedFormat:`Browser-side extraction for "{name}" is not supported. Please connect an Agent and try again.`,oldDocNotSupportedBrowser:`Legacy .doc format is not supported in the browser. Please save as .docx in Word and try again.`,extracting:`Extracting...`,failed:`Failed`,extractFailed:`Extraction failed`,removeFile:`Remove file`,workspaceFileMarker:`[Workspace file: {path} (original name: {name})]`,truncated:`...(content truncated)`,fileContentMarker:`[File content: {name}]`}});var Fm=`.txt,.md,.json,.js,.jsx,.ts,.tsx,.html,.css,.scss,.less,.xml,.yaml,.yml,.py,.java,.c,.cpp,.h,.go,.rs,.rb,.php,.sql,.sh,.bash,.zsh,.cfg,.ini,.toml,.conf,.log,.csv,.tsv,.env,.gitignore,.vue,.svelte,.astro,.rtf,.svg,.bat,.ps1,.makefile,.cmake,.gradle,.properties`.split(`,`);function Im(e){let t=e.toLowerCase();return t.endsWith(`.pdf`)?`pdf`:t.endsWith(`.docx`)?`docx`:t.endsWith(`.doc`)?`doc`:t.endsWith(`.xlsx`)||t.endsWith(`.xls`)?`xlsx`:Fm.some(e=>t.endsWith(e))?`text`:`unknown`}function Lm(e){switch(Im(e)){case`pdf`:return`📄`;case`docx`:case`doc`:return`📝`;case`xlsx`:return`📊`;case`text`:return`📃`;default:return`📎`}}function Rm(e){return e<1024?e+` B`:e<1024*1024?(e/1024).toFixed(1)+` KB`:(e/(1024*1024)).toFixed(1)+` MB`}async function zm(e){return new Promise((t,n)=>{let i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>n(Error(r(`fileExtract.fileReadFailed`))),i.readAsText(e,`UTF-8`)})}async function Bm(t){let n=await A(()=>import(`./pdf-DnVqBaAN.js`).then(t=>e(t.default,1)),__vite__mapDeps([4,1,5]));n.GlobalWorkerOptions.workerSrc=`libs/pdf.worker.min.js`;let r=await t.arrayBuffer(),i=await n.getDocument({data:r}).promise,a=[];for(let e=1;e<=i.numPages;e++){let t=(await(await i.getPage(e)).getTextContent()).items.map(e=>e.str).join(` `);a.push(t)}return a.join(`
|
|
690
692
|
|
|
691
|
-
`)}async function
|
|
693
|
+
`)}async function Vm(t){let n=(await A(async()=>{let{default:t}=await import(`./lib-YwkWjNcC.js`).then(t=>e(t.default,1));return{default:t}},__vite__mapDeps([6,1,7,5]))).default,r=await t.arrayBuffer();return(await n.extractRawText({arrayBuffer:r})).value}async function Hm(e){let t=await A(()=>import(`./xlsx-DGkz7cnk.js`),[]),n=await e.arrayBuffer(),r=t.read(n,{type:`array`}),i=[];for(let e of r.SheetNames){let n=r.Sheets[e],a=t.utils.sheet_to_csv(n);a.trim()&&i.push(`=== Sheet: ${e} ===\n${a}`)}return i.join(`
|
|
692
694
|
|
|
693
|
-
`)}async function
|
|
695
|
+
`)}async function Um(e){switch(Im(e.name)){case`pdf`:return await Bm(e);case`docx`:return await Vm(e);case`doc`:throw Error(r(`fileExtract.oldDocNotSupported`));case`xlsx`:return await Hm(e);case`text`:return await zm(e);default:return await zm(e)}}async function Wm(){let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),t=(e.pairedAgents||[]).map(e=>e.token?{...e,token:k(e.token)}:e).find(t=>t.id===e.activeAgentId);return!t?.url||!t?.token?null:{url:t.url,token:t.token}}function Gm(e){let t={Authorization:`Bearer ${e}`},n=C.activeSessionId;return n&&(t[`X-AIH-Session-Id`]=n),t}async function Km(e){let t=await Wm();if(!t)throw Error(r(`fileExtract.agentNotPaired`));let n=new FormData;n.append(`file`,e);let i=await fetch(`${t.url}/api/files/upload`,{method:`POST`,headers:Gm(t.token),body:n});if(!i.ok){let e=await i.text().catch(()=>``);throw Error(r(`fileExtract.agentUploadFailed`,{status:i.status,error:e}))}let a=await i.json();return{path:a.path||``,text:a.text||``}}async function qm(e,t){let n=await Wm();if(!n)throw Error(r(`fileExtract.agentNotPaired`));let i=await fetch(`${n.url}${e}`,{method:`POST`,headers:{"Content-Type":`application/json`,...Gm(n.token)},body:JSON.stringify(t)});if(!i.ok)throw Error(`HTTP ${i.status}`);return await i.json()}async function Jm(e){let t=await qm(`/api/documents/extract-images`,{path:e.agentPath});if(!t||t.success!==!0)throw Error(t?.error||`extractFailed`);e.images=t.images,e.truncated=t.truncated||0,e.skipped=t.skipped||0,e.imageSource=`agent`;let n=await Wm();if(n)for(let t of(e.images||[]).slice(0,ce.DESCRIBE_LIMIT))try{let e=await fetch(`${n.url}/api/fs/download`,{method:`POST`,headers:{"Content-Type":`application/json`,...Gm(n.token)},body:JSON.stringify({path:t.path})}).then(e=>e.json());if(e.success&&e.content){let n=await ae(`data:${e.mimeType};base64,${e.content}`);n===null?t.overLimit=!0:t.dataUrl=n}}catch{}}async function Ym(e,t,n){let{images:r,truncated:i,skipped:a}=n===`docx`?await ee(t):n===`xlsx`?await me(t):await re(t);for(let e of r){let t=await ae(e.dataUrl);t===null?(e.overLimit=!0,delete e.dataUrl):e.dataUrl=t}e.images=r,e.truncated=i,e.skipped=a,e.imageSource=`local`}async function Xm(e,t,n,r){if(C.enableImageInput&&!(n!==`docx`&&n!==`pdf`&&n!==`xlsx`))try{if(r&&n===`docx`)try{await Jm(e)}catch(r){i.warn(`[FileExtract] agent image extract failed, downgrade to local:`,r.message),await Ym(e,t,n)}else await Ym(e,t,n);if(!e.images||e.images.length===0){e.imageStatus=`none`;return}e.imageStatus=`extracted`,e.imageDescriptions={};let a=await te(e.images.filter(e=>e.dataUrl),ce.DESCRIBE_LIMIT,(t,n)=>{e.imageDescriptions[t]=n});e.imageDescriptions={...e.imageDescriptions,...a},e.imageStatus=`described`}catch(n){i.warn(`[FileExtract] image pipeline failed (degrade):`,t.name,n.message),e.images||(e.imageStatus=`error`)}}async function Zm(e,t){let n=C.attachedFiles[t];if(!n)return;n.status=`extracting`,th();let a=Im(e.name);try{if(C.agentPlatform?.connected)try{let t=await Km(e);n.agentPath=t.path,n.text=t.text||``,n.status=`done`,th(),await Xm(n,e,a,!0),th();return}catch(e){i.warn(`[FileExtract] Agent upload failed,downgrade to browserside extraction:`,e.message)}if(a===`unknown`)throw Error(r(`fileExtract.unsupportedFormat`,{name:e.name}));if(a===`doc`)throw Error(r(`fileExtract.oldDocNotSupportedBrowser`));n.text=await Um(e),n.status=`done`,th(),await Xm(n,e,a,!1)}catch(t){i.error(`[FileExtract] file extract failed:`,e.name,t),n.status=`error`,n.error=t.message}th()}function Qm(e){for(let t of e){if(C.attachedFiles.some(e=>e.name===t.name&&e.size===t.size))continue;let e=URL.createObjectURL(t),n={name:t.name,size:t.size,type:t.type,dataUrl:e,text:``,status:`pending`};C.attachedFiles.push(n),Zm(t,C.attachedFiles.length-1)}th()}function $m(e){let t=C.attachedFiles[e];t?.dataUrl&&URL.revokeObjectURL(t.dataUrl),C.attachedFiles.splice(e,1),th()}function eh(){for(let e of C.attachedFiles)e.dataUrl&&URL.revokeObjectURL(e.dataUrl);C.attachedFiles=[],th()}function th(){document.dispatchEvent(new CustomEvent(`input-attachments-changed`));let e=document.getElementById(`filePreviewBar`);if(e){if(e.innerHTML=``,C.attachedFiles.length===0){e.style.display=`none`;return}e.style.display=``,C.attachedFiles.forEach((t,n)=>{let i=document.createElement(`div`);if(i.className=`file-preview-item`,i.title=`${t.name} (${Rm(t.size)})`,t.isImage&&t.dataUrl){let e=document.createElement(`img`);e.className=`file-preview-thumb`,e.src=t.dataUrl,e.alt=t.name,i.appendChild(e);let n=document.createElement(`span`);n.className=`file-preview-thumb-label`,n.textContent=t.name,i.appendChild(n)}else{let e=document.createElement(`span`);e.className=`file-preview-icon`,e.textContent=Lm(t.name);let n=document.createElement(`div`);n.className=`file-preview-info`;let r=document.createElement(`span`);r.className=`file-preview-name`,r.textContent=t.name;let a=document.createElement(`span`);a.className=`file-preview-meta`,a.textContent=Rm(t.size),n.appendChild(r),n.appendChild(a),i.appendChild(e),i.appendChild(n)}if(t.status===`extracting`){let e=document.createElement(`span`);e.className=`file-preview-status extracting`,e.textContent=r(`fileExtract.extracting`),i.appendChild(e)}else if(t.status===`error`){let e=document.createElement(`span`);e.className=`file-preview-status error`,e.textContent=r(`fileExtract.failed`),e.title=t.error||r(`fileExtract.extractFailed`),i.appendChild(e)}else if(t.status===`done`){let e=document.createElement(`span`);e.className=`file-preview-status done`,e.textContent=`✓`,i.appendChild(e)}if(t.images&&t.images.length>0){let e=document.createElement(`span`);e.className=`file-preview-status images`,e.textContent=N(t),e.title=Ee(t),i.appendChild(e)}else !C.enableImageInput&&[`docx`,`pdf`,`xlsx`].includes(Im(t.name))&&(i.title=`${i.title} — ${r(`docImages.previewOff`)}`);let a=document.createElement(`button`);a.className=`file-preview-remove`,a.innerHTML=`×`,a.title=r(`fileExtract.removeFile`),a.addEventListener(`click`,e=>{e.stopPropagation(),$m(n)}),i.appendChild(a),e.appendChild(i)})}}function nh(e){let t=(e||C.attachedFiles||[]).filter(e=>e.status===`done`);if(t.length===0)return``;let n=[],i=t.filter(e=>e.agentPath),a=t.filter(e=>!e.agentPath&&e.text);for(let e of i)n.push(r(`fileExtract.workspaceFileMarker`,{path:e.agentPath,name:e.name})+ie(e,e.name));for(let e of a){let t=e.text.length>5e4?e.text.substring(0,5e4)+`
|
|
694
696
|
`+r(`fileExtract.truncated`):e.text;n.push(r(`fileExtract.fileContentMarker`,{name:e.name})+`
|
|
695
697
|
`+t+ie(e,e.name))}return`
|
|
696
698
|
|
|
@@ -698,7 +700,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
698
700
|
|
|
699
701
|
---
|
|
700
702
|
|
|
701
|
-
`)}async function
|
|
703
|
+
`)}async function rh(){try{C.bookmarks=await o()||[],i.debug(`[Bookmark] loadedbookmark:`,C.bookmarks.length,``)}catch(e){i.error(`[Bookmark] load bookmarks failed:`,e),C.bookmarks=[]}}function ih(e,t){return C.bookmarks.find(n=>n.sessionId===e&&n.messageId===t)||null}async function ah(e,t,n,r){if(!e||!t)return null;let a=ih(e,t);if(a)return a;let o={id:`bmk_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,6),sessionId:e,messageId:t,content:n||``,sessionTitle:r||``,createdAt:Date.now(),pinned:!1};try{if(await T(o))return C.bookmarks.push(o),i.debug(`[Bookmark] bookmark successful:`,o.id),o}catch(e){i.error(`[Bookmark] bookmark failed:`,e)}return null}async function oh(e,t){let n=ih(e,t);if(!n)return!1;try{if(await u(n.id))return C.bookmarks=C.bookmarks.filter(e=>e.id!==n.id),i.debug(`[Bookmark] cancelbookmark:`,n.id),!0}catch(e){i.error(`[Bookmark] cancelbookmark failed:`,e)}return!1}async function sh(e){try{if(await u(e))return C.bookmarks=C.bookmarks.filter(t=>t.id!==e),!0}catch(e){i.error(`[Bookmark] cancelbookmark failed:`,e)}return!1}async function ch(e,t){try{if(await v(e,t)){let n=C.bookmarks.find(t=>t.id===e);return n&&(n.pinned=t),!0}}catch(e){i.error(`[Bookmark] pin operation failed:`,e)}return!1}function lh(e=null){let t=C.bookmarks;return e&&(t=t.filter(t=>t.sessionId===e)),[...t].sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:t.createdAt-e.createdAt)}var uh=t({initBookmarkPanel:()=>dh,refreshBookmarkPanel:()=>fh,updateBookmarkBadge:()=>gh,updateBookmarkBtnState:()=>vh,updateBookmarkButtons:()=>_h});n(`zh`,{bookmark:{toggleTitle:`收藏列表`,title:`消息收藏`,searchPlaceholder:`搜索收藏内容(支持 & | 组合搜索)...`,clearSearchTitle:`清除搜索`,empty:`暂无收藏`,searchCount:`搜索 {filtered}/{total}`,countResult:`{count} 条`,noMatch:`无匹配结果`,otherSessions:`其他会话`,noTextContent:`(无文本内容)`,unpinTitle:`取消置顶`,pinTitle:`置顶`,removeBookmarkTitle:`取消收藏`,addBookmarkTitle:`收藏消息`,sessionNotExistToast:`会话已不存在,收藏已自动移除`,messageNotExistToast:`消息已不存在,收藏已自动移除`}}),n(`en`,{bookmark:{toggleTitle:`Bookmarks`,title:`Message bookmarks`,searchPlaceholder:`Search bookmarks (supports & | combined search)...`,clearSearchTitle:`Clear search`,empty:`No bookmarks`,searchCount:`Search {filtered}/{total}`,countResult:`{count} items`,noMatch:`No matching results`,otherSessions:`Other sessions`,noTextContent:`(No text content)`,unpinTitle:`Unpin`,pinTitle:`Pin`,removeBookmarkTitle:`Remove bookmark`,addBookmarkTitle:`Bookmark message`,sessionNotExistToast:`Session no longer exists, bookmark automatically removed`,messageNotExistToast:`Message no longer exists, bookmark automatically removed`}});function dh(){let e=document.createElement(`div`);e.className=`bookmark-panel-container`,e.id=`bookmarkPanelContainer`,e.innerHTML=`
|
|
702
704
|
<button class="bookmark-panel-toggle" id="bookmarkPanelToggle" title="${r(`bookmark.toggleTitle`)}">
|
|
703
705
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
704
706
|
<path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>
|
|
@@ -728,13 +730,13 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
728
730
|
<div class="bookmark-panel-empty">${r(`bookmark.empty`)}</div>
|
|
729
731
|
</div>
|
|
730
732
|
</div>
|
|
731
|
-
`,gn(`bookmark`).appendChild(e);let t=document.getElementById(`bookmarkPanelToggle`),n=document.getElementById(`bookmarkPanel`),a=document.getElementById(`bookmarkSearchInput`),o=document.getElementById(`bookmarkPanelClose`),s=Dn(`bookmark-panel-close-btn`);o.before(s),On(s,n,{onToggle:e=>{e||Ie(n)}}),C.bookmarkSearchHistory=[],C.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.get([`bookmarkSearchHistory`],e=>{e.bookmarkSearchHistory&&(C.bookmarkSearchHistory=e.bookmarkSearchHistory)})}catch{}function c(e){if(!e||!e.trim())return;let t=e.trim(),n=C.bookmarkSearchHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),C.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.set({bookmarkSearchHistory:n})}catch{}}t.addEventListener(`click`,()=>{n.classList.contains(`expanded`)?(Tn(n),n.classList.remove(`expanded`),Re(n)):(
|
|
733
|
+
`,gn(`bookmark`).appendChild(e);let t=document.getElementById(`bookmarkPanelToggle`),n=document.getElementById(`bookmarkPanel`),a=document.getElementById(`bookmarkSearchInput`),o=document.getElementById(`bookmarkPanelClose`),s=Dn(`bookmark-panel-close-btn`);o.before(s),On(s,n,{onToggle:e=>{e||Ie(n)}}),C.bookmarkSearchHistory=[],C.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.get([`bookmarkSearchHistory`],e=>{e.bookmarkSearchHistory&&(C.bookmarkSearchHistory=e.bookmarkSearchHistory)})}catch{}function c(e){if(!e||!e.trim())return;let t=e.trim(),n=C.bookmarkSearchHistory,r=n.indexOf(t);r!==-1&&n.splice(r,1),n.push(t),n.length>20&&n.shift(),C.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.set({bookmarkSearchHistory:n})}catch{}}t.addEventListener(`click`,()=>{n.classList.contains(`expanded`)?(Tn(n),n.classList.remove(`expanded`),Re(n)):(fh(a.value),n.classList.add(`expanded`),Ie(n))}),o.addEventListener(`click`,()=>{Tn(n),n.classList.remove(`expanded`),Re(n)});let l=document.getElementById(`bookmarkSearchClear`);a.addEventListener(`input`,()=>{let e=a.value.trim();fh(e),l.style.display=e?``:`none`}),l.addEventListener(`click`,()=>{a.value=``,l.style.display=`none`,C.bookmarkSearchHistoryIndex=-1,fh()}),a.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.preventDefault();let t=a.value.trim();t&&(c(t),fh(t))}else if(e.key===`Escape`)C.bookmarkSearchHistoryIndex>=0&&(C.bookmarkSearchHistoryIndex=-1,a.value=``,fh(),l.style.display=`none`);else if(e.key===`ArrowUp`){e.preventDefault();let t=C.bookmarkSearchHistory;if(t.length===0)return;C.bookmarkSearchHistoryIndex===-1?C.bookmarkSearchHistoryIndex=t.length-1:C.bookmarkSearchHistoryIndex>0&&C.bookmarkSearchHistoryIndex--,a.value=t[C.bookmarkSearchHistoryIndex]||``,l.style.display=a.value?``:`none`,fh(a.value)}else if(e.key===`ArrowDown`){e.preventDefault();let t=C.bookmarkSearchHistory;C.bookmarkSearchHistoryIndex>=0&&C.bookmarkSearchHistoryIndex<t.length-1?(C.bookmarkSearchHistoryIndex++,a.value=t[C.bookmarkSearchHistoryIndex]||``):(C.bookmarkSearchHistoryIndex=-1,a.value=``),l.style.display=a.value?``:`none`,fh(a.value)}}),document.getElementById(`bookmarkPanelContent`).addEventListener(`click`,async e=>{let t=e.target.closest(`.bookmark-item`);if(!t)return;let n=t.dataset.bookmarkId,r=t.dataset.sessionId,i=t.dataset.messageId;if(e.target.closest(`.bookmark-item-remove`)){e.stopPropagation(),await sh(n),fh(),_h();return}if(e.target.closest(`.bookmark-item-pin`)){e.stopPropagation();let t=C.bookmarks.find(e=>e.id===n);t&&(await ch(n,!t.pinned),fh());return}await hh(r,i)}),i.debug(`[BookmarkPanel] bookmark panelinitializing`)}function fh(e){let t=document.getElementById(`bookmarkPanelContent`),n=document.getElementById(`bookmarkPanelCount`);if(!t||!n)return;let i=C.activeSessionId,a=lh(i),o=i?C.bookmarks.filter(e=>e.sessionId!==i).sort((e,t)=>e.pinned&&!t.pinned?-1:!e.pinned&&t.pinned?1:t.createdAt-e.createdAt):[],s=(e||``).trim(),c=s.toLowerCase(),l=c.includes(`&`)||c.includes(`|`);if(s){let e=e=>{let t=((e.content||``)+` `+(e.sessionTitle||``)).toLowerCase();if(l){let e=c.split(`|`).map(e=>e.trim()).filter(Boolean);for(let n of e){let e=n.split(`&`).map(e=>e.trim()).filter(Boolean);if(e.length!==0&&e.every(e=>t.includes(e)))return!0}return!1}return t.includes(c)};a=a.filter(e),o=o.filter(e)}let u=C.bookmarks.length,d=a.length+o.length;if(c?n.textContent=r(`bookmark.searchCount`,{filtered:d,total:u}):n.textContent=u>0?r(`bookmark.countResult`,{count:u}):``,u===0){t.innerHTML=`<div class="bookmark-panel-empty">${r(`bookmark.empty`)}</div>`,gh();return}if(c&&d===0){t.innerHTML=`<div class="bookmark-panel-empty">${r(`bookmark.noMatch`)}</div>`,gh();return}let f=``;a.length>0&&(f+=`<div class="bookmark-section">
|
|
732
734
|
<div class="bookmark-section-title">${r(`searchPanel.currentSession`)}</div>
|
|
733
|
-
${
|
|
735
|
+
${ph(a,c)}
|
|
734
736
|
</div>`),o.length>0&&(f+=`<div class="bookmark-section">
|
|
735
737
|
<div class="bookmark-section-title">${r(`bookmark.otherSessions`)}</div>
|
|
736
|
-
${
|
|
737
|
-
</div>`),t.innerHTML=f,
|
|
738
|
+
${ph(o,c)}
|
|
739
|
+
</div>`),t.innerHTML=f,gh()}function ph(e,t){let n=(t||``).trim().toLowerCase();return e.map(e=>{let t=e.content||``,i=e.sessionTitle||r(`searchPanel.unknownSession`),a=t.length>60?t.substring(0,60)+`...`:t,o=i;n&&(a=mh(a,n),o=mh(o,n)),a||=r(`bookmark.noTextContent`);let s=e.pinned?`pinned`:``,c=new Date(e.createdAt).toLocaleString(`zh-CN`,{month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`});return`
|
|
738
740
|
<div class="bookmark-item ${s}" data-bookmark-id="${e.id}" data-session-id="${e.sessionId}" data-message-id="${e.messageId}">
|
|
739
741
|
<div class="bookmark-item-header">
|
|
740
742
|
<span class="bookmark-item-session" title="${L(i)}">${o}</span>
|
|
@@ -755,7 +757,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
755
757
|
</button>
|
|
756
758
|
</div>
|
|
757
759
|
</div>
|
|
758
|
-
`}).join(``)}function
|
|
760
|
+
`}).join(``)}function mh(e,t){if(!t)return e;let n=L(e),r=t.split(/[&|]/).map(e=>e.trim()).filter(Boolean);if(r.length===0)return n;let i=r.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)),a=RegExp(`(${i.join(`|`)})`,`gi`);return n.replace(a,`<mark class="bookmark-highlight-match">$1</mark>`)}async function hh(e,t){if(!(!e||!t)){if(C.activeSessionId!==e)try{let n=C.activeSessionId;if(await Ci(e)===!1||C.activeSessionId!==e){await oh(e,t),fh(),F(r(`bookmark.sessionNotExistToast`),`warning`);return}document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:e,previousSessionId:n,skipScrollRestore:!0}}));try{let{renderSessionTabs:e}=await A(async()=>{let{renderSessionTabs:e}=await Promise.resolve().then(()=>Fo);return{renderSessionTabs:e}},void 0);e()}catch(e){i.warn(`[BookmarkPanel] refreshsessionTab failed:`,e)}}catch(e){i.error(`[BookmarkPanel] switchsession failed:`,e);return}setTimeout(()=>{let n=document.getElementById(`chatContainer`);if(!n)return;let i=n.querySelector(`.message[data-message-id="${t}"]`);i?(i.scrollIntoView({behavior:`instant`,block:`nearest`}),i.classList.add(`bookmark-highlight`),setTimeout(()=>{i.classList.remove(`bookmark-highlight`)},2e3)):oh(e,t).then(()=>{fh(),F(r(`bookmark.messageNotExistToast`),`warning`)})},500)}}function gh(){let e=document.getElementById(`bookmarkPanelContainer`),t=C.bookmarks.length;e&&(e.style.display=t>0?``:`none`)}function _h(){let e=document.getElementById(`chatContainer`);e&&e.querySelectorAll(`.message.assistant`).forEach(e=>{let t=e.querySelector(`.bookmark-btn`);if(!t)return;let n=e.dataset.messageId,r=C.activeSessionId;vh(t,r,n)})}function vh(e,t,n){ih(t,n)?(e.classList.add(`bookmarked`),e.title=r(`bookmark.removeBookmarkTitle`),e.querySelector(`svg`).setAttribute(`fill`,`currentColor`)):(e.classList.remove(`bookmarked`),e.title=r(`bookmark.addBookmarkTitle`),e.querySelector(`svg`).setAttribute(`fill`,`none`))}function yh(e,t=`win32`){let n=String(e||``).trim();if(!n)return[];if(t===`win32`){if(n.startsWith(`\\\\`))return[{name:n,path:n}];let e=n.replace(/\//g,`\\`).split(`\\`).filter(Boolean);if(!e.length)return[];let t=[],r=``;return e.forEach((e,n)=>{r=n===0?`${e}\\`:r.endsWith(`\\`)?`${r}${e}`:`${r}\\${e}`,t.push({name:e,path:r})}),t}let r=n.split(`/`).filter(Boolean),i=[{name:`/`,path:`/`}],a=``;for(let e of r)a=`${a}/${e}`,i.push({name:e,path:a});return i}function bh(e){switch(e){case`path_not_found`:return`workspace.browseNotFound`;case`not_a_directory`:return`workspace.browseNotDir`;case`permission_denied`:return`workspace.browsePermissionDenied`;case`bad_path`:case`path_too_long`:return`workspace.browseBadPath`;case`timeout`:case`client-timeout`:return`workspace.browseTimeout`;case`rate_limited`:case`too-frequent`:return`workspace.browseRateLimited`;case`endpoint-missing`:return`workspace.browseUnsupported`;default:return`workspace.browseLoadFailed`}}function xh(e){return e===`drive`?`💽`:e===`home`?`🏠`:e===`root`?`🗂`:`📁`}function Sh(e){let{container:t,t:n,platform:r=`win32`,platformName:i=``,hostname:a=``,listDirs:o,onSelect:s,onClose:c,canUseNative:l=!1,onUseNative:u}=e,d=document.createElement(`div`);d.className=`wdb-view`,d.hidden=!0,d.innerHTML=`
|
|
759
761
|
<div class="wdb-header">
|
|
760
762
|
<div class="wdb-agent">${L(n(`workspace.browseAgentHost`,{platform:i||r,host:a||`-`}))}</div>
|
|
761
763
|
<div class="wdb-purge" hidden></div>
|
|
@@ -769,7 +771,7 @@ import{o as e,r as t}from"./chunk-CMxvf4Kt.js";import{a as n,c as r,l as i,r as
|
|
|
769
771
|
<span class="wdb-spacer"></span>
|
|
770
772
|
<button type="button" class="wdb-btn wdb-native" ${l?``:`hidden`}>${L(n(`workspace.browseUseNative`))}</button>
|
|
771
773
|
<button type="button" class="wdb-btn wdb-choose" disabled>${L(n(`workspace.browseChooseCurrent`))}</button>
|
|
772
|
-
</div>`,t.appendChild(d);let f={roots:d.querySelector(`.wdb-roots`),error:d.querySelector(`.wdb-error`),crumbs:d.querySelector(`.wdb-crumbs`),list:d.querySelector(`.wdb-list`),back:d.querySelector(`.wdb-back`),native:d.querySelector(`.wdb-native`),choose:d.querySelector(`.wdb-choose`)},p={currentPath:null,parent:null,roots:[],entries:[],selectedPath:null,selectedIndex:-1,truncated:!1,loading:!1,outdated:!1,errorText:``,reqSeq:0},m=null;function h(){return Array.from(f.list.querySelectorAll(`.wdb-item`))}function g(){if(!p.roots.length){f.roots.innerHTML=``;return}f.roots.innerHTML=`<span class="wdb-roots-label">${L(n(`workspace.browseRoots`))}</span>`+p.roots.map(e=>`<button type="button" class="wdb-root" data-path="${L(e.path)}" title="${L(e.path)}">${_h(e.kind)} ${L(e.name)}</button>`).join(``)}function _(){if(!p.currentPath){f.crumbs.innerHTML=``;return}let e=hh(p.currentPath,r);f.crumbs.innerHTML=e.map((t,n)=>{let r=n===e.length-1;return`<button type="button" class="wdb-crumb${r?` current`:``}" data-path="${L(t.path)}" title="${L(t.path)}"${r?` disabled`:``}>${L(t.name)}</button>`}).join(`<span class="wdb-crumb-sep">›</span>`)}function v(){if(p.outdated){f.list.innerHTML=`<div class="wdb-state">${L(n(`workspace.browseUnsupported`))}</div>`;return}if(p.loading){f.list.innerHTML=`<div class="wdb-state">${L(n(`workspace.browseLoading`))}</div>`;return}let e=!p.currentPath,t=e?p.roots.map(e=>({name:e.name,path:e.path,kind:e.kind,link:!1})):p.entries;if(!t.length){f.list.innerHTML=`<div class="wdb-state">${L(n(`workspace.browseEmpty`))}</div>`;return}f.list.innerHTML=t.map(t=>{let r=p.selectedPath&&t.path===p.selectedPath,i=e?_h(t.kind):`📁`,a=t.link?`<span class="wdb-link">${L(n(`workspace.browseLinkTag`))}</span>`:``,o=e?``:`<span class="wdb-pick" role="button" data-pick="1" title="${L(n(`workspace.browseChooseDir`))}" aria-label="${L(n(`workspace.browseChooseDir`))}">✓</span>`;return`<button type="button" class="wdb-item${r?` selected`:``}" role="option" aria-selected="${r?`true`:`false`}" data-path="${L(t.path)}" data-root="${e?`1`:`0`}" title="${L(t.path)}"><span class="wdb-item-icon">${i}</span><span class="wdb-item-name">${L(t.name)}</span>${a}${o}</button>`}).join(``),p.truncated&&f.list.insertAdjacentHTML(`beforeend`,`<div class="wdb-state wdb-truncated">${L(n(`workspace.browseTruncated`))}</div>`)}function y(){if(p.selectedPath){f.choose.disabled=!1,f.choose.textContent=n(`workspace.browseChooseDir`);return}f.choose.disabled=!p.currentPath,f.choose.textContent=n(`workspace.browseChooseCurrent`)}function b(){if(!p.errorText){f.error.hidden=!0,f.error.textContent=``;return}f.error.hidden=!1,f.error.textContent=p.errorText}function x(){g(),_(),v(),y(),b()}function S(e,t){p.selectedPath=e,p.selectedIndex=t,h().forEach(t=>{let n=t.dataset.path===e;t.classList.toggle(`selected`,n),t.setAttribute(`aria-selected`,n?`true`:`false`)}),y()}async function C(e){let t=++p.reqSeq;m=null,p.loading=!0,p.errorText=``,x();let r=await o(e||``);if(!(t!==p.reqSeq||d.hidden)){if(p.loading=!1,!r||r.success!==!0){if(r&&r.outdated)p.outdated=!0,p.errorText=n(`workspace.browseUnsupported`);else{let e=r&&r.error?r.error:`unknown`;p.errorText=r&&typeof r.message==`string`&&r.message?r.message:n(gh(e),{error:r&&r.message?r.message:e})}x();return}p.outdated=!1,p.currentPath=r.path||null,p.parent=r.parent||null,p.roots=Array.isArray(r.roots)?r.roots:[],p.entries=Array.isArray(r.entries)?r.entries:[],p.truncated=!!r.truncated,p.selectedPath=null,p.selectedIndex=-1,x(),f.list.scrollTop=0}}f.roots.addEventListener(`click`,e=>{let t=e.target.closest(`.wdb-root`);t&&C(t.dataset.path)}),f.crumbs.addEventListener(`click`,e=>{let t=e.target.closest(`.wdb-crumb`);!t||t.disabled||C(t.dataset.path)}),f.list.addEventListener(`click`,e=>{let t=e.detail>=2,n=e.target.closest(`.wdb-pick`);if(n){let e=n.closest(`.wdb-item`);e&&w(e.dataset.path);return}let r=e.target.closest(`.wdb-item`);if(r){if(r.dataset.root===`1`){if(t)return;m=null,C(r.dataset.path);return}S(r.dataset.path,h().indexOf(r)),t||(m={path:r.dataset.path,at:Date.now()})}}),f.list.addEventListener(`dblclick`,e=>{if(e.target.closest(`.wdb-pick`))return;let t=e.target.closest(`.wdb-item`);t&&(!m||m.path!==t.dataset.path||Date.now()-m.at>600||C(t.dataset.path))}),f.list.addEventListener(`keydown`,e=>{if(!(p.loading||p.outdated)){if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=h();if(!t.length)return;e.preventDefault();let n=e.key===`ArrowDown`?1:-1,r=Math.min(t.length-1,Math.max(0,p.selectedIndex+n));S(t[r].dataset.path,r),t[r].scrollIntoView({block:`nearest`});return}if(e.key===`Enter`){e.preventDefault();let t=h(),n=p.selectedIndex>=0?t[p.selectedIndex]:null;n&&C(n.dataset.path);return}e.key===`Backspace`&&(e.preventDefault(),p.parent&&C(p.parent))}}),f.list.addEventListener(`mousedown`,()=>{setTimeout(()=>f.list.focus(),0)}),f.back.addEventListener(`click`,()=>E()),f.native.addEventListener(`click`,()=>{typeof u==`function`&&u(),E()});function w(e){e&&(typeof s==`function`&&s(e),E())}f.choose.addEventListener(`click`,()=>{w(p.selectedPath||p.currentPath)});function T(e){p.outdated=!1,p.errorText=``,p.selectedPath=null,p.selectedIndex=-1,d.hidden=!1,C(e||``),setTimeout(()=>f.list.focus(),0)}function E(){d.hidden||(m=null,p.reqSeq+=1,d.hidden=!0,typeof c==`function`&&c())}function D(){p.reqSeq+=1,d.remove()}return{element:d,open:T,close:E,destroy:D,isOpen:()=>!d.hidden}}function yh(e){let t=e||C.activeSessionId;return t?!!(C.generatingSessionIds?.has(t)||kr(t)>0):!1}n(`zh`,{imageHelper:{uploadToAgentTitle:`上传文件到Agent工作目录,大模型通过工具直接操作`,uploadAndExtractTitle:`上传文件并提取文本内容(支持PDF/Word/Excel/文本等)`,clickToEnlarge:`点击查看大图`,removeImage:`移除图片`,enableImageInputFirst:`请先开启图片输入功能`,screenshotSuccess:`截图成功`,screenshotFailed:`截图失败,请重试`,noActiveTab:`无法获取当前标签页`,cropFailed:`裁剪失败,请重试`,regionScreenshotFailed:`区域截图失败,请确保页面已加载且未被浏览器限制`,imageLoadFailed:`图片加载失败`,screenshotProcessFailed:`截图处理失败,请重试`}}),n(`en`,{imageHelper:{uploadToAgentTitle:`Upload files to Agent workspace; the model operates on them directly via tools`,uploadAndExtractTitle:`Upload files and extract text content (supports PDF/Word/Excel/text, etc.)`,clickToEnlarge:`Click to enlarge`,removeImage:`Remove image`,enableImageInputFirst:`Please enable image input first`,screenshotSuccess:`Screenshot captured`,screenshotFailed:`Screenshot failed, please retry`,noActiveTab:`Unable to get the current tab`,cropFailed:`Cropping failed, please retry`,regionScreenshotFailed:`Region screenshot failed. Make sure the page is loaded and not restricted by the browser.`,imageLoadFailed:`Image load failed`,screenshotProcessFailed:`Screenshot processing failed, please retry`}});function bh(){let e=document.getElementById(`imagePreviewBar`),t=document.getElementById(`screenshotBtn`);e&&(e.style.display=C.attachedImages.length>0?``:`none`),t&&(C.enableImageInput?t.style.removeProperty(`display`):t.style.display=`none`),xh(),C.enableImageInput||(C.attachedImages=[]),Ch()}function xh(){let e=document.getElementById(`userInput`);e&&e.style.removeProperty(`padding-right`)}function Sh(){let e=document.getElementById(`fileAttachBtn`),t=document.getElementById(`fileInput`);e&&(e.style.display=C.enableFileInput?``:`none`),t&&(C.agentPlatform?.connected?(t.accept=`*`,e&&(e.title=r(`imageHelper.uploadToAgentTitle`))):(t.accept=`.pdf,.docx,.xlsx,.xls,.txt,.md,.json,.js,.jsx,.ts,.tsx,.html,.css,.scss,.less,.xml,.yaml,.yml,.py,.java,.c,.cpp,.h,.go,.rs,.rb,.php,.sql,.sh,.bash,.zsh,.cfg,.ini,.toml,.conf,.log,.csv,.tsv,.env,.vue,.svelte,.astro,.rtf`,e&&(e.title=r(`imageHelper.uploadAndExtractTitle`)))),xh(),C.enableFileInput||Xm()}function Ch(){document.dispatchEvent(new CustomEvent(`input-attachments-changed`));let e=document.getElementById(`imagePreviewBar`);if(e){if(e.innerHTML=``,C.attachedImages.length===0){e.style.display=`none`;return}e.style.display=``,C.attachedImages.forEach((t,n)=>{let i=document.createElement(`div`);i.className=`image-preview-item`;let a=document.createElement(`img`);a.src=t.dataUrl||t.compressedUrl||t.originalUrl,a.className=`image-preview-thumb`,a.title=r(`imageHelper.clickToEnlarge`),a.style.cursor=`zoom-in`,a.addEventListener(`click`,()=>{$p(t.originalUrl||t.dataUrl||t.compressedUrl,a)});let o=document.createElement(`button`);o.className=`image-preview-remove`,o.innerHTML=`×`,o.title=r(`imageHelper.removeImage`),o.addEventListener(`click`,e=>{e.stopPropagation(),C.attachedImages.splice(n,1),Ch()}),i.appendChild(a),i.appendChild(o),e.appendChild(i)})}}async function wh(){if(!C.enableImageInput){F(r(`imageHelper.enableImageInputFirst`));return}try{let e=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});e?.dataUrl&&(sm(await(await fetch(e.dataUrl)).blob()),F(r(`imageHelper.screenshotSuccess`)))}catch(e){i.error(`[SidePanel] full page screenshot failed:`,e),F(r(`imageHelper.screenshotFailed`))}}async function Th(){let e=await qe();if(!e){F(r(`imageHelper.noActiveTab`));return}try{let t=await chrome.tabs.sendMessage(e,{type:`START_REGION_SELECTION`});if(!t)return;i.debug(`[SidePanel] regionselectresult:`,t);let n=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});if(!n?.dataUrl){F(r(`imageHelper.screenshotFailed`));return}let a=await Eh(n.dataUrl,t);if(!a){F(r(`imageHelper.cropFailed`));return}sm(await(await fetch(a)).blob())}catch(e){i.error(`[SidePanel] region screenshot failed:`,e),F(r(`imageHelper.regionScreenshotFailed`))}}function Eh(e,t){return new Promise((n,i)=>{let a=new Image;a.onload=()=>{let e=document.createElement(`canvas`),r=window.devicePixelRatio||1,i=t.x*r,o=t.y*r,s=t.width*r,c=t.height*r;e.width=s,e.height=c,e.getContext(`2d`,{willReadFrequently:!0}).drawImage(a,i,o,s,c,0,0,s,c),n(e.toDataURL(`image/jpeg`,.85))},a.onerror=()=>i(Error(r(`imageHelper.imageLoadFailed`))),a.src=e})}async function Dh(e,t,n){if(!C.enableImageInput){F(r(`imageHelper.enableImageInputFirst`));return}try{let i=e;t===`region`&&n&&(i=await Eh(e,n)),sm(await(await fetch(i)).blob()),F(r(`imageHelper.screenshotSuccess`))}catch(e){i.error(`[SidePanel] pageshortcutscreenshotprocessing failed:`,e),F(r(`imageHelper.screenshotProcessFailed`))}}var Oh=t({attachFilesForQuestion:()=>Ly,closePreview:()=>yv,closeWorkspacePanel:()=>sy,closeWorkspacePreview:()=>oy,initWorkspacePanel:()=>Zh,locateFileInWorkspace:()=>iy,openWorkspacePanel:()=>vg,previewArtifactFile:()=>ay,refreshWorkspacePanel:()=>Zv,resetAndRefreshWorkspace:()=>Qv,resolveWorkspaceAbsolutePath:()=>cy,showSwitchWorkdirDialog:()=>Ty,updateWorkspacePanelVisibility:()=>$v});n(`zh`,{workspace:{workDir:`工作目录`,closePanel:`关闭面板`,embedMode:`嵌入模式`,floatMode:`浮窗模式`,openPanel:`打开工作目录面板`,narrowViewportHint:`视口过窄,已切回浮窗模式`,switchWorkdir:`切换工作目录`,backToParent:`返回上级目录`,uploadToCurrent:`上传文件到当前目录`,newFolder:`新建文件夹`,askSelectedFiles:`基于选中的文件进行问答`,downloadSelected:`下载选中的文件/目录(多选打包为ZIP)`,deleteSelected:`删除选中的文件`,clearSearch:`清除`,search:`搜索`,searchPlaceholder:`搜索...`,selectAllToggle:`全选/取消全选`,colName:`文件名`,colSize:`大小`,colTime:`修改时间`,noMatch:`未找到匹配的文件`,dirEmpty:`此目录为空`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,loadDirFailed:`加载目录失败`,refreshFailed:`无法刷新,请确认 Agent 已连接`,agentNotConnected:`Agent 未连接`,agentNotConnectedUpload:`Agent 未连接,无法上传`,unsupportedFileType:`不支持的文件类型`,binaryFileNoPreview:`疑似二进制文件,不支持文本预览,请直接下载`,unknownError:`未知错误`,copiedFileName:`已复制文件名: {name}`,copiedPath:`已复制路径: {path}`,copyFailed:`复制失败`,copiedToClipboard:`已复制到剪贴板`,copyFailedManual:`复制失败,请手动选择复制`,getContentFailed:`获取内容失败`,codeCopiedToClipboard:`代码已复制到剪贴板`,copyUnsupportedType:`此文件类型不支持复制文本内容`,copiedToClipboardShort:`已复制到剪贴板`,clickToCopy:`点击复制`,preview:`预览`,previewBtn:`预览`,details:`详情`,download:`下载`,downloadFile:`下载文件`,rename:`重命名`,askFile:`基于文件问答`,delete:`删除`,copyAll:`复制`,copyAllTitle:`复制全部内容`,toggleRenderPreview:`切换渲染预览`,openInBrowser:`在浏览器中打开`,openInBrowserBtn:`在浏览器中打开`,fullscreenPreview:`全屏预览`,exitFullscreen:`退出全屏`,enterEditMode:`进入编辑模式`,edit:`编辑`,save:`保存`,saveChanges:`保存修改 (Ctrl+S)`,cancelChanges:`取消修改 (Esc)`,closePreview:`关闭预览`,close:`关闭`,confirm:`确定`,cancel:`取消`,switchToSourcePreview:`切换为源码预览`,switchToRenderPreview:`切换为渲染预览`,markdownRendered:`Markdown 渲染`,lineCount:`{count} 行`,linesModified:`{count} 行 · 已修改`,truncatedHint:`(仅显示前 {shown} 行,共 {total} 行,请下载查看完整内容)`,fileTooLargeNoPreview:`文件过大 ({size}),不支持预览,请直接下载`,fileTooLargeOpenInBrowser:`文件过大 ({size}),无法内置预览,请点击上方「在浏览器中打开」按钮查看`,previewFailed:`预览失败: {error}`,openFailed:`打开失败: {error}`,documentEmpty:`(文档为空)`,pptxEmptyOrFailed:`PPTX 文件为空或解析失败`,pageCount:`{count} 页`,prevPage:`上一页`,nextPage:`下一页`,zoomOut:`缩小`,zoomIn:`放大`,fitPage:`适应页面`,originalSize:`原始大小`,imageLoadFailed:`图片加载失败`,parsingExcel:`正在解析 Excel 文件...`,loadingData:`正在加载数据...`,requestFailed:`请求失败: {error}`,parseFailed:`解析失败: {error}`,noSheetsInWorkbook:`工作簿中没有工作表`,sheetNotFound:`未找到工作表数据`,emptySheet:`(空工作表)`,xlsxTruncatedHint:`仅显示前 {shown} 行,共 {total} 行,请下载查看完整内容`,unsupportedMediaHint:`⚠ 浏览器不支持播放此格式({ext}),请下载后使用本地播放器查看。`,uploading:`上传中...`,downloadInProgress:`下载中`,uploadInProgress:`上传中`,cancelUpload:`取消上传`,downloadCanceled:`下载已取消`,downloadFailed:`下载失败`,downloadFailedWithError:`下载失败: {error}`,savingToLocal:`正在由浏览器保存至本地...`,savedToLocal:`已保存至本地`,downloaded:`已下载: {name}`,downloadedCount:`已下载 {count} 个文件`,downloadedZip:`已下载 {count} 个文件(ZIP 压缩包)`,fileCount:`{count} 个文件`,uploadCanceled:`已取消上传`,uploadSuccessCount:`成功 {count}`,uploadSkippedCount:`跳过 {count}`,uploadFailedCount:`失败 {count}`,uploadComplete:`上传完成`,uploadCompleteWithStats:`上传完成 · {stats}`,uploadedFiles:`成功上传 {count} 个文件`,filesSkipped:`{count} 个文件已存在,跳过上传`,filesUploadFailed:`{count} 个文件上传失败`,uploadFailed:`上传失败`,uploadFailedWithStatus:`上传失败 ({status})`,parseResponseFailed:`解析响应失败`,networkError:`网络错误`,cannotMoveToSubdir:`不能将目录移动到其子目录中`,moving:`移动中...`,movedToDir:`"{name}" 已移动到目标目录`,movedToTarget:`"{name}" 已移动到 "{target}"`,moveFailed:`移动失败: {error}`,searching:`搜索中...`,confirmDeleteDir:`确定要删除目录 "{name}" 及其所有内容吗?
|
|
774
|
+
</div>`,t.appendChild(d);let f={roots:d.querySelector(`.wdb-roots`),error:d.querySelector(`.wdb-error`),crumbs:d.querySelector(`.wdb-crumbs`),list:d.querySelector(`.wdb-list`),back:d.querySelector(`.wdb-back`),native:d.querySelector(`.wdb-native`),choose:d.querySelector(`.wdb-choose`)},p={currentPath:null,parent:null,roots:[],entries:[],selectedPath:null,selectedIndex:-1,truncated:!1,loading:!1,outdated:!1,errorText:``,reqSeq:0},m=null;function h(){return Array.from(f.list.querySelectorAll(`.wdb-item`))}function g(){if(!p.roots.length){f.roots.innerHTML=``;return}f.roots.innerHTML=`<span class="wdb-roots-label">${L(n(`workspace.browseRoots`))}</span>`+p.roots.map(e=>`<button type="button" class="wdb-root" data-path="${L(e.path)}" title="${L(e.path)}">${xh(e.kind)} ${L(e.name)}</button>`).join(``)}function _(){if(!p.currentPath){f.crumbs.innerHTML=``;return}let e=yh(p.currentPath,r);f.crumbs.innerHTML=e.map((t,n)=>{let r=n===e.length-1;return`<button type="button" class="wdb-crumb${r?` current`:``}" data-path="${L(t.path)}" title="${L(t.path)}"${r?` disabled`:``}>${L(t.name)}</button>`}).join(`<span class="wdb-crumb-sep">›</span>`)}function v(){if(p.outdated){f.list.innerHTML=`<div class="wdb-state">${L(n(`workspace.browseUnsupported`))}</div>`;return}if(p.loading){f.list.innerHTML=`<div class="wdb-state">${L(n(`workspace.browseLoading`))}</div>`;return}let e=!p.currentPath,t=e?p.roots.map(e=>({name:e.name,path:e.path,kind:e.kind,link:!1})):p.entries;if(!t.length){f.list.innerHTML=`<div class="wdb-state">${L(n(`workspace.browseEmpty`))}</div>`;return}f.list.innerHTML=t.map(t=>{let r=p.selectedPath&&t.path===p.selectedPath,i=e?xh(t.kind):`📁`,a=t.link?`<span class="wdb-link">${L(n(`workspace.browseLinkTag`))}</span>`:``,o=e?``:`<span class="wdb-pick" role="button" data-pick="1" title="${L(n(`workspace.browseChooseDir`))}" aria-label="${L(n(`workspace.browseChooseDir`))}">✓</span>`;return`<button type="button" class="wdb-item${r?` selected`:``}" role="option" aria-selected="${r?`true`:`false`}" data-path="${L(t.path)}" data-root="${e?`1`:`0`}" title="${L(t.path)}"><span class="wdb-item-icon">${i}</span><span class="wdb-item-name">${L(t.name)}</span>${a}${o}</button>`}).join(``),p.truncated&&f.list.insertAdjacentHTML(`beforeend`,`<div class="wdb-state wdb-truncated">${L(n(`workspace.browseTruncated`))}</div>`)}function y(){if(p.selectedPath){f.choose.disabled=!1,f.choose.textContent=n(`workspace.browseChooseDir`);return}f.choose.disabled=!p.currentPath,f.choose.textContent=n(`workspace.browseChooseCurrent`)}function b(){if(!p.errorText){f.error.hidden=!0,f.error.textContent=``;return}f.error.hidden=!1,f.error.textContent=p.errorText}function x(){g(),_(),v(),y(),b()}function S(e,t){p.selectedPath=e,p.selectedIndex=t,h().forEach(t=>{let n=t.dataset.path===e;t.classList.toggle(`selected`,n),t.setAttribute(`aria-selected`,n?`true`:`false`)}),y()}async function C(e){let t=++p.reqSeq;m=null,p.loading=!0,p.errorText=``,x();let r=await o(e||``);if(!(t!==p.reqSeq||d.hidden)){if(p.loading=!1,!r||r.success!==!0){if(r&&r.outdated)p.outdated=!0,p.errorText=n(`workspace.browseUnsupported`);else{let e=r&&r.error?r.error:`unknown`;p.errorText=r&&typeof r.message==`string`&&r.message?r.message:n(bh(e),{error:r&&r.message?r.message:e})}x();return}p.outdated=!1,p.currentPath=r.path||null,p.parent=r.parent||null,p.roots=Array.isArray(r.roots)?r.roots:[],p.entries=Array.isArray(r.entries)?r.entries:[],p.truncated=!!r.truncated,p.selectedPath=null,p.selectedIndex=-1,x(),f.list.scrollTop=0}}f.roots.addEventListener(`click`,e=>{let t=e.target.closest(`.wdb-root`);t&&C(t.dataset.path)}),f.crumbs.addEventListener(`click`,e=>{let t=e.target.closest(`.wdb-crumb`);!t||t.disabled||C(t.dataset.path)}),f.list.addEventListener(`click`,e=>{let t=e.detail>=2,n=e.target.closest(`.wdb-pick`);if(n){let e=n.closest(`.wdb-item`);e&&w(e.dataset.path);return}let r=e.target.closest(`.wdb-item`);if(r){if(r.dataset.root===`1`){if(t)return;m=null,C(r.dataset.path);return}S(r.dataset.path,h().indexOf(r)),t||(m={path:r.dataset.path,at:Date.now()})}}),f.list.addEventListener(`dblclick`,e=>{if(e.target.closest(`.wdb-pick`))return;let t=e.target.closest(`.wdb-item`);t&&(!m||m.path!==t.dataset.path||Date.now()-m.at>600||C(t.dataset.path))}),f.list.addEventListener(`keydown`,e=>{if(!(p.loading||p.outdated)){if(e.key===`ArrowDown`||e.key===`ArrowUp`){let t=h();if(!t.length)return;e.preventDefault();let n=e.key===`ArrowDown`?1:-1,r=Math.min(t.length-1,Math.max(0,p.selectedIndex+n));S(t[r].dataset.path,r),t[r].scrollIntoView({block:`nearest`});return}if(e.key===`Enter`){e.preventDefault();let t=h(),n=p.selectedIndex>=0?t[p.selectedIndex]:null;n&&C(n.dataset.path);return}e.key===`Backspace`&&(e.preventDefault(),p.parent&&C(p.parent))}}),f.list.addEventListener(`mousedown`,()=>{setTimeout(()=>f.list.focus(),0)}),f.back.addEventListener(`click`,()=>E()),f.native.addEventListener(`click`,()=>{typeof u==`function`&&u(),E()});function w(e){e&&(typeof s==`function`&&s(e),E())}f.choose.addEventListener(`click`,()=>{w(p.selectedPath||p.currentPath)});function T(e){p.outdated=!1,p.errorText=``,p.selectedPath=null,p.selectedIndex=-1,d.hidden=!1,C(e||``),setTimeout(()=>f.list.focus(),0)}function E(){d.hidden||(m=null,p.reqSeq+=1,d.hidden=!0,typeof c==`function`&&c())}function D(){p.reqSeq+=1,d.remove()}return{element:d,open:T,close:E,destroy:D,isOpen:()=>!d.hidden}}function Ch(e){let t=e||C.activeSessionId;return t?!!(C.generatingSessionIds?.has(t)||kr(t)>0):!1}n(`zh`,{imageHelper:{uploadToAgentTitle:`上传文件到Agent工作目录,大模型通过工具直接操作`,uploadAndExtractTitle:`上传文件并提取文本内容(支持PDF/Word/Excel/文本等)`,clickToEnlarge:`点击查看大图`,removeImage:`移除图片`,enableImageInputFirst:`请先开启图片输入功能`,screenshotSuccess:`截图成功`,screenshotFailed:`截图失败,请重试`,noActiveTab:`无法获取当前标签页`,cropFailed:`裁剪失败,请重试`,regionScreenshotFailed:`区域截图失败,请确保页面已加载且未被浏览器限制`,imageLoadFailed:`图片加载失败`,screenshotProcessFailed:`截图处理失败,请重试`}}),n(`en`,{imageHelper:{uploadToAgentTitle:`Upload files to Agent workspace; the model operates on them directly via tools`,uploadAndExtractTitle:`Upload files and extract text content (supports PDF/Word/Excel/text, etc.)`,clickToEnlarge:`Click to enlarge`,removeImage:`Remove image`,enableImageInputFirst:`Please enable image input first`,screenshotSuccess:`Screenshot captured`,screenshotFailed:`Screenshot failed, please retry`,noActiveTab:`Unable to get the current tab`,cropFailed:`Cropping failed, please retry`,regionScreenshotFailed:`Region screenshot failed. Make sure the page is loaded and not restricted by the browser.`,imageLoadFailed:`Image load failed`,screenshotProcessFailed:`Screenshot processing failed, please retry`}});function wh(){let e=document.getElementById(`imagePreviewBar`),t=document.getElementById(`screenshotBtn`);e&&(e.style.display=C.attachedImages.length>0?``:`none`),t&&(C.enableImageInput?t.style.removeProperty(`display`):t.style.display=`none`),Th(),C.enableImageInput||(C.attachedImages=[]),Dh()}function Th(){let e=document.getElementById(`userInput`);e&&e.style.removeProperty(`padding-right`)}function Eh(){let e=document.getElementById(`fileAttachBtn`),t=document.getElementById(`fileInput`);e&&(e.style.display=C.enableFileInput?``:`none`),t&&(C.agentPlatform?.connected?(t.accept=`*`,e&&(e.title=r(`imageHelper.uploadToAgentTitle`))):(t.accept=`.pdf,.docx,.xlsx,.xls,.txt,.md,.json,.js,.jsx,.ts,.tsx,.html,.css,.scss,.less,.xml,.yaml,.yml,.py,.java,.c,.cpp,.h,.go,.rs,.rb,.php,.sql,.sh,.bash,.zsh,.cfg,.ini,.toml,.conf,.log,.csv,.tsv,.env,.vue,.svelte,.astro,.rtf`,e&&(e.title=r(`imageHelper.uploadAndExtractTitle`)))),Th(),C.enableFileInput||eh()}function Dh(){document.dispatchEvent(new CustomEvent(`input-attachments-changed`));let e=document.getElementById(`imagePreviewBar`);if(e){if(e.innerHTML=``,C.attachedImages.length===0){e.style.display=`none`;return}e.style.display=``,C.attachedImages.forEach((t,n)=>{let i=document.createElement(`div`);i.className=`image-preview-item`;let a=document.createElement(`img`);a.src=t.dataUrl||t.compressedUrl||t.originalUrl,a.className=`image-preview-thumb`,a.title=r(`imageHelper.clickToEnlarge`),a.style.cursor=`zoom-in`,a.addEventListener(`click`,()=>{rm(t.originalUrl||t.dataUrl||t.compressedUrl,a)});let o=document.createElement(`button`);o.className=`image-preview-remove`,o.innerHTML=`×`,o.title=r(`imageHelper.removeImage`),o.addEventListener(`click`,e=>{e.stopPropagation(),C.attachedImages.splice(n,1),Dh()}),i.appendChild(a),i.appendChild(o),e.appendChild(i)})}}async function Oh(){if(!C.enableImageInput){F(r(`imageHelper.enableImageInputFirst`));return}try{let e=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});e?.dataUrl&&(dm(await(await fetch(e.dataUrl)).blob()),F(r(`imageHelper.screenshotSuccess`)))}catch(e){i.error(`[SidePanel] full page screenshot failed:`,e),F(r(`imageHelper.screenshotFailed`))}}async function kh(){let e=await qe();if(!e){F(r(`imageHelper.noActiveTab`));return}try{let t=await chrome.tabs.sendMessage(e,{type:`START_REGION_SELECTION`});if(!t)return;i.debug(`[SidePanel] regionselectresult:`,t);let n=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});if(!n?.dataUrl){F(r(`imageHelper.screenshotFailed`));return}let a=await Ah(n.dataUrl,t);if(!a){F(r(`imageHelper.cropFailed`));return}dm(await(await fetch(a)).blob())}catch(e){i.error(`[SidePanel] region screenshot failed:`,e),F(r(`imageHelper.regionScreenshotFailed`))}}function Ah(e,t){return new Promise((n,i)=>{let a=new Image;a.onload=()=>{let e=document.createElement(`canvas`),r=window.devicePixelRatio||1,i=t.x*r,o=t.y*r,s=t.width*r,c=t.height*r;e.width=s,e.height=c,e.getContext(`2d`,{willReadFrequently:!0}).drawImage(a,i,o,s,c,0,0,s,c),n(e.toDataURL(`image/jpeg`,.85))},a.onerror=()=>i(Error(r(`imageHelper.imageLoadFailed`))),a.src=e})}async function jh(e,t,n){if(!C.enableImageInput){F(r(`imageHelper.enableImageInputFirst`));return}try{let i=e;t===`region`&&n&&(i=await Ah(e,n)),dm(await(await fetch(i)).blob()),F(r(`imageHelper.screenshotSuccess`))}catch(e){i.error(`[SidePanel] pageshortcutscreenshotprocessing failed:`,e),F(r(`imageHelper.screenshotProcessFailed`))}}var Mh=t({attachFilesForQuestion:()=>Vy,closePreview:()=>Cv,closeWorkspacePanel:()=>dy,closeWorkspacePreview:()=>uy,initWorkspacePanel:()=>tg,locateFileInWorkspace:()=>cy,openWorkspacePanel:()=>Sg,previewArtifactFile:()=>ly,refreshWorkspacePanel:()=>ty,resetAndRefreshWorkspace:()=>ny,resolveWorkspaceAbsolutePath:()=>fy,showSwitchWorkdirDialog:()=>ky,updateWorkspacePanelVisibility:()=>ry});n(`zh`,{workspace:{workDir:`工作目录`,closePanel:`关闭面板`,embedMode:`嵌入模式`,floatMode:`浮窗模式`,openPanel:`打开工作目录面板`,narrowViewportHint:`视口过窄,已切回浮窗模式`,switchWorkdir:`切换工作目录`,backToParent:`返回上级目录`,uploadToCurrent:`上传文件到当前目录`,newFolder:`新建文件夹`,askSelectedFiles:`基于选中的文件进行问答`,downloadSelected:`下载选中的文件/目录(多选打包为ZIP)`,deleteSelected:`删除选中的文件`,clearSearch:`清除`,search:`搜索`,searchPlaceholder:`搜索...`,selectAllToggle:`全选/取消全选`,colName:`文件名`,colSize:`大小`,colTime:`修改时间`,noMatch:`未找到匹配的文件`,dirEmpty:`此目录为空`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,loadDirFailed:`加载目录失败`,refreshFailed:`无法刷新,请确认 Agent 已连接`,agentNotConnected:`Agent 未连接`,agentNotConnectedUpload:`Agent 未连接,无法上传`,unsupportedFileType:`不支持的文件类型`,binaryFileNoPreview:`疑似二进制文件,不支持文本预览,请直接下载`,unknownError:`未知错误`,copiedFileName:`已复制文件名: {name}`,copiedPath:`已复制路径: {path}`,copyFailed:`复制失败`,copiedToClipboard:`已复制到剪贴板`,copyFailedManual:`复制失败,请手动选择复制`,getContentFailed:`获取内容失败`,codeCopiedToClipboard:`代码已复制到剪贴板`,copyUnsupportedType:`此文件类型不支持复制文本内容`,copiedToClipboardShort:`已复制到剪贴板`,clickToCopy:`点击复制`,preview:`预览`,previewBtn:`预览`,details:`详情`,download:`下载`,downloadFile:`下载文件`,rename:`重命名`,askFile:`基于文件问答`,delete:`删除`,copyAll:`复制`,copyAllTitle:`复制全部内容`,toggleRenderPreview:`切换渲染预览`,openInBrowser:`在浏览器中打开`,openInBrowserBtn:`在浏览器中打开`,fullscreenPreview:`全屏预览`,exitFullscreen:`退出全屏`,enterEditMode:`进入编辑模式`,edit:`编辑`,save:`保存`,saveChanges:`保存修改 (Ctrl+S)`,cancelChanges:`取消修改 (Esc)`,closePreview:`关闭预览`,close:`关闭`,confirm:`确定`,cancel:`取消`,switchToSourcePreview:`切换为源码预览`,switchToRenderPreview:`切换为渲染预览`,markdownRendered:`Markdown 渲染`,lineCount:`{count} 行`,linesModified:`{count} 行 · 已修改`,truncatedHint:`(仅显示前 {shown} 行,共 {total} 行,请下载查看完整内容)`,fileTooLargeNoPreview:`文件过大 ({size}),不支持预览,请直接下载`,fileTooLargeOpenInBrowser:`文件过大 ({size}),无法内置预览,请点击上方「在浏览器中打开」按钮查看`,previewFailed:`预览失败: {error}`,openFailed:`打开失败: {error}`,documentEmpty:`(文档为空)`,pptxEmptyOrFailed:`PPTX 文件为空或解析失败`,pageCount:`{count} 页`,prevPage:`上一页`,nextPage:`下一页`,zoomOut:`缩小`,zoomIn:`放大`,fitPage:`适应页面`,originalSize:`原始大小`,imageLoadFailed:`图片加载失败`,parsingExcel:`正在解析 Excel 文件...`,loadingData:`正在加载数据...`,requestFailed:`请求失败: {error}`,parseFailed:`解析失败: {error}`,noSheetsInWorkbook:`工作簿中没有工作表`,sheetNotFound:`未找到工作表数据`,emptySheet:`(空工作表)`,xlsxTruncatedHint:`仅显示前 {shown} 行,共 {total} 行,请下载查看完整内容`,unsupportedMediaHint:`⚠ 浏览器不支持播放此格式({ext}),请下载后使用本地播放器查看。`,uploading:`上传中...`,downloadInProgress:`下载中`,uploadInProgress:`上传中`,cancelUpload:`取消上传`,downloadCanceled:`下载已取消`,downloadFailed:`下载失败`,downloadFailedWithError:`下载失败: {error}`,savingToLocal:`正在由浏览器保存至本地...`,savedToLocal:`已保存至本地`,downloaded:`已下载: {name}`,downloadedCount:`已下载 {count} 个文件`,downloadedZip:`已下载 {count} 个文件(ZIP 压缩包)`,fileCount:`{count} 个文件`,uploadCanceled:`已取消上传`,uploadSuccessCount:`成功 {count}`,uploadSkippedCount:`跳过 {count}`,uploadFailedCount:`失败 {count}`,uploadComplete:`上传完成`,uploadCompleteWithStats:`上传完成 · {stats}`,uploadedFiles:`成功上传 {count} 个文件`,filesSkipped:`{count} 个文件已存在,跳过上传`,filesUploadFailed:`{count} 个文件上传失败`,uploadFailed:`上传失败`,uploadFailedWithStatus:`上传失败 ({status})`,parseResponseFailed:`解析响应失败`,networkError:`网络错误`,cannotMoveToSubdir:`不能将目录移动到其子目录中`,moving:`移动中...`,movedToDir:`"{name}" 已移动到目标目录`,movedToTarget:`"{name}" 已移动到 "{target}"`,moveFailed:`移动失败: {error}`,searching:`搜索中...`,confirmDeleteDir:`确定要删除目录 "{name}" 及其所有内容吗?
|
|
773
775
|
|
|
774
776
|
路径: {path}
|
|
775
777
|
类型: 目录
|
|
@@ -813,7 +815,7 @@ After removal, the AI will no longer be able to access this directory. You can s
|
|
|
813
815
|
{path}
|
|
814
816
|
|
|
815
817
|
It is this session's directory or the agent default, so it stays accessible (working directories bypass the allowed list). It will simply no longer be listed as an additional allowed entry.`,confirmRemovePathTitle:`Confirm Remove Allowed Directory`,removedFromAllowed:`Removed from allowed list`,removedStillUsable:`Removed from allowed list (still available as the working/default directory)`,removeFailedWithError:`Remove failed: {error}`,selectOrInputPath:`Please select or enter a target path`,alreadyCurrentWorkdir:`This directory is already the current working directory`,confirmSwitchToNewDefault:`This path is not in the allowed list. It will become the agent default, so switching also creates the directory and adds it to the allowed list (affects unbound sessions):
|
|
816
|
-
{path}`,confirmSwitchToNewTitle:`Confirm Switch to New Default Directory`,switchFailedWithError:`Switch failed: {error}`,switchedTo:`Switched to: {path}`,switchedToAndSetDefault:`Switched to: {path} (set as agent default)`,setAsDefaultDone:`Set as agent default: {path}`,renameDir:`Rename Directory`,renameFile:`Rename File`,inputNewName:`Enter new name`,renamedTo:`Renamed to "{name}"`,renameFailedWithError:`Rename failed: {error}`,newFolderTitle:`New Folder`,inputFolderName:`Enter folder name`,folderCreated:`Folder "{name}" created`,createFailedWithError:`Create failed: {error}`,addedFilesToQuestion:`Added {count} file(s) to question`,addedFilesToQuestionNoImage:`Added {count} file(s) to question (image recognition disabled; images attached as files)`,selectedCount:`{count} selected`,unsavedChanges:`Unsaved Changes`,discardChangesPrompt:`You have unsaved changes. Are you sure you want to {action}?`,actionClosePreview:`close the preview`,actionCancelEdit:`cancel editing`,saving:`Saving...`,saveSuccess:`Saved successfully`,saveFailedWithError:`Save failed: {error}`,agentNamePrefix:` · {name}`,agentNotPaired:`Agent not paired`,fileDetailsLabel:`File Details`,loadingLabel:`Loading...`,export:`Export`,exportDocx:`Word`,exportPdf:`PDF`,exportImage:`Image`,exportMd:`Markdown`,copyMarkdownHint:`Ctrl/Cmd+Click to copy rich text`}});var q=null,
|
|
818
|
+
{path}`,confirmSwitchToNewTitle:`Confirm Switch to New Default Directory`,switchFailedWithError:`Switch failed: {error}`,switchedTo:`Switched to: {path}`,switchedToAndSetDefault:`Switched to: {path} (set as agent default)`,setAsDefaultDone:`Set as agent default: {path}`,renameDir:`Rename Directory`,renameFile:`Rename File`,inputNewName:`Enter new name`,renamedTo:`Renamed to "{name}"`,renameFailedWithError:`Rename failed: {error}`,newFolderTitle:`New Folder`,inputFolderName:`Enter folder name`,folderCreated:`Folder "{name}" created`,createFailedWithError:`Create failed: {error}`,addedFilesToQuestion:`Added {count} file(s) to question`,addedFilesToQuestionNoImage:`Added {count} file(s) to question (image recognition disabled; images attached as files)`,selectedCount:`{count} selected`,unsavedChanges:`Unsaved Changes`,discardChangesPrompt:`You have unsaved changes. Are you sure you want to {action}?`,actionClosePreview:`close the preview`,actionCancelEdit:`cancel editing`,saving:`Saving...`,saveSuccess:`Saved successfully`,saveFailedWithError:`Save failed: {error}`,agentNamePrefix:` · {name}`,agentNotPaired:`Agent not paired`,fileDetailsLabel:`File Details`,loadingLabel:`Loading...`,export:`Export`,exportDocx:`Word`,exportPdf:`PDF`,exportImage:`Image`,exportMd:`Markdown`,copyMarkdownHint:`Ctrl/Cmd+Click to copy rich text`}});var q=null,Nh=null,Ph=[],Fh=50,Ih=240,Lh=280,Rh=520,zh=320,Bh=`workspacePanelEmbedMode`,Vh=`workspacePanelEmbedWidth`,Hh=`workspacePanelExpanded`,Uh=!1,Wh=zh,Gh=!1,Kh=!1,qh=!1,Jh={field:`name`,asc:!0},J=new Set,Yh=!1,Xh=!1,Zh=-1,Qh=!1,$h=null;function eg(e,t,n){e?.aborted||window.addEventListener(t,n,e?{signal:e}:void 0)}function tg(){if(qh)return;qh=!0;let e=document.createElement(`div`);e.className=`workspace-panel-container`,e.id=`workspacePanelContainer`,e.innerHTML=`
|
|
817
819
|
<button class="workspace-panel-toggle" id="workspacePanelToggle" title="${r(`workspace.workDir`)}">
|
|
818
820
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
819
821
|
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
|
|
@@ -1014,7 +1016,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1014
1016
|
<div class="workspace-preview-rail" id="workspacePreviewRail"></div>
|
|
1015
1017
|
</div>
|
|
1016
1018
|
</div>
|
|
1017
|
-
`,gn(`workspace`).appendChild(e),Qh(),document.addEventListener(`session-switched`,()=>{Oy().catch(e=>i.warn(`[WorkspacePanel] sync after session switch failed`,e))}),document.addEventListener(`session-workdir-changed`,e=>{let t=e.detail?.sessionId;t&&t!==C.activeSessionId||Oy().catch(e=>i.warn(`[WorkspacePanel] sync after workdir change failed`,e))}),document.addEventListener(`session-hydrated`,()=>{Oy().catch(e=>i.warn(`[WorkspacePanel] sync after session hydrated failed`,e))}),hy(),Uv(),fg(),pg(),gg(),i.debug(`[WorkspacePanel] workspace panelinitializing`)}function Qh(){document.getElementById(`workspacePanelContainer`);let e=document.getElementById(`workspacePanel`);document.getElementById(`workspacePanelToggle`).addEventListener(`click`,async t=>{t.stopPropagation(),e.classList.contains(`expanded`)?yg():await vg()}),document.getElementById(`workspacePanelClose`).addEventListener(`click`,e=>{e.stopPropagation(),yg()});let t=Dn(`workspace-panel-mode-btn`);document.getElementById(`workspacePanelClose`).before(t),On(t,e,{onToggle:t=>{!t&&!zh&&Ie(e)}}),document.getElementById(`workspacePanelModeBtn`).addEventListener(`click`,async e=>{e.stopPropagation(),await dg()});let n=document.getElementById(`workspaceSwitchBtn`);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),await Ty()}),document.getElementById(`workspaceBackBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Gv()}),document.getElementById(`workspaceRefreshBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Kv()}),document.getElementById(`workspaceUploadBtn`).addEventListener(`click`,e=>{e.stopPropagation(),kv()}),document.getElementById(`workspaceNewFolderBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Fy()}),document.getElementById(`workspaceAskBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Ry()}),document.getElementById(`workspaceDownloadDirBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Dv()}),document.getElementById(`workspaceBatchDeleteBtn`).addEventListener(`click`,e=>{e.stopPropagation(),xy()});let i=document.getElementById(`workspaceSearchInput`),a=document.getElementById(`workspaceToolbar`),o=a.querySelector(`.workspace-search-box`);function s(){return a.clientWidth<188}function c(){i.value.trim()?(o.classList.add(`search-box-expanded`),s()&&a.classList.add(`search-focused`)):(o.classList.remove(`search-box-expanded`),a.classList.remove(`search-focused`))}i.addEventListener(`input`,e=>{_y(e),c()}),i.addEventListener(`focus`,()=>{s()&&a.classList.add(`search-focused`)}),i.addEventListener(`blur`,()=>{i.value.trim()||a.classList.remove(`search-focused`)}),i.addEventListener(`keydown`,e=>{if(e.key===`Enter`)e.stopPropagation(),vy();else if(e.key===`Escape`)e.stopPropagation(),yy();else if(e.key===`ArrowUp`){if(e.preventDefault(),py.length===0)return;my===-1?my=py.length-1:my>0&&my--,i.value=py[my],uy=i.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=uy?``:`none`}else e.key===`ArrowDown`&&(e.preventDefault(),my===-1||my>=py.length-1?(my=-1,i.value=``,uy=``,document.getElementById(`workspaceSearchClear`).style.display=`none`):(my++,i.value=py[my],uy=i.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=uy?``:`none`))}),document.getElementById(`workspaceSearchBtn`).addEventListener(`click`,()=>{i.focus(),vy()}),document.getElementById(`workspaceSearchClear`).addEventListener(`click`,yy),document.getElementById(`workspacePanel`).querySelectorAll(`.workspace-file-header .sortable`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;Wh.field===t?Wh.asc=!Wh.asc:(Wh.field=t,Wh.asc=!0),Yg(),Lg()})}),document.getElementById(`workspaceSelectAll`).addEventListener(`click`,qg),document.getElementById(`workspacePanelContent`).addEventListener(`click`,Wg),document.getElementById(`workspacePanelContent`).addEventListener(`dblclick`,Gg),document.getElementById(`workspacePanelContent`).addEventListener(`keydown`,Ug),document.getElementById(`workspacePanelContent`).tabIndex=0,document.getElementById(`workspacePanelContent`).addEventListener(`dragstart`,Hg);let l=null;document.getElementById(`workspacePanelContent`).addEventListener(`scroll`,()=>{Ng&&(l&&cancelAnimationFrame(l),l=requestAnimationFrame(()=>{l=null,document.getElementById(`workspacePanelContent`).scrollTop!==Pg&&Ig()}))}),document.getElementById(`workspacePreviewClose`).addEventListener(`click`,()=>yv()),document.getElementById(`workspacePreviewCopyBtn`).addEventListener(`click`,e=>ov(e)),document.getElementById(`workspacePreviewDownloadBtn`).addEventListener(`click`,lv),document.getElementById(`workspacePreviewOpenBrowserBtn`).addEventListener(`click`,uv),document.getElementById(`workspacePreviewFullscreenBtn`).addEventListener(`click`,mv),document.getElementById(`workspacePreviewMdToggleBtn`).addEventListener(`click`,hv),document.getElementById(`workspacePreviewEditBtn`).addEventListener(`click`,bv),document.getElementById(`workspacePreviewSaveBtn`).addEventListener(`click`,xv),document.getElementById(`workspacePreviewCancelBtn`).addEventListener(`click`,Sv),Y_(),document.addEventListener(`keydown`,Tv),document.getElementById(`workspacePreviewFilename`).addEventListener(`click`,async e=>{let t=document.getElementById(`workspacePreviewArea`),n=t.dataset.previewName,i=t.dataset.previewPath;if(n){if((e.ctrlKey||e.metaKey)&&!e.shiftKey){e.preventDefault();try{await navigator.clipboard.writeText(n),F(r(`workspace.copiedFileName`,{name:n}))}catch{F(r(`workspace.copyFailed`),`error`)}}else if((e.ctrlKey||e.metaKey)&&e.shiftKey){if(e.preventDefault(),!i)return;try{await navigator.clipboard.writeText(i),F(r(`workspace.copiedPath`,{path:i}))}catch{F(r(`workspace.copyFailed`),`error`)}}}}),Hv(),chrome.storage.local.onChanged.addListener(Wv);let u=document.createElement(`input`);u.type=`file`,u.multiple=!0,u.id=`workspaceFileInput`,u.style.display=`none`,u.addEventListener(`change`,Av),document.body.appendChild(u)}var $h=[];function eg(e){Ah.push(e),Ah.length>jh&&Ah.shift()}function tg(e){if(!e||typeof e!=`string`)return`unnamed`;let t=e.replace(/[<>:"|?*\\/\x00-\x1f]/g,`_`);return t=t.replace(/\.+$/,``),t=t.trim(),t||=`unnamed`,t}function ng(e,t){let n=X(e);if(!t)return n;let r=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return n.replace(RegExp(`(${r})`,`gi`),`<mark class="search-highlight">$1</mark>`)}var rg=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/></svg>`,ig=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/><path d="m8 9-3 3 3 3"/></svg>`;function ag(){let e=document.getElementById(`mainRow`),t=e?e.clientWidth:window.innerWidth;return Math.max(Mh,t-Nh)}function og(e){return Math.max(Mh,Math.min(e,ag()))}function sg(e){let t=document.getElementById(`workspacePanelModeBtn`);t&&(t.title=r(e?`workspace.floatMode`:`workspace.embedMode`),t.innerHTML=e?ig:rg)}function cg(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;let t=document.getElementById(`mainRow`);t&&e.parentElement!==t&&t.appendChild(e),e.classList.add(`embedded`),e.style.setProperty(`--ws-embed-width`,`${Bh}px`),sg(!0)}function lg(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;e.classList.remove(`embedded`);let t=gn(`workspace`);t&&e.parentElement!==t&&t.appendChild(e),sg(!1)}async function ug(){try{await chrome.storage.local.set({[Ih]:zh,[Lh]:Bh})}catch(e){i.warn(`[WorkspacePanel] persist embed state failed`,e)}}async function dg(){if(zh){zh=!1,Hh=!1,Vh=!1,lg(),await ug();return}let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<Ph){F(r(`workspace.narrowViewportHint`),`error`);return}document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await _g(),Bh=og(Bh),cg(),zh=!0,Hh=!0,Vh=!1,await ug()}function fg(){let e=document.getElementById(`workspacePanelContainer`),t=document.createElement(`div`);t.className=`workspace-embed-divider`,t.id=`workspaceEmbedDivider`,e.appendChild(t),t.addEventListener(`mousedown`,t=>{t.preventDefault();let n=t.clientX,r=Bh;e.classList.add(`resizing`);function i(t){let i=og(r+(n-t.clientX));Bh=i,e.style.setProperty(`--ws-embed-width`,`${i}px`)}function a(){document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),e.classList.remove(`resizing`),ug()}document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)})}function pg(){let e=document.getElementById(`mainRow`);!e||typeof ResizeObserver>`u`||new ResizeObserver(()=>{if(zh){e.clientWidth<Ph&&(Vh=!1,zh=!1,Hh=!1,lg(),ug(),F(r(`workspace.narrowViewportHint`),`error`));return}Vh&&e.clientWidth>=Ph&&hg()}).observe(e)}async function mg(){if(zh)return!0;let e=document.getElementById(`workspacePanelContainer`);if(e&&e.style.display===`none`)return!1;let t=document.getElementById(`mainRow`);return(t?t.clientWidth:window.innerWidth)<Ph?!1:(Bh=og(Bh),document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await _g(),cg(),zh=!0,!0)}function hg(){Vh=!1,mg().then(e=>{e||(Vh=!0)}).catch(e=>{i.warn(`[WorkspacePanel] deferred embed restore failed`,e),Vh=!0})}async function gg(){try{let e=await chrome.storage.local.get([Ih,Lh,Rh]);if(typeof e[Lh]==`number`&&e[Lh]>=Mh&&(Bh=Math.round(e[Lh])),!e[Ih]||(Hh=!0,e[Rh]===!1)||(await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e())};requestAnimationFrame(()=>requestAnimationFrame(n)),setTimeout(n,500)}),await mg()))return;Vh=!0}catch(e){i.warn(`[WorkspacePanel] restore embed state failed`,e)}}async function _g(){let e=document.getElementById(`workspacePanel`);e.classList.contains(`expanded`)||(e.classList.add(`expanded`),Ie(e),chrome.storage.local.set({[Rh]:!0}).catch(()=>{}),await Uv(),q||await bg())}async function vg(){let e=document.getElementById(`workspacePanel`);if(!(!e||e.classList.contains(`expanded`)))if(Jh=!1,Hh){let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<Ph){await _g(),F(r(`workspace.narrowViewportHint`),`error`);return}await _g(),Bh=og(Bh),cg(),zh=!0,Vh=!1,await ug()}else await _g()}function yg(){ly()}async function bg(){let e=await qt();if(!e){Yv(r(`workspace.noWorkspace`));return}kh=e,Ah=[],xg(e)}async function xg(e){q=e,J.clear(),qv(),Jv(),Vy(),Yg(),fy&&uy?(dy=await Tt(e,uy),Lg()):await Dg(e),Jg()}var Sg=new Map,Cg=3e4,wg=20;function Tg(e){let t=Sg.get(e);return t?Date.now()-t.timestamp>=Cg?(Sg.delete(e),null):(Sg.delete(e),Sg.set(e,t),t):null}function Eg(e,t){Sg.has(e)&&Sg.delete(e),Sg.set(e,t),Sg.size>wg&&Sg.delete(Sg.keys().next().value)}async function Dg(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-loading">${r(`common.loading`)}</div>`;let n=Tg(e);if(n){$h=n.entries,Lg();return}let i=await At(e);if(!i.success){Yv(i.error||r(`workspace.loadDirFailed`));return}$h=(i.entries||[]).map(t=>({...t,path:Og(`${e}/${t.name}`)})),Eg(e,{entries:$h,timestamp:Date.now()}),Lg()}function Og(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function kg(e){Sg.delete(e)}var Ag=200,jg=32,Mg=5,Ng=null,Pg=0;function Fg(e){let t=Ht(e.name,e.type),n=e.type===`directory`?`—`:Rt(e.size),i=Kt(e.mtime),a=e.type===`file`&&Lt(e.name),o=fy?e.fullPath:Og(`${q}/${e.name}`),s=J.has(o),c=fy&&e.matchPath!==q?Og(e.matchPath).replace(Og(kh),``).replace(/^\//,``)+`/`+e.name:``,l=fy?ng(e.name,uy):X(e.name);return`
|
|
1019
|
+
`,gn(`workspace`).appendChild(e),ng(),document.addEventListener(`session-switched`,()=>{My().catch(e=>i.warn(`[WorkspacePanel] sync after session switch failed`,e))}),document.addEventListener(`session-workdir-changed`,e=>{let t=e.detail?.sessionId;t&&t!==C.activeSessionId||My().catch(e=>i.warn(`[WorkspacePanel] sync after workdir change failed`,e))}),document.addEventListener(`session-hydrated`,()=>{My().catch(e=>i.warn(`[WorkspacePanel] sync after session hydrated failed`,e))}),yy(),qv(),gg(),_g(),bg(),i.debug(`[WorkspacePanel] workspace panelinitializing`)}function ng(){document.getElementById(`workspacePanelContainer`);let e=document.getElementById(`workspacePanel`);document.getElementById(`workspacePanelToggle`).addEventListener(`click`,async t=>{t.stopPropagation(),e.classList.contains(`expanded`)?Cg():await Sg()}),document.getElementById(`workspacePanelClose`).addEventListener(`click`,e=>{e.stopPropagation(),Cg()});let t=Dn(`workspace-panel-mode-btn`);document.getElementById(`workspacePanelClose`).before(t),On(t,e,{onToggle:t=>{!t&&!Uh&&Ie(e)}}),document.getElementById(`workspacePanelModeBtn`).addEventListener(`click`,async e=>{e.stopPropagation(),await hg()});let n=document.getElementById(`workspaceSwitchBtn`);n&&n.addEventListener(`click`,async e=>{e.stopPropagation(),await ky()}),document.getElementById(`workspaceBackBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Yv()}),document.getElementById(`workspaceRefreshBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Xv()}),document.getElementById(`workspaceUploadBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Nv()}),document.getElementById(`workspaceNewFolderBtn`).addEventListener(`click`,e=>{e.stopPropagation(),zy()}),document.getElementById(`workspaceAskBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Hy()}),document.getElementById(`workspaceDownloadDirBtn`).addEventListener(`click`,e=>{e.stopPropagation(),jv()}),document.getElementById(`workspaceBatchDeleteBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Ty()});let i=document.getElementById(`workspaceSearchInput`),a=document.getElementById(`workspaceToolbar`),o=a.querySelector(`.workspace-search-box`);function s(){return a.clientWidth<188}function c(){i.value.trim()?(o.classList.add(`search-box-expanded`),s()&&a.classList.add(`search-focused`)):(o.classList.remove(`search-box-expanded`),a.classList.remove(`search-focused`))}i.addEventListener(`input`,e=>{xy(e),c()}),i.addEventListener(`focus`,()=>{s()&&a.classList.add(`search-focused`)}),i.addEventListener(`blur`,()=>{i.value.trim()||a.classList.remove(`search-focused`)}),i.addEventListener(`keydown`,e=>{if(e.key===`Enter`)e.stopPropagation(),Sy();else if(e.key===`Escape`)e.stopPropagation(),Cy();else if(e.key===`ArrowUp`){if(e.preventDefault(),_y.length===0)return;vy===-1?vy=_y.length-1:vy>0&&vy--,i.value=_y[vy],my=i.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=my?``:`none`}else e.key===`ArrowDown`&&(e.preventDefault(),vy===-1||vy>=_y.length-1?(vy=-1,i.value=``,my=``,document.getElementById(`workspaceSearchClear`).style.display=`none`):(vy++,i.value=_y[vy],my=i.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=my?``:`none`))}),document.getElementById(`workspaceSearchBtn`).addEventListener(`click`,()=>{i.focus(),Sy()}),document.getElementById(`workspaceSearchClear`).addEventListener(`click`,Cy),document.getElementById(`workspacePanel`).querySelectorAll(`.workspace-file-header .sortable`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;Jh.field===t?Jh.asc=!Jh.asc:(Jh.field=t,Jh.asc=!0),$g(),Vg()})}),document.getElementById(`workspaceSelectAll`).addEventListener(`click`,Zg),document.getElementById(`workspacePanelContent`).addEventListener(`click`,Jg),document.getElementById(`workspacePanelContent`).addEventListener(`dblclick`,Yg),document.getElementById(`workspacePanelContent`).addEventListener(`keydown`,qg),document.getElementById(`workspacePanelContent`).tabIndex=0,document.getElementById(`workspacePanelContent`).addEventListener(`dragstart`,Kg);let l=null;document.getElementById(`workspacePanelContent`).addEventListener(`scroll`,()=>{Lg&&(l&&cancelAnimationFrame(l),l=requestAnimationFrame(()=>{l=null,document.getElementById(`workspacePanelContent`).scrollTop!==Rg&&Bg()}))}),document.getElementById(`workspacePreviewClose`).addEventListener(`click`,()=>Cv()),document.getElementById(`workspacePreviewCopyBtn`).addEventListener(`click`,e=>uv(e)),document.getElementById(`workspacePreviewDownloadBtn`).addEventListener(`click`,pv),document.getElementById(`workspacePreviewOpenBrowserBtn`).addEventListener(`click`,mv),document.getElementById(`workspacePreviewFullscreenBtn`).addEventListener(`click`,vv),document.getElementById(`workspacePreviewMdToggleBtn`).addEventListener(`click`,yv),document.getElementById(`workspacePreviewEditBtn`).addEventListener(`click`,wv),document.getElementById(`workspacePreviewSaveBtn`).addEventListener(`click`,Tv),document.getElementById(`workspacePreviewCancelBtn`).addEventListener(`click`,Ev),$_(),document.addEventListener(`keydown`,kv),document.getElementById(`workspacePreviewFilename`).addEventListener(`click`,async e=>{let t=document.getElementById(`workspacePreviewArea`),n=t.dataset.previewName,i=t.dataset.previewPath;if(n){if((e.ctrlKey||e.metaKey)&&!e.shiftKey){e.preventDefault();try{await navigator.clipboard.writeText(n),F(r(`workspace.copiedFileName`,{name:n}))}catch{F(r(`workspace.copyFailed`),`error`)}}else if((e.ctrlKey||e.metaKey)&&e.shiftKey){if(e.preventDefault(),!i)return;try{await navigator.clipboard.writeText(i),F(r(`workspace.copiedPath`,{path:i}))}catch{F(r(`workspace.copyFailed`),`error`)}}}}),Kv(),chrome.storage.local.onChanged.addListener(Jv);let u=document.createElement(`input`);u.type=`file`,u.multiple=!0,u.id=`workspaceFileInput`,u.style.display=`none`,u.addEventListener(`change`,Pv),document.body.appendChild(u)}var rg=[];function ig(e){Ph.push(e),Ph.length>Fh&&Ph.shift()}function ag(e){if(!e||typeof e!=`string`)return`unnamed`;let t=e.replace(/[<>:"|?*\\/\x00-\x1f]/g,`_`);return t=t.replace(/\.+$/,``),t=t.trim(),t||=`unnamed`,t}function og(e,t){let n=X(e);if(!t)return n;let r=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return n.replace(RegExp(`(${r})`,`gi`),`<mark class="search-highlight">$1</mark>`)}var sg=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/></svg>`,cg=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><path d="M15 3v18"/><path d="m8 9-3 3 3 3"/></svg>`;function lg(){let e=document.getElementById(`mainRow`),t=e?e.clientWidth:window.innerWidth;return Math.max(Ih,t-Lh)}function ug(e){return Math.max(Ih,Math.min(e,lg()))}function dg(e){let t=document.getElementById(`workspacePanelModeBtn`);t&&(t.title=r(e?`workspace.floatMode`:`workspace.embedMode`),t.innerHTML=e?cg:sg)}function fg(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;let t=document.getElementById(`mainRow`);t&&e.parentElement!==t&&t.appendChild(e),e.classList.add(`embedded`),e.style.setProperty(`--ws-embed-width`,`${Wh}px`),dg(!0)}function pg(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;e.classList.remove(`embedded`);let t=gn(`workspace`);t&&e.parentElement!==t&&t.appendChild(e),dg(!1)}async function mg(){try{await chrome.storage.local.set({[Bh]:Uh,[Vh]:Wh})}catch(e){i.warn(`[WorkspacePanel] persist embed state failed`,e)}}async function hg(){if(Uh){Uh=!1,Kh=!1,Gh=!1,pg(),await mg();return}let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<Rh){F(r(`workspace.narrowViewportHint`),`error`);return}document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await xg(),Wh=ug(Wh),fg(),Uh=!0,Kh=!0,Gh=!1,await mg()}function gg(){let e=document.getElementById(`workspacePanelContainer`),t=document.createElement(`div`);t.className=`workspace-embed-divider`,t.id=`workspaceEmbedDivider`,e.appendChild(t),t.addEventListener(`mousedown`,t=>{t.preventDefault();let n=t.clientX,r=Wh;e.classList.add(`resizing`);function i(t){let i=ug(r+(n-t.clientX));Wh=i,e.style.setProperty(`--ws-embed-width`,`${i}px`)}function a(){document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),e.classList.remove(`resizing`),mg()}document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)})}function _g(){let e=document.getElementById(`mainRow`);!e||typeof ResizeObserver>`u`||new ResizeObserver(()=>{if(Uh){e.clientWidth<Rh&&(Gh=!1,Uh=!1,Kh=!1,pg(),mg(),F(r(`workspace.narrowViewportHint`),`error`));return}Gh&&e.clientWidth>=Rh&&yg()}).observe(e)}async function vg(){if(Uh)return!0;let e=document.getElementById(`workspacePanelContainer`);if(e&&e.style.display===`none`)return!1;let t=document.getElementById(`mainRow`);return(t?t.clientWidth:window.innerWidth)<Rh?!1:(Wh=ug(Wh),document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await xg(),fg(),Uh=!0,!0)}function yg(){Gh=!1,vg().then(e=>{e||(Gh=!0)}).catch(e=>{i.warn(`[WorkspacePanel] deferred embed restore failed`,e),Gh=!0})}async function bg(){try{let e=await chrome.storage.local.get([Bh,Vh,Hh]);if(typeof e[Vh]==`number`&&e[Vh]>=Ih&&(Wh=Math.round(e[Vh])),!e[Bh]||(Kh=!0,e[Hh]===!1)||(await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e())};requestAnimationFrame(()=>requestAnimationFrame(n)),setTimeout(n,500)}),await vg()))return;Gh=!0}catch(e){i.warn(`[WorkspacePanel] restore embed state failed`,e)}}async function xg(){let e=document.getElementById(`workspacePanel`);e.classList.contains(`expanded`)||(e.classList.add(`expanded`),Ie(e),chrome.storage.local.set({[Hh]:!0}).catch(()=>{}),await qv(),q||await wg())}async function Sg(){let e=document.getElementById(`workspacePanel`);if(!(!e||e.classList.contains(`expanded`)))if(Qh=!1,Kh){let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<Rh){await xg(),F(r(`workspace.narrowViewportHint`),`error`);return}await xg(),Wh=ug(Wh),fg(),Uh=!0,Gh=!1,await mg()}else await xg()}function Cg(){py()}async function wg(){let e=await qt();if(!e){$v(r(`workspace.noWorkspace`));return}Nh=e,Ph=[],Tg(e)}async function Tg(e){q=e,J.clear(),Zv(),Qv(),Gy(),$g(),gy&&my?(hy=await Tt(e,my),Vg()):await jg(e),Qg()}var Eg=new Map,Dg=3e4,Og=20;function kg(e){let t=Eg.get(e);return t?Date.now()-t.timestamp>=Dg?(Eg.delete(e),null):(Eg.delete(e),Eg.set(e,t),t):null}function Ag(e,t){Eg.has(e)&&Eg.delete(e),Eg.set(e,t),Eg.size>Og&&Eg.delete(Eg.keys().next().value)}async function jg(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-loading">${r(`common.loading`)}</div>`;let n=kg(e);if(n){rg=n.entries,Vg();return}let i=await At(e);if(!i.success){$v(i.error||r(`workspace.loadDirFailed`));return}rg=(i.entries||[]).map(t=>({...t,path:Mg(`${e}/${t.name}`)})),Ag(e,{entries:rg,timestamp:Date.now()}),Vg()}function Mg(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function Ng(e){Eg.delete(e)}var Pg=200,Fg=32,Ig=5,Lg=null,Rg=0;function zg(e){let t=Ht(e.name,e.type),n=e.type===`directory`?`—`:Rt(e.size),i=Kt(e.mtime),a=e.type===`file`&&Lt(e.name),o=gy?e.fullPath:Mg(`${q}/${e.name}`),s=J.has(o),c=gy&&e.matchPath!==q?Mg(e.matchPath).replace(Mg(Nh),``).replace(/^\//,``)+`/`+e.name:``,l=gy?og(e.name,my):X(e.name);return`
|
|
1018
1020
|
<div class="workspace-file-item ${e.type} ${s?`selected`:``}" data-path="${X(o)}" data-type="${e.type}" data-name="${X(e.name)}" draggable="true">
|
|
1019
1021
|
<span class="workspace-file-select" data-action="select">
|
|
1020
1022
|
<span class="workspace-checkbox ${s?`checked`:``}"></span>
|
|
@@ -1031,8 +1033,8 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1031
1033
|
<button class="workspace-file-btn ask" title="${r(`workspace.askFile`)}" data-action="ask"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="13" height="13"><circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg></button>
|
|
1032
1034
|
<button class="workspace-file-btn delete" title="${r(`workspace.delete`)}" data-action="delete"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="13" height="13"><path d="M3 6h18M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg></button>
|
|
1033
1035
|
</span>
|
|
1034
|
-
</div>`}function Ig(){if(!Ng)return;let{sorted:e}=Ng,t=document.getElementById(`workspacePanelContent`),n=t.clientHeight,r=t.scrollTop,i=Ng.itemHeight,a=Math.max(0,Math.floor(r/i)-Mg),o=Math.min(e.length,Math.ceil((r+n)/i)+Mg),s=`<div class="workspace-file-list" style="padding-top:${a*i}px;padding-bottom:${(e.length-o)*i}px;">`;for(let t=a;t<o;t++)s+=Fg(e[t]);s+=`</div>`,t.innerHTML=s;let c=t.querySelector(`.workspace-file-item`);if(c){let a=c.offsetHeight;if(a&&Math.abs(a-i)>2){Ng.itemHeight=a;let i=Math.max(0,Math.floor(r/a)-Mg),o=Math.min(e.length,Math.ceil((r+n)/a)+Mg),s=`<div class="workspace-file-list" style="padding-top:${i*a}px;padding-bottom:${(e.length-o)*a}px;">`;for(let t=i;t<o;t++)s+=Fg(e[t]);s+=`</div>`,t.innerHTML=s}}zg(),Iv(),Pg=t.scrollTop}function Lg(){let e=document.getElementById(`workspacePanelContent`),t=[];if(t=fy?dy:[...$h],t.length===0){Ng=null,e.innerHTML=fy?`<div class="workspace-panel-empty">${r(`workspace.noMatch`)}</div>`:`<div class="workspace-panel-empty">${r(`workspace.dirEmpty`)}</div>`;return}let n=t.filter(e=>e.type===`directory`),i=t.filter(e=>e.type!==`directory`),a=(e,t)=>{let n;if(Wh.field===`name`)n=e.name.localeCompare(t.name);else if(Wh.field===`size`){if(e.type===`directory`&&t.type!==`directory`)return Wh.asc?-1:1;if(e.type!==`directory`&&t.type===`directory`)return Wh.asc?1:-1;n=(e.size||0)-(t.size||0)}else n=(e.mtime||0)-(t.mtime||0);return Wh.asc?n:-n},o=n.sort(a),s=i.sort(a),c;if(c=Wh.field===`name`?Wh.asc?[...o,...s]:[...s.reverse(),...o.reverse()]:[...o,...s],qh=-1,c.length>Ag){Ng={sorted:c,itemHeight:jg},e.scrollTop=0,Ig();return}Ng=null;let l=`<div class="workspace-file-list">`;for(let e of c)l+=Fg(e);l+=`</div>`,e.innerHTML=l}function Rg(){let e=document.getElementById(`workspacePanelContent`);return e?Array.from(e.querySelectorAll(`.workspace-file-item`)):[]}function zg(){let e=document.getElementById(`workspacePanelContent`);if(Ng&&qh>=0){let{sorted:t,itemHeight:n}=Ng;if(qh>=t.length)return;let r=e.scrollTop,i=e.clientHeight,a=qh*n,o=a+n;if(a<r||o>r+i){e.scrollTop=Math.max(0,a-(i-n)/2),Ig();return}}let t=Rg();if(t.forEach(e=>e.classList.remove(`keyboard-focused`)),!(qh<0))if(Ng){let e=Ng.sorted[qh];if(!e)return;let n=fy?e.fullPath:Og(`${q}/${e.name}`),r=t.find(e=>e.dataset.path===n);r&&r.classList.add(`keyboard-focused`)}else qh<t.length&&(t[qh].classList.add(`keyboard-focused`),t[qh].scrollIntoView({block:`nearest`,behavior:`smooth`}))}function Bg(e){let t=Rg();t.length!==0&&(qh=qh===-1?e>0?0:t.length-1:Math.max(0,Math.min(t.length-1,qh+e)),zg())}function Vg(){let e=Rg();if(qh<0||qh>=e.length)return null;let t=e[qh];return{el:t,path:t.dataset.path,name:t.dataset.name,type:t.dataset.type}}function Hg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;let n=t.dataset.path,r=t.dataset.type;n&&(e.dataTransfer.effectAllowed=`copy`,e.dataTransfer.setData(`application/x-workspace-file`,JSON.stringify({path:n,name:t.dataset.name,type:r})))}async function Ug(e){let t=e.target.tagName;if(!(t===`INPUT`||t===`TEXTAREA`))switch(e.key){case`ArrowDown`:e.preventDefault(),Bg(1);break;case`ArrowUp`:e.preventDefault(),Bg(-1);break;case`Enter`:{e.preventDefault();let t=Vg();if(!t)return;t.type===`directory`?(eg(q),await xg(t.path)):await s_(t.path,t.name);break}case`Delete`:{e.preventDefault();let t=Vg();if(!t)return;await by(t.path,t.name,t.type);break}case`F2`:{e.preventDefault();let t=Vg();if(!t)return;await Py(t.path,t.name,t.type);break}case` `:{e.preventDefault();let t=Vg();if(!t)return;Kg(t.path),Bg(1);break}case`Escape`:qh=-1,zg();break}}async function Wg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;Jh=!1;let n=t.dataset.path,i=t.dataset.type,a=e.target.closest(`[data-action]`),o=Rg(),s;if(Ng){let e=t.dataset.path;s=Ng.sorted.findIndex(t=>(fy?t.fullPath:Og(`${q}/${t.name}`))===e)}else s=o.indexOf(t);if(s>=0&&(qh=s,zg()),e.target.closest(`.workspace-file-select`)){e.stopPropagation(),Kg(n);return}if(a){let r=a.dataset.action;e.stopPropagation(),r===`preview`?await s_(n,t.dataset.name):r===`info`?await Cy(n,t.dataset.name,i):r===`download`?await Ev(n,t.dataset.name):r===`ask`?await Ly([n]):r===`delete`?await by(n,t.dataset.name,i):r===`rename`&&await Py(n,t.dataset.name,i);return}if((e.ctrlKey||e.metaKey)&&!e.shiftKey){e.stopPropagation(),navigator.clipboard.writeText(t.dataset.name).then(()=>{F(r(`workspace.copiedFileName`,{name:t.dataset.name}))}).catch(()=>{F(r(`workspace.copyFailed`),`error`)});return}if((e.ctrlKey||e.metaKey)&&e.shiftKey){e.stopPropagation(),navigator.clipboard.writeText(n).then(()=>{F(r(`workspace.copiedPath`,{path:n}))}).catch(()=>{F(r(`workspace.copyFailed`),`error`)});return}if(i===`directory`){e.stopPropagation(),eg(q),await xg(n);return}}async function Gg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;Jh=!1;let n=t.dataset.path,r=t.dataset.type,i=t.dataset.name;if(!e.target.closest(`[data-action]`)&&!e.target.closest(`.workspace-file-select`)){if(r===`directory`){e.stopPropagation(),eg(q),await xg(n);return}r===`file`&&Lt(i)&&(e.stopPropagation(),await s_(n,i))}}function Kg(e){J.has(e)?J.delete(e):J.add(e),Vy(),Jg();let t=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.path===e);if(t){let n=J.has(e);t.classList.toggle(`selected`,n);let r=t.querySelector(`.workspace-checkbox`);r&&r.classList.toggle(`checked`,n)}}function qg(){let e=(fy?dy:$h).map(e=>fy?e.fullPath:Og(`${q}/${e.name}`));if(e.length>0&&e.every(e=>J.has(e)))for(let t of e)J.delete(t);else for(let t of e)J.add(t);Vy(),Jg();for(let e of document.querySelectorAll(`.workspace-file-item`)){let t=J.has(e.dataset.path);e.classList.toggle(`selected`,t);let n=e.querySelector(`.workspace-checkbox`);n&&n.classList.toggle(`checked`,t)}}function Jg(){let e=(fy?dy:$h).map(e=>fy?e.fullPath:Og(`${q}/${e.name}`)),t=document.getElementById(`workspaceSelectAll`);if(!t)return;let n=t.querySelector(`.workspace-checkbox`);e.length===0?(n.classList.remove(`checked`),n.classList.remove(`indeterminate`)):e.every(e=>J.has(e))?(n.classList.add(`checked`),n.classList.remove(`indeterminate`)):e.some(e=>J.has(e))?(n.classList.remove(`checked`),n.classList.add(`indeterminate`)):(n.classList.remove(`checked`),n.classList.remove(`indeterminate`))}function Yg(){[`name`,`size`,`time`].forEach(e=>{let t=document.getElementById(`sort${e.charAt(0).toUpperCase()+e.slice(1)}Indicator`);t&&(Wh.field===e?t.textContent=Wh.asc?`▲`:`▼`:t.textContent=``)})}var Xg=1024*1024,Zg=50*1024*1024,Qg=20*1024*1024,$g=50*1024*1024,e_=50*1024*1024,t_=50*1024*1024,n_=200*1024*1024,r_=100*1024*1024,i_=1e4,a_=2e3;async function o_(e){let t=await Mt();if(!t)throw Error(r(`workspace.agentNotPaired`));let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...Bt(t)},body:JSON.stringify({path:e})});if(!n.ok){let e=await n.text().catch(()=>n.statusText);throw Error(typeof e==`string`?e:`HTTP ${n.status}`)}let i=n.body.getReader(),a=[];for(;;){let{done:e,value:t}=await i.read();if(e)break;a.push(t)}let o=a.reduce((e,t)=>e+t.length,0),s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.length;return s.buffer}async function s_(e,t){Yh&&Yh.abort(),Yh=new AbortController;let n=Yh.signal,a=document.getElementById(`workspacePreviewArea`),o=document.getElementById(`workspacePreviewContent`),s=document.getElementById(`workspacePreviewFilename`),c=document.getElementById(`workspacePreviewLineCount`),l=document.getElementById(`workspacePreviewCopyBtn`),u=document.getElementById(`workspacePreviewDownloadBtn`),d=document.getElementById(`workspacePreviewOpenBrowserBtn`),f=document.getElementById(`workspacePreviewFullscreenBtn`),p=document.getElementById(`workspacePreviewMdToggleBtn`);s.textContent=t,c.textContent=``,o.classList.remove(`xlsx-mode`),o.classList.remove(`markdown-rendered`),o.innerHTML=`<div class="workspace-panel-loading">${r(`common.loading`)}</div>`,a.style.display=`flex`,l.style.display=``,u.style.display=``,d.style.display=`none`,f.style.display=`none`,p.style.display=`none`,p.classList.remove(`active`),dv(p,!1);let m=document.getElementById(`workspacePreviewEditBtn`),h=document.getElementById(`workspacePreviewSaveBtn`),g=document.getElementById(`workspacePreviewCancelBtn`);m.style.display=`none`,h.style.display=`none`,g.style.display=`none`,delete a.dataset.editMode,delete a.dataset.origContent,a.classList.remove(`has-unsaved`),s.classList.remove(`modified`),a.classList.remove(`fullscreen`),document.getElementById(`workspacePanel`).classList.remove(`preview-fullscreen`),a.dataset.previewPath=e,a.dataset.previewName=t,delete a.dataset.previewType,delete a.dataset.previewSheets,delete a.dataset.previewMode,delete a.dataset.htmlText;let _=Ot(t),v=$h.find(t=>t.path===e)||dy.find(t=>t.fullPath===e),y=v?v.size:0;if(_===`text`){if(l.style.display=``,y>Xg){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.fileTooLargeNoPreview`,{size:Rt(y)})}</div>`;return}let n=(t.split(`.`).pop()||``).toLowerCase(),i=await Jt(e);if(!i.success){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.previewFailed`,{error:X(i.error||r(`workspace.unknownError`))})}</div>`;return}let s=i.size||0;if(s>Xg){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.fileTooLargeNoPreview`,{size:Rt(s)})}</div>`;return}let h=i.content||``;if(!Xt(t)&&Yt(h)){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.binaryFileNoPreview`)}</div>`;return}if(m.style.display=``,f.style.display=``,a.dataset.origContent=h,n===`md`||n===`markdown`){p.style.display=``,a.dataset.markdownText=h,a.dataset.previewMode=`markdown`,o.classList.add(`markdown-rendered`),p.classList.add(`active`),p.title=r(`workspace.switchToSourcePreview`),dv(p,!0),l.style.display=``;let e=document.getElementById(`workspacePreviewDownloadBtn`);e&&(e.style.display=`none`);let t=document.getElementById(`workspacePreviewExportMenu`);t&&(t.style.display=``),o.innerHTML=`<div class="markdown-body workspace-preview-markdown">${tt(h)}</div>`,_v(o),vv(o),Qe(),c.textContent=``,gv(!0);return}if(n===`html`||n===`htm`){p.style.display=``,a.dataset.htmlText=h,a.dataset.previewMode=`html`,o.classList.add(`markdown-rendered`),p.classList.add(`active`),p.title=r(`workspace.switchToSourcePreview`),dv(p,!0),l.style.display=``,u.style.display=`none`,d.style.display=``,c.textContent=``,pv(o,h),gv(!0);return}let g=Xv(t),_=h.split(`
|
|
1035
|
-
`);c.textContent=r(`workspace.lineCount`,{count:_.length});let v=_.length>
|
|
1036
|
+
</div>`}function Bg(){if(!Lg)return;let{sorted:e}=Lg,t=document.getElementById(`workspacePanelContent`),n=t.clientHeight,r=t.scrollTop,i=Lg.itemHeight,a=Math.max(0,Math.floor(r/i)-Ig),o=Math.min(e.length,Math.ceil((r+n)/i)+Ig),s=`<div class="workspace-file-list" style="padding-top:${a*i}px;padding-bottom:${(e.length-o)*i}px;">`;for(let t=a;t<o;t++)s+=zg(e[t]);s+=`</div>`,t.innerHTML=s;let c=t.querySelector(`.workspace-file-item`);if(c){let a=c.offsetHeight;if(a&&Math.abs(a-i)>2){Lg.itemHeight=a;let i=Math.max(0,Math.floor(r/a)-Ig),o=Math.min(e.length,Math.ceil((r+n)/a)+Ig),s=`<div class="workspace-file-list" style="padding-top:${i*a}px;padding-bottom:${(e.length-o)*a}px;">`;for(let t=i;t<o;t++)s+=zg(e[t]);s+=`</div>`,t.innerHTML=s}}Ug(),Bv(),Rg=t.scrollTop}function Vg(){let e=document.getElementById(`workspacePanelContent`),t=[];if(t=gy?hy:[...rg],t.length===0){Lg=null,e.innerHTML=gy?`<div class="workspace-panel-empty">${r(`workspace.noMatch`)}</div>`:`<div class="workspace-panel-empty">${r(`workspace.dirEmpty`)}</div>`;return}let n=t.filter(e=>e.type===`directory`),i=t.filter(e=>e.type!==`directory`),a=(e,t)=>{let n;if(Jh.field===`name`)n=e.name.localeCompare(t.name);else if(Jh.field===`size`){if(e.type===`directory`&&t.type!==`directory`)return Jh.asc?-1:1;if(e.type!==`directory`&&t.type===`directory`)return Jh.asc?1:-1;n=(e.size||0)-(t.size||0)}else n=(e.mtime||0)-(t.mtime||0);return Jh.asc?n:-n},o=n.sort(a),s=i.sort(a),c;if(c=Jh.field===`name`?Jh.asc?[...o,...s]:[...s.reverse(),...o.reverse()]:[...o,...s],Zh=-1,c.length>Pg){Lg={sorted:c,itemHeight:Fg},e.scrollTop=0,Bg();return}Lg=null;let l=`<div class="workspace-file-list">`;for(let e of c)l+=zg(e);l+=`</div>`,e.innerHTML=l}function Hg(){let e=document.getElementById(`workspacePanelContent`);return e?Array.from(e.querySelectorAll(`.workspace-file-item`)):[]}function Ug(){let e=document.getElementById(`workspacePanelContent`);if(Lg&&Zh>=0){let{sorted:t,itemHeight:n}=Lg;if(Zh>=t.length)return;let r=e.scrollTop,i=e.clientHeight,a=Zh*n,o=a+n;if(a<r||o>r+i){e.scrollTop=Math.max(0,a-(i-n)/2),Bg();return}}let t=Hg();if(t.forEach(e=>e.classList.remove(`keyboard-focused`)),!(Zh<0))if(Lg){let e=Lg.sorted[Zh];if(!e)return;let n=gy?e.fullPath:Mg(`${q}/${e.name}`),r=t.find(e=>e.dataset.path===n);r&&r.classList.add(`keyboard-focused`)}else Zh<t.length&&(t[Zh].classList.add(`keyboard-focused`),t[Zh].scrollIntoView({block:`nearest`,behavior:`smooth`}))}function Wg(e){let t=Hg();t.length!==0&&(Zh=Zh===-1?e>0?0:t.length-1:Math.max(0,Math.min(t.length-1,Zh+e)),Ug())}function Gg(){let e=Hg();if(Zh<0||Zh>=e.length)return null;let t=e[Zh];return{el:t,path:t.dataset.path,name:t.dataset.name,type:t.dataset.type}}function Kg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;let n=t.dataset.path,r=t.dataset.type;n&&(e.dataTransfer.effectAllowed=`copy`,e.dataTransfer.setData(`application/x-workspace-file`,JSON.stringify({path:n,name:t.dataset.name,type:r})))}async function qg(e){let t=e.target.tagName;if(!(t===`INPUT`||t===`TEXTAREA`))switch(e.key){case`ArrowDown`:e.preventDefault(),Wg(1);break;case`ArrowUp`:e.preventDefault(),Wg(-1);break;case`Enter`:{e.preventDefault();let t=Gg();if(!t)return;t.type===`directory`?(ig(q),await Tg(t.path)):await d_(t.path,t.name);break}case`Delete`:{e.preventDefault();let t=Gg();if(!t)return;await wy(t.path,t.name,t.type);break}case`F2`:{e.preventDefault();let t=Gg();if(!t)return;await Ry(t.path,t.name,t.type);break}case` `:{e.preventDefault();let t=Gg();if(!t)return;Xg(t.path),Wg(1);break}case`Escape`:Zh=-1,Ug();break}}async function Jg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;Qh=!1;let n=t.dataset.path,i=t.dataset.type,a=e.target.closest(`[data-action]`),o=Hg(),s;if(Lg){let e=t.dataset.path;s=Lg.sorted.findIndex(t=>(gy?t.fullPath:Mg(`${q}/${t.name}`))===e)}else s=o.indexOf(t);if(s>=0&&(Zh=s,Ug()),e.target.closest(`.workspace-file-select`)){e.stopPropagation(),Xg(n);return}if(a){let r=a.dataset.action;e.stopPropagation(),r===`preview`?await d_(n,t.dataset.name):r===`info`?await Dy(n,t.dataset.name,i):r===`download`?await Av(n,t.dataset.name):r===`ask`?await Vy([n]):r===`delete`?await wy(n,t.dataset.name,i):r===`rename`&&await Ry(n,t.dataset.name,i);return}if((e.ctrlKey||e.metaKey)&&!e.shiftKey){e.stopPropagation(),navigator.clipboard.writeText(t.dataset.name).then(()=>{F(r(`workspace.copiedFileName`,{name:t.dataset.name}))}).catch(()=>{F(r(`workspace.copyFailed`),`error`)});return}if((e.ctrlKey||e.metaKey)&&e.shiftKey){e.stopPropagation(),navigator.clipboard.writeText(n).then(()=>{F(r(`workspace.copiedPath`,{path:n}))}).catch(()=>{F(r(`workspace.copyFailed`),`error`)});return}if(i===`directory`){e.stopPropagation(),ig(q),await Tg(n);return}}async function Yg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;Qh=!1;let n=t.dataset.path,r=t.dataset.type,i=t.dataset.name;if(!e.target.closest(`[data-action]`)&&!e.target.closest(`.workspace-file-select`)){if(r===`directory`){e.stopPropagation(),ig(q),await Tg(n);return}r===`file`&&Lt(i)&&(e.stopPropagation(),await d_(n,i))}}function Xg(e){J.has(e)?J.delete(e):J.add(e),Gy(),Qg();let t=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.path===e);if(t){let n=J.has(e);t.classList.toggle(`selected`,n);let r=t.querySelector(`.workspace-checkbox`);r&&r.classList.toggle(`checked`,n)}}function Zg(){let e=(gy?hy:rg).map(e=>gy?e.fullPath:Mg(`${q}/${e.name}`));if(e.length>0&&e.every(e=>J.has(e)))for(let t of e)J.delete(t);else for(let t of e)J.add(t);Gy(),Qg();for(let e of document.querySelectorAll(`.workspace-file-item`)){let t=J.has(e.dataset.path);e.classList.toggle(`selected`,t);let n=e.querySelector(`.workspace-checkbox`);n&&n.classList.toggle(`checked`,t)}}function Qg(){let e=(gy?hy:rg).map(e=>gy?e.fullPath:Mg(`${q}/${e.name}`)),t=document.getElementById(`workspaceSelectAll`);if(!t)return;let n=t.querySelector(`.workspace-checkbox`);e.length===0?(n.classList.remove(`checked`),n.classList.remove(`indeterminate`)):e.every(e=>J.has(e))?(n.classList.add(`checked`),n.classList.remove(`indeterminate`)):e.some(e=>J.has(e))?(n.classList.remove(`checked`),n.classList.add(`indeterminate`)):(n.classList.remove(`checked`),n.classList.remove(`indeterminate`))}function $g(){[`name`,`size`,`time`].forEach(e=>{let t=document.getElementById(`sort${e.charAt(0).toUpperCase()+e.slice(1)}Indicator`);t&&(Jh.field===e?t.textContent=Jh.asc?`▲`:`▼`:t.textContent=``)})}var e_=1024*1024,t_=50*1024*1024,n_=20*1024*1024,r_=50*1024*1024,i_=50*1024*1024,a_=50*1024*1024,o_=200*1024*1024,s_=100*1024*1024,c_=1e4,l_=2e3;async function u_(e){let t=await Mt();if(!t)throw Error(r(`workspace.agentNotPaired`));let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...Bt(t)},body:JSON.stringify({path:e})});if(!n.ok){let e=await n.text().catch(()=>n.statusText);throw Error(typeof e==`string`?e:`HTTP ${n.status}`)}let i=n.body.getReader(),a=[];for(;;){let{done:e,value:t}=await i.read();if(e)break;a.push(t)}let o=a.reduce((e,t)=>e+t.length,0),s=new Uint8Array(o),c=0;for(let e of a)s.set(e,c),c+=e.length;return s.buffer}async function d_(e,t){$h&&$h.abort(),$h=new AbortController;let n=$h.signal,a=document.getElementById(`workspacePreviewArea`),o=document.getElementById(`workspacePreviewContent`),s=document.getElementById(`workspacePreviewFilename`),c=document.getElementById(`workspacePreviewLineCount`),l=document.getElementById(`workspacePreviewCopyBtn`),u=document.getElementById(`workspacePreviewDownloadBtn`),d=document.getElementById(`workspacePreviewOpenBrowserBtn`),f=document.getElementById(`workspacePreviewFullscreenBtn`),p=document.getElementById(`workspacePreviewMdToggleBtn`);s.textContent=t,c.textContent=``,o.classList.remove(`xlsx-mode`),o.classList.remove(`markdown-rendered`),o.innerHTML=`<div class="workspace-panel-loading">${r(`common.loading`)}</div>`,a.style.display=`flex`,l.style.display=``,u.style.display=``,d.style.display=`none`,f.style.display=`none`,p.style.display=`none`,p.classList.remove(`active`),hv(p,!1);let m=document.getElementById(`workspacePreviewEditBtn`),h=document.getElementById(`workspacePreviewSaveBtn`),g=document.getElementById(`workspacePreviewCancelBtn`);m.style.display=`none`,h.style.display=`none`,g.style.display=`none`,delete a.dataset.editMode,delete a.dataset.origContent,a.classList.remove(`has-unsaved`),s.classList.remove(`modified`),a.classList.remove(`fullscreen`),document.getElementById(`workspacePanel`).classList.remove(`preview-fullscreen`),a.dataset.previewPath=e,a.dataset.previewName=t,delete a.dataset.previewType,delete a.dataset.previewSheets,delete a.dataset.previewMode,delete a.dataset.htmlText;let _=Ot(t),v=rg.find(t=>t.path===e)||hy.find(t=>t.fullPath===e),y=v?v.size:0;if(_===`text`){if(l.style.display=``,y>e_){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.fileTooLargeNoPreview`,{size:Rt(y)})}</div>`;return}let n=(t.split(`.`).pop()||``).toLowerCase(),i=await Jt(e);if(!i.success){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.previewFailed`,{error:X(i.error||r(`workspace.unknownError`))})}</div>`;return}let s=i.size||0;if(s>e_){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.fileTooLargeNoPreview`,{size:Rt(s)})}</div>`;return}let h=i.content||``;if(!Xt(t)&&Yt(h)){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.binaryFileNoPreview`)}</div>`;return}if(m.style.display=``,f.style.display=``,a.dataset.origContent=h,n===`md`||n===`markdown`){p.style.display=``,a.dataset.markdownText=h,a.dataset.previewMode=`markdown`,o.classList.add(`markdown-rendered`),p.classList.add(`active`),p.title=r(`workspace.switchToSourcePreview`),hv(p,!0),l.style.display=``;let e=document.getElementById(`workspacePreviewDownloadBtn`);e&&(e.style.display=`none`);let t=document.getElementById(`workspacePreviewExportMenu`);t&&(t.style.display=``),o.innerHTML=`<div class="markdown-body workspace-preview-markdown">${tt(h)}</div>`,xv(o),Sv(o),Qe(),c.textContent=``,bv(!0);return}if(n===`html`||n===`htm`){p.style.display=``,a.dataset.htmlText=h,a.dataset.previewMode=`html`,o.classList.add(`markdown-rendered`),p.classList.add(`active`),p.title=r(`workspace.switchToSourcePreview`),hv(p,!0),l.style.display=``,u.style.display=`none`,d.style.display=``,c.textContent=``,_v(o,h),bv(!0);return}let g=ey(t),_=h.split(`
|
|
1037
|
+
`);c.textContent=r(`workspace.lineCount`,{count:_.length});let v=_.length>c_,b=v?_.slice(0,c_):_,x=`<table class="workspace-preview-code-table"><tbody>`;for(let e=0;e<b.length;e++)x+=`<tr><td class="line-num">${e+1}</td><td class="line-content"><code class="${g}">${X(b[e])}</code></td></tr>`;v&&(x+=`<tr><td class="line-num">…</td><td class="line-content"><code>${r(`workspace.truncatedHint`,{shown:c_,total:_.length})}</code></td></tr>`),x+=`</tbody></table>`,o.innerHTML=x;return}l.style.display=`none`,d.style.display=_===`pdf`||_===`image`?``:`none`;try{if(y>({pdf:t_,docx:n_,pptx:r_,xlsx:i_,image:a_,video:o_,audio:s_}[_]||e_)){o.innerHTML=`<div class="workspace-panel-error">${r(_===`pdf`||_===`image`?`workspace.fileTooLargeOpenInBrowser`:`workspace.fileTooLargeNoPreview`,{size:Rt(y)})}</div>`;return}if(_===`xlsx`){f.style.display=``,await W_(t,o,a);return}let i=await u_(e);switch(_){case`pdf`:f.style.display=``,await E_(i,t,o,a,n);break;case`docx`:f.style.display=``,await D_(i,o);break;case`pptx`:f.style.display=``,await R_(i,t,o,a,n);break;case`image`:f.style.display=``,await q_(i,t,o,n);break;case`video`:case`audio`:f.style.display=``,await Y_(i,t,_,o,a);break;default:o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.unsupportedFileType`)}</div>`}}catch(t){i.error(`[WorkspacePanel] preview failed:`,e,t),o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.previewFailed`,{error:X((t instanceof Error?t.message:typeof t==`string`?t:String(t))||r(`workspace.unknownError`))})}</div>`}}var f_=null,p_=1,m_=1,h_=1,g_=1,__=0,v_=0,y_=!1,b_=0,x_=0,S_=0,C_=0,w_=null,T_=1;async function E_(t,n,i,a,o){let s=await A(()=>import(`./pdf-DnVqBaAN.js`).then(t=>e(t.default,1)),__vite__mapDeps([4,1,5]));s.GlobalWorkerOptions.workerSrc=`libs/pdf.worker.min.js`;let c=await s.getDocument({data:t}).promise;f_=c,p_=1,m_=1,h_=1,g_=1,T_=1,__=0,v_=0,a.dataset.previewType=`pdf`;let l=c.numPages;document.getElementById(`workspacePreviewLineCount`).textContent=r(`workspace.pageCount`,{count:l}),i.innerHTML=`
|
|
1036
1038
|
<div class="pdf-wrap">
|
|
1037
1039
|
<div class="pdf-toolbar">
|
|
1038
1040
|
<button class="pdf-toolbar-btn" id="pdfPrevPage" title="${r(`workspace.prevPage`)}" disabled>
|
|
@@ -1061,7 +1063,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1061
1063
|
</div>
|
|
1062
1064
|
</div>
|
|
1063
1065
|
</div>
|
|
1064
|
-
`;let u=document.getElementById(`pdfViewport`),d=document.getElementById(`pdfPan`),f=document.getElementById(`pdfCanvas`),p=document.getElementById(`pdfZoomInfo`);function m(){d.style.transform=`translate(${
|
|
1066
|
+
`;let u=document.getElementById(`pdfViewport`),d=document.getElementById(`pdfPan`),f=document.getElementById(`pdfCanvas`),p=document.getElementById(`pdfZoomInfo`);function m(){d.style.transform=`translate(${__}px, ${v_}px) scale(${h_})`,p.textContent=Math.round(m_*100)+`%`,y_||(u.style.cursor=m_>g_?`grab`:`default`)}function h(){m_<=g_&&(__=0,v_=0)}function g(e,t,n){let r=m_;if(m_=Math.max(.05,Math.min(5,e)),h_=m_/T_,t!==void 0&&n!==void 0){let e=u.getBoundingClientRect(),i=t-e.left-e.width/2,a=n-e.top-e.height/2,o=m_/r;__=i-o*(i-__),v_=a-o*(a-v_)}h(),m(),_()}function _(){w_&&clearTimeout(w_),w_=setTimeout(()=>{v()},180)}async function v(){if(!f_)return;let e=await f_.getPage(p_),t=window.devicePixelRatio||1,n=Math.max(m_,1);T_=n;let r=e.getViewport({scale:n});f.width=Math.floor(r.width*t),f.height=Math.floor(r.height*t),f.style.width=r.width+`px`,f.style.height=r.height+`px`;let i=f.getContext(`2d`);i.setTransform(t,0,0,t,0,0),await e.render({canvasContext:i,viewport:r}).promise;let a=e.getViewport({scale:1}),o=u.clientWidth,s=u.clientHeight;g_=o>0&&s>0&&a.width>0&&a.height>0?Math.min((o-24)/a.width,(s-24)/a.height):1,h_=m_/n,m_<g_*1.05&&m_>g_*.95&&(m_=g_,h_=g_/n,__=0,v_=0),h(),m();let c=document.getElementById(`pdfPrevPage`),l=document.getElementById(`pdfNextPage`),d=document.getElementById(`pdfPageInput`);c&&(c.disabled=p_<=1),l&&(l.disabled=p_>=f_.numPages),d&&(d.value=p_)}await v(),u.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;g(m_+t*m_,e.clientX,e.clientY)},{passive:!1}),u.addEventListener(`mousedown`,e=>{e.button===0&&(y_=!0,b_=e.clientX,x_=e.clientY,S_=__,C_=v_,u.style.cursor=`grabbing`,e.preventDefault())}),eg(o,`mousemove`,e=>{y_&&(__=S_+(e.clientX-b_),v_=C_+(e.clientY-x_),h(),m())}),eg(o,`mouseup`,()=>{y_&&(y_=!1,u.style.cursor=m_>g_?`grab`:`default`)}),document.getElementById(`pdfPrevPage`).addEventListener(`click`,()=>{p_>1&&(p_--,v())}),document.getElementById(`pdfNextPage`).addEventListener(`click`,()=>{p_<l&&(p_++,v())}),document.getElementById(`pdfPageInput`).addEventListener(`change`,e=>{let t=parseInt(e.target.value,10);t>=1&&t<=l&&(p_=t,v())}),document.getElementById(`pdfZoomIn`).addEventListener(`click`,()=>{let e=u.getBoundingClientRect();g(m_*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pdfZoomOut`).addEventListener(`click`,()=>{let e=u.getBoundingClientRect();g(m_/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pdfZoomFit`).addEventListener(`click`,()=>{m_=g_,__=0,v_=0,v()}),u.addEventListener(`dblclick`,()=>{m_=g_,__=0,v_=0,v()}),eg(o,`resize`,()=>{f_&&v()})}async function D_(t,n){let i=await(await A(async()=>{let{default:t}=await import(`./lib-YwkWjNcC.js`).then(t=>e(t.default,1));return{default:t}},__vite__mapDeps([6,1,7,5]))).default.convertToHtml({arrayBuffer:t},{styleMap:[`p[style-name='Heading 1'] => h1:fresh`,`p[style-name='Heading 2'] => h2:fresh`,`p[style-name='Heading 3'] => h3:fresh`,`r[style-name='Strong'] => strong`,`r[style-name='Emphasis'] => em`]}),a=i.value||`<p>${r(`workspace.documentEmpty`)}</p>`,o=je.sanitize(a,{ALLOWED_TAGS:`h1.h2.h3.h4.h5.h6.p.br.strong.em.u.s.a.img.table.thead.tbody.tr.td.th.ul.ol.li.blockquote.pre.code.hr.sup.sub`.split(`.`),ALLOWED_ATTR:[`href`,`src`,`alt`,`title`,`style`]}),s=i.messages?i.messages.filter(e=>e.type===`error`):[];s.length>0?n.innerHTML=`<div class="workspace-preview-docx">${o}<div class="docx-warnings">${s.map(e=>`<div class="docx-warning">⚠ ${X(e.message)}</div>`).join(``)}</div></div>`:n.innerHTML=`<div class="workspace-preview-docx">${o}</div>`}var O_=[],k_=0,Y=1,A_=1,j_=0,M_=0,N_=!1,P_=0,F_=0,I_=0,L_=0;async function R_(e,t,n,i,a){i.dataset.previewType=`pptx`;let{pptxToHtml:o}=await A(async()=>{let{pptxToHtml:e}=await import(`./dist-DuuG_8Br.js`);return{pptxToHtml:e}},__vite__mapDeps([8,1,7]));if(O_=await o(e,{width:960,height:540,scaleToFit:!0,letterbox:!0}),k_=0,Y=1,A_=1,j_=0,M_=0,!O_||O_.length===0){n.innerHTML=`<div class="workspace-panel-error">${r(`workspace.pptxEmptyOrFailed`)}</div>`;return}let s=O_.length;document.getElementById(`workspacePreviewLineCount`).textContent=r(`workspace.pageCount`,{count:s}),n.innerHTML=`
|
|
1065
1067
|
<div class="pptx-wrap">
|
|
1066
1068
|
<div class="pptx-toolbar">
|
|
1067
1069
|
<button class="pptx-toolbar-btn" id="pptxPrevSlide" title="${r(`workspace.prevPage`)}" disabled>
|
|
@@ -1090,7 +1092,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1090
1092
|
</div>
|
|
1091
1093
|
</div>
|
|
1092
1094
|
</div>
|
|
1093
|
-
`,
|
|
1095
|
+
`,V_();let c=document.getElementById(`pptxViewport`),l=document.getElementById(`pptxPan`),u=document.getElementById(`pptxZoomInfo`);function d(){l.style.transform=`translate(${j_}px, ${M_}px) scale(${Y})`,u.textContent=Math.round(Y*100)+`%`,N_||(c.style.cursor=Y>A_?`grab`:`default`)}function f(){Y<=A_&&(j_=0,M_=0)}function p(e,t,n){let r=Y;if(Y=Math.max(.05,Math.min(5,e)),t!==void 0&&n!==void 0){let e=c.getBoundingClientRect(),i=t-e.left-e.width/2,a=n-e.top-e.height/2,o=Y/r;j_=i-o*(i-j_),M_=a-o*(a-M_)}Y<A_*1.05&&Y>A_*.95&&(Y=A_,j_=0,M_=0),f(),d()}c.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;p(Y+t*Y,e.clientX,e.clientY)},{passive:!1}),c.addEventListener(`mousedown`,e=>{e.button===0&&(N_=!0,P_=e.clientX,F_=e.clientY,I_=j_,L_=M_,c.style.cursor=`grabbing`,e.preventDefault())}),eg(a,`mousemove`,e=>{N_&&(j_=I_+(e.clientX-P_),M_=L_+(e.clientY-F_),f(),d())}),eg(a,`mouseup`,()=>{N_&&(N_=!1,c.style.cursor=Y>A_?`grab`:`default`)}),document.getElementById(`pptxPrevSlide`).addEventListener(`click`,()=>{k_>0&&(k_--,V_())}),document.getElementById(`pptxNextSlide`).addEventListener(`click`,()=>{k_<s-1&&(k_++,V_())}),document.getElementById(`pptxZoomIn`).addEventListener(`click`,()=>{let e=c.getBoundingClientRect();p(Y*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pptxZoomOut`).addEventListener(`click`,()=>{let e=c.getBoundingClientRect();p(Y/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pptxZoomFit`).addEventListener(`click`,()=>{requestAnimationFrame(()=>{z_(),Y=A_,j_=0,M_=0,l.style.transform=`translate(0px, 0px) scale(${A_})`,u.textContent=Math.round(A_*100)+`%`,c.style.cursor=`default`})}),c.addEventListener(`dblclick`,()=>{requestAnimationFrame(()=>{z_(),Y=A_,j_=0,M_=0,l.style.transform=`translate(0px, 0px) scale(${A_})`,u.textContent=Math.round(A_*100)+`%`,c.style.cursor=`default`})}),eg(a,`resize`,()=>{!O_||O_.length===0||requestAnimationFrame(()=>{B_()})})}function z_(){let e=document.getElementById(`pptxViewport`),t=document.getElementById(`pptxSlideContainer`);if(!e||!t)return;let n=parseFloat(t.style.width)||960,r=parseFloat(t.style.height)||540,i=e.clientWidth,a=e.clientHeight;A_=i>0&&a>0&&n>0&&r>0?Math.min((i-8)/n,(a-8)/r):1}function B_(){let e=document.getElementById(`pptxViewport`),t=document.getElementById(`pptxPan`),n=document.getElementById(`pptxZoomInfo`);if(!e||!t)return;let r=A_;z_(),Y<=r*1.05&&(Y=A_,j_=0,M_=0),t.style.transform=`translate(${j_}px, ${M_}px) scale(${Y})`,n&&(n.textContent=Math.round(Y*100)+`%`),N_||(e.style.cursor=Y>A_?`grab`:`default`)}function V_(){let e=document.getElementById(`pptxSlideContainer`),t=document.getElementById(`pptxPan`);if(!e||!t||k_<0||k_>=O_.length)return;t.style.transform=`scale(1)`;let n=O_[k_],r=je.sanitize(n,{ALLOWED_TAGS:`div.span.p.a.img.svg.path.circle.rect.line.polyline.polygon.ellipse.g.defs.linearGradient.radialGradient.stop.text.tspan.table.thead.tbody.tr.td.th.br.h1.h2.h3.h4.h5.h6.ul.ol.li.strong.em.b.i.u`.split(`.`),ALLOWED_ATTR:`class.style.id.src.alt.width.height.href.target.d.fill.stroke.stroke-width.transform.viewBox.x.y.cx.cy.r.rx.ry.x1.y1.x2.y2.points.opacity.font-size.font-family.text-anchor.dominant-baseline.clip-path.preserveAspectRatio.xmlns`.split(`.`)});e.style.width=``,e.style.height=``,e.innerHTML=r;let i=e.firstElementChild;i?(e.style.width=(i.offsetWidth||960)+`px`,e.style.height=(i.offsetHeight||540)+`px`):(e.style.width=`960px`,e.style.height=`540px`),z_(),Y=A_,j_=0,M_=0,t.style.transform=`translate(0px, 0px) scale(${A_})`;let a=document.getElementById(`pptxZoomInfo`);a&&(a.textContent=Math.round(Y*100)+`%`);let o=document.getElementById(`pptxViewport`);o&&!N_&&(o.style.cursor=`default`);let s=document.getElementById(`pptxPrevSlide`),c=document.getElementById(`pptxNextSlide`),l=document.getElementById(`pptxSlideNum`);s&&(s.disabled=k_<=0),c&&(c.disabled=k_>=O_.length-1),l&&(l.textContent=k_+1)}var H_=[],U_=0;async function W_(e,t,n){t.innerHTML=`<div class="workspace-panel-empty">${r(`workspace.parsingExcel`)}</div>`;let i=n.dataset.previewPath,a;try{let e=await Mt();if(!e)throw Error(r(`workspace.agentNotPaired`));a=await(await fetch(`${e.url}/api/fs/preview-xlsx`,{method:`POST`,headers:{"Content-Type":`application/json`,...Bt(e)},body:JSON.stringify({path:i,maxRows:500})})).json()}catch(e){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.requestFailed`,{error:X(e.message)})}</div>`;return}if(!a.success){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.parseFailed`,{error:X(a.error||r(`workspace.unknownError`))})}</div>`;return}let{sheets:o}=a.data;if(!o||o.length===0){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.noSheetsInWorkbook`)}</div>`;return}H_=o,U_=0,n.dataset.previewType=`xlsx`,n.dataset.previewSheets=JSON.stringify(o.map(e=>e.name)),t.classList.add(`xlsx-mode`);let s=`<div class="xlsx-sheet-tabs" id="xlsxSheetTabs">`;o.forEach((e,t)=>{s+=`<button class="xlsx-sheet-tab${t===0?` active`:``}" data-sheet="${t}">${X(e.name)}</button>`}),s+=`</div>`,t.innerHTML=s+`<div class="xlsx-sheet-content" id="xlsxSheetContent"><div class="workspace-panel-empty">${r(`workspace.loadingData`)}</div></div>`,document.getElementById(`xlsxSheetTabs`).addEventListener(`click`,e=>{let t=e.target.closest(`.xlsx-sheet-tab`);if(!t)return;let n=parseInt(t.dataset.sheet,10);n!==U_&&(document.querySelectorAll(`.xlsx-sheet-tab`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`),G_(n))}),await G_(0)}async function G_(e){let t=document.getElementById(`xlsxSheetContent`);if(!t)return;U_=e;let n=H_[e];if(!n){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.sheetNotFound`)}</div>`;return}K_(n.rows,n.colCount,n.totalRows,t)}function K_(e,t,n,i){let a=i.querySelector(`.xlsx-table-scrollbar-mirror`);if(a&&a.remove(),!e||e.length===0){i.innerHTML=`<div class="workspace-panel-empty">${r(`workspace.emptySheet`)}</div>`;return}let o=e[0],s=`<div class="xlsx-table-scroll" id="xlsxTableScroll"><table class="xlsx-preview-table"><thead><tr>`;for(let e of o)s+=`<th>${X(String(e??``))}</th>`;s+=`</tr></thead><tbody>`;for(let n=1;n<e.length;n++){s+=`<tr>`;for(let r=0;r<t;r++)s+=`<td>${X(String(e[n][r]??``))}</td>`;s+=`</tr>`}s+=`</tbody></table></div>`,n>l_&&(s+=`<div class="xlsx-truncated-msg">${r(`workspace.xlsxTruncatedHint`,{shown:l_,total:n})}</div>`),i.innerHTML=s;let c=i.querySelector(`#xlsxTableScroll`);if(c){let e=document.createElement(`div`);e.className=`xlsx-table-scrollbar-mirror`,e.innerHTML=`<div class="xlsx-table-scrollbar-mirror-inner" style="width:${c.scrollWidth}px;"></div>`;let t=!1;c.addEventListener(`scroll`,()=>{if(t){t=!1;return}t=!0,e.scrollLeft=c.scrollLeft}),e.addEventListener(`scroll`,()=>{if(t){t=!1;return}t=!0,c.scrollLeft=e.scrollLeft}),i.appendChild(e)}}async function q_(e,t,n,i){let a={png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`,webp:`image/webp`,bmp:`image/bmp`,ico:`image/x-icon`}[(t.split(`.`).pop()||``).toLowerCase()]||`image/png`,o=new Blob([e],{type:a}),s=URL.createObjectURL(o);n.innerHTML=`
|
|
1094
1096
|
<div class="image-preview-wrap">
|
|
1095
1097
|
<div class="image-preview-toolbar">
|
|
1096
1098
|
<button class="image-preview-btn" id="imgZoomOut" title="${r(`workspace.zoomOut`)}">
|
|
@@ -1111,27 +1113,27 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1111
1113
|
</div>
|
|
1112
1114
|
</div>
|
|
1113
1115
|
</div>
|
|
1114
|
-
`;let c=document.getElementById(`imgPreviewImage`),l=document.getElementById(`imgViewport`),u=document.getElementById(`imgPan`),d=document.getElementById(`imgZoomLevel`),f=1,p=1,m=0,h=0,g=!1,_=0,v=0,y=0,b=0;function x(){if(!c.naturalWidth||!c.naturalHeight)return 1;let e=l.clientWidth,t=l.clientHeight;return e<=0||t<=0?1:Math.min((e-20)/c.naturalWidth,(t-20)/c.naturalHeight)}function S(){u.style.transform=`translate(${m}px, ${h}px) scale(${p})`,d.textContent=Math.round(p*100)+`%`,g||(l.style.cursor=p>f?`grab`:`default`)}function C(){p<=f&&(m=0,h=0)}function w(e,t,n){let r=p;if(p=Math.max(.01,Math.min(20,e)),t!==void 0&&n!==void 0){let e=l.getBoundingClientRect(),i=t-e.left-e.width/2,a=n-e.top-e.height/2,o=p/r;m=i-o*(i-m),h=a-o*(a-h)}C(),S()}function T(){p=f,m=0,h=0,S()}l.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;w(p+t*p,e.clientX,e.clientY)},{passive:!1}),l.addEventListener(`mousedown`,e=>{e.button===0&&(g=!0,_=e.clientX,v=e.clientY,y=m,b=h,l.style.cursor=`grabbing`,e.preventDefault())}),
|
|
1116
|
+
`;let c=document.getElementById(`imgPreviewImage`),l=document.getElementById(`imgViewport`),u=document.getElementById(`imgPan`),d=document.getElementById(`imgZoomLevel`),f=1,p=1,m=0,h=0,g=!1,_=0,v=0,y=0,b=0;function x(){if(!c.naturalWidth||!c.naturalHeight)return 1;let e=l.clientWidth,t=l.clientHeight;return e<=0||t<=0?1:Math.min((e-20)/c.naturalWidth,(t-20)/c.naturalHeight)}function S(){u.style.transform=`translate(${m}px, ${h}px) scale(${p})`,d.textContent=Math.round(p*100)+`%`,g||(l.style.cursor=p>f?`grab`:`default`)}function C(){p<=f&&(m=0,h=0)}function w(e,t,n){let r=p;if(p=Math.max(.01,Math.min(20,e)),t!==void 0&&n!==void 0){let e=l.getBoundingClientRect(),i=t-e.left-e.width/2,a=n-e.top-e.height/2,o=p/r;m=i-o*(i-m),h=a-o*(a-h)}C(),S()}function T(){p=f,m=0,h=0,S()}l.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;w(p+t*p,e.clientX,e.clientY)},{passive:!1}),l.addEventListener(`mousedown`,e=>{e.button===0&&(g=!0,_=e.clientX,v=e.clientY,y=m,b=h,l.style.cursor=`grabbing`,e.preventDefault())}),eg(i,`mousemove`,e=>{g&&(m=y+(e.clientX-_),h=b+(e.clientY-v),C(),S())}),eg(i,`mouseup`,()=>{g&&(g=!1,l.style.cursor=p>f?`grab`:`default`)}),document.getElementById(`imgZoomIn`).addEventListener(`click`,()=>{let e=l.getBoundingClientRect();w(p*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`imgZoomOut`).addEventListener(`click`,()=>{let e=l.getBoundingClientRect();w(p/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`imgZoomReset`).addEventListener(`click`,T),l.addEventListener(`dblclick`,T),c.addEventListener(`load`,()=>{f=x(),p=f,m=0,h=0,S(),setTimeout(()=>URL.revokeObjectURL(s),1e3)}),c.addEventListener(`error`,()=>{URL.revokeObjectURL(s),n.innerHTML=`<div class="workspace-panel-error">${r(`workspace.imageLoadFailed`)}</div>`}),eg(i,`resize`,()=>{l.isConnected&&(f=x(),C(),S())})}var J_=null;async function Y_(e,t,n,i,a){J_&&=(URL.revokeObjectURL(J_),null);let o=Pt(t),s=new Blob([e],{type:o}),c=URL.createObjectURL(s);J_=c,a.dataset.previewType=n;let l=n===`video`,u=`<div class="workspace-panel-error" style="margin-top:10px;">${r(`workspace.unsupportedMediaHint`,{ext:X((t.split(`.`).pop()||``).toUpperCase())})}</div>`;if(l){i.innerHTML=`
|
|
1115
1117
|
<div class="media-preview-wrap" style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:12px;">
|
|
1116
1118
|
<video controls autoplay style="max-width:100%;max-height:calc(100% - 24px);border-radius:8px;background:#000;">
|
|
1117
1119
|
<source src="${c}" type="${X(o)}">
|
|
1118
1120
|
</video>
|
|
1119
1121
|
<div id="mediaUnsupportedHint" style="display:none;">${u}</div>
|
|
1120
|
-
</div>`;let e=i.querySelector(`video`);e&&e.addEventListener(`dblclick`,()=>
|
|
1122
|
+
</div>`;let e=i.querySelector(`video`);e&&e.addEventListener(`dblclick`,()=>vv())}else i.innerHTML=`
|
|
1121
1123
|
<div class="media-preview-wrap" style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:12px;gap:16px;">
|
|
1122
1124
|
<div style="font-size:14px;color:var(--text-secondary);">🎵 ${X(t)}</div>
|
|
1123
1125
|
<audio controls autoplay style="width:100%;max-width:560px;">
|
|
1124
1126
|
<source src="${c}" type="${X(o)}">
|
|
1125
1127
|
</audio>
|
|
1126
1128
|
<div id="mediaUnsupportedHint" style="display:none;">${u}</div>
|
|
1127
|
-
</div>`;let d=i.querySelector(`video, audio`),f=i.querySelector(`#mediaUnsupportedHint`);if(d){let e=()=>{d.style.display=`none`,f&&(f.style.display=`block`)};d.addEventListener(`error`,e),i.querySelectorAll(`source`).forEach(t=>t.addEventListener(`error`,e))}}var
|
|
1129
|
+
</div>`;let d=i.querySelector(`video, audio`),f=i.querySelector(`#mediaUnsupportedHint`);if(d){let e=()=>{d.style.display=`none`,f&&(f.style.display=`block`)};d.addEventListener(`error`,e),i.querySelectorAll(`source`).forEach(t=>t.addEventListener(`error`,e))}}var X_=!1;function Z_(e,t){let n=e.getBoundingClientRect();t.style.top=n.bottom+4+`px`;let r=n.right-160;t.style.left=Math.max(4,r)+`px`,t.style.right=`auto`}function Q_(e,t){Z_(e,t),t.classList.add(`show`)}function $_(){let e=document.getElementById(`workspacePreviewExportMenu`),t=document.getElementById(`workspacePreviewExportBtn`),n=document.getElementById(`workspacePreviewExportDropdown`);if(!e||!t||!n)return;document.body.appendChild(n),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.contains(`show`)?n.classList.remove(`show`):Q_(t,n)});let r=null,i=null;e.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null),r=setTimeout(()=>{Q_(t,n)},200)}),e.addEventListener(`mouseleave`,()=>{r&&=(clearTimeout(r),null),i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},300)}),n.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null)}),n.addEventListener(`mouseleave`,()=>{i=setTimeout(()=>{!e.matches(`:hover`)&&!n.matches(`:hover`)&&n.classList.remove(`show`)},200)}),n.querySelectorAll(`.ws-export-dropdown-item`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let r=e.dataset.exportType;n.classList.remove(`show`),tv(r)})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&!n.contains(t.target)&&n.classList.remove(`show`)});let a=()=>{n.classList.contains(`show`)&&Z_(t,n)};document.getElementById(`workspacePreviewContent`)?.addEventListener(`scroll`,a),window.addEventListener(`resize`,a)}function ev(){return document.getElementById(`workspacePreviewArea`).dataset.markdownText||``}async function tv(e){if(X_)return;X_=!0;let t=document.getElementById(`workspacePreviewExportBtn`);document.getElementById(`workspacePreviewExportMenu`);let n=document.getElementById(`workspacePreviewExportDropdown`),a=document.getElementById(`workspacePreviewArea`).dataset.previewName||`export`,o=t.innerHTML;t.innerHTML=`<svg viewBox="0 0 24 24" fill="none" style="animation: spin 0.8s linear infinite; width: 14px; height: 14px; flex-shrink: 0;"><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10" opacity="0.25"/><circle cx="12" cy="12" r="10" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-dasharray="31.4" stroke-dashoffset="10"/></svg>`,t.disabled=!0,t.style.opacity=`0.6`;try{switch(e){case`docx`:await iv(a);break;case`pdf`:await ov(a);break;case`image`:await sv(a);break;case`md`:cv(a);break}}catch(e){i.error(`[WorkspacePanel] export failed:`,e),F(r(`chatExport.exportFailed`,{message:e.message}),`error`)}finally{X_=!1,t.innerHTML=o,t.disabled=!1,t.style.opacity=`1`,n.classList.remove(`show`)}}async function nv(e){if(typeof mermaid>`u`)return;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await A(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-DcDe1GQ_.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([9,10,1,11,2,3,12,0]));await t(e),await n(e)}async function rv(e){if(typeof mermaid>`u`||!/```mermaid/i.test(e))return e;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await A(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-DcDe1GQ_.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([9,10,1,11,2,3,12,0]));try{let r=tt(e),i=document.createElement(`div`);i.style.cssText=`position:fixed;left:-9999px;top:-9999px;`,i.innerHTML=r,document.body.appendChild(i),await t(i),await n(i);let a=i.querySelectorAll(`.mermaid`),o=[];for(let e of a){let t=e.querySelector(`img`);t&&t.src&&t.src.startsWith(`data:`)?o.push(t.src):o.push(null)}if(document.body.removeChild(i),o.length===0)return e;let s=0;return e.replace(/```\s*mermaid\s*[\r\n]+([\s\S]*?)```/gi,e=>{let t=o[s];return s++,t?``:e})}catch(t){return i.warn(`[WorkspacePanel] Mermaid pre-render failed:`,t.message),e}}async function iv(e){let{Packer:t}=await A(async()=>{let{Packer:e}=await import(`./dist-BUuoW_84.js`);return{Packer:e}},__vite__mapDeps([10,1])),{createDocxDocument:n}=await A(async()=>{let{createDocxDocument:e}=await import(`./chat-export-DcDe1GQ_.js`);return{createDocxDocument:e}},__vite__mapDeps([9,10,1,11,2,3,12,0])),i=ev();if(!i){F(r(`chatExport.noContent`),`error`);return}i=await rv(i);let a=n(await av(i)),o=await t.toBlob(a),s=`word-${new Date().getTime()}.docx`;lv(o,s),F(r(`workspace.downloaded`,{name:s}),`success`)}async function av(e){let{Document:t,Packer:n,Paragraph:r,TextRun:i,HeadingLevel:a,Table:o,TableRow:s,TableCell:c,AlignmentType:l,WidthType:u,BorderStyle:d,ImageRun:f,ExternalHyperlink:p,convertInchesToTwip:m}=await A(async()=>{let{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}=await import(`./dist-BUuoW_84.js`);return{Document:e,Packer:t,Paragraph:n,TextRun:r,HeadingLevel:i,Table:a,TableRow:o,TableCell:s,AlignmentType:c,WidthType:l,BorderStyle:u,ImageRun:d,ExternalHyperlink:f,convertInchesToTwip:p}},__vite__mapDeps([10,1])),{createTextRuns:h,sanitizeDocxText:g,nextDocxImageId:_,isDocxEmbeddableImageType:v}=await A(async()=>{let{createTextRuns:e,sanitizeDocxText:t,nextDocxImageId:n,isDocxEmbeddableImageType:r}=await import(`./chat-export-DcDe1GQ_.js`);return{createTextRuns:e,sanitizeDocxText:t,nextDocxImageId:n,isDocxEmbeddableImageType:r}},__vite__mapDeps([9,10,1,11,2,3,12,0]));if(!e||!e.trim())return[new r({children:[new i({text:``})]})];let y=[],b=g(e),x=[];b=b.replace(/```(\w*)\n([\s\S]*?)```/g,(e,t,n)=>{let r=x.length;return x.push({lang:t||``,code:n.trimEnd()}),`\n\n%%CODEBLOCK_${r}%%\n\n`});let S=[];b=b.replace(/<table[\s\S]*?<\/table>/gi,e=>{let t=S.length;return S.push(e),`\n\n%%HTMLTABLE_${t}%%\n\n`});let C=[];b=b.replace(/(?:^\|.+\|\s*$\n)+^\|[\s\-:|]+\|\s*$\n(?:^\|.+\|\s*$\n?)+/gm,e=>{let t=C.length;return C.push(e),`\n\n%%MDTABLE_${t}%%\n\n`});let w=b.split(/\n{2,}/).filter(e=>e.trim());function T(e){if(!e)return[];let t=/(\*\*(.+?)\*\*|(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)|__(.+?)__|(?<!_)_(?!_)(.+?)(?<!_)_(?!_)|`([^`]+)`|\[([^\]]+)\]\(([^)]+)\)|!\[([^\]]*)\]\(([^)]+)\))/,n=[],r=e;for(;r.length>0;){let e=r.match(t);if(!e){n.push(...h(r));break}let a=e.index;a>0&&n.push(...h(r.slice(0,a)));let o=e[1];if(e[2]!==void 0)n.push(...h(e[2],{bold:!0}));else if(e[3]!==void 0)n.push(...h(e[3],{italics:!0}));else if(e[4]!==void 0)n.push(...h(e[4],{bold:!0}));else if(e[5]!==void 0)n.push(...h(e[5],{italics:!0}));else if(e[6]!==void 0)n.push(new i({text:e[6],font:`Consolas`,size:20}));else if(e[7]!==void 0)n.push(new p({children:[new i({text:e[7],style:`Hyperlink`})],link:e[8]}));else if(e[9]!==void 0){let t=e[10];if(t.startsWith(`data:`))try{let[r,a]=t.split(`,`),o=r.match(/data:(image\/(\w+))/);if(o&&a&&v(o[2])){let t=atob(a),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);n.push(new f({data:r,transformation:{width:400,height:300},type:o[2],altText:{id:_(),name:e[9]||`image`}}))}else n.push(new i({text:`[Image: `+(e[9]||`image`)+`]`,italics:!0,color:`999999`}))}catch{n.push(new i({text:`[Image]`,italics:!0,color:`999999`}))}else n.push(new i({text:`[Image: `+(e[9]||t)+`]`,italics:!0,color:`999999`}))}r=r.slice(a+o.length)}return n}function E(e){let t=new DOMParser().parseFromString(e,`text/html`),n=[];return t.querySelectorAll(`tr`).forEach(e=>{let t=[];e.querySelectorAll(`th, td`).forEach(e=>t.push(e.textContent.trim())),t.length>0&&n.push(t)}),n}function D(e){let t=e.trim().split(`
|
|
1128
1130
|
`),n=[];for(let e of t){if(/^[\s\|:\-]+$/.test(e.replace(/\|/g,``)))continue;let t=Ze(e).slice(1,-1).map(e=>e.trim());t.length>0&&n.push(t)}return n}function O(e){if(e.length===0)return new r({children:[]});let t=Math.max(...e.map(e=>e.length));return new o({rows:e.map((e,n)=>{let i=[];for(let a=0;a<t;a++){let o=e[a]||``;i.push(new c({children:[new r({children:T(o),spacing:{before:40,after:40}})],shading:n===0?{fill:`F2F2F2`}:void 0,width:{size:Math.round(100/t*100)/100,type:u.PERCENTAGE}}))}return new s({children:i})}),width:{size:100,type:u.PERCENTAGE},borders:{top:{style:d.SINGLE,size:1,color:`DDDDDD`},bottom:{style:d.SINGLE,size:1,color:`DDDDDD`},left:{style:d.SINGLE,size:1,color:`DDDDDD`},right:{style:d.SINGLE,size:1,color:`DDDDDD`},insideHorizontal:{style:d.SINGLE,size:1,color:`DDDDDD`},insideVertical:{style:d.SINGLE,size:1,color:`DDDDDD`}}})}for(let e of w){let t=e.trim(),n=t.match(/^%%CODEBLOCK_(\d+)%%$/);if(n){let{lang:e,code:t}=x[parseInt(n[1])],a=e?`${e} code`:`code`;y.push(new r({children:[new i({text:a,bold:!0,font:`Consolas`,size:18})]}));let o=t.split(`
|
|
1129
1131
|
`);for(let e of o)y.push(new r({children:[new i({text:e||` `,font:`Consolas`,size:18})],spacing:{before:0,after:0,line:240},shading:{fill:`F5F5F5`}}));y.push(new r({children:[new i({text:``})]}));continue}let o=t.match(/^%%HTMLTABLE_(\d+)%%$/);if(o){let e=E(S[parseInt(o[1])]);e.length>0&&(y.push(O(e)),y.push(new r({children:[new i({text:``})]})));continue}let s=t.match(/^%%MDTABLE_(\d+)%%$/);if(s){let e=D(C[parseInt(s[1])]);y.push(O(e)),y.push(new r({children:[new i({text:``})]}));continue}let c=t.match(/^(#{1,6})\s+(.+)/);if(c){let e={1:a.HEADING_1,2:a.HEADING_2,3:a.HEADING_3,4:a.HEADING_4,5:a.HEADING_5,6:a.HEADING_6};y.push(new r({children:T(c[2]),heading:e[c[1].length]||a.HEADING_1,border:{bottom:{style:d.SINGLE,size:6,color:`EAECEF`}}}));let n=t.slice(c[0].length).replace(/^\n+/,``).trim();n&&y.push(new r({children:T(n),spacing:{before:60,after:60}}));continue}if(/^(---|\*\*\*|___)\s*$/.test(t)){y.push(new r({children:[],border:{bottom:{style:d.SINGLE,size:6,color:`CCCCCC`}},spacing:{before:200,after:200}}));continue}if(/^[\-\*\+]\s+/.test(t)){let t=e.split(/\n(?=[\-\*\+]\s+)/);for(let e of t)y.push(new r({children:T(e.replace(/^[\-\*\+]\s+/,``)),bullet:{level:0},spacing:{before:40,after:40}}));continue}if(/^\d+\.\s+/.test(t)){let t=e.split(/\n(?=\d+\.\s+)/);for(let e of t)y.push(new r({children:T(e.replace(/^\d+\.\s+/,``)),numbering:{reference:`default`,level:0},spacing:{before:40,after:40}}));continue}if(t.startsWith(`>`)){let t=e.split(`
|
|
1130
1132
|
`).map(e=>e.replace(/^>\s?/,``)).join(`
|
|
1131
|
-
`);y.push(new r({children:T(t),indent:{left:m(.5)},border:{left:{style:d.SINGLE,size:12,color:`CCCCCC`}},spacing:{before:60,after:60}}));continue}let l=T(t);y.push(new r({children:l.length>0?l:h(t),spacing:{before:60,after:60}}))}return y}async function
|
|
1133
|
+
`);y.push(new r({children:T(t),indent:{left:m(.5)},border:{left:{style:d.SINGLE,size:12,color:`CCCCCC`}},spacing:{before:60,after:60}}));continue}let l=T(t);y.push(new r({children:l.length>0?l:h(t),spacing:{before:60,after:60}}))}return y}async function ov(e){let{jsPDF:t,html2canvas:n}=await Fe();if(!t||!n){F(r(`chatExport.pdfLibNotLoaded`),`error`);return}let a=ev();if(!a){F(r(`chatExport.noContent`),`error`);return}let o=document.createElement(`div`);o.style.cssText=`position:fixed;left:-9999px;top:-9999px;width:515px;padding:40px;background:white;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','PingFang SC','Hiragino Sans GB','Microsoft YaHei',sans-serif;font-size:12px;line-height:1.6;color:#333;box-sizing:border-box;`,o.innerHTML=`<div class="markdown-body">${tt(a)}</div>`,document.body.appendChild(o),await nv(o);let s=o.scrollHeight,c=Math.ceil(s/762);n(o,{scale:2,useCORS:!0,logging:!1,backgroundColor:`#ffffff`,willReadFrequently:!0}).then(e=>{let n=new t({orientation:`portrait`,unit:`px`,format:[595,842],compress:!0}),i=e.width,a=e.height,l=a/s,u=762*l;for(let t=0;t<c;t++){t>0&&n.addPage();let r=t*u,o=Math.min(r+u,a)-r,s=document.createElement(`canvas`);s.width=i,s.height=o;let c=s.getContext(`2d`,{willReadFrequently:!0});c.fillStyle=`#ffffff`,c.fillRect(0,0,s.width,s.height),c.drawImage(e,0,r,i,o,0,0,i,o);let d,f;try{d=s.toDataURL(`image/jpeg`,.85),f=`JPEG`}catch{d=s.toDataURL(`image/png`),f=`PNG`}let p=o/l;n.addImage(d,f,0,0,595,p,void 0,`FAST`)}let d=`pdf-${new Date().getTime()}.pdf`;n.save(d),document.body.removeChild(o),F(r(`workspace.downloaded`,{name:d}),`success`)}).catch(e=>{i.error(`[WorkspacePanel] PDF export failed:`,e),F(r(`chatExport.exportFailed`,{message:e.message}),`error`),document.body.removeChild(o)})}async function sv(e){let t=await We();if(!t){F(r(`chatExport.imageLibNotLoaded`),`error`);return}let n=document.getElementById(`workspacePreviewContent`).querySelector(`.workspace-preview-markdown`);if(!n){F(r(`chatExport.noContent`),`error`);return}let a=n.cloneNode(!0),o=document.createElement(`div`);o.style.cssText=`position:fixed;left:-9999px;top:-9999px;width:800px;padding:40px;background:white;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;font-size:14px;line-height:1.6;color:#333;box-sizing:border-box;`,o.appendChild(a),document.body.appendChild(o),await nv(o),await new Promise(e=>requestAnimationFrame(()=>requestAnimationFrame(e)));try{let e=(await t(o,{scale:2,useCORS:!0,logging:!1,backgroundColor:`#ffffff`,willReadFrequently:!0})).toDataURL(`image/jpeg`,.92),n=document.createElement(`a`);n.href=e;let i=`image-${new Date().getTime()}.jpg`;n.download=i,document.body.appendChild(n),n.click(),document.body.removeChild(n),F(r(`workspace.downloaded`,{name:i}),`success`)}catch(e){i.error(`[WorkspacePanel] image export failed:`,e),F(r(`chatExport.exportFailed`,{message:e.message}),`error`)}finally{document.body.removeChild(o)}}function cv(e){let t=ev();if(!t){F(r(`chatExport.noContent`),`error`);return}let n=t.replace(/\r\n/g,`
|
|
1132
1134
|
`).replace(/\n{3,}/g,`
|
|
1133
1135
|
|
|
1134
|
-
`),i=new Blob([n],{type:`text/markdown;charset=utf-8`}),a=`md-${new Date().getTime()}.md`;
|
|
1136
|
+
`),i=new Blob([n],{type:`text/markdown;charset=utf-8`}),a=`md-${new Date().getTime()}.md`;lv(i,a),F(r(`workspace.downloaded`,{name:a}),`success`)}function lv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}async function uv(e){let t=document.getElementById(`workspacePreviewArea`),n=t.dataset.previewPath;if(!n)return;if((t.dataset.previewType||Ot(t.dataset.previewName||``))!==`text`){F(r(`workspace.copyUnsupportedType`),`info`);return}let i=e&&(e.ctrlKey||e.metaKey),a=document.getElementById(`workspacePreviewContent`).classList.contains(`markdown-rendered`);if(i&&a)await dv();else{let e=t.dataset.markdownText||t.dataset.htmlText||``;if(e)try{await navigator.clipboard.writeText(e),F(r(`workspace.copiedToClipboard`),`success`)}catch{F(r(`workspace.copyFailedManual`),`error`)}else{let e=await Jt(n);if(e.success)try{await navigator.clipboard.writeText(e.content||``),F(r(`workspace.copiedToClipboard`),`success`)}catch{F(r(`workspace.copyFailedManual`),`error`)}else F(r(`workspace.getContentFailed`),`error`)}}}async function dv(){let e=document.getElementById(`workspacePreviewContent`).querySelector(`.workspace-preview-markdown`);if(!e){F(r(`chatCopy.copyFailedManual`),`error`);return}let t=e.cloneNode(!0);t.querySelectorAll(`table`).forEach(e=>{let t=at(e);e.parentNode.replaceChild(t,e)});let n=t.innerHTML,a=t.textContent||``,o=fv(n);try{if(typeof ClipboardItem<`u`){let e=new ClipboardItem({"text/plain":new Blob([a],{type:`text/plain`}),"text/html":new Blob([o],{type:`text/html`})});await navigator.clipboard.write([e])}else{let e=document.createElement(`div`);e.style.position=`fixed`,e.style.left=`-999999px`,e.style.top=`-999999px`,e.innerHTML=o,document.body.appendChild(e);let t=document.createRange();t.selectNodeContents(e);let n=window.getSelection();n.removeAllRanges(),n.addRange(t);try{document.execCommand(`copy`)}catch{await navigator.clipboard.writeText(a)}finally{n.removeAllRanges(),document.body.removeChild(e)}}F(r(`chatCopy.copiedRich`),`success`)}catch(e){i.warn(`[WorkspacePanel] rich textcopy failed:`,e.message);try{await navigator.clipboard.writeText(a),F(r(`workspace.copiedToClipboard`),`success`)}catch{F(r(`workspace.copyFailedManual`),`error`)}}}function fv(e){return`<!DOCTYPE html><html><head>
|
|
1135
1137
|
<style>
|
|
1136
1138
|
h1 { font-size: 24px; font-weight: bold; margin: 16px 0 8px; }
|
|
1137
1139
|
h2 { font-size: 20px; font-weight: bold; margin: 14px 0 6px; }
|
|
@@ -1152,17 +1154,17 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1152
1154
|
a { color: #007bff; text-decoration: underline; }
|
|
1153
1155
|
img { max-width: 100%; }
|
|
1154
1156
|
</style>
|
|
1155
|
-
</head><body>${e}</body></html>`}async function
|
|
1157
|
+
</head><body>${e}</body></html>`}async function pv(){let e=document.getElementById(`workspacePreviewArea`),t=e.dataset.previewPath,n=e.dataset.previewName;t&&await Av(t,n)}async function mv(){let e=document.getElementById(`workspacePreviewArea`).dataset.previewPath;if(e)try{let t=await kt(e);if(!t.success){F(r(`workspace.requestFailed`,{error:t.error}),`error`);return}let n=URL.createObjectURL(t.blob);window.open(n,`_blank`),setTimeout(()=>URL.revokeObjectURL(n),6e4),F(r(`workspace.openInBrowser`),`success`)}catch(e){F(r(`workspace.openFailed`,{error:e.message}),`error`)}}function hv(e,t){let n=e.querySelector(`.workspace-preview-md-icon-preview`),r=e.querySelector(`.workspace-preview-md-icon-source`);n&&(n.style.display=t?`none`:``),r&&(r.style.display=t?``:`none`)}function gv(e){let t=e.trim();if(/^\s*<!DOCTYPE\s/i.test(t)||/^\s*<html[\s>]/i.test(t)){if(/<\/body>/i.test(t)){let e=t.replace(/<\/head>/i,`<style>html,body{overflow:auto!important;height:auto!important;}</style></head>`);return e=e.replace(/<\/body>/i,`<script>(function(){var s=document.createElement('style');s.textContent='.aih-broken-resp{display:inline-flex;align-items:center;justify-content:center;min-width:60px;min-height:40px;background:#f0f0f0;border:1px dashed #ccc;border-radius:4px;color:#999;font-size:12px;padding:4px 8px;}';document.head.appendChild(s);function mark(el){if(el.dataset.aihBroken)return;el.dataset.aihBroken='1';var ph=document.createElement('span');ph.className='aih-broken-resp';ph.textContent='资源未加载';if(el.tagName==='IMG'){el.style.display='none';el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}else if(el.tagName==='LINK'){el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}}document.querySelectorAll('img').forEach(function(img){if(img.complete&&img.naturalWidth===0)mark(img);img.addEventListener('error',function(){mark(img);});});document.addEventListener('error',function(e){var t=e.target;if(t&&(t.tagName==='IMG'||t.tagName==='LINK'||t.tagName==='SCRIPT'))mark(t);},true);})();<\/script></body>`),e}else if(/<\/head>/i.test(t))return t.replace(/<\/head>/i,`<style>html,body{overflow:auto!important;height:auto!important;}</style><script>(function(){var s=document.createElement('style');s.textContent='.aih-broken-resp{display:inline-flex;align-items:center;justify-content:center;min-width:60px;min-height:40px;background:#f0f0f0;border:1px dashed #ccc;border-radius:4px;color:#999;font-size:12px;padding:4px 8px;}';document.head.appendChild(s);function mark(el){if(el.dataset.aihBroken)return;el.dataset.aihBroken='1';var ph=document.createElement('span');ph.className='aih-broken-resp';ph.textContent='资源未加载';if(el.tagName==='IMG'){el.style.display='none';el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}else if(el.tagName==='LINK'){el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}}document.querySelectorAll('img').forEach(function(img){if(img.complete&&img.naturalWidth===0)mark(img);img.addEventListener('error',function(){mark(img);});});document.addEventListener('error',function(e){var t=e.target;if(t&&(t.tagName==='IMG'||t.tagName==='LINK'||t.tagName==='SCRIPT'))mark(t);},true);})();<\/script></head>`);else if(/<body[\s>]/i.test(t))return t.replace(/<body([\s>])/i,`<body$1<style>html,body{overflow:auto!important;height:auto!important;}</style><script>(function(){var s=document.createElement('style');s.textContent='.aih-broken-resp{display:inline-flex;align-items:center;justify-content:center;min-width:60px;min-height:40px;background:#f0f0f0;border:1px dashed #ccc;border-radius:4px;color:#999;font-size:12px;padding:4px 8px;}';document.head.appendChild(s);function mark(el){if(el.dataset.aihBroken)return;el.dataset.aihBroken='1';var ph=document.createElement('span');ph.className='aih-broken-resp';ph.textContent='资源未加载';if(el.tagName==='IMG'){el.style.display='none';el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}else if(el.tagName==='LINK'){el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}}document.querySelectorAll('img').forEach(function(img){if(img.complete&&img.naturalWidth===0)mark(img);img.addEventListener('error',function(){mark(img);});});document.addEventListener('error',function(e){var t=e.target;if(t&&(t.tagName==='IMG'||t.tagName==='LINK'||t.tagName==='SCRIPT'))mark(t);},true);})();<\/script>`);return t}return`<!DOCTYPE html>
|
|
1156
1158
|
<html>
|
|
1157
1159
|
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
|
|
1158
1160
|
<body style="margin:0;padding:0;overflow:auto;">${t}<script>(function(){var s=document.createElement('style');s.textContent='.aih-broken-resp{display:inline-flex;align-items:center;justify-content:center;min-width:60px;min-height:40px;background:#f0f0f0;border:1px dashed #ccc;border-radius:4px;color:#999;font-size:12px;padding:4px 8px;}';document.head.appendChild(s);function mark(el){if(el.dataset.aihBroken)return;el.dataset.aihBroken='1';var ph=document.createElement('span');ph.className='aih-broken-resp';ph.textContent='资源未加载';if(el.tagName==='IMG'){el.style.display='none';el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}else if(el.tagName==='LINK'){el.parentNode&&el.parentNode.insertBefore(ph,el.nextSibling);}}document.querySelectorAll('img').forEach(function(img){if(img.complete&&img.naturalWidth===0)mark(img);img.addEventListener('error',function(){mark(img);});});document.addEventListener('error',function(e){var t=e.target;if(t&&(t.tagName==='IMG'||t.tagName==='LINK'||t.tagName==='SCRIPT'))mark(t);},true);})();<\/script></body>
|
|
1159
|
-
</html>`}function
|
|
1160
|
-
`);i.textContent=r(`workspace.lineCount`,{count:d.length});let f=`<table class="workspace-preview-code-table"><tbody>`;for(let e=0;e<d.length;e++)f+=`<tr><td class="line-num">${e+1}</td><td class="line-content"><code class="${u}">${X(d[e])}</code></td></tr>`;f+=`</tbody></table>`,t.innerHTML=f}}else{let c=e.dataset.markdownText||``;if(u)n.classList.add(`active`),n.title=r(`workspace.switchToSourcePreview`),
|
|
1161
|
-
`);i.textContent=r(`workspace.lineCount`,{count:u.length});let d=`<table class="workspace-preview-code-table"><tbody>`;for(let e=0;e<u.length;e++)d+=`<tr><td class="line-num">${e+1}</td><td class="line-content"><code class="${l}">${X(u[e])}</code></td></tr>`;d+=`</tbody></table>`,t.innerHTML=d}}
|
|
1162
|
-
`+r(`workspace.copyMarkdownHint`):t.title=r(`workspace.copyAllTitle`))}async function
|
|
1161
|
+
</html>`}function _v(e,t){let n=gv(t),r=document.createElement(`iframe`);r.setAttribute(`sandbox`,`allow-scripts allow-same-origin allow-popups`),r.setAttribute(`srcdoc`,n),r.className=`workspace-html-preview-frame`,e.innerHTML=``,e.appendChild(r)}function vv(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePreviewFullscreenBtn`),i=e.classList.toggle(`fullscreen`);if(Yn(),i)t.classList.add(`preview-fullscreen`),n.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14"><path d="M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"/></svg>`,n.title=r(`workspace.exitFullscreen`);else{t.classList.remove(`preview-fullscreen`),n.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>`,n.title=r(`workspace.fullscreenPreview`);let e=document.getElementById(`workspacePreviewRail`);e&&e.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove())}}function yv(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePreviewContent`),n=document.getElementById(`workspacePreviewMdToggleBtn`),i=document.getElementById(`workspacePreviewLineCount`),a=document.getElementById(`workspacePreviewCopyBtn`),o=document.getElementById(`workspacePreviewDownloadBtn`),s=document.getElementById(`workspacePreviewExportMenu`),c=document.getElementById(`workspacePreviewOpenBrowserBtn`),l=e.dataset.previewMode||`markdown`;Yn();let u=t.classList.toggle(`markdown-rendered`);if(l===`html`){let l=e.dataset.htmlText||``;if(u)n.classList.add(`active`),n.title=r(`workspace.switchToSourcePreview`),hv(n,!0),a.style.display=``,o&&(o.style.display=`none`),s&&(s.style.display=`none`),c&&(c.style.display=``),i.textContent=``,_v(t,l);else{n.classList.remove(`active`),n.title=r(`workspace.switchToRenderPreview`),hv(n,!1),a.style.display=``,o&&(o.style.display=``),s&&(s.style.display=`none`),c&&(c.style.display=`none`);let u=ey(e.dataset.previewName||``),d=l.split(`
|
|
1162
|
+
`);i.textContent=r(`workspace.lineCount`,{count:d.length});let f=`<table class="workspace-preview-code-table"><tbody>`;for(let e=0;e<d.length;e++)f+=`<tr><td class="line-num">${e+1}</td><td class="line-content"><code class="${u}">${X(d[e])}</code></td></tr>`;f+=`</tbody></table>`,t.innerHTML=f}}else{let c=e.dataset.markdownText||``;if(u)n.classList.add(`active`),n.title=r(`workspace.switchToSourcePreview`),hv(n,!0),a.style.display=``,o&&(o.style.display=`none`),s&&(s.style.display=``),t.innerHTML=`<div class="markdown-body workspace-preview-markdown">${tt(c)}</div>`,xv(t),Sv(t),Qe(),i.textContent=``;else{n.classList.remove(`active`),n.title=r(`workspace.switchToRenderPreview`),hv(n,!1),a.style.display=``,o&&(o.style.display=``),s&&(s.style.display=`none`);let l=ey(e.dataset.previewName||``),u=(c||``).split(`
|
|
1163
|
+
`);i.textContent=r(`workspace.lineCount`,{count:u.length});let d=`<table class="workspace-preview-code-table"><tbody>`;for(let e=0;e<u.length;e++)d+=`<tr><td class="line-num">${e+1}</td><td class="line-content"><code class="${l}">${X(u[e])}</code></td></tr>`;d+=`</tbody></table>`,t.innerHTML=d}}bv(u)}function bv(e){let t=document.getElementById(`workspacePreviewCopyBtn`);t&&(e?t.title=r(`workspace.copyAllTitle`)+`
|
|
1164
|
+
`+r(`workspace.copyMarkdownHint`):t.title=r(`workspace.copyAllTitle`))}async function xv(e){if(typeof mermaid>`u`)return;let t=e.querySelectorAll(`.mermaid`);for(let e of t){if(e.querySelector(`svg`))continue;let t=e.getAttribute(`data-raw-code`),n=t?decodeURIComponent(t):e.textContent||``;try{await mermaid.run({nodes:[e]}),typeof ct==`function`&&ct(e)}catch{e.textContent=n}}}function Sv(e){e.querySelectorAll(`.code-copy-btn`).forEach(e=>{e.dataset.bound||(e.dataset.bound=`true`,e.addEventListener(`click`,t=>{t.stopPropagation();let n=e.closest(`.code-block-container`);if(n){let t=n.querySelector(`pre code`);t&&He(t.textContent||``,e)}}))}),e.dataset.ctrlClickBound||(e.dataset.ctrlClickBound=`true`,e.addEventListener(`click`,e=>{if(!e.ctrlKey&&!e.metaKey||e.button!==0)return;let t=e.target.closest(`code`);if(!t){let n=e.target.closest(`pre`);if(n&&(t=n.querySelector(`code`)),!t){let n=e.target.closest(`.code-block-container`);n&&(t=n.querySelector(`code`))}}if(!t||e.target.closest(`.code-copy-btn`))return;e.preventDefault();let n=t.textContent;n&&navigator.clipboard.writeText(n).then(()=>{F(r(`workspace.codeCopiedToClipboard`),`success`)}).catch(()=>{let e=document.createElement(`textarea`);e.value=n,e.style.position=`fixed`,e.style.left=`-999999px`,document.body.appendChild(e),e.select(),document.execCommand(`copy`),document.body.removeChild(e),F(r(`workspace.codeCopiedToClipboard`),`success`)})}))}async function Cv(e=!1){let t=document.getElementById(`workspacePreviewArea`);if(!e&&t.dataset.editMode===`true`&&t.classList.contains(`has-unsaved`)&&!await Ov(r(`workspace.actionClosePreview`)))return!1;Dv(!1),$h&&=($h.abort(),null);let n=document.getElementById(`workspacePanel`),i=document.getElementById(`workspacePreviewContent`);i.classList.remove(`xlsx-mode`),i.classList.remove(`markdown-rendered`),delete t.dataset.markdownText,delete t.dataset.htmlText,delete t.dataset.previewMode;let a=document.getElementById(`workspacePreviewMdToggleBtn`);if(a&&(a.classList.remove(`active`),a.style.display=`none`,hv(a,!1)),t.classList.contains(`fullscreen`)){t.classList.remove(`fullscreen`),n.classList.remove(`preview-fullscreen`);let e=document.getElementById(`workspacePreviewFullscreenBtn`);e&&(e.innerHTML=`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>`,e.title=r(`workspace.fullscreenPreview`))}Yn();let o=document.getElementById(`workspacePreviewRail`);o&&o.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove()),f_&&=(f_.destroy(),null),p_=1,h_=1,J_&&=(URL.revokeObjectURL(J_),null);let s=document.getElementById(`workspacePreviewExportMenu`);s&&(s.style.display=`none`);let c=document.getElementById(`workspacePreviewCopyBtn`);return c&&(c.title=r(`workspace.copyAllTitle`)),t.style.display=`none`,document.getElementById(`workspacePreviewContent`).innerHTML=``,Qh&&(Qh=!1,py(!1)),!0}function wv(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePreviewContent`),n=document.getElementById(`workspacePreviewEditBtn`),i=document.getElementById(`workspacePreviewSaveBtn`),a=document.getElementById(`workspacePreviewCancelBtn`),o=document.getElementById(`workspacePreviewCopyBtn`),s=document.getElementById(`workspacePreviewDownloadBtn`),c=document.getElementById(`workspacePreviewMdToggleBtn`);document.getElementById(`workspacePreviewFullscreenBtn`);let l=document.getElementById(`workspacePreviewLineCount`),u=document.getElementById(`workspacePreviewFilename`),d=e.dataset.origContent||``;e.dataset.editMode=`true`,i.title=r(`workspace.saveChanges`),i.disabled=!1,o.style.display=`none`,s.style.display=`none`,c.style.display=`none`,n.style.display=`none`;let f=document.getElementById(`workspacePreviewExportMenu`);f&&(f.style.display=`none`),i.style.display=``,a.style.display=``,t.innerHTML=`<textarea class="workspace-preview-editor" id="workspacePreviewEditor" spellcheck="false"></textarea>`;let p=t.querySelector(`#workspacePreviewEditor`);p.value=d,p.focus(),p.setSelectionRange(p.value.length,p.value.length),l.textContent=r(`workspace.lineCount`,{count:d.split(`
|
|
1163
1165
|
`).length}),u.classList.add(`modified`),u.textContent=(e.dataset.previewName||``)+` *`,p.addEventListener(`input`,()=>{p.value===d?(e.classList.remove(`has-unsaved`),l.textContent=r(`workspace.lineCount`,{count:p.value.split(`
|
|
1164
1166
|
`).length})):(e.classList.add(`has-unsaved`),l.textContent=r(`workspace.linesModified`,{count:p.value.split(`
|
|
1165
|
-
`).length}))})}async function
|
|
1167
|
+
`).length}))})}async function Tv(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePreviewEditor`);if(!t)return;let n=e.dataset.previewPath,a=t.value;if(a===(e.dataset.origContent||``)){Ev();return}let o=document.getElementById(`workspacePreviewSaveBtn`),s=o.title;o.title=r(`workspace.saving`),o.disabled=!0;try{let t=await wt(n,a);if(t.success){i.info(`[WorkspacePanel] file save successful:`,n),F(r(`workspace.saveSuccess`)),e.dataset.origContent=a,Dv(!1);let t=e.dataset.previewName;await d_(n,t)}else i.error(`[WorkspacePanel] filesave failed:`,n,t.error),F(r(`workspace.saveFailedWithError`,{error:t.error||r(`workspace.unknownError`)})),o.title=s,o.disabled=!1}catch(e){i.error(`[WorkspacePanel] file saveexception:`,n,e),F(r(`workspace.saveFailedWithError`,{error:e.message||e})),o.title=s,o.disabled=!1}}async function Ev(){let e=document.getElementById(`workspacePreviewArea`);if(e.classList.contains(`has-unsaved`)&&!await Ov(r(`workspace.actionCancelEdit`)))return;Dv(!0);let t=e.dataset.previewPath,n=e.dataset.previewName;t&&n&&await d_(t,n)}function Dv(e){let t=document.getElementById(`workspacePreviewArea`),n=document.getElementById(`workspacePreviewFilename`),r=document.getElementById(`workspacePreviewSaveBtn`),i=document.getElementById(`workspacePreviewCancelBtn`);delete t.dataset.editMode,t.classList.remove(`has-unsaved`),n.classList.remove(`modified`),r.style.display=`none`,i.style.display=`none`}async function Ov(e){return typeof window.showCustomConfirm==`function`?await window.showCustomConfirm(r(`workspace.discardChangesPrompt`,{action:e}),r(`workspace.unsavedChanges`)):window.confirm(r(`workspace.discardChangesPrompt`,{action:e}))}function kv(e){let t=document.getElementById(`workspacePreviewArea`);if(t.style.display===`none`)return;if(t.dataset.editMode===`true`){(e.ctrlKey||e.metaKey)&&e.key===`s`&&(e.preventDefault(),Tv()),e.key===`Escape`&&(e.preventDefault(),Ev());return}let n=(e.target?.tagName||``).toLowerCase();if(n===`input`||n===`textarea`||e.target?.isContentEditable)return;let r=t.dataset.previewType;if(!(r!==`pdf`&&r!==`pptx`)){if(e.key===`ArrowLeft`){e.preventDefault();let t=document.getElementById(r===`pdf`?`pdfPrevPage`:`pptxPrevSlide`);t&&!t.disabled&&t.click()}else if(e.key===`ArrowRight`){e.preventDefault();let t=document.getElementById(r===`pdf`?`pdfNextPage`:`pptxNextSlide`);t&&!t.disabled&&t.click()}}}async function Av(e,t){if(Yh)return;Yh=!0,Fv(!0);let n=Lv(e),i=new AbortController,a=[],o=()=>{if(a.length<2)return 0;let e=a[0],t=a[a.length-1],n=(t.time-e.time)/1e3;return n<=0?0:(t.loaded-e.loaded)/n},s=Vv(()=>i.abort());s.classList.add(`download-mode`),Hv(s,{percent:0,fileName:t,loaded:0,totalBytes:0,speed:0});try{let c=await Vt(e,({loaded:e,total:r,percent:i})=>{Rv(n,i);let c=Date.now();a.push({time:c,loaded:e}),a.length>8&&a.shift(),Hv(s,{percent:i,fileName:t,loaded:e,totalBytes:r,speed:o()})},i.signal);if(c.aborted){Uv(s,r(`workspace.downloadCanceled`),!0),F(r(`workspace.downloadCanceled`),`info`);return}if(!c.success){Uv(s,r(`workspace.downloadFailed`),!0),F(r(`workspace.downloadFailedWithError`,{error:c.error}),`error`);return}Mv(c.blob,c.name||t),Hv(s,{percent:100,fileName:t,loaded:c.blob.size,totalBytes:c.blob.size,speed:0,statusText:r(`workspace.savingToLocal`)}),setTimeout(()=>{Uv(s,r(`workspace.savedToLocal`),!1)},1500),F(r(`workspace.downloaded`,{name:c.name||t}),`success`)}catch(e){e.name===`AbortError`?(Uv(s,r(`workspace.downloadCanceled`),!0),F(r(`workspace.downloadCanceled`),`info`)):(Uv(s,r(`workspace.downloadFailed`),!0),F(r(`workspace.downloadFailedWithError`,{error:e.message}),`error`))}finally{setTimeout(()=>zv(n),600),Yh=!1,Fv(!1)}}async function jv(){if(J.size===0||Yh)return;let e=Array.from(J);if(e.length===1){let t=e[0].split(/[\\/]/).pop();await Av(e[0],t);return}Yh=!0,Fv(!0);let t=new AbortController,n=[],i=()=>{if(n.length<2)return 0;let e=n[0],t=n[n.length-1],r=(t.time-e.time)/1e3;return r<=0?0:(t.loaded-e.loaded)/r},a=r(`workspace.fileCount`,{count:e.length}),o=Vv(()=>t.abort());o.classList.add(`download-mode`),Hv(o,{percent:0,fileName:a,loaded:0,totalBytes:0,speed:0});try{let s=await jt(e,({loaded:e,total:t,percent:r})=>{let s=Date.now();n.push({time:s,loaded:e}),n.length>8&&n.shift(),Hv(o,{percent:r,fileName:a,loaded:e,totalBytes:t,speed:i()})},t.signal);if(s.aborted){Uv(o,r(`workspace.downloadCanceled`),!0),F(r(`workspace.downloadCanceled`),`info`);return}s.success&&s.blob?(Mv(s.blob,s.name||`workspace.zip`),Uv(o,r(`workspace.downloadedCount`,{count:e.length}),!1),F(r(`workspace.downloadedZip`,{count:e.length}),`success`)):(Uv(o,r(`workspace.downloadFailed`),!0),F(r(`workspace.downloadFailedWithError`,{error:s.error||r(`workspace.unknownError`)}),`error`))}catch(e){e.name===`AbortError`?(Uv(o,r(`workspace.downloadCanceled`),!0),F(r(`workspace.downloadCanceled`),`info`)):(Uv(o,r(`workspace.downloadFailed`),!0),F(r(`workspace.downloadFailedWithError`,{error:e.message}),`error`))}finally{Yh=!1,Fv(!1)}}function Mv(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);r.href=n,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>URL.revokeObjectURL(n),6e4)}function Nv(){let e=document.getElementById(`workspaceFileInput`);e&&e.click()}async function Pv(e){let t=e.target.files;if(!t||t.length===0)return;let n=Array.from(t);e.target.value=``,await Gv(n)}function Fv(e){document.querySelectorAll(`.workspace-file-btn.download`).forEach(t=>{t.disabled=e});let t=document.getElementById(`workspaceDownloadDirBtn`);t&&(t.disabled=e||J.size===0);let n=document.getElementById(`workspacePreviewDownloadBtn`);n&&(n.disabled=e)}var Iv=new Map;function Lv(e){return Iv.set(e,0),Bv(),e}function Rv(e,t){if(!e)return;let n=e;Iv.set(n,t);let r=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(e=>e.dataset.path===n);if(r){let e=r.querySelector(`.workspace-file-progress`);e||(e=document.createElement(`div`),e.className=`workspace-file-progress`,e.innerHTML=`<div class="workspace-file-progress-bar"></div>`,r.appendChild(e));let n=e.querySelector(`.workspace-file-progress-bar`);n&&(n.style.width=t+`%`)}}function zv(e){if(!e)return;let t=e;Iv.delete(t);let n=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(e=>e.dataset.path===t);if(n){let e=n.querySelector(`.workspace-file-progress`);e&&e.remove()}}function Bv(){for(let[e,t]of Iv){let n=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.path===e);if(n&&!n.querySelector(`.workspace-file-progress`)){let e=document.createElement(`div`);e.className=`workspace-file-progress`,e.innerHTML=`<div class="workspace-file-progress-bar" style="width:${t}%"></div>`,n.appendChild(e)}}}function Vv(e){let t=document.createElement(`div`);t.className=`workspace-upload-progress`,t.innerHTML=`
|
|
1166
1168
|
<div class="workspace-upload-progress-header">
|
|
1167
1169
|
<span class="workspace-upload-progress-title">${r(`workspace.uploading`)}</span>
|
|
1168
1170
|
<button class="workspace-upload-progress-cancel" title="${r(`workspace.cancelUpload`)}">
|
|
@@ -1179,8 +1181,8 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1179
1181
|
<span class="workspace-upload-progress-bytes"></span>
|
|
1180
1182
|
<span class="workspace-upload-progress-speed"></span>
|
|
1181
1183
|
</div>
|
|
1182
|
-
`,document.body.appendChild(t);let n=t.querySelector(`.workspace-upload-progress-cancel`);return n&&n.addEventListener(`click`,()=>{n.style.display=`none`,typeof e==`function`&&e()}),t}function Rv(e,t){if(!e)return;let{percent:n,completed:i,total:a,fileName:o,loaded:s,totalBytes:c,speed:l,statusText:u}=t,d=e.querySelector(`.workspace-upload-progress-title`),f=e.querySelector(`.workspace-upload-progress-file`),p=e.querySelector(`.workspace-upload-progress-bar`),m=e.querySelector(`.workspace-upload-progress-bytes`),h=e.querySelector(`.workspace-upload-progress-speed`),g=e.classList.contains(`download-mode`)?r(`workspace.downloadInProgress`):r(`workspace.uploadInProgress`);d&&(u?d.textContent=u:i!=null&&a!=null?d.textContent=`${g} ${i}/${a} · ${n}%`:d.textContent=`${g} ${n}%`),f&&o&&(f.textContent=o,f.title=o),p&&(p.style.width=n+`%`),m&&(s!=null&&c!=null&&c>0?m.textContent=`${Rt(s)} / ${Rt(c)}`:s!=null&&(m.textContent=Rt(s))),h&&(h.textContent=l>0?`${Rt(l)}/s`:``)}function zv(e,t,n){if(!e)return;let r=e.querySelector(`.workspace-upload-progress-title`),i=e.querySelector(`.workspace-upload-progress-cancel`),a=e.querySelector(`.workspace-upload-progress-bar`);i&&(i.style.display=`none`),r&&(r.textContent=t),a&&!n&&(a.style.width=`100%`),e.classList.add(`workspace-upload-progress-done`),n&&e.classList.add(`workspace-upload-progress-error`),setTimeout(()=>{try{e.remove()}catch{}},1500)}function Bv(e){let t=document.getElementById(`workspaceUploadBtn`);t&&(t.disabled=e,e?(t.dataset.originalHtml=t.innerHTML,t.innerHTML=`<span class="workspace-upload-spinner"></span>`):t.dataset.originalHtml&&(t.innerHTML=t.dataset.originalHtml,delete t.dataset.originalHtml));let n=document.getElementById(`workspacePanel`);n&&n.classList.toggle(`upload-in-progress`,e)}async function Vv(e){let t=Array.from(e);if(t.length===0||Kh)return;Kh=!0,Bv(!0);let n=await Mt();if(!n){F(r(`workspace.agentNotConnectedUpload`),`error`),Kh=!1,Bv(!1);return}let i=new Set;try{let e=await At(q);e.success&&Array.isArray(e.entries)&&(i=new Set(e.entries.map(e=>e.name)))}catch{}let a=0,o=0,s=0,c=t.reduce((e,t)=>e+t.size,0),l=Array(t.length).fill(0),u=new Set,d=!1,f=``,p=[],m=()=>{if(p.length<2)return 0;let e=p[0],t=p[p.length-1],n=(t.time-e.time)/1e3;return n<=0?0:(t.loaded-e.loaded)/n},h=Lv(()=>{d=!0;for(let e of u)try{e.abort()}catch{}u.clear()}),g=e=>{e&&(f=e);let n=l.reduce((e,t)=>e+t,0),r=c>0?Math.round(n/c*100):0,i=Date.now();p.push({time:i,loaded:n}),p.length>8&&p.shift(),Rv(h,{percent:r,completed:a+o+s,total:t.length,fileName:f,loaded:n,totalBytes:c,speed:m()})};g();for(let e=0;e<t.length&&!d;e+=3){let c=t.slice(e,e+3),f=await Promise.allSettled(c.map(async(t,a)=>{let o=e+a,s=tg(t.name),c=Og(`${q}/${s}`);if(i.has(s))throw l[o]=t.size,g(s),Error(`__SKIPPED__`);if(d)throw Error(`__CANCELLED__`);await new Promise((e,i)=>{let a=new XMLHttpRequest;u.add(a);let s=`${n.url}/api/fs/upload-stream?path=${encodeURIComponent(c)}`;a.open(`POST`,s);for(let[e,t]of Object.entries(Bt(n)))a.setRequestHeader(e,t);a.upload.onprogress=e=>{e.lengthComputable&&(l[o]=e.loaded,g(t.name))},a.onload=()=>{if(u.delete(a),d){i(Error(`__CANCELLED__`));return}if(a.status>=200&&a.status<300)try{let n=JSON.parse(a.responseText);n.success?(l[o]=t.size,g(t.name),e()):i(Error(n.error||r(`workspace.uploadFailed`)))}catch{i(Error(r(`workspace.parseResponseFailed`)))}else try{let e=JSON.parse(a.responseText);i(Error(e.error||r(`workspace.uploadFailedWithStatus`,{status:a.status})))}catch{i(Error(r(`workspace.uploadFailedWithStatus`,{status:a.status})))}},a.onerror=()=>{u.delete(a),i(Error(d?`__CANCELLED__`:r(`workspace.networkError`)))},a.onabort=()=>{u.delete(a),i(Error(`__CANCELLED__`))},a.send(t)})}));for(let e of f)if(e.status===`fulfilled`)a++;else{let t=e.reason&&e.reason.message?e.reason.message:``;t.includes(`__SKIPPED__`)||t.includes(`已存在`)?o++:t.includes(`__CANCELLED__`)||s++}}let _,v=!1;if(d)_=r(`workspace.uploadCanceled`),v=!0;else{let e=[];a>0&&e.push(r(`workspace.uploadSuccessCount`,{count:a})),o>0&&e.push(r(`workspace.uploadSkippedCount`,{count:o})),s>0&&e.push(r(`workspace.uploadFailedCount`,{count:s})),_=e.length>0?r(`workspace.uploadCompleteWithStats`,{stats:e.join(` / `)}):r(`workspace.uploadComplete`),v=s>0}zv(h,_,v),a>0&&F(r(`workspace.uploadedFiles`,{count:a}),`success`),o>0&&F(r(`workspace.filesSkipped`,{count:o}),`info`),s>0&&F(r(`workspace.filesUploadFailed`,{count:s}),`error`),d&&F(r(`workspace.uploadCanceled`),`info`),Kh=!1,Bv(!1),a>0&&(await Kv(),zy(t[t.length-1].name))}function Hv(){let e=document.getElementById(`workspacePanel`);if(!e)return;let t=document.getElementById(`workspacePanelContent`);t.addEventListener(`dragstart`,e=>{let t=e.target.closest(`.workspace-file-item`);if(!t)return;let n=t.dataset.path,r=t.dataset.name;e.dataTransfer.setData(`application/x-workspace-move`,JSON.stringify({path:n,name:r})),e.dataTransfer.effectAllowed=`move`,t.classList.add(`dragging`);let i=()=>{t.classList.remove(`dragging`),t.removeEventListener(`dragend`,i)};t.addEventListener(`dragend`,i)}),t.addEventListener(`dragover`,n=>{n.preventDefault(),n.stopPropagation();let r=n.target.closest(`.workspace-file-item.directory`);t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),r?(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(`application/x-workspace-move`)?`move`:`copy`,r.classList.add(`drop-target`),e.classList.remove(`drag-over`)):n.dataTransfer.types.includes(`application/x-workspace-move`)||e.classList.add(`drag-over`)}),t.addEventListener(`dragleave`,n=>{n.preventDefault(),n.stopPropagation(),t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),e.classList.remove(`drag-over`)}),t.addEventListener(`drop`,async n=>{n.preventDefault(),n.stopPropagation();let i=n.target.closest(`.workspace-file-item.directory`);if(t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),e.classList.remove(`drag-over`),i&&n.dataTransfer.types.includes(`application/x-workspace-move`)){try{let e=JSON.parse(n.dataTransfer.getData(`application/x-workspace-move`)),t=e.path,a=i.dataset.path,o=e.name,s=Og(t),c=Og(a);if(s===c)return;if(s.startsWith(c+`/`)){F(r(`workspace.cannotMoveToSubdir`),`error`);return}F(r(`workspace.moving`),`info`);let l=await Et(t,a);if(l.success){F(r(`workspace.movedToDir`,{name:o}),`success`),kg(q),kg(a);let e=a.split(/[\\/]/).pop();await Kv(),zy(e)}else F(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){F(r(`workspace.moveFailed`,{error:e.message}),`error`)}return}if(i&&n.dataTransfer.files&&n.dataTransfer.files.length>0){let e=i.dataset.path;e.split(/[\\/]/).pop(),eg(q),q=e,await Vv(n.dataTransfer.files),qv(),Jv();return}if(n.dataTransfer.files&&n.dataTransfer.files.length>0){await Vv(n.dataTransfer.files);return}}),e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),!t.dataTransfer.types.includes(`application/x-workspace-move`)&&e.classList.add(`drag-over`)}),e.addEventListener(`dragleave`,t=>{t.preventDefault(),t.stopPropagation(),!t.dataTransfer.types.includes(`application/x-workspace-move`)&&e.classList.remove(`drag-over`)}),e.addEventListener(`drop`,async t=>{if(t.preventDefault(),t.stopPropagation(),t.dataTransfer.types.includes(`application/x-workspace-move`))return;e.classList.remove(`drag-over`);let n=t.dataTransfer.files;!n||n.length===0||await Vv(n)})}async function Uv(){try{let e=document.getElementById(`workspaceAgentName`);if(!e)return;let t=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=t.pairedAgents||[],r=t.activeAgentId;if(r){let t=n.find(e=>e.id===r);if(t&&t.name){e.textContent=` · ${t.name}`,e.style.display=``;return}}e.textContent=``,e.style.display=`none`}catch(e){i.debug(`[WorkspacePanel] update agentname failed:`,e)}}async function Wv(e,t){if(t===`local`&&!(!e.pairedAgents&&!e.activeAgentId)&&(await Uv(),e.activeAgentId?.newValue!==e.activeAgentId?.oldValue)){i.debug(`[WorkspacePanel] Agent changed,refreshworking directory`),St(),kh=null,q=null,Ah=[],J.clear(),uy=``,dy=[],fy=!1,Sg.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await bg()}}async function Gv(){if(Ah.length===0)return;let e=Ah.pop();J.clear(),await xg(e)}async function Kv(e){if(!q){let e=kh||await qt();if(!e){F(r(`workspace.refreshFailed`),`error`);return}kh=e,q=e}if(kg(q),J.clear(),Vy(),fy&&uy?(dy=await Tt(q,uy),Lg()):await Dg(q),yv(),Jg(),e!==void 0){let t=document.getElementById(`workspacePanelContent`);t&&requestAnimationFrame(()=>{t.scrollTop=e})}}function qv(){let e=document.getElementById(`workspaceBreadcrumb`);if(!q){e.innerHTML=``;return}let t=Og(q).split(`/`).filter(Boolean),n=kh?Og(kh).replace(/\/$/,``):null,i=``,a=``;for(let e=0;e<t.length;e++){a=e===0?/^[a-zA-Z]:$/.test(t[e])?t[e]+`/`:`/`+t[e]:(a.endsWith(`/`)?a:a+`/`)+t[e];let r=e===t.length-1,o=!n||a===n||a.startsWith(n+`/`);e>0&&(i+=`<span class="workspace-breadcrumb-sep">/</span>`),r?i+=`<span class="workspace-breadcrumb-current">${X(t[e])}</span>`:o?i+=`<span class="workspace-breadcrumb-link" data-path="${X(a)}">${X(t[e])}</span>`:i+=`<span class="workspace-breadcrumb-disabled">${X(t[e])}</span>`}e.innerHTML=i||`<span class="workspace-breadcrumb-current">/</span>`,e.querySelectorAll(`.workspace-breadcrumb-link`).forEach(e=>{e.addEventListener(`click`,async t=>{t.stopPropagation();let n=e.dataset.path,r=Ah.findIndex(e=>e===n);Ah=r>=0?Ah.slice(0,r):[],J.clear(),await xg(n)}),e.addEventListener(`dragover`,t=>{t.dataTransfer.types.includes(`application/x-workspace-move`)&&(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`,e.classList.add(`drop-target`))}),e.addEventListener(`dragleave`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.remove(`drop-target`)}),e.addEventListener(`drop`,async t=>{if(t.preventDefault(),t.stopPropagation(),e.classList.remove(`drop-target`),t.dataTransfer.types.includes(`application/x-workspace-move`))try{let n=JSON.parse(t.dataTransfer.getData(`application/x-workspace-move`)),i=n.path,a=e.dataset.path,o=n.name,s=Og(i),c=Og(a);if(s===c)return;if(c.startsWith(s+`/`)){F(r(`workspace.cannotMoveToSubdir`),`error`);return}F(r(`workspace.moving`),`info`);let l=await Et(i,a);l.success?(F(r(`workspace.movedToTarget`,{name:o,target:a.split(/[\\/]/).pop()}),`success`),kg(q),kg(a),await Kv()):F(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){F(r(`workspace.moveFailed`,{error:e.message}),`error`)}})})}function Jv(){let e=document.getElementById(`workspaceBackBtn`);e.disabled=!(kh&&q&&q!==kh)}function Yv(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-error">${X(e)}</div>`}function X(e){return e?String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`):``}function Xv(e){let t=(e.split(`.`).pop()||``).toLowerCase(),n={js:`javascript`,mjs:`javascript`,ts:`typescript`,jsx:`jsx`,tsx:`tsx`,html:`html`,htm:`html`,css:`css`,scss:`scss`,less:`less`,json:`json`,xml:`xml`,yaml:`yaml`,yml:`yaml`,py:`python`,java:`java`,c:`c`,cpp:`cpp`,h:`c`,go:`go`,rs:`rust`,rb:`ruby`,php:`php`,sql:`sql`,sh:`bash`,bash:`bash`,zsh:`bash`,md:`markdown`,vue:`html`,svelte:`html`};return n[t]?`language-${n[t]}`:``}async function Zv(){q&&await Dg(q)}async function Qv(){St(),kh=null,q=null,Ah=[],J.clear(),uy=``,dy=[],fy=!1,Sg.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await bg()}function $v(e){let t=document.getElementById(`workspacePanelContainer`);if(t)if(e){t.style.display=``;let e=document.getElementById(`workspacePanel`),n=!!(e&&e.classList.contains(`expanded`));zh&&e&&!n?_g().catch(e=>i.warn(`[WorkspacePanel] reopen panel after reconnect failed`,e)):n&&!q&&bg().catch(e=>i.warn(`[WorkspacePanel] navigate after reconnect failed`,e)),Vh&&hg()}else t.style.display=`none`,ly(!0)}function ey(e,t){let n=t.toLowerCase(),r=e.toLowerCase();return r===n?``:r.startsWith(n+`/`)?e.substring(t.length+1):null}function ty(e,t){let n=t.split(`/`).filter(Boolean).pop();if(!n)return null;let r=e.lastIndexOf(`/`+n);if(r===-1)return null;let i=e.substring(r+n.length+1);return i===``?``:i}function ny(e,t){if(!e)return null;let n=Og(t);if(!n)return null;let r=Og(e).trim();if(!r||r===`.`||r===`~`||r.startsWith(`~/`))return null;if(!(r.startsWith(`/`)||/^[a-zA-Z]:\//.test(r)))return n+`/`+r;let i=ey(r,n);return i===null&&(i=ty(r,n)),i===null?null:i===``?n:n+`/`+i}async function ry(e){if(!(e===`~`||e&&e.startsWith(`~/`)))return e;try{let t=await Ft();if(t)return Og(e===`~`?t:t+`/`+e.slice(2))}catch{}return e}async function iy(e){if(!e)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);if(!t||!n)return;if(t.classList.add(`expanded`),Ie(t),n.classList.add(`click-opened`),kh||=await qt(),!kh){Yv(r(`workspace.noWorkspace`));return}let i=ny(await ry(e),kh);if(!i){Yv(r(`artifacts.locateFailed`));return}let a=i.lastIndexOf(`/`),o=a>0?i.substring(0,a):kh,s=a>0?i.substring(a+1):i;kg(o),await xg(o);let c=e=>{let t=()=>{let t=null;return document.querySelectorAll(`.workspace-file-item`).forEach(n=>{n.dataset.name===e&&(t=n)}),t},n=t();if(n||!Ng)return n;let r=Ng.sorted.findIndex(t=>t.name===e);if(r<0)return null;let i=document.getElementById(`workspacePanelContent`);if(!i)return null;let{itemHeight:a}=Ng;return i.scrollTop=Math.max(0,r*a-i.clientHeight/2+a/2),Ig(),t()};setTimeout(async()=>{let e=c(s);e||=(kg(o),await xg(o),await new Promise(e=>setTimeout(e,300)),c(s)),e?(e.classList.add(`highlighted`),e.scrollIntoView({behavior:`smooth`,block:`center`}),setTimeout(()=>e.classList.remove(`highlighted`),3e3)):F(r(`artifacts.fileNotFound`))},300)}async function ay(e,t){if(!e)return;let n=document.getElementById(`workspacePanel`),i=document.getElementById(`workspacePanelContainer`);if(!n||!i)return;let a=n.classList.contains(`expanded`);if(n.classList.add(`expanded`),Ie(n),i.classList.add(`click-opened`),kh||=await qt(),!kh){Yv(r(`workspace.noWorkspace`));return}let o=ny(await ry(e),kh);if(!o){Yv(r(`artifacts.locateFailed`));return}await yv(!0),await s_(o,t),Jh=!a}async function oy(){await yv(!0)}function sy(){ly(!0)}async function cy(e){return!e||(kh||=await qt(),!kh)?null:ny(await ry(e),kh)}async function ly(e=!1){if(e&&await yv(!0)===!1)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);t&&(Tn(t),t.classList.remove(`expanded`),Re(t),e||chrome.storage.local.set({[Rh]:!1}).catch(()=>{})),n&&(n.classList.remove(`hover-expanded`),n.classList.remove(`click-opened`),zh&&!e&&(zh=!1,Vh=!1,n.classList.add(`closing-no-anim`),lg(),requestAnimationFrame(()=>n.classList.remove(`closing-no-anim`))))}var uy=``,dy=[],fy=!1,py=[],my=-1;function hy(){try{chrome.storage.local.get([`workspaceSearchHistory`],e=>{py=e.workspaceSearchHistory||[]})}catch{}}function gy(e){if(!e.trim())return;let t=py.indexOf(e);t!==-1&&py.splice(t,1),py.push(e),py.length>20&&py.shift();try{chrome.storage.local.set({workspaceSearchHistory:py})}catch{}}function _y(e){uy=e.target.value.trim();let t=document.getElementById(`workspaceSearchClear`);t.style.display=uy?``:`none`}async function vy(){if(!uy){fy=!1,dy=[],Lg(),Jg();return}gy(uy),my=-1,F(r(`workspace.searching`),`info`),dy=await Tt(q,uy),fy=!0,Lg(),Jg()}async function yy(){let e=document.getElementById(`workspaceSearchInput`),t=document.getElementById(`workspaceToolbar`),n=t.querySelector(`.workspace-search-box`);e.value=``,uy=``,fy=!1,dy=[],J.clear(),document.getElementById(`workspaceSearchClear`).style.display=`none`,t.classList.remove(`search-focused`),n.classList.remove(`search-box-expanded`),e.blur(),await Dg(q),Jg(),Vy()}async function by(e,t,n){let i=n===`directory`,a=r(i?`workspace.confirmDeleteDir`:`workspace.confirmDeleteFile`,{name:t,path:e});if(typeof window.showCustomConfirm!=`function`){if(!confirm(a))return}else if(!await window.showCustomConfirm(a,r(`workspace.confirmDeleteTitle`)))return;let o=document.getElementById(`workspacePanelContent`),s=o?o.scrollTop:0;try{let t=await Mt();if(!t){F(r(`workspace.agentNotConnected`),`error`);return}let n=await(await fetch(`${t.url}/api/fs/delete`,{method:`POST`,headers:{"Content-Type":`application/json`,...Bt(t)},body:JSON.stringify({path:e})})).json();n.success?(F(r(i?`workspace.dirDeleted`:`workspace.fileDeleted`),`success`),J.delete(e),Vy(),await Kv(s)):F(r(`workspace.deleteFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}catch(e){F(r(`workspace.deleteFailedWithError`,{error:e.message}),`error`)}}async function xy(){if(J.size===0)return;let e=Array.from(J),t=e.map(e=>{let t=$h.find(t=>t.path===e)||dy.find(t=>t.fullPath===e);return t?t.name:e.split(/[\\/]/).pop()}),n=t.slice(0,5).map(e=>`• ${e}`).join(`
|
|
1183
|
-
`)+(t.length>5?r(`workspace.batchNamesMore`,{count:t.length}):``),i=r(`workspace.confirmBatchDelete`,{count:e.length,names:n});if(typeof window.showCustomConfirm!=`function`){if(!confirm(i))return}else if(!await window.showCustomConfirm(i,r(`workspace.confirmBatchDeleteTitle`)))return;let a=document.getElementById(`workspacePanelContent`),o=a?a.scrollTop:0;try{let t=await Mt();if(!t){F(r(`workspace.agentNotConnected`),`error`);return}let n=0,i=0;for(let r of e)try{(await(await fetch(`${t.url}/api/fs/delete`,{method:`POST`,headers:{"Content-Type":`application/json`,...Bt(t)},body:JSON.stringify({path:r})})).json()).success?(J.delete(r),n++):i++}catch{i++}n>0?(F(r(`workspace.deletedCount`,{success:n,failed:i>0?r(`workspace.deletedCountFailed`,{count:i}):``}),i>0?`warning`:`success`),
|
|
1184
|
+
`,document.body.appendChild(t);let n=t.querySelector(`.workspace-upload-progress-cancel`);return n&&n.addEventListener(`click`,()=>{n.style.display=`none`,typeof e==`function`&&e()}),t}function Hv(e,t){if(!e)return;let{percent:n,completed:i,total:a,fileName:o,loaded:s,totalBytes:c,speed:l,statusText:u}=t,d=e.querySelector(`.workspace-upload-progress-title`),f=e.querySelector(`.workspace-upload-progress-file`),p=e.querySelector(`.workspace-upload-progress-bar`),m=e.querySelector(`.workspace-upload-progress-bytes`),h=e.querySelector(`.workspace-upload-progress-speed`),g=e.classList.contains(`download-mode`)?r(`workspace.downloadInProgress`):r(`workspace.uploadInProgress`);d&&(u?d.textContent=u:i!=null&&a!=null?d.textContent=`${g} ${i}/${a} · ${n}%`:d.textContent=`${g} ${n}%`),f&&o&&(f.textContent=o,f.title=o),p&&(p.style.width=n+`%`),m&&(s!=null&&c!=null&&c>0?m.textContent=`${Rt(s)} / ${Rt(c)}`:s!=null&&(m.textContent=Rt(s))),h&&(h.textContent=l>0?`${Rt(l)}/s`:``)}function Uv(e,t,n){if(!e)return;let r=e.querySelector(`.workspace-upload-progress-title`),i=e.querySelector(`.workspace-upload-progress-cancel`),a=e.querySelector(`.workspace-upload-progress-bar`);i&&(i.style.display=`none`),r&&(r.textContent=t),a&&!n&&(a.style.width=`100%`),e.classList.add(`workspace-upload-progress-done`),n&&e.classList.add(`workspace-upload-progress-error`),setTimeout(()=>{try{e.remove()}catch{}},1500)}function Wv(e){let t=document.getElementById(`workspaceUploadBtn`);t&&(t.disabled=e,e?(t.dataset.originalHtml=t.innerHTML,t.innerHTML=`<span class="workspace-upload-spinner"></span>`):t.dataset.originalHtml&&(t.innerHTML=t.dataset.originalHtml,delete t.dataset.originalHtml));let n=document.getElementById(`workspacePanel`);n&&n.classList.toggle(`upload-in-progress`,e)}async function Gv(e){let t=Array.from(e);if(t.length===0||Xh)return;Xh=!0,Wv(!0);let n=await Mt();if(!n){F(r(`workspace.agentNotConnectedUpload`),`error`),Xh=!1,Wv(!1);return}let i=new Set;try{let e=await At(q);e.success&&Array.isArray(e.entries)&&(i=new Set(e.entries.map(e=>e.name)))}catch{}let a=0,o=0,s=0,c=t.reduce((e,t)=>e+t.size,0),l=Array(t.length).fill(0),u=new Set,d=!1,f=``,p=[],m=()=>{if(p.length<2)return 0;let e=p[0],t=p[p.length-1],n=(t.time-e.time)/1e3;return n<=0?0:(t.loaded-e.loaded)/n},h=Vv(()=>{d=!0;for(let e of u)try{e.abort()}catch{}u.clear()}),g=e=>{e&&(f=e);let n=l.reduce((e,t)=>e+t,0),r=c>0?Math.round(n/c*100):0,i=Date.now();p.push({time:i,loaded:n}),p.length>8&&p.shift(),Hv(h,{percent:r,completed:a+o+s,total:t.length,fileName:f,loaded:n,totalBytes:c,speed:m()})};g();for(let e=0;e<t.length&&!d;e+=3){let c=t.slice(e,e+3),f=await Promise.allSettled(c.map(async(t,a)=>{let o=e+a,s=ag(t.name),c=Mg(`${q}/${s}`);if(i.has(s))throw l[o]=t.size,g(s),Error(`__SKIPPED__`);if(d)throw Error(`__CANCELLED__`);await new Promise((e,i)=>{let a=new XMLHttpRequest;u.add(a);let s=`${n.url}/api/fs/upload-stream?path=${encodeURIComponent(c)}`;a.open(`POST`,s);for(let[e,t]of Object.entries(Bt(n)))a.setRequestHeader(e,t);a.upload.onprogress=e=>{e.lengthComputable&&(l[o]=e.loaded,g(t.name))},a.onload=()=>{if(u.delete(a),d){i(Error(`__CANCELLED__`));return}if(a.status>=200&&a.status<300)try{let n=JSON.parse(a.responseText);n.success?(l[o]=t.size,g(t.name),e()):i(Error(n.error||r(`workspace.uploadFailed`)))}catch{i(Error(r(`workspace.parseResponseFailed`)))}else try{let e=JSON.parse(a.responseText);i(Error(e.error||r(`workspace.uploadFailedWithStatus`,{status:a.status})))}catch{i(Error(r(`workspace.uploadFailedWithStatus`,{status:a.status})))}},a.onerror=()=>{u.delete(a),i(Error(d?`__CANCELLED__`:r(`workspace.networkError`)))},a.onabort=()=>{u.delete(a),i(Error(`__CANCELLED__`))},a.send(t)})}));for(let e of f)if(e.status===`fulfilled`)a++;else{let t=e.reason&&e.reason.message?e.reason.message:``;t.includes(`__SKIPPED__`)||t.includes(`已存在`)?o++:t.includes(`__CANCELLED__`)||s++}}let _,v=!1;if(d)_=r(`workspace.uploadCanceled`),v=!0;else{let e=[];a>0&&e.push(r(`workspace.uploadSuccessCount`,{count:a})),o>0&&e.push(r(`workspace.uploadSkippedCount`,{count:o})),s>0&&e.push(r(`workspace.uploadFailedCount`,{count:s})),_=e.length>0?r(`workspace.uploadCompleteWithStats`,{stats:e.join(` / `)}):r(`workspace.uploadComplete`),v=s>0}Uv(h,_,v),a>0&&F(r(`workspace.uploadedFiles`,{count:a}),`success`),o>0&&F(r(`workspace.filesSkipped`,{count:o}),`info`),s>0&&F(r(`workspace.filesUploadFailed`,{count:s}),`error`),d&&F(r(`workspace.uploadCanceled`),`info`),Xh=!1,Wv(!1),a>0&&(await Xv(),Uy(t[t.length-1].name))}function Kv(){let e=document.getElementById(`workspacePanel`);if(!e)return;let t=document.getElementById(`workspacePanelContent`);t.addEventListener(`dragstart`,e=>{let t=e.target.closest(`.workspace-file-item`);if(!t)return;let n=t.dataset.path,r=t.dataset.name;e.dataTransfer.setData(`application/x-workspace-move`,JSON.stringify({path:n,name:r})),e.dataTransfer.effectAllowed=`move`,t.classList.add(`dragging`);let i=()=>{t.classList.remove(`dragging`),t.removeEventListener(`dragend`,i)};t.addEventListener(`dragend`,i)}),t.addEventListener(`dragover`,n=>{n.preventDefault(),n.stopPropagation();let r=n.target.closest(`.workspace-file-item.directory`);t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),r?(n.dataTransfer.dropEffect=n.dataTransfer.types.includes(`application/x-workspace-move`)?`move`:`copy`,r.classList.add(`drop-target`),e.classList.remove(`drag-over`)):n.dataTransfer.types.includes(`application/x-workspace-move`)||e.classList.add(`drag-over`)}),t.addEventListener(`dragleave`,n=>{n.preventDefault(),n.stopPropagation(),t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),e.classList.remove(`drag-over`)}),t.addEventListener(`drop`,async n=>{n.preventDefault(),n.stopPropagation();let i=n.target.closest(`.workspace-file-item.directory`);if(t.querySelectorAll(`.workspace-file-item.directory.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),e.classList.remove(`drag-over`),i&&n.dataTransfer.types.includes(`application/x-workspace-move`)){try{let e=JSON.parse(n.dataTransfer.getData(`application/x-workspace-move`)),t=e.path,a=i.dataset.path,o=e.name,s=Mg(t),c=Mg(a);if(s===c)return;if(s.startsWith(c+`/`)){F(r(`workspace.cannotMoveToSubdir`),`error`);return}F(r(`workspace.moving`),`info`);let l=await Et(t,a);if(l.success){F(r(`workspace.movedToDir`,{name:o}),`success`),Ng(q),Ng(a);let e=a.split(/[\\/]/).pop();await Xv(),Uy(e)}else F(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){F(r(`workspace.moveFailed`,{error:e.message}),`error`)}return}if(i&&n.dataTransfer.files&&n.dataTransfer.files.length>0){let e=i.dataset.path;e.split(/[\\/]/).pop(),ig(q),q=e,await Gv(n.dataTransfer.files),Zv(),Qv();return}if(n.dataTransfer.files&&n.dataTransfer.files.length>0){await Gv(n.dataTransfer.files);return}}),e.addEventListener(`dragover`,t=>{t.preventDefault(),t.stopPropagation(),!t.dataTransfer.types.includes(`application/x-workspace-move`)&&e.classList.add(`drag-over`)}),e.addEventListener(`dragleave`,t=>{t.preventDefault(),t.stopPropagation(),!t.dataTransfer.types.includes(`application/x-workspace-move`)&&e.classList.remove(`drag-over`)}),e.addEventListener(`drop`,async t=>{if(t.preventDefault(),t.stopPropagation(),t.dataTransfer.types.includes(`application/x-workspace-move`))return;e.classList.remove(`drag-over`);let n=t.dataTransfer.files;!n||n.length===0||await Gv(n)})}async function qv(){try{let e=document.getElementById(`workspaceAgentName`);if(!e)return;let t=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),n=t.pairedAgents||[],r=t.activeAgentId;if(r){let t=n.find(e=>e.id===r);if(t&&t.name){e.textContent=` · ${t.name}`,e.style.display=``;return}}e.textContent=``,e.style.display=`none`}catch(e){i.debug(`[WorkspacePanel] update agentname failed:`,e)}}async function Jv(e,t){if(t===`local`&&!(!e.pairedAgents&&!e.activeAgentId)&&(await qv(),e.activeAgentId?.newValue!==e.activeAgentId?.oldValue)){i.debug(`[WorkspacePanel] Agent changed,refreshworking directory`),St(),Nh=null,q=null,Ph=[],J.clear(),my=``,hy=[],gy=!1,Eg.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await wg()}}async function Yv(){if(Ph.length===0)return;let e=Ph.pop();J.clear(),await Tg(e)}async function Xv(e){if(!q){let e=Nh||await qt();if(!e){F(r(`workspace.refreshFailed`),`error`);return}Nh=e,q=e}if(Ng(q),J.clear(),Gy(),gy&&my?(hy=await Tt(q,my),Vg()):await jg(q),Cv(),Qg(),e!==void 0){let t=document.getElementById(`workspacePanelContent`);t&&requestAnimationFrame(()=>{t.scrollTop=e})}}function Zv(){let e=document.getElementById(`workspaceBreadcrumb`);if(!q){e.innerHTML=``;return}let t=Mg(q).split(`/`).filter(Boolean),n=Nh?Mg(Nh).replace(/\/$/,``):null,i=``,a=``;for(let e=0;e<t.length;e++){a=e===0?/^[a-zA-Z]:$/.test(t[e])?t[e]+`/`:`/`+t[e]:(a.endsWith(`/`)?a:a+`/`)+t[e];let r=e===t.length-1,o=!n||a===n||a.startsWith(n+`/`);e>0&&(i+=`<span class="workspace-breadcrumb-sep">/</span>`),r?i+=`<span class="workspace-breadcrumb-current">${X(t[e])}</span>`:o?i+=`<span class="workspace-breadcrumb-link" data-path="${X(a)}">${X(t[e])}</span>`:i+=`<span class="workspace-breadcrumb-disabled">${X(t[e])}</span>`}e.innerHTML=i||`<span class="workspace-breadcrumb-current">/</span>`,e.querySelectorAll(`.workspace-breadcrumb-link`).forEach(e=>{e.addEventListener(`click`,async t=>{t.stopPropagation();let n=e.dataset.path,r=Ph.findIndex(e=>e===n);Ph=r>=0?Ph.slice(0,r):[],J.clear(),await Tg(n)}),e.addEventListener(`dragover`,t=>{t.dataTransfer.types.includes(`application/x-workspace-move`)&&(t.preventDefault(),t.stopPropagation(),t.dataTransfer.dropEffect=`move`,e.classList.add(`drop-target`))}),e.addEventListener(`dragleave`,t=>{t.preventDefault(),t.stopPropagation(),e.classList.remove(`drop-target`)}),e.addEventListener(`drop`,async t=>{if(t.preventDefault(),t.stopPropagation(),e.classList.remove(`drop-target`),t.dataTransfer.types.includes(`application/x-workspace-move`))try{let n=JSON.parse(t.dataTransfer.getData(`application/x-workspace-move`)),i=n.path,a=e.dataset.path,o=n.name,s=Mg(i),c=Mg(a);if(s===c)return;if(c.startsWith(s+`/`)){F(r(`workspace.cannotMoveToSubdir`),`error`);return}F(r(`workspace.moving`),`info`);let l=await Et(i,a);l.success?(F(r(`workspace.movedToTarget`,{name:o,target:a.split(/[\\/]/).pop()}),`success`),Ng(q),Ng(a),await Xv()):F(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){F(r(`workspace.moveFailed`,{error:e.message}),`error`)}})})}function Qv(){let e=document.getElementById(`workspaceBackBtn`);e.disabled=!(Nh&&q&&q!==Nh)}function $v(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-error">${X(e)}</div>`}function X(e){return e?String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`):``}function ey(e){let t=(e.split(`.`).pop()||``).toLowerCase(),n={js:`javascript`,mjs:`javascript`,ts:`typescript`,jsx:`jsx`,tsx:`tsx`,html:`html`,htm:`html`,css:`css`,scss:`scss`,less:`less`,json:`json`,xml:`xml`,yaml:`yaml`,yml:`yaml`,py:`python`,java:`java`,c:`c`,cpp:`cpp`,h:`c`,go:`go`,rs:`rust`,rb:`ruby`,php:`php`,sql:`sql`,sh:`bash`,bash:`bash`,zsh:`bash`,md:`markdown`,vue:`html`,svelte:`html`};return n[t]?`language-${n[t]}`:``}async function ty(){q&&await jg(q)}async function ny(){St(),Nh=null,q=null,Ph=[],J.clear(),my=``,hy=[],gy=!1,Eg.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await wg()}function ry(e){let t=document.getElementById(`workspacePanelContainer`);if(t)if(e){t.style.display=``;let e=document.getElementById(`workspacePanel`),n=!!(e&&e.classList.contains(`expanded`));Uh&&e&&!n?xg().catch(e=>i.warn(`[WorkspacePanel] reopen panel after reconnect failed`,e)):n&&!q&&wg().catch(e=>i.warn(`[WorkspacePanel] navigate after reconnect failed`,e)),Gh&&yg()}else t.style.display=`none`,py(!0)}function iy(e,t){let n=t.toLowerCase(),r=e.toLowerCase();return r===n?``:r.startsWith(n+`/`)?e.substring(t.length+1):null}function ay(e,t){let n=t.split(`/`).filter(Boolean).pop();if(!n)return null;let r=e.lastIndexOf(`/`+n);if(r===-1)return null;let i=e.substring(r+n.length+1);return i===``?``:i}function oy(e,t){if(!e)return null;let n=Mg(t);if(!n)return null;let r=Mg(e).trim();if(!r||r===`.`||r===`~`||r.startsWith(`~/`))return null;if(!(r.startsWith(`/`)||/^[a-zA-Z]:\//.test(r)))return n+`/`+r;let i=iy(r,n);return i===null&&(i=ay(r,n)),i===null?null:i===``?n:n+`/`+i}async function sy(e){if(!(e===`~`||e&&e.startsWith(`~/`)))return e;try{let t=await Ft();if(t)return Mg(e===`~`?t:t+`/`+e.slice(2))}catch{}return e}async function cy(e){if(!e)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);if(!t||!n)return;if(t.classList.add(`expanded`),Ie(t),n.classList.add(`click-opened`),Nh||=await qt(),!Nh){$v(r(`workspace.noWorkspace`));return}let i=oy(await sy(e),Nh);if(!i){$v(r(`artifacts.locateFailed`));return}let a=i.lastIndexOf(`/`),o=a>0?i.substring(0,a):Nh,s=a>0?i.substring(a+1):i;Ng(o),await Tg(o);let c=e=>{let t=()=>{let t=null;return document.querySelectorAll(`.workspace-file-item`).forEach(n=>{n.dataset.name===e&&(t=n)}),t},n=t();if(n||!Lg)return n;let r=Lg.sorted.findIndex(t=>t.name===e);if(r<0)return null;let i=document.getElementById(`workspacePanelContent`);if(!i)return null;let{itemHeight:a}=Lg;return i.scrollTop=Math.max(0,r*a-i.clientHeight/2+a/2),Bg(),t()};setTimeout(async()=>{let e=c(s);e||=(Ng(o),await Tg(o),await new Promise(e=>setTimeout(e,300)),c(s)),e?(e.classList.add(`highlighted`),e.scrollIntoView({behavior:`smooth`,block:`center`}),setTimeout(()=>e.classList.remove(`highlighted`),3e3)):F(r(`artifacts.fileNotFound`))},300)}async function ly(e,t){if(!e)return;let n=document.getElementById(`workspacePanel`),i=document.getElementById(`workspacePanelContainer`);if(!n||!i)return;let a=n.classList.contains(`expanded`);if(n.classList.add(`expanded`),Ie(n),i.classList.add(`click-opened`),Nh||=await qt(),!Nh){$v(r(`workspace.noWorkspace`));return}let o=oy(await sy(e),Nh);if(!o){$v(r(`artifacts.locateFailed`));return}await Cv(!0),await d_(o,t),Qh=!a}async function uy(){await Cv(!0)}function dy(){py(!0)}async function fy(e){return!e||(Nh||=await qt(),!Nh)?null:oy(await sy(e),Nh)}async function py(e=!1){if(e&&await Cv(!0)===!1)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);t&&(Tn(t),t.classList.remove(`expanded`),Re(t),e||chrome.storage.local.set({[Hh]:!1}).catch(()=>{})),n&&(n.classList.remove(`hover-expanded`),n.classList.remove(`click-opened`),Uh&&!e&&(Uh=!1,Gh=!1,n.classList.add(`closing-no-anim`),pg(),requestAnimationFrame(()=>n.classList.remove(`closing-no-anim`))))}var my=``,hy=[],gy=!1,_y=[],vy=-1;function yy(){try{chrome.storage.local.get([`workspaceSearchHistory`],e=>{_y=e.workspaceSearchHistory||[]})}catch{}}function by(e){if(!e.trim())return;let t=_y.indexOf(e);t!==-1&&_y.splice(t,1),_y.push(e),_y.length>20&&_y.shift();try{chrome.storage.local.set({workspaceSearchHistory:_y})}catch{}}function xy(e){my=e.target.value.trim();let t=document.getElementById(`workspaceSearchClear`);t.style.display=my?``:`none`}async function Sy(){if(!my){gy=!1,hy=[],Vg(),Qg();return}by(my),vy=-1,F(r(`workspace.searching`),`info`),hy=await Tt(q,my),gy=!0,Vg(),Qg()}async function Cy(){let e=document.getElementById(`workspaceSearchInput`),t=document.getElementById(`workspaceToolbar`),n=t.querySelector(`.workspace-search-box`);e.value=``,my=``,gy=!1,hy=[],J.clear(),document.getElementById(`workspaceSearchClear`).style.display=`none`,t.classList.remove(`search-focused`),n.classList.remove(`search-box-expanded`),e.blur(),await jg(q),Qg(),Gy()}async function wy(e,t,n){let i=n===`directory`,a=r(i?`workspace.confirmDeleteDir`:`workspace.confirmDeleteFile`,{name:t,path:e});if(typeof window.showCustomConfirm!=`function`){if(!confirm(a))return}else if(!await window.showCustomConfirm(a,r(`workspace.confirmDeleteTitle`)))return;let o=document.getElementById(`workspacePanelContent`),s=o?o.scrollTop:0;try{let t=await Mt();if(!t){F(r(`workspace.agentNotConnected`),`error`);return}let n=await(await fetch(`${t.url}/api/fs/delete`,{method:`POST`,headers:{"Content-Type":`application/json`,...Bt(t)},body:JSON.stringify({path:e})})).json();n.success?(F(r(i?`workspace.dirDeleted`:`workspace.fileDeleted`),`success`),J.delete(e),Gy(),await Xv(s)):F(r(`workspace.deleteFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}catch(e){F(r(`workspace.deleteFailedWithError`,{error:e.message}),`error`)}}async function Ty(){if(J.size===0)return;let e=Array.from(J),t=e.map(e=>{let t=rg.find(t=>t.path===e)||hy.find(t=>t.fullPath===e);return t?t.name:e.split(/[\\/]/).pop()}),n=t.slice(0,5).map(e=>`• ${e}`).join(`
|
|
1185
|
+
`)+(t.length>5?r(`workspace.batchNamesMore`,{count:t.length}):``),i=r(`workspace.confirmBatchDelete`,{count:e.length,names:n});if(typeof window.showCustomConfirm!=`function`){if(!confirm(i))return}else if(!await window.showCustomConfirm(i,r(`workspace.confirmBatchDeleteTitle`)))return;let a=document.getElementById(`workspacePanelContent`),o=a?a.scrollTop:0;try{let t=await Mt();if(!t){F(r(`workspace.agentNotConnected`),`error`);return}let n=0,i=0;for(let r of e)try{(await(await fetch(`${t.url}/api/fs/delete`,{method:`POST`,headers:{"Content-Type":`application/json`,...Bt(t)},body:JSON.stringify({path:r})})).json()).success?(J.delete(r),n++):i++}catch{i++}n>0?(F(r(`workspace.deletedCount`,{success:n,failed:i>0?r(`workspace.deletedCountFailed`,{count:i}):``}),i>0?`warning`:`success`),Gy(),await Xv(o)):F(r(`workspace.deleteFailed`),`error`)}catch(e){F(r(`workspace.deleteFailedWithError`,{error:e.message}),`error`)}}function Ey(e,t){let n=[{bit:256,ch:`r`},{bit:128,ch:`w`},{bit:64,ch:`x`},{bit:32,ch:`r`},{bit:16,ch:`w`},{bit:8,ch:`x`},{bit:4,ch:`r`},{bit:2,ch:`w`},{bit:1,ch:`x`}],r=t?`d`:`-`;for(let t of n)r+=e&t.bit?t.ch:`-`,t.ch===`x`&&e&t.bit<<9&&(r=r.slice(0,-1)+(t.ch===`x`?`s`:`S`));let i=(e&511).toString(8).padStart(3,`0`);return`${r} (${i})`}async function Dy(e,t,n){let i=document.createElement(`div`);i.className=`modal-overlay show`,i.innerHTML=`
|
|
1184
1186
|
<div class="modal-container file-info-modal">
|
|
1185
1187
|
<button class="file-info-close" title="${r(`workspace.close`)}" style="position:absolute;top:10px;right:12px;background:none;border:none;font-size:20px;color:var(--text-tertiary);cursor:pointer;padding:4px 8px;line-height:1;transition:color 0.15s ease;">×</button>
|
|
1186
1188
|
<div class="modal-title">${X(t)} - ${r(`workspace.fileDetailsLabel`)}</div>
|
|
@@ -1188,7 +1190,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1188
1190
|
<div class="modal-actions" style="display:flex;justify-content:flex-end;gap:8px;margin-top:12px;">
|
|
1189
1191
|
<button class="modal-btn-cancel" style="padding:6px 16px;border:1px solid var(--border-default);border-radius:6px;background:var(--bg-surface);cursor:pointer;">${r(`workspace.close`)}</button>
|
|
1190
1192
|
</div>
|
|
1191
|
-
</div>`,document.body.appendChild(i);let o=()=>i.remove();i.querySelector(`.modal-btn-cancel`).addEventListener(`click`,o),i.querySelector(`.file-info-close`).addEventListener(`click`,o);try{let t=await zt(e),n=i.querySelector(`.file-info-loading`);if(!t.success||!t.info){n.className=``,n.innerHTML=`<div class="workspace-panel-error">${r(`workspace.getDetailsFailed`,{error:t.error||r(`workspace.unknownError`)})}</div>`;return}let o=t.info,s=e=>e?new Date(e).toLocaleString(a()===`en`?`en-US`:`zh-CN`):`—`,c=o.isDirectory?r(`workspace.getTypeDir`):o.isSymbolicLink?r(`workspace.getTypeSymlink`):r(`workspace.getTypeFile`),l=o.isDirectory?null:Rt(o.size)+` (${o.size.toLocaleString()} ${r(`workspace.bytes`)})`,u=o.mimeType||null,d=
|
|
1193
|
+
</div>`,document.body.appendChild(i);let o=()=>i.remove();i.querySelector(`.modal-btn-cancel`).addEventListener(`click`,o),i.querySelector(`.file-info-close`).addEventListener(`click`,o);try{let t=await zt(e),n=i.querySelector(`.file-info-loading`);if(!t.success||!t.info){n.className=``,n.innerHTML=`<div class="workspace-panel-error">${r(`workspace.getDetailsFailed`,{error:t.error||r(`workspace.unknownError`)})}</div>`;return}let o=t.info,s=e=>e?new Date(e).toLocaleString(a()===`en`?`en-US`:`zh-CN`):`—`,c=o.isDirectory?r(`workspace.getTypeDir`):o.isSymbolicLink?r(`workspace.getTypeSymlink`):r(`workspace.getTypeFile`),l=o.isDirectory?null:Rt(o.size)+` (${o.size.toLocaleString()} ${r(`workspace.bytes`)})`,u=o.mimeType||null,d=Ey(o.mode,o.isDirectory),f=[[r(`workspace.infoName`),X(o.name),o.name],[r(`workspace.infoType`),c,c],[r(`workspace.infoPath`),`<span style="word-break:break-all;">${X(o.path)}</span>`,o.path],[r(`workspace.infoSize`),l||`—`,l],[r(`workspace.infoMime`),u?X(u):`—`,u],[r(`workspace.infoMtime`),s(o.mtime),s(o.mtime)],[r(`workspace.infoCtime`),s(o.ctime),s(o.ctime)],[r(`workspace.infoAtime`),s(o.atime),s(o.atime)],[r(`workspace.infoPermission`),X(d),d]];o.uid!==void 0&&f.push([`UID`,String(o.uid),String(o.uid)]),o.gid!==void 0&&f.push([`GID`,String(o.gid),String(o.gid)]),n.className=`file-info-body`,n.innerHTML=`<table class="file-info-table">${f.map(([e,t,n])=>n==null?`<tr><td class="file-info-key">${e}</td><td class="file-info-val">${t}</td></tr>`:`<tr><td class="file-info-key">${e}</td><td class="file-info-val file-info-copyable" data-copy="${X(n)}" title="${r(`workspace.clickToCopy`)}">${t}<svg class="file-info-copy-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="12" height="12"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></td></tr>`).join(``)}</table>`,n.querySelectorAll(`.file-info-copyable`).forEach(e=>{e.addEventListener(`click`,async()=>{let t=e.dataset.copy;if(t)try{await navigator.clipboard.writeText(t),F(r(`workspace.copiedToClipboard`),`success`)}catch{F(r(`workspace.copyFailed`),`error`)}})})}catch(e){let t=i.querySelector(`.file-info-loading`);t.className=``,t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.getDetailsFailed`,{error:e.message})}</div>`}}function Oy(e,t=``,n=``){return new Promise(i=>{let a=document.createElement(`div`);a.className=`modal-overlay show`,a.innerHTML=`
|
|
1192
1194
|
<div class="modal-container input-dialog" style="min-width:320px;">
|
|
1193
1195
|
<div class="modal-title">${X(e)}</div>
|
|
1194
1196
|
<input type="text" class="modal-input" value="${X(t)}" placeholder="${X(n)}" autofocus style="width:100%;padding:8px 12px;border:1px solid var(--border-default);border-radius:6px;font-size:14px;margin:8px 0;box-sizing:border-box;">
|
|
@@ -1196,7 +1198,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1196
1198
|
<button class="modal-btn-cancel" style="padding:6px 16px;border:1px solid var(--border-default);border-radius:6px;background:var(--bg-surface);cursor:pointer;">${r(`workspace.cancel`)}</button>
|
|
1197
1199
|
<button class="modal-btn-confirm" style="padding:6px 16px;border:none;border-radius:6px;background:var(--info-500);color:var(--text-inverse);cursor:pointer;">${r(`workspace.confirm`)}</button>
|
|
1198
1200
|
</div>
|
|
1199
|
-
</div>`,document.body.appendChild(a);let o=a.querySelector(`.modal-input`),s=a.querySelector(`.modal-btn-confirm`),c=a.querySelector(`.modal-btn-cancel`),l=()=>{a.remove()},u=()=>{let e=o.value.trim();l(),i(e||null)};s.addEventListener(`click`,u),c.addEventListener(`click`,()=>{l(),i(null)}),o.addEventListener(`keydown`,e=>{e.key===`Enter`&&u(),e.key===`Escape`&&(l(),i(null))}),setTimeout(()=>o.select(),50)})}async function
|
|
1201
|
+
</div>`,document.body.appendChild(a);let o=a.querySelector(`.modal-input`),s=a.querySelector(`.modal-btn-confirm`),c=a.querySelector(`.modal-btn-cancel`),l=()=>{a.remove()},u=()=>{let e=o.value.trim();l(),i(e||null)};s.addEventListener(`click`,u),c.addEventListener(`click`,()=>{l(),i(null)}),o.addEventListener(`keydown`,e=>{e.key===`Enter`&&u(),e.key===`Escape`&&(l(),i(null))}),setTimeout(()=>o.select(),50)})}async function ky(e={}){let t=e.sessionId===void 0?C.activeSessionId||null:e.sessionId;if(Ch(t))return F(r(`workdirTag.lockedHint`),`warning`),!1;let n=null;try{n=await Nt(t)}catch{return F(r(`workspace.getWorkdirInfoFailed`),`error`),!1}if(!n)return F(r(`workspace.cannotConnectAgent`),`error`),!1;let a=!!t&&n.sessionWorkdirSupported===!0,o=!!(a&&n.sessionWorkdir),s=r(o?`workdirTag.sessionScope`:`workdirTag.defaultScope`),c=n.workdir||``,l=n.defaultWorkdir||c,u=Array.isArray(n.allowedPaths)?[...n.allowedPaths]:[],d=(e,t)=>String(e||``).replace(/\\/g,`/`).toLowerCase()===String(t||``).replace(/\\/g,`/`).toLowerCase(),f=()=>{let e=[...u],t=t=>{t&&!e.some(e=>d(e,t))&&e.push(t)};return t(l),t(c),e},p=!1;try{let e=await Mt(),t=e&&e.url?new URL(e.url).hostname:``;p=t===`localhost`||t===`127.0.0.1`||t===`[::1]`}catch(e){i.debug(`[WorkspacePanel] detect local agent failed:`,e)}let m=n.platform||`linux`,h=n.platformName||m,g=n.hostname||``;return new Promise(e=>{let n=document.createElement(`div`);n.className=`modal-overlay show`,n.innerHTML=`
|
|
1200
1202
|
<div class="modal-container switch-workdir-dialog" style="max-width:480px;width:90%;box-sizing:border-box;position:relative;">
|
|
1201
1203
|
<button class="switch-workdir-close" title="${r(`workspace.close`)}" style="position:absolute;top:10px;right:12px;width:28px;height:28px;border:none;background:transparent;color:var(--text-tertiary);border-radius:6px;font-size:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;line-height:1;padding:0;transition:all 0.2s;">✕</button>
|
|
1202
1204
|
<div class="modal-title">${r(a?`workdirTag.switchTitle`:`workspace.switchWorkdirTitle`)}</div>
|
|
@@ -1217,19 +1219,19 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1217
1219
|
<button class="switch-workdir-cancel" style="padding:6px 16px;border:1px solid var(--border-default);border-radius:6px;background:var(--bg-surface);cursor:pointer;">${r(`workspace.cancel`)}</button>
|
|
1218
1220
|
<button class="switch-workdir-confirm" style="padding:6px 16px;border:none;border-radius:6px;background:var(--info-500);color:var(--text-inverse);cursor:pointer;">${r(`workspace.switchBtn`)}</button>
|
|
1219
1221
|
</div>
|
|
1220
|
-
</div>`,document.body.appendChild(n);let i=n.querySelector(`#switchWorkdirList`),_=n.querySelector(`.switch-workdir-list-label`),v=n.querySelector(`.switch-workdir-browser`),y=n.querySelector(`.switch-workdir-manual`),b=n.querySelector(`.switch-workdir-cancel`),x=n.querySelector(`.switch-workdir-confirm`),S=n.querySelector(`.switch-workdir-close`),C=n.querySelector(`.switch-workdir-browse`),w=n.querySelector(`.switch-workdir-restore`),T=n.querySelector(`.switch-workdir-set-default`),E=e=>{e&&(y.value=e,y.focus())};async function D(){let e=C.textContent;C.disabled=!0,C.textContent=r(`workspace.picking`);try{let e=await xt();!e.success&&e.error===`busy`&&e.cancellable&&(await Ut(),e=await xt());let t=typeof e.error==`string`?e.error:``;e.success&&e.path?E(e.path):e.success||t===`cancelled`||(e.outdated?F(r(`workspace.browseAgentOutdated`),`error`):t===`busy`?F(r(`workspace.browseBusy`),`info`):t===`timeout`||t===`client-timeout`?F(r(`workspace.browseTimeout`),`info`,5e3):/^(no-dialog-tool|no-display|remote-source)/.test(t)?F(r(`workspace.browseUnavailable`),`info`):F(r(`workspace.browseFailedWithError`,{error:t||r(`workspace.unknownError`)}),`error`,8e3))}catch(e){F(r(`workspace.browseFailedWithError`,{error:e.message||e}),`error`)}finally{C.disabled=!1,C.textContent=e}}let O=v?
|
|
1222
|
+
</div>`,document.body.appendChild(n);let i=n.querySelector(`#switchWorkdirList`),_=n.querySelector(`.switch-workdir-list-label`),v=n.querySelector(`.switch-workdir-browser`),y=n.querySelector(`.switch-workdir-manual`),b=n.querySelector(`.switch-workdir-cancel`),x=n.querySelector(`.switch-workdir-confirm`),S=n.querySelector(`.switch-workdir-close`),C=n.querySelector(`.switch-workdir-browse`),w=n.querySelector(`.switch-workdir-restore`),T=n.querySelector(`.switch-workdir-set-default`),E=e=>{e&&(y.value=e,y.focus())};async function D(){let e=C.textContent;C.disabled=!0,C.textContent=r(`workspace.picking`);try{let e=await xt();!e.success&&e.error===`busy`&&e.cancellable&&(await Ut(),e=await xt());let t=typeof e.error==`string`?e.error:``;e.success&&e.path?E(e.path):e.success||t===`cancelled`||(e.outdated?F(r(`workspace.browseAgentOutdated`),`error`):t===`busy`?F(r(`workspace.browseBusy`),`info`):t===`timeout`||t===`client-timeout`?F(r(`workspace.browseTimeout`),`info`,5e3):/^(no-dialog-tool|no-display|remote-source)/.test(t)?F(r(`workspace.browseUnavailable`),`info`):F(r(`workspace.browseFailedWithError`,{error:t||r(`workspace.unknownError`)}),`error`,8e3))}catch(e){F(r(`workspace.browseFailedWithError`,{error:e.message||e}),`error`)}finally{C.disabled=!1,C.textContent=e}}let O=v?Sh({container:v,t:r,platform:m,platformName:h,hostname:g,listDirs:Gt,canUseNative:p,onUseNative:()=>{D()},onSelect:e=>{E(e)},onClose:()=>{v.hidden=!0,i&&(i.hidden=!1),_&&(_.hidden=!1),y.focus()}}):null;C&&O&&C.addEventListener(`click`,()=>{i&&(i.hidden=!0),_&&(_.hidden=!0),v.hidden=!1,O.open(y.value.trim()||c||``),C.blur()});let k=e=>{e.key===`Escape`&&O&&O.isOpen()&&(e.preventDefault(),e.stopPropagation(),O.close())};document.addEventListener(`keydown`,k,!0);let A=!1,j=()=>{A||(A=!0,document.removeEventListener(`keydown`,k,!0),O&&O.destroy(),n.remove())};function M(){let e=f();if(!e.length){i.innerHTML=`<div style="padding:16px;text-align:center;color:var(--text-disabled);font-size:13px;">`+r(`workspace.noAllowedPaths`)+`</div>`;return}i.innerHTML=e.map(e=>{let t=d(e,c),n=d(e,l),i=u.some(t=>d(t,e)),a=`<span style="flex-shrink:0;font-size:11px;color:var(--info-500);border:1px solid var(--info-500);border-radius:4px;padding:0 6px;">`+r(`workspace.currentTag`)+`</span>`,o=`<span style="flex-shrink:0;font-size:11px;color:var(--text-tertiary);border:1px solid var(--border-default);border-radius:4px;padding:0 6px;">`+r(`workspace.defaultTag`)+`</span>`;return`
|
|
1221
1223
|
<div class="switch-workdir-item${t?` current`:``}" data-path="${X(e)}" title="${X(e)}" style="display:flex;align-items:center;gap:8px;padding:8px 12px;cursor:${t?`default`:`pointer`};font-size:13px;color:${t?`var(--text-tertiary)`:`var(--text-primary)`};word-break:break-all;border-bottom:1px solid var(--bg-subtle);${t?`background:var(--bg-subtle);`:``}">
|
|
1222
1224
|
<span style="flex-shrink:0;">📁</span>
|
|
1223
1225
|
<span style="flex:1;">${X(e)}</span>
|
|
1224
1226
|
${t?a:``}${n?o:``}
|
|
1225
1227
|
${i?`<button class="switch-workdir-remove" data-remove-path="${X(e)}" title="${r(`workspace.removeFromAllowed`)}" style="flex-shrink:0;background:none;border:none;color:var(--danger-500);cursor:pointer;font-size:16px;line-height:1;padding:2px 6px;border-radius:4px;">×</button>`:``}
|
|
1226
|
-
</div>`}).join(``)}M(),T&&T.addEventListener(`change`,()=>{i.querySelectorAll(`.switch-workdir-item.current`).forEach(e=>{e.style.cursor=ee(e.dataset.path)?`pointer`:`default`})});async function N(e){let t=d(e,l)||d(e,c);if(!await window.showCustomConfirm(r(t?`workspace.confirmRemoveStillUsable`:`workspace.confirmRemovePath`,{path:e}),r(`workspace.confirmRemovePathTitle`)))return;let n=await Dt(e);n.success?(u=Array.isArray(n.allowedPaths)?n.allowedPaths:u.filter(t=>t!==e),M(),F(r(t?`workspace.removedStillUsable`:`workspace.removedFromAllowed`),`success`)):F(r(`workspace.removeFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}let ee=e=>{if(!(T&&T.checked))return!1;let t=e=>String(e||``).replace(/\\/g,`/`).toLowerCase();return!l||t(e)!==t(l)};i.addEventListener(`click`,e=>{let t=e.target.closest(`.switch-workdir-remove`);if(t){e.stopPropagation(),N(t.dataset.removePath);return}let n=e.target.closest(`.switch-workdir-item`);n&&(n.classList.contains(`current`)&&!ee(n.dataset.path)||te(n.dataset.path))});async function te(n){if(!n){F(r(`workspace.selectOrInputPath`),`error`);return}n=n.trim();let i=e=>e.replace(/\\/g,`/`).toLowerCase(),o=(e,t)=>!!e&&!!t&&i(e)===i(t),s=!!(T&&T.checked);if(o(n,c)){if(s&&!o(n,l)){j(),e(await jy(n));return}F(r(`workspace.alreadyCurrentWorkdir`),`info`),j(),e(!1);return}let d=a?t:null,f=!d||s;!u.some(e=>{let t=i(n),r=i(e);return t===r||t.startsWith(r+`/`)})&&f&&!await window.showCustomConfirm(r(`workspace.confirmSwitchToNewDefault`,{path:n}),r(`workspace.confirmSwitchToNewTitle`))||(j(),e(await My(n,{sessionId:d,setAsDefault:s})))}w&&w.addEventListener(`click`,async()=>{w.disabled=!0,j(),e(await Ny(t,{sessionSupported:a}))}),x.addEventListener(`click`,()=>te(y.value)),b.addEventListener(`click`,()=>{j(),e(!1)}),S.addEventListener(`click`,()=>{j(),e(!1)}),S.addEventListener(`mouseenter`,()=>{S.style.color=`var(--text-primary)`,S.style.background=`var(--border-subtle)`}),S.addEventListener(`mouseleave`,()=>{S.style.color=`var(--text-tertiary)`,S.style.background=`transparent`}),y.addEventListener(`keydown`,t=>{t.key===`Enter`&&(t.preventDefault(),te(y.value)),t.key===`Escape`&&(j(),e(!1))}),n.addEventListener(`click`,e=>{e.target===n&&e.stopPropagation()}),setTimeout(()=>y.focus(),50)})}function Ey(){kh=null,q=null,Ah=[],J.clear(),uy=``,dy=[],fy=!1,Sg.clear();let e=document.getElementById(`workspaceSearchInput`);e&&(e.value=``);let t=document.getElementById(`workspaceSearchClear`);t&&(t.style.display=`none`);let n=document.getElementById(`workspaceToolbar`);if(n){n.classList.remove(`search-focused`);let e=n.querySelector(`.workspace-search-box`);e&&e.classList.remove(`search-box-expanded`)}}var Dy=0;async function Oy(){let e=++Dy;if(C.agentPlatform?.connected!==!0){St(),Ey();return}await Uv();let t=kh;St();let n=null;try{n=await qt()}catch(e){i.warn(`[WorkspacePanel] resolve root for session failed:`,e?.message||e)}if(e!==Dy||t&&n&&t===n)return;Ey();let r=document.getElementById(`workspacePreviewArea`);if(r&&r.dataset.previewPath&&(Jh=!1,await yv(!0)),await Promise.resolve(),e!==Dy)return;let a=document.getElementById(`workspacePanel`);!a||!a.classList.contains(`expanded`)||await bg()}async function ky(e,t){document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:t}}))}async function Ay(e){C.defaultWorkdir=e,C.agentPlatform&&={...C.agentPlatform,workdir:e};try{let{activeAgentId:t}=await chrome.storage.local.get([`activeAgentId`]);t&&(C.agentWorkdirs.set(t,e),typeof window.updateAgentItemWorkdir==`function`&&window.updateAgentItemWorkdir(t,e))}catch(e){i.debug(`[WorkspacePanel] sync dropdown column table workdir failed:`,e)}}async function jy(e){let t=await bt(e,{sessionId:null});return t.success?(await Ay(t.workdir),await ky(null,t.workdir),F(r(`workspace.setAsDefaultDone`,{path:t.workdir}),`success`),!0):(F(r(`workspace.switchFailedWithError`,{error:t.error||r(`workspace.unknownError`)}),`error`),!1)}async function My(e,t={}){let n=t.sessionId===void 0?C.activeSessionId||null:t.sessionId,a=t.setAsDefault===!0,o=await bt(e,{sessionId:n});if(!o.success)return F(r(`workspace.switchFailedWithError`,{error:o.error||r(`workspace.unknownError`)}),`error`),!1;if(n)try{let{setSessionWorkdirBinding:e}=await A(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-BU0hS2_b.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([13,1,2,3])),t=(await Mt())?.id||null;await e(n,o.workdir,t)}catch(e){i.warn(`[WorkspacePanel] persist session workdir failed:`,e)}let s=!1;if(a){let e=await bt(o.workdir,{sessionId:null});e.success?s=!0:F(r(`workspace.switchFailedWithError`,{error:e.error||r(`workspace.unknownError`)}),`error`)}return(!n||a)&&await Ay(o.workdir),await ky(n,o.workdir),F(r(s?`workspace.switchedToAndSetDefault`:`workspace.switchedTo`,{path:o.workdir}),`success`),!0}async function Ny(e,t={}){if(!e)return!1;let{unbindSessionWorkdirRemote:n}=await A(async()=>{let{unbindSessionWorkdirRemote:e}=await import(`./model-profiles-C7nNtymU.js`).then(e=>e.z);return{unbindSessionWorkdirRemote:e}},__vite__mapDeps([2,1,3]));if(await n(e)===null&&t.sessionSupported)return F(r(`workspace.switchFailedWithError`,{error:r(`workspace.unknownError`)}),`error`),!1;try{let{setSessionWorkdirBinding:t}=await A(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-BU0hS2_b.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([13,1,2,3]));await t(e,null,null)}catch(e){i.warn(`[WorkspacePanel] clear session workdir failed:`,e)}return await ky(e,``),F(r(`workdirTag.restoredDefault`),`success`),!0}async function Py(e,t,n){let i=t,a=``,o=t.lastIndexOf(`.`);n!==`directory`&&o>0&&(i=t.substring(0,o),a=t.substring(o));let s=await wy(r(n===`directory`?`workspace.renameDir`:`workspace.renameFile`),i,r(`workspace.inputNewName`));if(!s||s===i)return;let c=s+a;try{let t=await Ct(e,c);t.success?(F(r(`workspace.renamedTo`,{name:c}),`success`),kg(q),await Kv(),zy(c)):F(r(`workspace.renameFailedWithError`,{error:t.error}),`error`)}catch(e){F(r(`workspace.renameFailedWithError`,{error:e.message}),`error`)}}async function Fy(){if(!q)return;let e=await wy(r(`workspace.newFolderTitle`),``,r(`workspace.inputFolderName`));if(!e)return;let t=Og(`${q}/${e}`);try{let n=await It(t);n.success?(F(r(`workspace.folderCreated`,{name:e}),`success`),kg(q),await Kv(),zy(e)):F(r(`workspace.createFailedWithError`,{error:n.error}),`error`)}catch(e){F(r(`workspace.createFailedWithError`,{error:e.message}),`error`)}}async function Iy(e){return new Promise((t,n)=>{let i=new Image,a=URL.createObjectURL(e);i.onload=()=>{URL.revokeObjectURL(a);let n=new FileReader;n.onloadend=()=>{let e=n.result,r=i.width,a=i.height,o=Math.max(r,a),s,c;o<=768?(s=o,c=.75):o<=1280?(s=768,c=.7):o<=2560?(s=1024,c=.65):o<=3840?(s=1280,c=.6):(s=1280,c=.55);let l=r,u=a;o>s&&(r>a?(u=Math.round(s/r*a),l=s):(l=Math.round(s/a*r),u=s));let d=document.createElement(`canvas`);d.width=l,d.height=u;let f=d.getContext(`2d`);f.imageSmoothingEnabled=!0,f.imageSmoothingQuality=`high`,f.drawImage(i,0,0,l,u),t({originalUrl:e,compressedUrl:d.toDataURL(`image/jpeg`,c)})},n.readAsDataURL(e)},i.onerror=()=>{URL.revokeObjectURL(a),n(Error(r(`workspace.imageLoadFailed`)))},i.src=a})}async function Ly(e){let t=[],n=[];for(let r of e){let e=r&&typeof r==`object`,i=e?r.fullPath||r.path:r,a=i.split(/[\\/]/).pop(),o;e?o=r:(o=$h.find(e=>e.path===i),o||=dy.find(e=>e.fullPath===i));let s=o?o.size:0,c=Pt(a);if(c.startsWith(`image/`)&&C.enableImageInput)n.push({name:a,size:s,type:c,path:i});else{let e={name:a,size:s,type:c,text:``,status:`done`,agentPath:i};t.push(e)}}for(let e of n)try{let t=await Mt();if(t){let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...Bt(t)},body:JSON.stringify({path:e.path})});if(n.ok){let{originalUrl:e,compressedUrl:t}=await Iy(await n.blob());C.attachedImages.some(e=>e.compressedUrl===t)||C.attachedImages.push({originalUrl:e,compressedUrl:t})}}}catch{}for(let e of t)C.attachedFiles.some(t=>t.name===e.name&&t.agentPath===e.agentPath)||C.attachedFiles.push(e);Zm(),Ch();let i=t.length+n.length;i>0&&(!C.enableImageInput&&t.some(e=>e.type?.startsWith(`image/`))?F(r(`workspace.addedFilesToQuestionNoImage`,{count:i}),`success`):F(r(`workspace.addedFilesToQuestion`,{count:i}),`success`))}async function Ry(){J.size!==0&&await Ly(Array.from(J))}function zy(e,t=0){let n=document.getElementById(`workspacePanelContent`);if(!n)return;if(Ng){let t=Ng.sorted.findIndex(t=>t.name===e);if(t>=0){let r=Ng.itemHeight;n.scrollTop=Math.max(0,t*r-n.clientHeight/2+r/2),Ig();let i=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);i&&(i.classList.add(`highlight-new`),setTimeout(()=>i.classList.remove(`highlight-new`),2e3));return}}let r=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);r?(r.scrollIntoView({behavior:`smooth`,block:`center`}),r.classList.add(`highlight-new`),setTimeout(()=>r.classList.remove(`highlight-new`),2e3)):t<5&&setTimeout(()=>zy(e,t+1),150)}function By(){let e=document.getElementById(`workspaceAskBtn`);J.size===0?e.style.display=`none`:e.style.display=``}function Vy(){let e=document.getElementById(`workspaceDownloadDirBtn`),t=document.getElementById(`workspaceBatchDeleteBtn`),n=document.getElementById(`workspaceSelectedCount`);J.size===0?(e.style.display=`none`,t.style.display=`none`,n.style.display=`none`):(e.style.display=``,t.style.display=``,n.style.display=``,n.textContent=r(`workspace.selectedCount`,{count:J.size}),e.disabled=Gh),By()}n(`zh`,{artifacts:{btnTitle:`文件产物({count})`,modalTitle:`本次任务的文件产物`,emptyHint:`本次任务没有产生文件产物`,fileCol:`文件`,sizeCol:`大小`,typeCol:`类型`,timeCol:`时间`,actionCol:`操作`,locate:`定位到文件`,preview:`预览`,closeBtn:`关闭`,typeWrite:`写入`,typeDelete:`删除`,typeCreate:`创建`,typeEdit:`编辑`,typeOther:`操作`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,locateFailed:`定位文件失败`,fileNotFound:`目录已定位,但未找到该文件(可能已被删除)`,previewFailed:`预览文件失败`,previewNotSupported:`此文件类型不支持预览`,totalCount:`共 {count} 个文件`,badgeLabel:`产物`,download:`下载`,downloadFailed:`下载失败`,copyFileName:`复制文件名`,copyFilePath:`复制文件路径`,copiedName:`已复制文件名:{name}`,copiedPath:`已复制文件路径`,dblClickHint:`双击文件名可预览`,sortHint:`点击排序`,serialCol:`序号`}}),n(`en`,{artifacts:{btnTitle:`Artifacts ({count})`,modalTitle:`File Artifacts of This Task`,emptyHint:`No file artifacts produced in this task`,fileCol:`File`,sizeCol:`Size`,typeCol:`Type`,timeCol:`Time`,actionCol:`Actions`,locate:`Locate File`,preview:`Preview`,closeBtn:`Close`,typeWrite:`Write`,typeDelete:`Delete`,typeCreate:`Create`,typeEdit:`Edit`,typeOther:`Op`,noWorkspace:`Unable to access working directory. Please confirm the Agent is connected.`,locateFailed:`Failed to locate file`,fileNotFound:`Directory located, but file not found (may have been deleted)`,previewFailed:`Failed to preview file`,previewNotSupported:`Preview not supported for this file type`,totalCount:`{count} files in total`,badgeLabel:`Artifacts`,download:`Download`,downloadFailed:`Download failed`,copyFileName:`Copy File Name`,copyFilePath:`Copy File Path`,copiedName:`Copied file name: {name}`,copiedPath:`File path copied`,dblClickHint:`Double-click to preview`,sortHint:`Click to sort`,serialCol:`#`}});function Hy(e){let t=(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`),n=t.replace(/\/+$/,``);return n?/^[A-Za-z]:$/.test(n)?n+`/`:n:t?`/`:``}function Uy(e){if(!e)return``;let t=Hy(e).replace(/\/+$/,``).split(`/`);return t[t.length-1]||``}function Wy(e){if(!e)return``;let t=Uy(e),n=t.lastIndexOf(`.`);return n>0?t.substring(n+1).toLowerCase():``}function Gy(e){return String(e??``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function Ky(e,t){let n=new Set(t),r=[],i=0,a=``;for(let t of e)t===`{`?i++:t===`}`&&(i=Math.max(0,i-1)),i===0&&n.has(t)?(r.push(a),a=``):a+=t;return r.push(a),r}function qy(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=0,r=-1;for(let i=t;i<e.length;i++)if(e[i]===`{`)n++;else if(e[i]===`}`&&(n--,n===0)){r=i;break}if(r===-1)return[e];let i=e.substring(0,t),a=e.substring(t+1,r),o=e.substring(r+1),s=Ky(a,`,`).map(e=>e.trim());if(s.length<=1)return[e];let c=[];for(let e of s)for(let t of qy(e))for(let e of qy(o))c.push(i+t+e);return c}function Jy(e,t){let n=[],r=new Set;for(let i of e)if(i)for(let e of qy(i)){if(!e)continue;let i=t(e);!i||r.has(i)||(r.add(i),n.push(i))}return n}function Yy(e){if(!e)return null;let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{let e=t.match(/["']?path["']?\s*[:=]\s*["']([^"']+)["']/i);return e?e[1]:null}return t&&typeof t==`object`&&(t.path||t.filePath||t.file_path||t.result?.path)||null}function Xy(e){let t=[],n=0,r=``;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`?n++:a===`}`&&(n=Math.max(0,n-1)),n===0&&a===`<`&&e[i+1]===`<`){let t=Zy(e,i);if(t>i){r+=e.substring(i,t),i=t-1;continue}}n===0&&a===`;`?(t.push(r),r=``):n===0&&a===`&`&&e[i+1]===`&`?(t.push(r),r=``,i++):r+=a}return t.push(r),t}function Zy(e,t){let n=e.substring(t).match(/^<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/);if(!n)return-1;let r=n[1],i=t+n[0].length,a=e.substring(i),o=RegExp(`\\n\\s*`+r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)+`\\s*(?=\\n|$)`),s=a.match(o);return s?i+s.index+s[0].length:-1}function Qy(e){let t=Hy(e||``).replace(/\/$/,``);if(!t)return``;let n=t.lastIndexOf(`/`);return n>0?t.substring(0,n):``}var $y=new Set([`du`,`df`,`stat`,`wc`,`file`,`cat`,`head`,`tail`,`grep`,`rg`]);function eb(e){if(!e||typeof e!=`string`)return!1;let t=Xy(e);if(t.length===0)return!1;for(let e of t){let t=e.trim().split(/\s+/).filter(Boolean);for(;t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0]);)t.shift();if(!t.length)continue;let n=t[0].split(`/`).pop().toLowerCase();if(n===`sudo`&&t.length>1&&(n=t[1].split(`/`).pop().toLowerCase()),!$y.has(n))return!1}return!0}function tb(e,t){let n=t=>e===t||e.startsWith(t.endsWith(`/`)?t:t+`/`);return[...t].some(n)}function nb(e,t){if(!e||typeof e!=`string`)return t||``;let n=t||``;for(let t of Xy(e)){let e=t.trim().match(/^cd\s+(.+?)\s*$/);if(!e)continue;let r=e[1].trim().replace(/^['"]|['"]$/g,``);n=r.startsWith(`/`)||r.startsWith(`~/`)?r:r===`..`?n?Hy(n).replace(/\/[^/]+$/,``)||`/`:`..`:Hy(n?n.replace(/\/$/,``)+`/`+r:r)}return n}function rb(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=Xy(e);for(let e of i){let t=e.trim();if(!t)continue;let i=t.replace(/"[^"]*"/g,`""`).replace(/'[^']*'/g,`''`),a=t.match(/^cd\s+(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||e.startsWith(`~/`)?e:e===`..`?r?Hy(r).replace(/\/[^/]+$/,``)||`/`:`..`:Hy(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&r&&(e=Hy(r.replace(/\/$/,``)+`/`+e)),Hy(e)),s=t.match(/^(\S+)\s+.*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*$/);if(s){let e=s[1].split(`/`).pop().toLowerCase(),t=s[3],r=null;if(/^python[\d.]*$/.test(e)?r=`py`:/^(ba)?sh$/.test(e)&&(r=`sh`),r){for(let e of ib(t,r))e&&n.push({path:o(e),isDir:!1});continue}}let c=i.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(c){let e=Jy(Ky(c[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!0});continue}let l=i.match(/^touch\s+(.+)$/);if(l){let e=Jy(Ky(l[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!1});continue}let u=null,d=i.match(/\s[>]{1,2}\s*['"]?([^\s|&;'"]+)['"]?\s*$/);if(d&&(u=d[1]),!u){let e=i.match(/^cat\s+>\s*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(!u){let e=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);e&&(u=e[1])}if(!u){let e=i.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(u){let e=Jy([u],o);for(let t of e)n.push({path:t,isDir:!1})}}return n}function ib(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=e.split(`
|
|
1227
|
-
`);if([`sh`,`bash`,`zsh`].includes(t))for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=[...t.matchAll(/[>]{1,2}\s*['"]?([^\s|&;>'"]+)['"]?/g)];for(let e of r)e[1]&&!e[1].startsWith(`/dev/`)&&n.push(e[1]);let i=t.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(i){let e=Ky(i[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`));n.push(...e)}let a=t.match(/^touch\s+(.+)$/);if(a){let e=Ky(a[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`));n.push(...e)}let o=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);o&&n.push(o[1]);let s=t.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);s&&n.push(s[1])}else if(t===`bat`||t===`cmd`)for(let e of r){let t=e.trim().replace(/^@/,``);if(!t||(t.toUpperCase(),/^REM\b/i.test(t)||t.startsWith(`::`))||/^ECHO\b/i.test(t)&&!/[>]{1,2}/.test(t))continue;let r=[...t.matchAll(/[>]{1,2}\s*"?([^\s|&;>"]+)"?/g)];for(let e of r)e[1]&&e[1].toUpperCase()!==`NUL`&&n.push(e[1]);let i=t.match(/^(?:mkdir|md)\s+(?:"([^"]+)"|(\S+))/i);i&&n.push(i[1]||i[2]);let a=t.match(/^copy\s+(?:\/\S+\s+)*(?:.+?\s+)+?"?([^\s|&;"]+)"?\s*$/i);a&&n.push(a[1]);let o=t.match(/^xcopy\s+(?:\/\S+\s+)*(?:"[^"]+"|\S+)\s+(?:"([^"]+)"|(\S+))/i);o&&n.push(o[1]||o[2])}else if(t===`ps1`)for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=[...t.matchAll(/[>]{1,2}\s*"?([^\s|;>'"]+)"?/g)];for(let e of r)e[1]&&e[1].toUpperCase()!==`NUL`&&n.push(e[1]);let i=t.match(/(?:Set-Content|Out-File|Add-Content)\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?/i);i&&n.push(i[1]);let a=t.match(/New-Item\s+(?:-[\w]+\s+)*-Path\s+"?([^";\s|]+)"?/i);a&&n.push(a[1]);let o=t.match(/New-Item\s+"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-ItemType/i);o&&n.push(o[1]);let s=t.match(/Copy-Item\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-Destination\s+"?([^";\s|]+)"?/i);s&&n.push(s[2]);let c=t.match(/Move-Item\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-Destination\s+"?([^";\s|]+)"?/i);c&&n.push(c[2])}else if(t===`py`)for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=t.match(/open\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"][wax][+]?['"]/);r&&n.push(r[1]);let i=t.match(/os\.(?:makedirs|mkdir)\s*\(\s*['"]([^'"]+)['"]/);i&&n.push(i[1]);let a=t.match(/shutil\.(?:copy2?|move)\s*\([^,]+,\s*['"]([^'"]+)['"]/);a&&n.push(a[1]);let o=t.match(/Path\s*\(\s*['"]([^'"]+)['"]\s*\)\s*\.\s*(?:write_text|write_bytes|touch|mkdir)/);o&&n.push(o[1])}let i=new Set;return n.filter(e=>!e||i.has(e)||(i.add(e),/\$[\w({]|%[\w]+%/.test(e))?!1:e.includes(`/`)||e.includes(`\\`)||e.includes(`.`))}function ab(e,t,n){if(!e||typeof e!=`string`||e.startsWith(`{`)||e.startsWith(`[`))return[];let r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[];let i=new Set([`total`,`.`,`..`,`...`,`.git`,`.DS_Store`,`node_modules`,`__pycache__`,`.learnings`,`dist`,`.trae`]),a=r.some(e=>/^[d-][rwx-]{9}[@+*]?$/.test(e)),o=n?[...n.matchAll(/find\b[\s\S]*?-type\s+([df])/g)].map(e=>e[1]):[],s=o.length===1?o[0]:null,c=/[<>"'`|&;()[\]*?#!]/,l=new Map,u=(e,t)=>{!e||i.has(e)||/^\d+$/.test(e)||c.test(e)||(!l.has(e)||t)&&l.set(e,t)},d=e=>e.startsWith(`/`)?Hy(e):Hy((t?t.replace(/\/$/,``)+`/`:``)+e),f=e=>!(e.split(`/`).pop()||``).includes(`.`);if(r.some(e=>/^\.\/([^:]+):$/.test(e)&&e.length>3)){let e=new Set;for(let t of r){let n=t.match(/^\.\/([^:]+):$/);n&&n[1]&&e.add(n[1])}let t=null;for(let n of r){let r=n.match(/^\.\/([^:]+):$/);if(r&&r[1]){t=r[1],u(t,!0);continue}if(n.startsWith(`./`)){let t=n.slice(2);t&&!i.has(t)&&u(t,e.has(t)||f(t)&&s!==`f`);continue}if(!(i.has(n)||n.startsWith(`-`)||a||n.endsWith(`...`)))if(t===null)(n.includes(`.`)||e.has(n))&&u(n,e.has(n));else{if(n.includes(`/`)){u(n,e.has(n)||f(n));continue}let r=t+`/`+n;u(r,e.has(r)||f(r))}}}else for(let e of r){if(i.has(e)||e.startsWith(`-`)||e.startsWith(`=`)||e.endsWith(`...`)||e.includes(`:`)||e.includes(`=`)||/^\d+$/.test(e)||/^[\d.]+[KMGTPE]?B?$/i.test(e))continue;let t=null;if(e.startsWith(`./`)){if(e.length<=2)continue;t=e.slice(2)}else if(a)continue;else{if(!e.includes(`/`)&&!/^.+\.[a-zA-Z0-9]+$/.test(e))continue;t=e}!t||i.has(t)||u(t,f(t)&&s!==`f`)}let p=[];for(let[e,t]of l)p.push({path:d(e),isDir:t});return p}function ob(e){if(!e||typeof e!=`string`)return[];let t=[],n=/cat\s+>\s*['"]?(\S+)['"]?\s*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*(?=\n|$)/g,r;for(;(r=n.exec(e))!==null;){let e=r[1],n=Wy(e);[`sh`,`bash`,`zsh`,`bat`,`cmd`,`ps1`,`py`].includes(n)&&t.push({path:Hy(e),content:r[3],ext:n})}return t}function sb(e,t){if(!e||typeof e!=`string`)return null;let n=e.trim();for(let e of t){let t=Uy(e).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),r=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=e.replace(/\//g,`\\`).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(RegExp(`(?:^|[;\\s&|])(?:ba)?sh\\s+.*${t}|(?:^|[;\\s&|])python[23]?\\s+.*${t}|(?:^|[;\\s&|])node\\s+.*${t}|(?:^|[;\\s&|])\\.?/${t}|(?:^|[;\\s&|])cmd(?:\\.exe)?\\s+(?:/c|/k)\\s+.*${t}|(?:^|[;\\s&|])(?:powershell|pwsh)(?:\\.exe)?\\s+(?:-[\w-]+\\s+)*-File\\s+.*${t}|(?:^|[;\\s&|])${r}|(?:^|[;\\s&|])${i}`).test(n))return e}return null}function cb(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&!/^[A-Za-z]:[\\/]/.test(e)&&r&&(e=Hy(r.replace(/\/$/,``)+`/`+e)),Hy(e)),a=Xy(e);for(let e of a){let t=e.trim();if(!t)continue;let a=t.match(/^cd\s+(?:\/[dD]\s+)?(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||/^[A-Za-z]:/.test(e)?Hy(e):e.startsWith(`~/`)?e:e===`..`?r?Hy(r).replace(/\/[^/]+$/,``)||`/`:`..`:Hy(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=t.match(/^rm\s+((?:-[a-zA-Z]+\s+)*)(.+)$/);if(o){let e=o[1],t=o[2],r=/r|R/i.test(e),a=Jy(Ky(t,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)),i);for(let e of a)n.push({path:e,isDir:r});continue}let s=t.match(/^(?:del|erase)\s+((?:\/[a-zA-Z]+\s+)*)(.+)$/i);if(s){s[1];let e=s[2],t=Jy(Ky(e,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`/`)),i);for(let e of t)n.push({path:e,isDir:!1});continue}let c=t.match(/^(?:rmdir|rd)\s+((?:\/[a-zA-Z]+\s+)*)(.+)$/i);if(c){let e=c[1],t=c[2],r=/s|S/i.test(e),a=Jy(Ky(t,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`/`)),i);for(let e of a)n.push({path:e,isDir:r});continue}let l=t.match(/^Remove-Item\s+((?:-[\w-]+\s+)*(?:"[^"]+"|\S+)?(?:\s+(?:-[\w-]+\s+)*(?:"[^"]+"|\S+))*)/i);if(l){let e=l[1],t=/-Recurse/i.test(e),r=Jy([...e.matchAll(/(?:"([^"]+)"|(?<![-\/])(\S+))/g)].map(e=>e[1]||e[2]).filter(e=>e&&!e.startsWith(`-`)),i);for(let e of r)n.push({path:e,isDir:t});continue}}return n}function lb(e){if(!Array.isArray(e)||e.length===0)return[];let t=[],n=new Set,r=[...e].sort((e,t)=>new Date(e.timestamp||0)-new Date(t.timestamp||0)),i=new Map;for(let e of r)if(!(e.nodeType!==`tool_exec`||e.status===`failed`)){if(e.action?.name===`agent_file`){let t=e.action.params;if(typeof t==`string`)try{t=JSON.parse(t)}catch{continue}if(!t||t.action!==`write`||typeof t.content!=`string`)continue;let n=Hy(t.path||t.filePath||``),r=Wy(n);[`sh`,`bash`,`zsh`,`bat`,`cmd`,`ps1`,`py`].includes(r)&&i.set(n,{content:t.content,ext:r})}else if(e.action?.name===`agent_exec`){let t=e.action.params,n=typeof t==`string`?t:t&&typeof t==`object`?t.command:null;if(typeof n==`string`)for(let e of ob(n))i.has(e.path)||i.set(e.path,{content:e.content,ext:e.ext})}}let a=[...i.keys()],o=new Map,s=(e,t)=>!t||e==null||t.timestamp==null?!0:new Date(t.timestamp||0).getTime()>=new Date(e||0).getTime(),c=new Set,l=!1;for(let e of r){if(e.nodeType!==`tool_exec`||!e.action)continue;let r=e.action.name||``,s=e.action.params;if(s==null)continue;if(typeof s==`string`)try{s=JSON.parse(s)}catch{continue}if(typeof s!=`object`)continue;if(r===`agent_exec`){let u=s.command||``;if(!u)continue;let d=sb(u,a);if(d&&e.status!==`failed`){let a=i.get(d);if(a){let i=ib(a.content,a.ext);for(let a of i){if(!a)continue;let i=(a.startsWith(`/`),Hy(a));if(n.has(i)){let e=t.findIndex(e=>e.path===i);e>=0&&t.splice(e,1)}n.add(i),t.push({path:i,fileName:Uy(i),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:`file`})}}}if(e.status!==`failed`){let t=cb(u,s.cwd);for(let n of t)o.set(n.path,{isDir:n.isDir,timestamp:e.timestamp})}let f=rb(u,s.cwd);for(let e of f)if(e&&e.path){let t=e.isDir?e.path:Qy(e.path);t&&c.add(t)}for(let i of f){let a=i&&i.path;if(a){if(n.has(a)){let e=t.findIndex(e=>e.path===a);e>=0&&t.splice(e,1)}n.add(a),e.status!==`failed`&&t.push({path:a,fileName:Uy(a),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:i.isDir?`directory`:`file`})}}let p=f.length>0||!!d||/<<-?/.test(u);if(e.status!==`failed`&&typeof e.observation==`string`){let i=nb(u,s.cwd);/\bcd\s/.test(u)&&i&&(p||l)&&c.add(Hy(i));let a=ab(e.observation,i,u);a.length>0&&!p&&(a=eb(u)?[]:a.filter(e=>tb(e.path,c)));for(let i of a){if(n.has(i.path)){let e=t.findIndex(e=>e.path===i.path);e>=0&&t.splice(e,1)}n.add(i.path),t.push({path:i.path,fileName:Uy(i.path),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:i.isDir?`directory`:`file`})}}e.status!==`failed`&&p&&(l=!0);continue}let u=null,d=`typeOther`;if(r===`agent_file`){let t=s.action;if(t===`write`)u=s.path||s.filePath,d=`typeWrite`;else if(t===`delete`){let t=Hy(s.path||s.filePath||``);t&&e.status!==`failed`&&o.set(t,{isDir:!1,timestamp:e.timestamp});continue}else continue}else if(r===`file_upload`)u=s.path||s.filePath||s.filename,d=`typeCreate`;else if(r===`download_file`)continue;else s.file_path&&(s.content!==void 0||s.action===`write`||s.action===`create`)&&(u=s.file_path,d=s.action===`create`?`typeCreate`:`typeWrite`);if(!u)continue;let f=Hy(Yy(e.observation)||u);if(!f)continue;if(n.has(f)){let e=t.findIndex(e=>e.path===f);e>=0&&t.splice(e,1)}if(n.add(f),e.status===`failed`)continue;let p=Qy(f);p&&c.add(p),l=!0;let m=0;if(e.observation){let t=e.observation;if(typeof t==`string`)try{t=JSON.parse(t)}catch{}t&&typeof t==`object`&&(m=t.size||t.fileSize||t.file_size||0)}t.push({path:f,fileName:Uy(f),toolName:r,action:d,size:m,timestamp:e.timestamp||null,status:e.status||`unknown`,type:`file`})}if(o.size>0){let e=[...o.keys()],n=(e,t)=>{if(e===t)return!0;let n=e.startsWith(`/`),r=t.startsWith(`/`);return n&&!r?e.endsWith(`/`+t)||e.endsWith(t):r&&!n?t.endsWith(`/`+e)||t.endsWith(e):!1};for(let r of t)r.deleted||(o.has(r.path)&&s(r.timestamp,o.get(r.path))||e.some(e=>{let t=o.get(e);return s(r.timestamp,t)?n(r.path,e)?!0:t&&t.isDir&&(r.path.startsWith(e+`/`)||r.path.startsWith(e+`\\`)):!1}))&&(r.deleted=!0)}return t.filter(e=>e&&e.fileName)}function ub(e){if(!e||typeof e!=`string`)return[];let t=[],n=new Set,r=/\[\[artifact:([^\]|]+)(?:\|([^\]]*))?\]\]/g,i;for(;(i=r.exec(e))!==null;){let e=(i[1]||``).trim(),r=(i[2]||``).trim();if(!e||/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z0-9_]+%/.test(e))continue;let a=db(e);!a||n.has(a)||(n.add(a),t.push({path:e,note:r}))}return t}function db(e){return Hy(e).replace(/^\.\//,``)}function fb(e,t){let n=(e||[]).map(e=>({...e,source:e.source||`static`})),r=n.map(e=>db(e.path));for(let e of t||[]){let t=db(e.path);if(!t)continue;let i=Uy(e.path);if(!i)continue;let a=r.indexOf(t);if(a===-1&&(a=r.findIndex(e=>e.endsWith(`/`+t))),a!==-1){let t=n[a];t&&e.note&&!t.note&&(t.note=e.note);continue}r.push(t),n.push({path:e.path,fileName:i,toolName:`declared`,action:`typeCreate`,size:0,timestamp:null,status:`unknown`,type:`file`,source:`declared`,note:e.note||``})}return n}function pb(e,t){return fb(lb(e),ub(t))}function mb(e){try{return Lt(e)}catch{return!1}}var hb=null,gb=null,_b=null,vb=1;function yb(e){if(!e)return`—`;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function bb(e){if(!_b)return e;let t=vb;return[...e].sort((e,n)=>{let r,i;return _b===`name`?(r=(e.fileName||e.path||``).toLowerCase(),i=(n.fileName||n.path||``).toLowerCase()):_b===`type`?(r=e.type||`file`,i=n.type||`file`):(r=new Date(e.timestamp||0).getTime(),i=new Date(n.timestamp||0).getTime()),r<i?-t:r>i?t:0})}function xb(e,t){let n=Ht(e.fileName,e.type),i=r(`artifacts.${e.action}`),a=yb(e.timestamp),o=mb(e.fileName),s=`${Gy(e.path)} · ${r(`artifacts.dblClickHint`)}`;return`
|
|
1228
|
-
<tr class="artifacts-row" data-idx="${t}" data-path="${
|
|
1228
|
+
</div>`}).join(``)}M(),T&&T.addEventListener(`change`,()=>{i.querySelectorAll(`.switch-workdir-item.current`).forEach(e=>{e.style.cursor=ee(e.dataset.path)?`pointer`:`default`})});async function N(e){let t=d(e,l)||d(e,c);if(!await window.showCustomConfirm(r(t?`workspace.confirmRemoveStillUsable`:`workspace.confirmRemovePath`,{path:e}),r(`workspace.confirmRemovePathTitle`)))return;let n=await Dt(e);n.success?(u=Array.isArray(n.allowedPaths)?n.allowedPaths:u.filter(t=>t!==e),M(),F(r(t?`workspace.removedStillUsable`:`workspace.removedFromAllowed`),`success`)):F(r(`workspace.removeFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}let ee=e=>{if(!(T&&T.checked))return!1;let t=e=>String(e||``).replace(/\\/g,`/`).toLowerCase();return!l||t(e)!==t(l)};i.addEventListener(`click`,e=>{let t=e.target.closest(`.switch-workdir-remove`);if(t){e.stopPropagation(),N(t.dataset.removePath);return}let n=e.target.closest(`.switch-workdir-item`);n&&(n.classList.contains(`current`)&&!ee(n.dataset.path)||te(n.dataset.path))});async function te(n){if(!n){F(r(`workspace.selectOrInputPath`),`error`);return}n=n.trim();let i=e=>e.replace(/\\/g,`/`).toLowerCase(),o=(e,t)=>!!e&&!!t&&i(e)===i(t),s=!!(T&&T.checked);if(o(n,c)){if(s&&!o(n,l)){j(),e(await Fy(n));return}F(r(`workspace.alreadyCurrentWorkdir`),`info`),j(),e(!1);return}let d=a?t:null,f=!d||s;!u.some(e=>{let t=i(n),r=i(e);return t===r||t.startsWith(r+`/`)})&&f&&!await window.showCustomConfirm(r(`workspace.confirmSwitchToNewDefault`,{path:n}),r(`workspace.confirmSwitchToNewTitle`))||(j(),e(await Iy(n,{sessionId:d,setAsDefault:s})))}w&&w.addEventListener(`click`,async()=>{w.disabled=!0,j(),e(await Ly(t,{sessionSupported:a}))}),x.addEventListener(`click`,()=>te(y.value)),b.addEventListener(`click`,()=>{j(),e(!1)}),S.addEventListener(`click`,()=>{j(),e(!1)}),S.addEventListener(`mouseenter`,()=>{S.style.color=`var(--text-primary)`,S.style.background=`var(--border-subtle)`}),S.addEventListener(`mouseleave`,()=>{S.style.color=`var(--text-tertiary)`,S.style.background=`transparent`}),y.addEventListener(`keydown`,t=>{t.key===`Enter`&&(t.preventDefault(),te(y.value)),t.key===`Escape`&&(j(),e(!1))}),n.addEventListener(`click`,e=>{e.target===n&&e.stopPropagation()}),setTimeout(()=>y.focus(),50)})}function Ay(){Nh=null,q=null,Ph=[],J.clear(),my=``,hy=[],gy=!1,Eg.clear();let e=document.getElementById(`workspaceSearchInput`);e&&(e.value=``);let t=document.getElementById(`workspaceSearchClear`);t&&(t.style.display=`none`);let n=document.getElementById(`workspaceToolbar`);if(n){n.classList.remove(`search-focused`);let e=n.querySelector(`.workspace-search-box`);e&&e.classList.remove(`search-box-expanded`)}}var jy=0;async function My(){let e=++jy;if(C.agentPlatform?.connected!==!0){St(),Ay();return}await qv();let t=Nh;St();let n=null;try{n=await qt()}catch(e){i.warn(`[WorkspacePanel] resolve root for session failed:`,e?.message||e)}if(e!==jy||t&&n&&t===n)return;Ay();let r=document.getElementById(`workspacePreviewArea`);if(r&&r.dataset.previewPath&&(Qh=!1,await Cv(!0)),await Promise.resolve(),e!==jy)return;let a=document.getElementById(`workspacePanel`);!a||!a.classList.contains(`expanded`)||await wg()}async function Ny(e,t){document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:t}}))}async function Py(e){C.defaultWorkdir=e,C.agentPlatform&&={...C.agentPlatform,workdir:e};try{let{activeAgentId:t}=await chrome.storage.local.get([`activeAgentId`]);t&&(C.agentWorkdirs.set(t,e),typeof window.updateAgentItemWorkdir==`function`&&window.updateAgentItemWorkdir(t,e))}catch(e){i.debug(`[WorkspacePanel] sync dropdown column table workdir failed:`,e)}}async function Fy(e){let t=await bt(e,{sessionId:null});return t.success?(await Py(t.workdir),await Ny(null,t.workdir),F(r(`workspace.setAsDefaultDone`,{path:t.workdir}),`success`),!0):(F(r(`workspace.switchFailedWithError`,{error:t.error||r(`workspace.unknownError`)}),`error`),!1)}async function Iy(e,t={}){let n=t.sessionId===void 0?C.activeSessionId||null:t.sessionId,a=t.setAsDefault===!0,o=await bt(e,{sessionId:n});if(!o.success)return F(r(`workspace.switchFailedWithError`,{error:o.error||r(`workspace.unknownError`)}),`error`),!1;if(n)try{let{setSessionWorkdirBinding:e}=await A(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-M5mPmMr3.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([13,1,2,3])),t=(await Mt())?.id||null;await e(n,o.workdir,t)}catch(e){i.warn(`[WorkspacePanel] persist session workdir failed:`,e)}let s=!1;if(a){let e=await bt(o.workdir,{sessionId:null});e.success?s=!0:F(r(`workspace.switchFailedWithError`,{error:e.error||r(`workspace.unknownError`)}),`error`)}return(!n||a)&&await Py(o.workdir),await Ny(n,o.workdir),F(r(s?`workspace.switchedToAndSetDefault`:`workspace.switchedTo`,{path:o.workdir}),`success`),!0}async function Ly(e,t={}){if(!e)return!1;let{unbindSessionWorkdirRemote:n}=await A(async()=>{let{unbindSessionWorkdirRemote:e}=await import(`./model-profiles-ClPgbQ-J.js`).then(e=>e.z);return{unbindSessionWorkdirRemote:e}},__vite__mapDeps([2,1,3]));if(await n(e)===null&&t.sessionSupported)return F(r(`workspace.switchFailedWithError`,{error:r(`workspace.unknownError`)}),`error`),!1;try{let{setSessionWorkdirBinding:t}=await A(async()=>{let{setSessionWorkdirBinding:e}=await import(`./session-store-M5mPmMr3.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([13,1,2,3]));await t(e,null,null)}catch(e){i.warn(`[WorkspacePanel] clear session workdir failed:`,e)}return await Ny(e,``),F(r(`workdirTag.restoredDefault`),`success`),!0}async function Ry(e,t,n){let i=t,a=``,o=t.lastIndexOf(`.`);n!==`directory`&&o>0&&(i=t.substring(0,o),a=t.substring(o));let s=await Oy(r(n===`directory`?`workspace.renameDir`:`workspace.renameFile`),i,r(`workspace.inputNewName`));if(!s||s===i)return;let c=s+a;try{let t=await Ct(e,c);t.success?(F(r(`workspace.renamedTo`,{name:c}),`success`),Ng(q),await Xv(),Uy(c)):F(r(`workspace.renameFailedWithError`,{error:t.error}),`error`)}catch(e){F(r(`workspace.renameFailedWithError`,{error:e.message}),`error`)}}async function zy(){if(!q)return;let e=await Oy(r(`workspace.newFolderTitle`),``,r(`workspace.inputFolderName`));if(!e)return;let t=Mg(`${q}/${e}`);try{let n=await It(t);n.success?(F(r(`workspace.folderCreated`,{name:e}),`success`),Ng(q),await Xv(),Uy(e)):F(r(`workspace.createFailedWithError`,{error:n.error}),`error`)}catch(e){F(r(`workspace.createFailedWithError`,{error:e.message}),`error`)}}async function By(e){return new Promise((t,n)=>{let i=new Image,a=URL.createObjectURL(e);i.onload=()=>{URL.revokeObjectURL(a);let n=new FileReader;n.onloadend=()=>{let e=n.result,r=i.width,a=i.height,o=Math.max(r,a),s,c;o<=768?(s=o,c=.75):o<=1280?(s=768,c=.7):o<=2560?(s=1024,c=.65):o<=3840?(s=1280,c=.6):(s=1280,c=.55);let l=r,u=a;o>s&&(r>a?(u=Math.round(s/r*a),l=s):(l=Math.round(s/a*r),u=s));let d=document.createElement(`canvas`);d.width=l,d.height=u;let f=d.getContext(`2d`);f.imageSmoothingEnabled=!0,f.imageSmoothingQuality=`high`,f.drawImage(i,0,0,l,u),t({originalUrl:e,compressedUrl:d.toDataURL(`image/jpeg`,c)})},n.readAsDataURL(e)},i.onerror=()=>{URL.revokeObjectURL(a),n(Error(r(`workspace.imageLoadFailed`)))},i.src=a})}async function Vy(e){let t=[],n=[];for(let r of e){let e=r&&typeof r==`object`,i=e?r.fullPath||r.path:r,a=i.split(/[\\/]/).pop(),o;e?o=r:(o=rg.find(e=>e.path===i),o||=hy.find(e=>e.fullPath===i));let s=o?o.size:0,c=Pt(a);if(c.startsWith(`image/`)&&C.enableImageInput)n.push({name:a,size:s,type:c,path:i});else{let e={name:a,size:s,type:c,text:``,status:`done`,agentPath:i};t.push(e)}}for(let e of n)try{let t=await Mt();if(t){let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...Bt(t)},body:JSON.stringify({path:e.path})});if(n.ok){let{originalUrl:e,compressedUrl:t}=await By(await n.blob());C.attachedImages.some(e=>e.compressedUrl===t)||C.attachedImages.push({originalUrl:e,compressedUrl:t})}}}catch{}for(let e of t)C.attachedFiles.some(t=>t.name===e.name&&t.agentPath===e.agentPath)||C.attachedFiles.push(e);th(),Dh();let i=t.length+n.length;i>0&&(!C.enableImageInput&&t.some(e=>e.type?.startsWith(`image/`))?F(r(`workspace.addedFilesToQuestionNoImage`,{count:i}),`success`):F(r(`workspace.addedFilesToQuestion`,{count:i}),`success`))}async function Hy(){J.size!==0&&await Vy(Array.from(J))}function Uy(e,t=0){let n=document.getElementById(`workspacePanelContent`);if(!n)return;if(Lg){let t=Lg.sorted.findIndex(t=>t.name===e);if(t>=0){let r=Lg.itemHeight;n.scrollTop=Math.max(0,t*r-n.clientHeight/2+r/2),Bg();let i=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);i&&(i.classList.add(`highlight-new`),setTimeout(()=>i.classList.remove(`highlight-new`),2e3));return}}let r=Array.from(n.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.name===e);r?(r.scrollIntoView({behavior:`smooth`,block:`center`}),r.classList.add(`highlight-new`),setTimeout(()=>r.classList.remove(`highlight-new`),2e3)):t<5&&setTimeout(()=>Uy(e,t+1),150)}function Wy(){let e=document.getElementById(`workspaceAskBtn`);J.size===0?e.style.display=`none`:e.style.display=``}function Gy(){let e=document.getElementById(`workspaceDownloadDirBtn`),t=document.getElementById(`workspaceBatchDeleteBtn`),n=document.getElementById(`workspaceSelectedCount`);J.size===0?(e.style.display=`none`,t.style.display=`none`,n.style.display=`none`):(e.style.display=``,t.style.display=``,n.style.display=``,n.textContent=r(`workspace.selectedCount`,{count:J.size}),e.disabled=Yh),Wy()}n(`zh`,{artifacts:{btnTitle:`文件产物({count})`,modalTitle:`本次任务的文件产物`,emptyHint:`本次任务没有产生文件产物`,fileCol:`文件`,sizeCol:`大小`,typeCol:`类型`,timeCol:`时间`,actionCol:`操作`,locate:`定位到文件`,preview:`预览`,closeBtn:`关闭`,typeWrite:`写入`,typeDelete:`删除`,typeCreate:`创建`,typeEdit:`编辑`,typeOther:`操作`,noWorkspace:`无法获取工作目录,请确认 Agent 已连接`,locateFailed:`定位文件失败`,fileNotFound:`目录已定位,但未找到该文件(可能已被删除)`,previewFailed:`预览文件失败`,previewNotSupported:`此文件类型不支持预览`,totalCount:`共 {count} 个文件`,badgeLabel:`产物`,download:`下载`,downloadFailed:`下载失败`,copyFileName:`复制文件名`,copyFilePath:`复制文件路径`,copiedName:`已复制文件名:{name}`,copiedPath:`已复制文件路径`,dblClickHint:`双击文件名可预览`,sortHint:`点击排序`,serialCol:`序号`}}),n(`en`,{artifacts:{btnTitle:`Artifacts ({count})`,modalTitle:`File Artifacts of This Task`,emptyHint:`No file artifacts produced in this task`,fileCol:`File`,sizeCol:`Size`,typeCol:`Type`,timeCol:`Time`,actionCol:`Actions`,locate:`Locate File`,preview:`Preview`,closeBtn:`Close`,typeWrite:`Write`,typeDelete:`Delete`,typeCreate:`Create`,typeEdit:`Edit`,typeOther:`Op`,noWorkspace:`Unable to access working directory. Please confirm the Agent is connected.`,locateFailed:`Failed to locate file`,fileNotFound:`Directory located, but file not found (may have been deleted)`,previewFailed:`Failed to preview file`,previewNotSupported:`Preview not supported for this file type`,totalCount:`{count} files in total`,badgeLabel:`Artifacts`,download:`Download`,downloadFailed:`Download failed`,copyFileName:`Copy File Name`,copyFilePath:`Copy File Path`,copiedName:`Copied file name: {name}`,copiedPath:`File path copied`,dblClickHint:`Double-click to preview`,sortHint:`Click to sort`,serialCol:`#`}});function Ky(e){let t=(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`),n=t.replace(/\/+$/,``);return n?/^[A-Za-z]:$/.test(n)?n+`/`:n:t?`/`:``}function qy(e){if(!e)return``;let t=Ky(e).replace(/\/+$/,``).split(`/`);return t[t.length-1]||``}function Jy(e){if(!e)return``;let t=qy(e),n=t.lastIndexOf(`.`);return n>0?t.substring(n+1).toLowerCase():``}function Yy(e){return String(e??``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function Xy(e,t){let n=new Set(t),r=[],i=0,a=``;for(let t of e)t===`{`?i++:t===`}`&&(i=Math.max(0,i-1)),i===0&&n.has(t)?(r.push(a),a=``):a+=t;return r.push(a),r}function Zy(e){let t=e.indexOf(`{`);if(t===-1)return[e];let n=0,r=-1;for(let i=t;i<e.length;i++)if(e[i]===`{`)n++;else if(e[i]===`}`&&(n--,n===0)){r=i;break}if(r===-1)return[e];let i=e.substring(0,t),a=e.substring(t+1,r),o=e.substring(r+1),s=Xy(a,`,`).map(e=>e.trim());if(s.length<=1)return[e];let c=[];for(let e of s)for(let t of Zy(e))for(let e of Zy(o))c.push(i+t+e);return c}function Qy(e,t){let n=[],r=new Set;for(let i of e)if(i)for(let e of Zy(i)){if(!e)continue;let i=t(e);!i||r.has(i)||(r.add(i),n.push(i))}return n}function $y(e){if(!e)return null;let t=e;if(typeof t==`string`)try{t=JSON.parse(t)}catch{let e=t.match(/["']?path["']?\s*[:=]\s*["']([^"']+)["']/i);return e?e[1]:null}return t&&typeof t==`object`&&(t.path||t.filePath||t.file_path||t.result?.path)||null}function eb(e){let t=[],n=0,r=``;for(let i=0;i<e.length;i++){let a=e[i];if(a===`{`?n++:a===`}`&&(n=Math.max(0,n-1)),n===0&&a===`<`&&e[i+1]===`<`){let t=tb(e,i);if(t>i){r+=e.substring(i,t),i=t-1;continue}}n===0&&a===`;`?(t.push(r),r=``):n===0&&a===`&`&&e[i+1]===`&`?(t.push(r),r=``,i++):r+=a}return t.push(r),t}function tb(e,t){let n=e.substring(t).match(/^<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/);if(!n)return-1;let r=n[1],i=t+n[0].length,a=e.substring(i),o=RegExp(`\\n\\s*`+r.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)+`\\s*(?=\\n|$)`),s=a.match(o);return s?i+s.index+s[0].length:-1}function nb(e){let t=Ky(e||``).replace(/\/$/,``);if(!t)return``;let n=t.lastIndexOf(`/`);return n>0?t.substring(0,n):``}var rb=new Set([`du`,`df`,`stat`,`wc`,`file`,`cat`,`head`,`tail`,`grep`,`rg`]);function ib(e){if(!e||typeof e!=`string`)return!1;let t=eb(e);if(t.length===0)return!1;for(let e of t){let t=e.trim().split(/\s+/).filter(Boolean);for(;t.length&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(t[0]);)t.shift();if(!t.length)continue;let n=t[0].split(`/`).pop().toLowerCase();if(n===`sudo`&&t.length>1&&(n=t[1].split(`/`).pop().toLowerCase()),!rb.has(n))return!1}return!0}function ab(e,t){let n=t=>e===t||e.startsWith(t.endsWith(`/`)?t:t+`/`);return[...t].some(n)}function ob(e,t){if(!e||typeof e!=`string`)return t||``;let n=t||``;for(let t of eb(e)){let e=t.trim().match(/^cd\s+(.+?)\s*$/);if(!e)continue;let r=e[1].trim().replace(/^['"]|['"]$/g,``);n=r.startsWith(`/`)||r.startsWith(`~/`)?r:r===`..`?n?Ky(n).replace(/\/[^/]+$/,``)||`/`:`..`:Ky(n?n.replace(/\/$/,``)+`/`+r:r)}return n}function sb(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=eb(e);for(let e of i){let t=e.trim();if(!t)continue;let i=t.replace(/"[^"]*"/g,`""`).replace(/'[^']*'/g,`''`),a=t.match(/^cd\s+(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||e.startsWith(`~/`)?e:e===`..`?r?Ky(r).replace(/\/[^/]+$/,``)||`/`:`..`:Ky(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&r&&(e=Ky(r.replace(/\/$/,``)+`/`+e)),Ky(e)),s=t.match(/^(\S+)\s+.*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*$/);if(s){let e=s[1].split(`/`).pop().toLowerCase(),t=s[3],r=null;if(/^python[\d.]*$/.test(e)?r=`py`:/^(ba)?sh$/.test(e)&&(r=`sh`),r){for(let e of cb(t,r))e&&n.push({path:o(e),isDir:!1});continue}}let c=i.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(c){let e=Qy(Xy(c[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!0});continue}let l=i.match(/^touch\s+(.+)$/);if(l){let e=Qy(Xy(l[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)&&e!==`""`&&e!==`''`),o);for(let t of e)n.push({path:t,isDir:!1});continue}let u=null,d=i.match(/\s[>]{1,2}\s*['"]?([^\s|&;'"]+)['"]?\s*$/);if(d&&(u=d[1]),!u){let e=i.match(/^cat\s+>\s*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(!u){let e=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);e&&(u=e[1])}if(!u){let e=i.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);e&&(u=e[1])}if(u){let e=Qy([u],o);for(let t of e)n.push({path:t,isDir:!1})}}return n}function cb(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=e.split(`
|
|
1229
|
+
`);if([`sh`,`bash`,`zsh`].includes(t))for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=[...t.matchAll(/[>]{1,2}\s*['"]?([^\s|&;>'"]+)['"]?/g)];for(let e of r)e[1]&&!e[1].startsWith(`/dev/`)&&n.push(e[1]);let i=t.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(i){let e=Xy(i[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`));n.push(...e)}let a=t.match(/^touch\s+(.+)$/);if(a){let e=Xy(a[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`));n.push(...e)}let o=t.match(/^cp\s+(?:-[a-zA-Z]+\s+)*(?:.+?\s+)+?['"]?([^\s|&;'"]+)['"]?\s*$/);o&&n.push(o[1]);let s=t.match(/tee\s+(?:-[a-zA-Z]+\s+)*['"]?([^\s|&;'"]+)['"]?/);s&&n.push(s[1])}else if(t===`bat`||t===`cmd`)for(let e of r){let t=e.trim().replace(/^@/,``);if(!t||(t.toUpperCase(),/^REM\b/i.test(t)||t.startsWith(`::`))||/^ECHO\b/i.test(t)&&!/[>]{1,2}/.test(t))continue;let r=[...t.matchAll(/[>]{1,2}\s*"?([^\s|&;>"]+)"?/g)];for(let e of r)e[1]&&e[1].toUpperCase()!==`NUL`&&n.push(e[1]);let i=t.match(/^(?:mkdir|md)\s+(?:"([^"]+)"|(\S+))/i);i&&n.push(i[1]||i[2]);let a=t.match(/^copy\s+(?:\/\S+\s+)*(?:.+?\s+)+?"?([^\s|&;"]+)"?\s*$/i);a&&n.push(a[1]);let o=t.match(/^xcopy\s+(?:\/\S+\s+)*(?:"[^"]+"|\S+)\s+(?:"([^"]+)"|(\S+))/i);o&&n.push(o[1]||o[2])}else if(t===`ps1`)for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=[...t.matchAll(/[>]{1,2}\s*"?([^\s|;>'"]+)"?/g)];for(let e of r)e[1]&&e[1].toUpperCase()!==`NUL`&&n.push(e[1]);let i=t.match(/(?:Set-Content|Out-File|Add-Content)\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?/i);i&&n.push(i[1]);let a=t.match(/New-Item\s+(?:-[\w]+\s+)*-Path\s+"?([^";\s|]+)"?/i);a&&n.push(a[1]);let o=t.match(/New-Item\s+"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-ItemType/i);o&&n.push(o[1]);let s=t.match(/Copy-Item\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-Destination\s+"?([^";\s|]+)"?/i);s&&n.push(s[2]);let c=t.match(/Move-Item\s+(?:-[\w]+\s+)*"?([^";\s|]+)"?\s+(?:-[\w]+\s+)*-Destination\s+"?([^";\s|]+)"?/i);c&&n.push(c[2])}else if(t===`py`)for(let e of r){let t=e.trim();if(!t||t.startsWith(`#`))continue;let r=t.match(/open\s*\(\s*['"]([^'"]+)['"]\s*,\s*['"][wax][+]?['"]/);r&&n.push(r[1]);let i=t.match(/os\.(?:makedirs|mkdir)\s*\(\s*['"]([^'"]+)['"]/);i&&n.push(i[1]);let a=t.match(/shutil\.(?:copy2?|move)\s*\([^,]+,\s*['"]([^'"]+)['"]/);a&&n.push(a[1]);let o=t.match(/Path\s*\(\s*['"]([^'"]+)['"]\s*\)\s*\.\s*(?:write_text|write_bytes|touch|mkdir)/);o&&n.push(o[1])}let i=new Set;return n.filter(e=>!e||i.has(e)||(i.add(e),/\$[\w({]|%[\w]+%/.test(e))?!1:e.includes(`/`)||e.includes(`\\`)||e.includes(`.`))}function lb(e,t,n){if(!e||typeof e!=`string`||e.startsWith(`{`)||e.startsWith(`[`))return[];let r=e.split(/\s+/).filter(Boolean);if(r.length===0)return[];let i=new Set([`total`,`.`,`..`,`...`,`.git`,`.DS_Store`,`node_modules`,`__pycache__`,`.learnings`,`dist`,`.trae`]),a=r.some(e=>/^[d-][rwx-]{9}[@+*]?$/.test(e)),o=n?[...n.matchAll(/find\b[\s\S]*?-type\s+([df])/g)].map(e=>e[1]):[],s=o.length===1?o[0]:null,c=/[<>"'`|&;()[\]*?#!]/,l=new Map,u=(e,t)=>{!e||i.has(e)||/^\d+$/.test(e)||c.test(e)||(!l.has(e)||t)&&l.set(e,t)},d=e=>e.startsWith(`/`)?Ky(e):Ky((t?t.replace(/\/$/,``)+`/`:``)+e),f=e=>!(e.split(`/`).pop()||``).includes(`.`);if(r.some(e=>/^\.\/([^:]+):$/.test(e)&&e.length>3)){let e=new Set;for(let t of r){let n=t.match(/^\.\/([^:]+):$/);n&&n[1]&&e.add(n[1])}let t=null;for(let n of r){let r=n.match(/^\.\/([^:]+):$/);if(r&&r[1]){t=r[1],u(t,!0);continue}if(n.startsWith(`./`)){let t=n.slice(2);t&&!i.has(t)&&u(t,e.has(t)||f(t)&&s!==`f`);continue}if(!(i.has(n)||n.startsWith(`-`)||a||n.endsWith(`...`)))if(t===null)(n.includes(`.`)||e.has(n))&&u(n,e.has(n));else{if(n.includes(`/`)){u(n,e.has(n)||f(n));continue}let r=t+`/`+n;u(r,e.has(r)||f(r))}}}else for(let e of r){if(i.has(e)||e.startsWith(`-`)||e.startsWith(`=`)||e.endsWith(`...`)||e.includes(`:`)||e.includes(`=`)||/^\d+$/.test(e)||/^[\d.]+[KMGTPE]?B?$/i.test(e))continue;let t=null;if(e.startsWith(`./`)){if(e.length<=2)continue;t=e.slice(2)}else if(a)continue;else{if(!e.includes(`/`)&&!/^.+\.[a-zA-Z0-9]+$/.test(e))continue;t=e}!t||i.has(t)||u(t,f(t)&&s!==`f`)}let p=[];for(let[e,t]of l)p.push({path:d(e),isDir:t});return p}function ub(e){if(!e||typeof e!=`string`)return[];let t=[],n=/cat\s+>\s*['"]?(\S+)['"]?\s*<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?\s*\n([\s\S]*?)\n\s*\2\s*(?=\n|$)/g,r;for(;(r=n.exec(e))!==null;){let e=r[1],n=Jy(e);[`sh`,`bash`,`zsh`,`bat`,`cmd`,`ps1`,`py`].includes(n)&&t.push({path:Ky(e),content:r[3],ext:n})}return t}function db(e,t){if(!e||typeof e!=`string`)return null;let n=e.trim();for(let e of t){let t=qy(e).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),r=e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),i=e.replace(/\//g,`\\`).replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);if(RegExp(`(?:^|[;\\s&|])(?:ba)?sh\\s+.*${t}|(?:^|[;\\s&|])python[23]?\\s+.*${t}|(?:^|[;\\s&|])node\\s+.*${t}|(?:^|[;\\s&|])\\.?/${t}|(?:^|[;\\s&|])cmd(?:\\.exe)?\\s+(?:/c|/k)\\s+.*${t}|(?:^|[;\\s&|])(?:powershell|pwsh)(?:\\.exe)?\\s+(?:-[\w-]+\\s+)*-File\\s+.*${t}|(?:^|[;\\s&|])${r}|(?:^|[;\\s&|])${i}`).test(n))return e}return null}function fb(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&!/^[A-Za-z]:[\\/]/.test(e)&&r&&(e=Ky(r.replace(/\/$/,``)+`/`+e)),Ky(e)),a=eb(e);for(let e of a){let t=e.trim();if(!t)continue;let a=t.match(/^cd\s+(?:\/[dD]\s+)?(.+?)\s*$/);if(a){let e=a[1].trim().replace(/^['"]|['"]$/g,``);r=e.startsWith(`/`)||/^[A-Za-z]:/.test(e)?Ky(e):e.startsWith(`~/`)?e:e===`..`?r?Ky(r).replace(/\/[^/]+$/,``)||`/`:`..`:Ky(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=t.match(/^rm\s+((?:-[a-zA-Z]+\s+)*)(.+)$/);if(o){let e=o[1],t=o[2],r=/r|R/i.test(e),a=Qy(Xy(t,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`)),i);for(let e of a)n.push({path:e,isDir:r});continue}let s=t.match(/^(?:del|erase)\s+((?:\/[a-zA-Z]+\s+)*)(.+)$/i);if(s){s[1];let e=s[2],t=Qy(Xy(e,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`/`)),i);for(let e of t)n.push({path:e,isDir:!1});continue}let c=t.match(/^(?:rmdir|rd)\s+((?:\/[a-zA-Z]+\s+)*)(.+)$/i);if(c){let e=c[1],t=c[2],r=/s|S/i.test(e),a=Qy(Xy(t,` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`/`)),i);for(let e of a)n.push({path:e,isDir:r});continue}let l=t.match(/^Remove-Item\s+((?:-[\w-]+\s+)*(?:"[^"]+"|\S+)?(?:\s+(?:-[\w-]+\s+)*(?:"[^"]+"|\S+))*)/i);if(l){let e=l[1],t=/-Recurse/i.test(e),r=Qy([...e.matchAll(/(?:"([^"]+)"|(?<![-\/])(\S+))/g)].map(e=>e[1]||e[2]).filter(e=>e&&!e.startsWith(`-`)),i);for(let e of r)n.push({path:e,isDir:t});continue}}return n}function pb(e){if(!Array.isArray(e)||e.length===0)return[];let t=[],n=new Set,r=[...e].sort((e,t)=>new Date(e.timestamp||0)-new Date(t.timestamp||0)),i=new Map;for(let e of r)if(!(e.nodeType!==`tool_exec`||e.status===`failed`)){if(e.action?.name===`agent_file`){let t=e.action.params;if(typeof t==`string`)try{t=JSON.parse(t)}catch{continue}if(!t||t.action!==`write`||typeof t.content!=`string`)continue;let n=Ky(t.path||t.filePath||``),r=Jy(n);[`sh`,`bash`,`zsh`,`bat`,`cmd`,`ps1`,`py`].includes(r)&&i.set(n,{content:t.content,ext:r})}else if(e.action?.name===`agent_exec`){let t=e.action.params,n=typeof t==`string`?t:t&&typeof t==`object`?t.command:null;if(typeof n==`string`)for(let e of ub(n))i.has(e.path)||i.set(e.path,{content:e.content,ext:e.ext})}}let a=[...i.keys()],o=new Map,s=(e,t)=>!t||e==null||t.timestamp==null?!0:new Date(t.timestamp||0).getTime()>=new Date(e||0).getTime(),c=new Set,l=!1;for(let e of r){if(e.nodeType!==`tool_exec`||!e.action)continue;let r=e.action.name||``,s=e.action.params;if(s==null)continue;if(typeof s==`string`)try{s=JSON.parse(s)}catch{continue}if(typeof s!=`object`)continue;if(r===`agent_exec`){let u=s.command||``;if(!u)continue;let d=db(u,a);if(d&&e.status!==`failed`){let a=i.get(d);if(a){let i=cb(a.content,a.ext);for(let a of i){if(!a)continue;let i=(a.startsWith(`/`),Ky(a));if(n.has(i)){let e=t.findIndex(e=>e.path===i);e>=0&&t.splice(e,1)}n.add(i),t.push({path:i,fileName:qy(i),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:`file`})}}}if(e.status!==`failed`){let t=fb(u,s.cwd);for(let n of t)o.set(n.path,{isDir:n.isDir,timestamp:e.timestamp})}let f=sb(u,s.cwd);for(let e of f)if(e&&e.path){let t=e.isDir?e.path:nb(e.path);t&&c.add(t)}for(let i of f){let a=i&&i.path;if(a){if(n.has(a)){let e=t.findIndex(e=>e.path===a);e>=0&&t.splice(e,1)}n.add(a),e.status!==`failed`&&t.push({path:a,fileName:qy(a),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:i.isDir?`directory`:`file`})}}let p=f.length>0||!!d||/<<-?/.test(u);if(e.status!==`failed`&&typeof e.observation==`string`){let i=ob(u,s.cwd);/\bcd\s/.test(u)&&i&&(p||l)&&c.add(Ky(i));let a=lb(e.observation,i,u);a.length>0&&!p&&(a=ib(u)?[]:a.filter(e=>ab(e.path,c)));for(let i of a){if(n.has(i.path)){let e=t.findIndex(e=>e.path===i.path);e>=0&&t.splice(e,1)}n.add(i.path),t.push({path:i.path,fileName:qy(i.path),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:i.isDir?`directory`:`file`})}}e.status!==`failed`&&p&&(l=!0);continue}let u=null,d=`typeOther`;if(r===`agent_file`){let t=s.action;if(t===`write`)u=s.path||s.filePath,d=`typeWrite`;else if(t===`delete`){let t=Ky(s.path||s.filePath||``);t&&e.status!==`failed`&&o.set(t,{isDir:!1,timestamp:e.timestamp});continue}else continue}else if(r===`file_upload`)u=s.path||s.filePath||s.filename,d=`typeCreate`;else if(r===`download_file`)continue;else s.file_path&&(s.content!==void 0||s.action===`write`||s.action===`create`)&&(u=s.file_path,d=s.action===`create`?`typeCreate`:`typeWrite`);if(!u)continue;let f=Ky($y(e.observation)||u);if(!f)continue;if(n.has(f)){let e=t.findIndex(e=>e.path===f);e>=0&&t.splice(e,1)}if(n.add(f),e.status===`failed`)continue;let p=nb(f);p&&c.add(p),l=!0;let m=0;if(e.observation){let t=e.observation;if(typeof t==`string`)try{t=JSON.parse(t)}catch{}t&&typeof t==`object`&&(m=t.size||t.fileSize||t.file_size||0)}t.push({path:f,fileName:qy(f),toolName:r,action:d,size:m,timestamp:e.timestamp||null,status:e.status||`unknown`,type:`file`})}if(o.size>0){let e=[...o.keys()],n=(e,t)=>{if(e===t)return!0;let n=e.startsWith(`/`),r=t.startsWith(`/`);return n&&!r?e.endsWith(`/`+t)||e.endsWith(t):r&&!n?t.endsWith(`/`+e)||t.endsWith(e):!1};for(let r of t)r.deleted||(o.has(r.path)&&s(r.timestamp,o.get(r.path))||e.some(e=>{let t=o.get(e);return s(r.timestamp,t)?n(r.path,e)?!0:t&&t.isDir&&(r.path.startsWith(e+`/`)||r.path.startsWith(e+`\\`)):!1}))&&(r.deleted=!0)}return t.filter(e=>e&&e.fileName)}function mb(e){if(!e||typeof e!=`string`)return[];let t=[],n=new Set,r=/\[\[artifact:([^\]|]+)(?:\|([^\]]*))?\]\]/g,i;for(;(i=r.exec(e))!==null;){let e=(i[1]||``).trim(),r=(i[2]||``).trim();if(!e||/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?|%[A-Za-z0-9_]+%/.test(e))continue;let a=hb(e);!a||n.has(a)||(n.add(a),t.push({path:e,note:r}))}return t}function hb(e){return Ky(e).replace(/^\.\//,``)}function gb(e,t){let n=(e||[]).map(e=>({...e,source:e.source||`static`})),r=n.map(e=>hb(e.path));for(let e of t||[]){let t=hb(e.path);if(!t)continue;let i=qy(e.path);if(!i)continue;let a=r.indexOf(t);if(a===-1&&(a=r.findIndex(e=>e.endsWith(`/`+t))),a!==-1){let t=n[a];t&&e.note&&!t.note&&(t.note=e.note);continue}r.push(t),n.push({path:e.path,fileName:i,toolName:`declared`,action:`typeCreate`,size:0,timestamp:null,status:`unknown`,type:`file`,source:`declared`,note:e.note||``})}return n}function _b(e,t){return gb(pb(e),mb(t))}function vb(e){try{return Lt(e)}catch{return!1}}var yb=null,bb=null,xb=null,Sb=1;function Cb(e){if(!e)return`—`;let t=new Date(e),n=e=>String(e).padStart(2,`0`);return`${n(t.getHours())}:${n(t.getMinutes())}:${n(t.getSeconds())}`}function wb(e){if(!xb)return e;let t=Sb;return[...e].sort((e,n)=>{let r,i;return xb===`name`?(r=(e.fileName||e.path||``).toLowerCase(),i=(n.fileName||n.path||``).toLowerCase()):xb===`type`?(r=e.type||`file`,i=n.type||`file`):(r=new Date(e.timestamp||0).getTime(),i=new Date(n.timestamp||0).getTime()),r<i?-t:r>i?t:0})}function Tb(e,t){let n=Ht(e.fileName,e.type),i=r(`artifacts.${e.action}`),a=Cb(e.timestamp),o=vb(e.fileName),s=`${Yy(e.path)} · ${r(`artifacts.dblClickHint`)}`;return`
|
|
1230
|
+
<tr class="artifacts-row" data-idx="${t}" data-path="${Yy(e.path)}" data-name="${Yy(e.fileName)}">
|
|
1229
1231
|
<td class="col-index">${t+1}</td>
|
|
1230
1232
|
<td class="col-file">
|
|
1231
1233
|
<span class="artifact-icon">${n}</span>
|
|
1232
|
-
<span class="artifact-name" title="${s}">${
|
|
1234
|
+
<span class="artifact-name" title="${s}">${Yy(e.fileName)}</span>
|
|
1233
1235
|
<button class="artifact-copy-btn" title="${r(`artifacts.copyFileName`)}">
|
|
1234
1236
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="13" height="13">
|
|
1235
1237
|
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
|
|
@@ -1262,7 +1264,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1262
1264
|
</button>`:``}
|
|
1263
1265
|
</td>
|
|
1264
1266
|
</tr>
|
|
1265
|
-
`}function
|
|
1267
|
+
`}function Eb(e,t){e.querySelectorAll(`.artifacts-row`).forEach(e=>{let n=t[parseInt(e.dataset.idx,10)];if(!n)return;e.addEventListener(`click`,e=>{e.target.closest(`.artifact-action-btn`)||e.target.closest(`.artifact-copy-btn`)||(clearTimeout(bb),bb=setTimeout(()=>{bb=null,uy().catch(()=>{}),cy(n.path).catch(e=>{i.error(`[Artifacts] locate failed:`,e)})},250))});let a=e.querySelector(`.artifact-name`);a&&a.addEventListener(`dblclick`,e=>{e.stopPropagation(),e.preventDefault(),clearTimeout(bb),bb=null,vb(n.fileName)&&ly(n.path,n.fileName).catch(e=>{i.error(`[Artifacts] preview failed:`,e)})});let o=e.querySelector(`.artifact-copy-btn`);o&&o.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.ctrlKey||e.metaKey,i=n.fileName;t&&(i=await fy(n.path)||n.path),He(i,o),F(t?r(`artifacts.copiedPath`):r(`artifacts.copiedName`,{name:n.fileName}),`success`)});let s=e.querySelector(`.download-btn`);s&&s.addEventListener(`click`,e=>{e.stopPropagation(),Ob(n)}),e.querySelectorAll(`.locate-btn, .preview-btn`).forEach(e=>{e.addEventListener(`click`,async t=>{if(t.stopPropagation(),e.classList.contains(`locate-btn`)){uy().catch(()=>{});try{await cy(n.path)}catch(e){i.error(`[Artifacts] locate failed:`,e)}}else if(e.classList.contains(`preview-btn`))try{await ly(n.path,n.fileName)}catch(e){i.error(`[Artifacts] preview failed:`,e)}})})})}function Db(e,t){let n=wb(t),r=e.querySelector(`.artifacts-table tbody`);r.innerHTML=n.map((e,t)=>Tb(e,t)).join(``),e.querySelectorAll(`.artifacts-table th.sortable`).forEach(e=>{let t=e.dataset.sort;e.classList.toggle(`sorted-asc`,t===xb&&Sb===1),e.classList.toggle(`sorted-desc`,t===xb&&Sb===-1)}),Eb(e,n)}async function Ob(e){let t=null;try{t=e.type===`directory`?await Wt([e.path]):await kt(e.path)}catch(e){t={success:!1,error:e.message}}if(!t||!t.success){let e=t&&t.error?`: ${t.error}`:``;F(r(`artifacts.downloadFailed`)+e,`error`);return}let n=URL.createObjectURL(t.blob),i=document.createElement(`a`),a=t.name||qy(e.path)||`workspace.zip`;if(e.type===`directory`){let t=qy(e.path);t&&(a=t.replace(/\.zip$/i,``)+`.zip`)}i.href=n,i.download=a,document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>URL.revokeObjectURL(n),5e3)}function kb(e,t){if(!t)return!0;let n=Ky(e||``);if(!n||n.startsWith(`~/`)||n===`~`)return!1;if(!(n.startsWith(`/`)||/^[a-zA-Z]:\//.test(n)))return!0;let r=n.toLowerCase(),i=t.toLowerCase();return r===i||r.startsWith(i+`/`)}function Ab(e,t){return!t||!(e===`~`||e&&e.startsWith(`~/`))?e:Ky(e===`~`?t:t+`/`+e.slice(2))}function jb(e,t){let n=e.querySelector(`.artifacts-modal-count`);n&&(n.textContent=r(`artifacts.totalCount`,{count:t.length}))}async function Mb(e){if(!e||e.length===0)return!1;let t=null;try{let e=await qt();e&&(t=Ky(e))}catch{}let n=null;try{n=await Ft()}catch{}let r=!1;if(t)for(let i=e.length-1;i>=0;i--){let a=e[i];kb(Ab(a.path,n),t)||(e.splice(i,1),r=!0)}if(e.length===0)return r;try{let t=new Map;await Promise.all(e.map(async e=>{let n=e.path;try{let t=await fy(e.path);t&&(n=t)}catch{}t.has(n)||t.set(n,[]),t.get(n).push(e.path)}));let n=[...t.keys()];if(n.length===0)return r;let i=await chrome.runtime.sendMessage({type:`CHECK_FILES_EXIST`,paths:n});if(!i||!i.success||!i.results)return r;let a=new Set;for(let[e,n]of t)if(i.results[e]===!1)for(let e of n)a.add(e);if(a.size>0)for(let t=e.length-1;t>=0;t--)a.has(e[t].path)&&(e.splice(t,1),r=!0)}catch{}return r}function Nb(e,t){if(!e)return;let n=e.querySelector(`.artifacts-btn-count`);t>0?(n&&(n.textContent=t),e.title=r(`artifacts.btnTitle`,{count:t}),e.style.display=``):e.style.display=`none`}function Pb(e,t){!e||e.length===0||!t||Mb(e).then(n=>{n&&Nb(t,e.length)}).catch(()=>{})}function Fb(e){if(!e)return 0;for(let t=e.length-1;t>=0;t--)e[t].deleted&&e.splice(t,1);return e.length}function Ib(e,t){if(Lb(),!e)return;for(let t=e.length-1;t>=0;t--)e[t].deleted&&e.splice(t,1);if(e.length===0){Nb(t,0);return}xb=null,Sb=1,yb=document.createElement(`div`),yb.className=`artifacts-modal-overlay`,yb.id=`artifactsModalOverlay`;let n=document.createElement(`div`);n.className=`artifacts-modal`;let i=document.createElement(`div`);i.className=`artifacts-modal-header`,i.innerHTML=`
|
|
1266
1268
|
<div class="artifacts-modal-title">
|
|
1267
1269
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:18px;height:18px;color:var(--info-500);">
|
|
1268
1270
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
@@ -1285,7 +1287,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1285
1287
|
</tr>
|
|
1286
1288
|
</thead>
|
|
1287
1289
|
<tbody></tbody>
|
|
1288
|
-
`,a.appendChild(o);let s=document.createElement(`div`);s.className=`artifacts-modal-footer`;let c=document.createElement(`button`);c.className=`artifacts-modal-close-btn`,c.textContent=r(`artifacts.closeBtn`),c.addEventListener(`click`,
|
|
1290
|
+
`,a.appendChild(o);let s=document.createElement(`div`);s.className=`artifacts-modal-footer`;let c=document.createElement(`button`);c.className=`artifacts-modal-close-btn`,c.textContent=r(`artifacts.closeBtn`),c.addEventListener(`click`,Lb),s.appendChild(c),n.appendChild(i),n.appendChild(a),n.appendChild(s),yb.appendChild(n);let l=document.body,u=document.getElementById(`workspacePanelContainer`);if(u&&u.classList.contains(`embedded`)){let e=document.getElementById(`mainLeft`);e&&(yb.classList.add(`embedded-mode`),e.style.position=`relative`,l=e)}l.appendChild(yb),document.getElementById(`artifactsModalClose`).addEventListener(`click`,Lb);let d=e=>{e.key===`Escape`&&(Lb(),document.removeEventListener(`keydown`,d))};document.addEventListener(`keydown`,d),o.querySelectorAll(`th.sortable`).forEach(t=>{t.addEventListener(`click`,()=>{let r=t.dataset.sort;xb===r?Sb=-Sb:(xb=r,Sb=1),Db(n,e)})}),Db(n,e),Mb(e).then(i=>{if(!(!i||!yb)){if(e.length===0){let t=n.querySelector(`.artifacts-table tbody`);t&&(t.innerHTML=`<tr><td colspan="5" class="artifacts-empty">${r(`artifacts.emptyHint`)}</td></tr>`),jb(n,e)}else jb(n,e),Db(n,e);Nb(t,e.length)}}).catch(()=>{})}function Lb(){bb&&=(clearTimeout(bb),null),yb&&=(yb.remove(),null)}n(`zh`,{promptSelector:{noMatchAgent:`没有匹配的 Agent`,inheritGlobal:`继承全局设置`,editAgentTitle:`编辑此 Agent`,deleteAgentTitle:`删除此 Agent`,noMatchProxy:`没有匹配的代理`,unnamedProxy:`未命名代理`,enableTitle:`启用此代理`,disableTitle:`禁用此代理`,noMatchAll:`没有匹配的 Agent、网页或代理`,noTitle:`无标题`,proxyAddress:`代理地址`,deleteProxyTitle:`删除此代理`,confirmDeleteProxy:`确定要删除此代理吗?`},knowledgeSelector:{disabled:`知识库检索已关闭(可在设置页「知识库」中开启)`,notAvailable:`知识库不可用(请确认代理已连接、检索依赖已安装)`,noCollections:`暂无知识库(可在设置页「知识库」中创建)`,docChunk:`{docs} 文档 · {chunks} 分块`,docsCount:`{docs} 文档`,chunksCount:`{chunks} 分块`,openDocsTitle:`在配置页打开该知识库的文档管理`,disabledBadge:`已停用`,disabledTooltip:`已停用(大模型不会自主检索该库),仍可手动 @ 引用`,manualSuffix:`手动引用`}}),n(`en`,{promptSelector:{noMatchAgent:`No matching agent`,inheritGlobal:`Inherit global settings`,editAgentTitle:`Edit this agent`,deleteAgentTitle:`Delete this agent`,noMatchProxy:`No matching proxy`,unnamedProxy:`Unnamed proxy`,enableTitle:`Enable this proxy`,disableTitle:`Disable this proxy`,noMatchAll:`No matching agent, page or proxy`,noTitle:`Untitled`,proxyAddress:`Proxy address`,deleteProxyTitle:`Delete this proxy`,confirmDeleteProxy:`Are you sure you want to delete this proxy?`},knowledgeSelector:{disabled:`Knowledge retrieval is turned off (you can enable it in Settings - Knowledge)`,notAvailable:`Knowledge base unavailable (check the agent connection and installed retrieval dependencies)`,noCollections:`No knowledge base yet (create one in Settings - Knowledge)`,docChunk:`{docs} docs · {chunks} chunks`,docsCount:`{docs} docs`,chunksCount:`{chunks} chunks`,openDocsTitle:`Open this knowledge base's documents in Settings`,disabledBadge:`Disabled`,disabledTooltip:`Disabled (the model won't search this knowledge base autonomously); you can still reference it manually via @`,manualSuffix:`manual`}});var Rb=`pages`;async function zb(){try{let e=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]);return(e.pairedAgents||[]).map(t=>({...t,isActive:t.id===e.activeAgentId,isDisabled:!!t.disabled}))}catch{return[]}}var Bb=!1;async function Vb(e=``,t=null){let n=document.getElementById(`agentAtSelector`),r=document.getElementById(`agentAtDropdown`);Je(),n.style.display=`block`,r.classList.add(`show`),Gb(),t?await Kb(t):await qb(e),Hb()}async function Hb(){try{let[e,t,n,i]=await Promise.all([_t(),Ox(),zb(),Sx()]),a=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="agents"]`),o=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="pages"]`),s=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="proxies"]`),c=document.querySelector(`#agentAtTabs .prompt-tab[data-tab="knowledge"]`);a&&(a.textContent=r(`promptSelector.agentsCount`,{count:e.length})),o&&(o.textContent=r(`promptSelector.pagesCount`,{count:t.length})),s&&(s.textContent=r(`promptSelector.proxiesCount`,{count:n.length}),s.style.display=n.length>0?``:`none`),c&&(c.textContent=r(`promptSelector.knowledgeCount`,{count:i.collections.length}),c.style.display=i.ok?``:`none`,!i.ok&&Rb===`knowledge`&&Kb(`pages`))}catch{}}function Ub(e){let t=document.querySelector(`#agentAtDropdown .prompt-dropdown-header > span[data-i18n]`);if(!t)return;let n=e===`knowledge`?`promptSelector.switchHintMulti`:`promptSelector.agentHeaderHint`;t.textContent=r(n),t.setAttribute(`data-i18n`,n)}function Wb(){let e=document.getElementById(`agentAtSelector`),t=document.getElementById(`agentAtDropdown`);e.style.display=`none`,t.classList.remove(`show`),C.selectedAgentAtIndex=-1,C.selectedPageIndex=-1,C.selectedProxyAtIndex=-1,C.selectedKnowledgeAtIndex=-1}function Gb(){let e=document.getElementById(`agentAtDropdown`);if(!e||e.dataset.initialized)return;e.dataset.initialized=`1`,e.addEventListener(`mousedown`,e=>{e.target.closest(`.prompt-item, .prompt-tab, .skill-list-item, .mcp-list-item`)&&e.preventDefault()});let t=document.getElementById(`agentAtTabs`);t&&t.querySelectorAll(`.prompt-tab`).forEach(e=>{e.addEventListener(`click`,()=>{Kb(e.dataset.tab)})}),e.addEventListener(`click`,async e=>{if(e.target.closest(`#agentAddBtn`)){e.stopPropagation(),Wb(),oO(null);return}if(e.target.closest(`#proxyAddBtn`)){e.stopPropagation(),Wb(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`agent`});return}if(e.target.closest(`#knowledgeAddBtn`)){e.stopPropagation(),Wb(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`knowledge`});return}if(e.target.closest(`#pageAddBtn`)){e.stopPropagation(),Wb(),chrome.tabs.create({});return}let t=e.target.closest(`.agent-edit-btn`);if(t){e.stopPropagation();let n=t.dataset.agentId;Wb(),oO(n);return}let n=e.target.closest(`.agent-delete-btn`);if(n){e.stopPropagation();let t=n.dataset.agentId;if(await EO(t)){let e=document.getElementById(`userInput`);await qb(e?Jb(e.value,e.selectionStart):``)}}})}async function Kb(e){Rb=e,Ub(e);let t=document.getElementById(`agentAtTabs`);t&&t.querySelectorAll(`.prompt-tab`).forEach(t=>{t.classList.toggle(`active`,t.dataset.tab===e)});let n=document.getElementById(`agentAtList`),r=document.getElementById(`agentPageList`),i=document.getElementById(`agentProxyList`),a=document.getElementById(`agentKnowledgeList`);n&&(n.style.display=e===`agents`?``:`none`),r&&(r.style.display=e===`pages`?``:`none`),i&&(i.style.display=e===`proxies`?``:`none`),a&&(a.style.display=e===`knowledge`?``:`none`);let o=document.getElementById(`agentAtDropdown`);o&&o.setAttribute(`data-active-tab`,e);let s=document.getElementById(`userInput`);s&&s.focus(),await qb(s?Jb(s.value,s.selectionStart):``)}async function qb(e=``){let t=document.getElementById(`agentAtTabs`),n=document.getElementById(`agentPageList`),r=document.getElementById(`agentAtList`),i=document.getElementById(`agentProxyList`),a=document.getElementById(`agentKnowledgeList`);if(e){Bb=!0,Ub(`merged`),t&&t.classList.add(`merged-mode`),n&&(n.style.display=`none`),i&&(i.style.display=`none`),a&&(a.style.display=`none`),r&&(r.style.display=``),await ax(e);let o=document.getElementById(`agentAtDropdown`);o&&o.setAttribute(`data-active-tab`,`merged`)}else{Bb=!1,Ub(Rb),t&&t.classList.remove(`merged-mode`),t&&t.querySelectorAll(`.prompt-tab`).forEach(e=>{e.classList.toggle(`active`,e.dataset.tab===Rb)}),n&&(n.style.display=Rb===`pages`?``:`none`),r&&(r.style.display=Rb===`agents`?``:`none`),i&&(i.style.display=Rb===`proxies`?``:`none`),a&&(a.style.display=Rb===`knowledge`?``:`none`);let e=document.getElementById(`agentAtDropdown`);e&&e.setAttribute(`data-active-tab`,Rb),Rb===`pages`?await kx(``):Rb===`proxies`?await ix(``):Rb===`knowledge`?await Cx(``):await Zb(``)}}function Jb(e,t){let n=wa({value:e,caret:t});return!n||n.key!==`at`?``:n.filterText}function Yb(e){return e.id==="default"?r(`agentMgr.defaultAgentName`):e.name}function Xb(e){return e.id==="default"?r(`agentMgr.defaultAgentDesc`):e.description}async function Zb(e=``){let t=document.getElementById(`agentAtList`);if(!t)return;let n=await _t(),i=(e||``).toLowerCase(),a=n.filter(t=>{if(!e)return!0;let n=Yb(t),r=Xb(t);return n&&n.toLowerCase().includes(i)||r&&r.toLowerCase().includes(i)});if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`promptSelector.noMatchAgent`)}</div>`,C.selectedAgentAtIndex=-1;return}C.selectedAgentAtIndex=0,t.innerHTML=a.map((e,t)=>{let n=e.id===C.activeAgentId||!C.activeAgentId&&e.id==="default",i=e.toolIds?e.toolIds.length:e.toolIds===null?null:0,a=i===null?r(`promptSelector.inheritGlobal`):r(`promptSelector.toolCount`,{count:i}),o=Yb(e),s=Xb(e);return`
|
|
1289
1291
|
<div class="prompt-item ${t===0?`selected`:``} ${n?`agent-at-active`:``}"
|
|
1290
1292
|
data-index="${t}" data-agent-id="${L(e.id)}">
|
|
1291
1293
|
<span class="prompt-item-index">${t+1}</span>
|
|
@@ -1298,7 +1300,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1298
1300
|
${e.isBuiltin?``:`<span class="agent-delete-btn" data-agent-id="${L(e.id)}" title="${r(`promptSelector.deleteAgentTitle`)}">✕</span>`}
|
|
1299
1301
|
</span>
|
|
1300
1302
|
</div>
|
|
1301
|
-
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{t.target.closest(`.agent-edit-btn`)||t.target.closest(`.agent-delete-btn`)||await
|
|
1303
|
+
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{t.target.closest(`.agent-edit-btn`)||t.target.closest(`.agent-delete-btn`)||await lx(e.dataset.agentId)})})}async function Qb(e){if(!e?.url)return{online:!1};try{let t=new AbortController;setTimeout(()=>t.abort(),2e3);let n=await fetch(`${e.url}/api/status`,{signal:t.signal});if(!n.ok)return{online:!1};let r=await n.json();return{online:!0,version:r.version||null,platformName:r.platformName||r.platform||null,arch:r.arch||null}}catch{return{online:!1}}}var $b=new Map,ex=1e4;function tx(e){let t=$b.get(e.id);return t&&Date.now()-t.ts<ex?t:null}function nx(e,t){return e.isDisabled?`disabled`:e.isActive?t?`connected`:`disconnected`:t?`online`:`offline`}async function rx(e){if(tx(e))return;let t=await Qb(e);$b.set(e.id,{online:t.online,version:t.version||null,platformName:t.platformName||null,ts:Date.now()}),document.querySelectorAll(`.prompt-item-proxy`).forEach(n=>{if(n.dataset.proxyId===e.id){let r=n.querySelector(`.agent-at-dot`);r&&(r.className=`agent-at-dot agent-at-dot-${nx(e,t.online)}`)}})}async function ix(e=``){let t=document.getElementById(`agentProxyList`);if(!t)return;let n=await zb(),i=(e||``).toLowerCase(),a=n.filter(t=>e?t.name.toLowerCase().includes(i)||t.url&&t.url.toLowerCase().includes(i):!0);if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`promptSelector.noMatchProxy`)}</div>`,C.selectedProxyAtIndex=-1;return}C.selectedProxyAtIndex=0,t.innerHTML=a.map((e,t)=>{let n=tx(e),i=e.isActive,a=e.isDisabled,o=nx(e,n?n.online:!1),s=e.name||r(`promptSelector.unnamedProxy`);return`
|
|
1302
1304
|
<div class="prompt-item ${t===0?`selected`:``} ${i?`agent-at-active`:``} ${a?`agent-disabled`:``} prompt-item-proxy"
|
|
1303
1305
|
data-index="${t}" data-proxy-id="${L(e.id)}">
|
|
1304
1306
|
<span class="prompt-item-index">${t+1}</span>
|
|
@@ -1311,7 +1313,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1311
1313
|
${a?`<span class="proxy-enable-btn" data-action="enable" data-id="${L(e.id)}" title="${r(`promptSelector.enableTitle`)}">▶</span>`:`<span class="proxy-disable-btn" data-action="disable" data-id="${L(e.id)}" title="${r(`promptSelector.disableTitle`)}">⏸</span>`}
|
|
1312
1314
|
<span class="proxy-delete-btn" data-action="delete" data-id="${L(e.id)}" title="${r(`common.delete`)}">✕</span>
|
|
1313
1315
|
</div>
|
|
1314
|
-
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=t.target.closest(`.proxy-disable-btn, .proxy-delete-btn, .proxy-enable-btn`);if(n){t.stopPropagation(),await
|
|
1316
|
+
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=t.target.closest(`.proxy-disable-btn, .proxy-delete-btn, .proxy-enable-btn`);if(n){t.stopPropagation(),await Dx(n.dataset.action,n.dataset.id);return}await wx(e.dataset.proxyId)})}),a.forEach(e=>rx(e))}async function ax(e=``){let t=document.getElementById(`agentAtList`);if(!t)return;let n=e.toLowerCase(),[i,a,o,s]=await Promise.all([_t(),Ox(),zb(),Sx()]),c=i.filter(e=>{let t=Yb(e),r=Xb(e);return t&&t.toLowerCase().includes(n)||r&&r.toLowerCase().includes(n)}),l=a.filter(e=>{if(!e.url)return!1;let t=(e.title||``).toLowerCase().includes(n),r=e.url.toLowerCase().includes(n);return t||r}),u=o.filter(e=>e.name.toLowerCase().includes(n)||e.url&&e.url.toLowerCase().includes(n)),d=s.ok?s.collections.filter(e=>e.name&&e.name.toLowerCase().includes(n)||e.description&&e.description.toLowerCase().includes(n)):[],f=c.length+l.length+u.length+d.length,p=document.getElementById(`agentAtMergedTitle`);if(p&&(p.textContent=r(`promptSelector.mergedTitleCount`,{count:f})),f===0){t.innerHTML=`<div class="prompt-empty">${r(`promptSelector.noMatchAll`)}</div>`,C.selectedAgentAtIndex=-1;return}C.selectedAgentAtIndex=0;let m=``,h=0;c.forEach(e=>{let t=e.id===C.activeAgentId||!C.activeAgentId&&e.id==="default",n=e.toolIds?e.toolIds.length:e.toolIds===null?null:0,i=n===null?r(`promptSelector.inheritGlobal`):r(`promptSelector.toolCount`,{count:n}),a=Yb(e),o=Xb(e);m+=`
|
|
1315
1317
|
<div class="prompt-item${h===0?` selected`:``}${t?` agent-at-active`:``}"
|
|
1316
1318
|
data-index="${h}" data-type="agent" data-agent-id="${L(e.id)}">
|
|
1317
1319
|
<span class="prompt-item-index">${h+1}</span>
|
|
@@ -1344,8 +1346,8 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1344
1346
|
<span class="agent-at-icon">📚</span>
|
|
1345
1347
|
<span class="prompt-item-content">${L(e.name||``)}</span>
|
|
1346
1348
|
${n?`<span class="knowledge-item-badge badge-disabled">${r(`knowledgeSelector.disabledBadge`)}</span>`:``}
|
|
1347
|
-
<span class="prompt-item-code">${
|
|
1348
|
-
</div>`,h++}),u.forEach(e=>{let t=e.isActive,n=e.isDisabled,i=
|
|
1349
|
+
<span class="prompt-item-code">${fx(e)}</span>
|
|
1350
|
+
</div>`,h++}),u.forEach(e=>{let t=e.isActive,n=e.isDisabled,i=tx(e),a=nx(e,i?i.online:!1),o=e.name||r(`promptSelector.unnamedProxy`);m+=`
|
|
1349
1351
|
<div class="prompt-item${h===0?` selected`:``}${t?` agent-at-active`:``}${n?` agent-disabled`:``} prompt-item-proxy"
|
|
1350
1352
|
data-index="${h}" data-type="proxy" data-proxy-id="${L(e.id)}">
|
|
1351
1353
|
<span class="prompt-item-index">${h+1}</span>
|
|
@@ -1355,22 +1357,22 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1355
1357
|
${t?`<span class="agent-item-actions"><span class="agent-active-mark">✓</span></span>`:``}
|
|
1356
1358
|
${n?`<span class="proxy-enable-btn" data-action="enable" data-id="${L(e.id)}" title="${r(`promptSelector.enableTitle`)}">▶</span>`:`<span class="proxy-disable-btn" data-action="disable" data-id="${L(e.id)}" title="${r(`promptSelector.disableTitle`)}">⏸</span>`}
|
|
1357
1359
|
<span class="proxy-delete-btn" data-action="delete" data-id="${L(e.id)}" title="${r(`common.delete`)}">✕</span>
|
|
1358
|
-
</div>`,h++}),t.innerHTML=m,t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),u.forEach(e=>
|
|
1360
|
+
</div>`,h++}),t.innerHTML=m,t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),u.forEach(e=>rx(e)),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),Px(parseInt(n.dataset.tabId),n.dataset.action);return}let r=t.target.closest(`.proxy-disable-btn, .proxy-delete-btn, .proxy-enable-btn`);if(r){t.stopPropagation(),await Dx(r.dataset.action,r.dataset.id);return}if(t.target.closest(`.agent-edit-btn`)||t.target.closest(`.agent-delete-btn`))return;if(t.target.closest(`.kb-docs-link`)){t.stopPropagation(),px(e.dataset.kbId);return}let i=e.dataset.type;i===`agent`?await lx(e.dataset.agentId):i===`page`?ux(parseInt(e.dataset.tabId)):i===`knowledge`?(mx({id:e.dataset.kbId,name:e.dataset.kbName,enabled:e.dataset.kbDisabled!==`1`}),(t.ctrlKey||t.metaKey)&&Wb()):i===`proxy`&&await wx(e.dataset.proxyId)})})}function ox(e){let t;t=Bb?C.selectedAgentAtIndex:Rb===`proxies`?C.selectedProxyAtIndex:Rb===`knowledge`?C.selectedKnowledgeAtIndex:C.selectedAgentAtIndex,e.forEach((e,n)=>{n===t?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function sx(){let e=document.getElementById(`userInput`);if(!e)return;let t=Ea(e.value,e.selectionStart,`at`);t&&(e.value=t.value,e.selectionStart=e.selectionEnd=t.caret),e.focus()}function cx(){let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}async function lx(e,{clearTrigger:t=!0}={}){t?sx():cx(),Wb(),await GD(e),ut()}function ux(e){sx(),chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){i.error(`[AgentAtSelector] getlabelpageinfo failed:`,chrome.runtime.lastError);return}jx(e),Wb();let t=document.getElementById(`userInput`);t&&(t.focus(),ut())})}function dx(){let e=new Set(C.knowledgeRefs.map(e=>e.id));document.querySelectorAll(`.prompt-item-knowledge`).forEach(t=>{let n=e.has(t.dataset.kbId);t.classList.toggle(`agent-at-active`,n),t.classList.toggle(`picked`,n)})}function fx(e){let t=r(`knowledgeSelector.docsCount`,{docs:e.documentCount||0}),n=r(`knowledgeSelector.chunksCount`,{chunks:e.chunkCount||0});return`<span class="kb-docs-link" title="${L(r(`knowledgeSelector.openDocsTitle`))}">${L(t)}</span> · ${L(n)}`}function px(e){e&&(Wb(),chrome.storage.local.set({pendingKbDocs:{id:e,ts:Date.now()}}).catch(()=>{}),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`knowledge`}))}function mx(e,{clearTrigger:t=!0,toggle:n=!0}={}){t?sx():cx();let r=C.knowledgeRefs.findIndex(t=>t.id===e.id);r>=0?n&&C.knowledgeRefs.splice(r,1):C.knowledgeRefs.push({id:e.id,name:e.name||e.id,enabled:e.enabled!==!1}),dx(),vx(),ut()}function hx(e,{multi:t=!1}={}){mx(e,{toggle:t}),t||Wb()}function gx(e){C.knowledgeRefs=C.knowledgeRefs.filter(t=>t.id!==e),dx(),vx()}function _x(){C.knowledgeRefs=[],dx(),vx()}function vx(){let e=document.getElementById(`knowledgeIndicator`);if(e){if(C.knowledgeRefs.length===0){e.style.display=`none`,e.innerHTML=``;return}e.innerHTML=C.knowledgeRefs.map(e=>{let t=e.enabled===!1,n=t?`${e.name} (${r(`knowledgeSelector.manualSuffix`)})`:e.name;return`
|
|
1359
1361
|
<span class="knowledge-chip${t?` knowledge-chip-manual`:``}">
|
|
1360
1362
|
<span class="knowledge-chip-name" title="${L(t?r(`knowledgeSelector.disabledTooltip`):e.name)}">📚 ${L(n)}</span>
|
|
1361
1363
|
<button class="knowledge-chip-close" data-kb-id="${L(e.id)}" title="${r(`common.delete`)}">✕</button>
|
|
1362
1364
|
</span>
|
|
1363
|
-
`}).join(``),e.querySelectorAll(`.knowledge-chip-close`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),
|
|
1365
|
+
`}).join(``),e.querySelectorAll(`.knowledge-chip-close`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),gx(e.dataset.kbId)})}),e.style.display=`flex`}}var yx={ok:!1,collections:[],ts:0},bx=null,xx=15e3;async function Sx(e=!1){let t=Date.now(),{ragEnabled:n}=await chrome.storage.local.get(`ragEnabled`);return n===!0?!e&&yx.ts&&t-yx.ts<xx?yx:bx||(bx=new Promise(e=>{try{chrome.runtime.sendMessage({type:`RAG_LIST_COLLECTIONS`},t=>{yx=chrome.runtime.lastError||!t||!t.success?{ok:!1,collections:[],ts:Date.now()}:{ok:!0,collections:[...t.collections||[]].sort((e,t)=>(e.enabled===!1)-+(t.enabled===!1)),ts:Date.now()},e(yx)})}catch{yx={ok:!1,collections:[],ts:Date.now()},e(yx)}}).finally(()=>{bx=null}),bx):{ok:!1,disabled:!0,collections:[],ts:Date.now()}}async function Cx(e=``){let t=document.getElementById(`agentKnowledgeList`);if(!t)return;let n=await Sx();if(!n.ok){t.innerHTML=`<div class="prompt-empty">${r(n.disabled?`knowledgeSelector.disabled`:`knowledgeSelector.notAvailable`)}</div>`,C.selectedKnowledgeAtIndex=-1;return}let i=(e||``).toLowerCase(),a=n.collections.filter(t=>e?t.name&&t.name.toLowerCase().includes(i)||t.description&&t.description.toLowerCase().includes(i):!0);if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`knowledgeSelector.noCollections`)}</div>`,C.selectedKnowledgeAtIndex=-1;return}C.selectedKnowledgeAtIndex=0,t.innerHTML=a.map((e,t)=>{let n=C.knowledgeRefs.some(t=>t.id===e.id),i=e.enabled===!1;return`
|
|
1364
1366
|
<div class="prompt-item ${t===0?`selected`:``} ${n?`agent-at-active picked`:``} ${i?`knowledge-item-disabled`:``} prompt-item-knowledge"
|
|
1365
|
-
data-index="${t}" data-kb-id="${L(e.id)}" data-kb-name="${L(e.name||``)}"
|
|
1367
|
+
data-index="${t}" data-type="knowledge" data-kb-id="${L(e.id)}" data-kb-name="${L(e.name||``)}"
|
|
1366
1368
|
data-kb-disabled="${i?`1`:`0`}"${i?` title="${L(r(`knowledgeSelector.disabledTooltip`))}"`:``}>
|
|
1367
1369
|
<span class="prompt-item-index">${t+1}</span>
|
|
1368
1370
|
<span class="agent-at-icon">📚</span>
|
|
1369
1371
|
<span class="prompt-item-content">${L(e.name||``)}</span>
|
|
1370
1372
|
${i?`<span class="knowledge-item-badge badge-disabled">${r(`knowledgeSelector.disabledBadge`)}</span>`:``}
|
|
1371
|
-
<span class="prompt-item-code">${
|
|
1373
|
+
<span class="prompt-item-code">${fx(e)}</span>
|
|
1372
1374
|
</div>
|
|
1373
|
-
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{if(t.target.closest(`.kb-docs-link`)){t.stopPropagation(),
|
|
1375
|
+
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{if(t.target.closest(`.kb-docs-link`)){t.stopPropagation(),px(e.dataset.kbId);return}mx({id:e.dataset.kbId,name:e.dataset.kbName,enabled:e.dataset.kbDisabled!==`1`}),(t.ctrlKey||t.metaKey)&&Wb()})})}async function wx(e,{clearTrigger:t=!0}={}){t?sx():cx(),Wb();try{await chrome.storage.local.set({activeAgentId:e}),chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}),i.debug(`[AgentAtSelector] switched to agent:`,e)}catch(e){i.error(`[AgentAtSelector] switchagent failed:`,e)}ut()}var Tx=!1;function Ex(){Tx||(Tx=!0,chrome.tabs.onActivated.addListener(()=>{let e=document.getElementById(`agentAtSelector`);if(!e||e.style.display!==`block`||Rb!==`pages`&&!Bb)return;let t=document.getElementById(`userInput`);qb(t?Jb(t.value,t.selectionStart):``)}))}Ex();async function Dx(e,t){let n=await chrome.storage.local.get([`pairedAgents`,`activeAgentId`]),i=n.pairedAgents||[];switch(e){case`enable`:i=i.map(e=>e.id===t?{...e,disabled:!1}:e),await chrome.storage.local.set({pairedAgents:i});break;case`disable`:{i=i.map(e=>e.id===t?{...e,disabled:!0}:e);let e=n.activeAgentId;n.activeAgentId===t&&(e=i.find(e=>e.id!==t&&!e.disabled)?.id||null),await chrome.storage.local.set({pairedAgents:i,activeAgentId:e||``}),e?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:e}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}case`delete`:{let e=i.find(e=>e.id===t),a=e?.url?`\n${r(`promptSelector.proxyAddress`)}: ${e.url}`:``;if(!await window.showCustomConfirm(r(`promptSelector.deleteProxyTitle`),r(`promptSelector.confirmDeleteProxy`,{name:e?.name||t,urlInfo:a})))return;i=i.filter(e=>e.id!==t);let o=n.activeAgentId===t?i.find(e=>!e.disabled)?.id||null:n.activeAgentId;await chrome.storage.local.set({pairedAgents:i,activeAgentId:o||``}),o?chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!0,agentId:o}):chrome.runtime.sendMessage({type:`AGENT_CONNECTION_CHANGED`,connected:!1});break}}let a=document.getElementById(`userInput`);await qb(a?Jb(a.value,a.selectionStart):``)}n(`zh`,{pageSelector:{noOpenPages:`暂无打开的网页`,noTitle:`无标题`,currentTab:`当前`,openNewTab:`新建标签页`,interpretPage:`解读`,summarizePage:`总结`,translatePage:`翻译`,interpretMsg:`解读一下当前网页`,summarizeMsg:`总结一下当前网页`,translateMsg:`翻译一下当前网页`}}),n(`en`,{pageSelector:{noOpenPages:`No open pages`,noTitle:`Untitled`,currentTab:`Current`,openNewTab:`Open new tab`,interpretPage:`Interpret`,summarizePage:`Summarize`,translatePage:`Translate`,interpretMsg:`Interpret the current webpage`,summarizeMsg:`Summarize the current webpage`,translateMsg:`Translate the current webpage`}});async function Ox(){try{return[...await chrome.tabs.query({currentWindow:!0})].sort((e,t)=>e.active===t.active?0:e.active?-1:1)}catch(e){return i.error(`[PageSelector] getlabelpage failed:`,e),[]}}async function kx(e=``){let t=document.getElementById(`agentPageList`);if(!t)return;let n=await Ox(),i=e.toLowerCase(),a=n.filter(t=>{if(!t.url)return!1;if(!e)return!0;let n=(t.title||``).toLowerCase().includes(i),r=t.url.toLowerCase().includes(i);return n||r});if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`pageSelector.noOpenPages`)}</div>`,C.selectedPageIndex=-1;return}C.selectedPageIndex=0;let o=C.selectedPage?C.selectedPage.id:null;t.innerHTML=a.map((e,t)=>{let n=e.title||r(`pageSelector.noTitle`),i=e.url||``,a=e.favIconUrl?`<img src="${L(e.favIconUrl)}" width="16" height="16" style="flex-shrink:0;" class="favicon-img">`:`<span style="font-size:14px;flex-shrink:0;">🌐</span>`,s=e.active?`<span class="current-tab-badge">${r(`pageSelector.currentTab`)}</span>`:``,c=e.id===o;return`
|
|
1374
1376
|
<div class="prompt-item prompt-item-page ${t===0?`selected`:``}"
|
|
1375
1377
|
data-index="${t}" data-tab-id="${e.id}">
|
|
1376
1378
|
<span class="prompt-item-index">${t+1}</span>
|
|
@@ -1385,8 +1387,8 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1385
1387
|
<span class="page-action-btn" data-action="translate" data-tab-id="${e.id}" title="${r(`pageSelector.translatePage`)}">${r(`pageSelector.translatePage`)}</span>
|
|
1386
1388
|
</span>
|
|
1387
1389
|
</div>
|
|
1388
|
-
`}).join(``),t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),Ox(parseInt(n.dataset.tabId),n.dataset.action);return}Dx(parseInt(e.dataset.tabId))})})}function wx(e){e.forEach((e,t)=>{t===C.selectedPageIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function Tx(e){C.selectedPage={id:e.id,title:e.title||r(`pageSelector.noTitle`),url:e.url||``,favIconUrl:e.favIconUrl||``};let t=document.getElementById(`pageIndicator`),n=document.getElementById(`pageIndicatorName`);if(t&&n){let e=C.selectedPage.title&&C.selectedPage.title!==r(`pageSelector.noTitle`)?C.selectedPage.title:``,i=C.selectedPage.url||``;e&&i?n.textContent=`${e} · ${i}`:n.textContent=e||i,t.style.display=`flex`}}function Ex(){C.selectedPage=null,C.selectedPageIndex=-1;let e=document.getElementById(`pageIndicator`);e&&(e.style.display=`none`)}function Dx(e){let t=document.getElementById(`userInput`),n=t?t.value:``,r=n.lastIndexOf(`@`);r!==-1&&(t.value=n.substring(0,r)),t&&(t.focus(),t.selectionStart=t.selectionEnd=t.value.length),chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){i.error(`[PageSelector] getlabelpageinfo failed:`,chrome.runtime.lastError);return}Tx(e),zb(),t&&(t.focus(),ut())})}function Ox(e,t){let n={interpret:r(`pageSelector.interpretMsg`),summarize:r(`pageSelector.summarizeMsg`),translate:r(`pageSelector.translateMsg`)}[t];n&&chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){i.error(`[PageSelector] get tab info failed:`,chrome.runtime.lastError);return}Tx(e),zb();let t=document.getElementById(`userInput`);t&&(t.value=n,ut()),rT()})}function kx(){let e=document.getElementById(`pageIndicatorClose`);e&&e.addEventListener(`click`,()=>{Ex()})}n(`zh`,{msgFullscreen:{title:`全屏阅读`,btnTitle:`全屏查看本回答 (Alt+双击 / Alt+F)`,btnLabel:`全屏`,copy:`复制`,copyTitle:`复制回答内容(Ctrl/⌘+点击复制富文本)`,export:`导出`,exportTitle:`导出下载本回答`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,close:`退出全屏`,closeTitle:`退出全屏 (Esc)`}}),n(`en`,{msgFullscreen:{title:`Fullscreen Reading`,btnTitle:`View this answer fullscreen (Alt+Double-click / Alt+F)`,btnLabel:`Fullscreen`,copy:`Copy`,copyTitle:`Copy answer (Ctrl/Cmd+click for rich text)`,export:`Export`,exportTitle:`Export / download this answer`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,close:`Exit fullscreen`,closeTitle:`Exit fullscreen (Esc)`}});var Ax=`messageFullscreenOverlay`,jx=`messageFullscreenBody`,Mx=`messageFullscreenTitle`,Nx=`messageFullscreenCopyBtn`,Px=`messageFullscreenCloseBtn`,Fx=`messageFullscreenExportBtn`,Ix=`messageFullscreenExportDropdown`,Lx=null,Rx=null,zx=null,Bx=!1,Vx=null,Hx=!1;function Ux(){return Lx!==null}function Wx(e){return!e||Ux()?null:e.innerHTML}function Gx(){let e=document.querySelectorAll(`#chatContainer .message.assistant`);return e.length?e[e.length-1]:null}function Kx(){let e=document.createElement(`button`);return e.className=`fullscreen-btn`,e.title=r(`msgFullscreen.btnTitle`),e.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">`,`<path d="M6 2H2v4M10 2h4v4M6 14H2v-4M10 14h4v-4"/>`,`</svg>`,`<span>${r(`msgFullscreen.btnLabel`)}</span>`].join(``),e}function qx(){let e=document.getElementById(Ax),t=document.getElementById(jx);return!e||!t?(i.warn(`[MsgFullscreen] overlay/body element missing`),null):{overlay:e,body:t,title:document.getElementById(Mx),copyBtn:document.getElementById(Nx),closeBtn:document.getElementById(Px)}}function Jx(e){if(!e)return;let t=qx();if(t&&Lx!==e){if(!Lx){let e=document.getElementById(`chatContainer`);Vx=e?e.scrollTop:null}Lx&&(Hx=!0,Yx(),Hx=!1),Rx=document.createComment(`msg-fullscreen-anchor`),e.parentNode.insertBefore(Rx,e),e.dataset.fullscreen=`1`,t.body.appendChild(e),Lx=e,t.overlay.style.display=`flex`,document.body.classList.add(`message-fullscreen-viewing`),t.title&&(t.title.textContent=r(`msgFullscreen.title`)),t.copyBtn&&(t.copyBtn.title=r(`msgFullscreen.copyTitle`)),t.closeBtn&&(t.closeBtn.title=r(`msgFullscreen.closeTitle`)),aS(),Zx(t.body)}}function Yx(){if(!Lx)return;let e=qx();if($x(),oS(),Rx&&Rx.parentNode)Rx.parentNode.insertBefore(Lx,Rx);else if(e){let e=document.getElementById(`chatContainer`);e&&e.appendChild(Lx)}if(Rx&&Rx.parentNode&&Rx.parentNode.removeChild(Rx),delete Lx.dataset.fullscreen,Lx=null,Rx=null,e){e.overlay.style.display=`none`,e.body.innerHTML=``;let t=e.overlay.querySelector(`.message-fullscreen-rail`);t&&t.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove())}if(document.body.classList.remove(`message-fullscreen-viewing`),!Hx&&Vx!==null){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=Vx),Vx=null}}function Xx(e){if(Lx&&Lx===e){Yx();return}Jx(e||Gx())}function Zx(e){$x(),Bx=!1,e.scrollTop=e.scrollHeight,e.addEventListener(`scroll`,Qx,{passive:!0}),typeof ResizeObserver<`u`&&(zx=new ResizeObserver(()=>{Bx||(e.scrollTop=e.scrollHeight)}),zx.observe(e.firstElementChild||e))}function Qx(){let e=document.getElementById(jx);e&&(Bx=e.scrollHeight-e.scrollTop-e.clientHeight>60)}function $x(){let e=document.getElementById(jx);e&&e.removeEventListener(`scroll`,Qx),zx&&=(zx.disconnect(),null)}function eS(e){if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyF`){e.preventDefault(),Lx?Yx():Jx(Gx());return}e.key===`Escape`&&Lx&&(e.preventDefault(),e.stopImmediatePropagation(),Yx())}function tS(e){if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let t=e.target.closest?.(`#chatContainer .message.assistant`);t&&(e.preventDefault(),Xx(t))}async function nS(e){if(!Lx)return;let{copyAssistantMessage:t}=await A(async()=>{let{copyAssistantMessage:e}=await Promise.resolve().then(()=>lS);return{copyAssistantMessage:e}},void 0);t(Lx,document.getElementById(Nx),e)}var rS={docx:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6 8h4M6 10.5h4"/>`,pdf:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6.5 11.5c2-1 2.5-4 1-4s-1 4 2 4"/>`,image:`<rect x="2.5" y="3" width="11" height="10" rx="1.2"/><circle cx="6" cy="6.5" r="1"/><path d="M13.5 10 10 6.5 4.5 12.5"/>`,markdown:`<path d="M2.5 12V4l3 3 3-3v8"/><path d="M12.5 4v6m0 0 2-2.2m-2 2.2L10.5 7.8"/>`};function iS(){let e=document.createElement(`div`);e.className=`message-fullscreen-export`;let t=document.createElement(`button`);t.className=`message-fullscreen-icon-btn`,t.id=Fx,t.type=`button`,t.title=r(`msgFullscreen.exportTitle`),t.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="16" height="16">`,`<path d="M8 2v8m0 0 3-3M8 10 5 7M2.5 13.5h11"/>`,`</svg>`,`<span>${r(`msgFullscreen.export`)}</span>`,`<svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`].join(``);let n=document.createElement(`div`);n.className=`message-fullscreen-export-dropdown`,n.id=Ix;let i=e=>`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${rS[e]}</svg>`;n.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">${i(`docx`)}<span>${r(`msgFullscreen.exportWord`)}</span></button>`,`<button class="export-dropdown-item export-pdf-item" type="button">${i(`pdf`)}<span>${r(`msgFullscreen.exportPdf`)}</span></button>`,`<button class="export-dropdown-item export-image-item" type="button">${i(`image`)}<span>${r(`msgFullscreen.exportImage`)}</span></button>`,`<button class="export-dropdown-item export-md-item" type="button">${i(`markdown`)}<span>${r(`msgFullscreen.exportMarkdown`)}</span></button>`].join(``),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.toggle(`show`)});let a=(e,t)=>{let r=n.querySelector(e);r.addEventListener(`click`,async e=>{e.stopPropagation(),Lx&&(n.classList.remove(`show`),(await A(()=>import(`./chat-export-DRUG3mwM.js`),__vite__mapDeps([9,10,1,11,2,3,12,0])))[t](Lx,r,n))})};return a(`.export-docx-item`,`exportAssistantMessageToDocx`),a(`.export-pdf-item`,`exportAssistantMessageToPdf`),a(`.export-image-item`,`exportAssistantMessageToImage`),a(`.export-md-item`,`exportAssistantMessageToMarkdown`),e.appendChild(t),e.appendChild(n),e}function aS(){if(document.getElementById(Fx))return;let e=document.getElementById(Px),t=e?e.parentNode:document.querySelector(`.message-fullscreen-actions`);t&&t.insertBefore(iS(),e||null)}function oS(){let e=document.getElementById(Ix);e&&e.classList.remove(`show`)}var sS=!1;function cS(){sS||(sS=!0,document.addEventListener(`click`,e=>{let t=document.getElementById(Ix);t&&t.classList.contains(`show`)&&!e.target.closest?.(`.message-fullscreen-export`)&&t.classList.remove(`show`);let n=e.target.closest?.(`.fullscreen-btn`);if(n){e.stopPropagation(),Xx(n.closest(`.message`));return}if(e.target.closest?.(`#messageFullscreenCloseBtn`)){e.stopPropagation(),Yx();return}e.target.closest?.(`#messageFullscreenCopyBtn`)&&(e.stopPropagation(),nS(e))},!0),document.addEventListener(`keydown`,eS,!0),document.addEventListener(`dblclick`,tS,!0))}var lS=t({copyAssistantMessage:()=>fS,copyMessage:()=>dS,copyRichText:()=>hS,fallbackCopyRichText:()=>_S,fallbackCopyText:()=>mS,quoteAndAsk:()=>bS,setQuoteContextInjector:()=>yS,showCopySuccess:()=>pS,wrapHtmlWithStyles:()=>gS});n(`zh`,{chatCopy:{copiedMarkdown:`已复制 Markdown`,copiedRich:`已复制富文本`,copyFailedManual:`复制失败,请手动复制`}}),n(`en`,{chatCopy:{copiedMarkdown:`Markdown copied`,copiedRich:`Rich text copied`,copyFailedManual:`Copy failed, please copy manually`}});function uS(e){let t=e.querySelectorAll(`.mermaid`),n=null;for(let e of t)try{if(!n&&e._pngDataUrl){let t=e._pngDataUrl.split(`,`)[1]||``,r=atob(t),i=r.length,a=new Uint8Array(i);for(let e=0;e<i;e++)a[e]=r.charCodeAt(e);n=new Blob([a],{type:`image/png`})}let t=e.getAttribute(`data-raw-code`),r=t?decodeURIComponent(t):e.dataset.rawMermaidCode||(e.textContent||``).trim();if(r){let t=r.split(`
|
|
1389
|
-
`),n=document.createElement(`pre`);n.appendChild(document.createTextNode(t[0]||``));for(let e=1;e<t.length;e++)n.appendChild(document.createElement(`br`)),n.appendChild(document.createTextNode(t[e]));e.parentNode.replaceChild(n,e)}else e.remove()}catch(t){i.warn(`[SidePanel] Mermaid chartprocessing failed,remove:`,t.message),e.remove()}return{html:e.innerHTML,firstPngBlob:n}}function
|
|
1390
|
+
`}).join(``),t.querySelectorAll(`img.favicon-img`).forEach(e=>{e.addEventListener(`error`,()=>{e.style.display=`none`})}),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),Px(parseInt(n.dataset.tabId),n.dataset.action);return}Nx(parseInt(e.dataset.tabId))})})}function Ax(e){e.forEach((e,t)=>{t===C.selectedPageIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function jx(e){C.selectedPage={id:e.id,title:e.title||r(`pageSelector.noTitle`),url:e.url||``,favIconUrl:e.favIconUrl||``};let t=document.getElementById(`pageIndicator`),n=document.getElementById(`pageIndicatorName`);if(t&&n){let e=C.selectedPage.title&&C.selectedPage.title!==r(`pageSelector.noTitle`)?C.selectedPage.title:``,i=C.selectedPage.url||``;e&&i?n.textContent=`${e} · ${i}`:n.textContent=e||i,t.style.display=`flex`}}function Mx(){C.selectedPage=null,C.selectedPageIndex=-1;let e=document.getElementById(`pageIndicator`);e&&(e.style.display=`none`)}function Nx(e){let t=document.getElementById(`userInput`);if(t){let e=Ea(t.value,t.selectionStart,`at`);e&&(t.value=e.value,t.selectionStart=t.selectionEnd=e.caret),t.focus()}chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){i.error(`[PageSelector] getlabelpageinfo failed:`,chrome.runtime.lastError);return}jx(e),Wb(),t&&(t.focus(),ut())})}function Px(e,t){let n={interpret:r(`pageSelector.interpretMsg`),summarize:r(`pageSelector.summarizeMsg`),translate:r(`pageSelector.translateMsg`)}[t];n&&chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){i.error(`[PageSelector] get tab info failed:`,chrome.runtime.lastError);return}jx(e),Wb();let t=document.getElementById(`userInput`);t&&(t.value=n,ut()),lT()})}function Fx(){let e=document.getElementById(`pageIndicatorClose`);e&&e.addEventListener(`click`,()=>{Mx()})}n(`zh`,{msgFullscreen:{title:`全屏阅读`,btnTitle:`全屏查看本回答 (Alt+双击 / Alt+F)`,btnLabel:`全屏`,copy:`复制`,copyTitle:`复制回答内容(Ctrl/⌘+点击复制富文本)`,export:`导出`,exportTitle:`导出下载本回答`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,close:`退出全屏`,closeTitle:`退出全屏 (Esc)`}}),n(`en`,{msgFullscreen:{title:`Fullscreen Reading`,btnTitle:`View this answer fullscreen (Alt+Double-click / Alt+F)`,btnLabel:`Fullscreen`,copy:`Copy`,copyTitle:`Copy answer (Ctrl/Cmd+click for rich text)`,export:`Export`,exportTitle:`Export / download this answer`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,close:`Exit fullscreen`,closeTitle:`Exit fullscreen (Esc)`}});var Ix=`messageFullscreenOverlay`,Lx=`messageFullscreenBody`,Rx=`messageFullscreenTitle`,zx=`messageFullscreenCopyBtn`,Bx=`messageFullscreenCloseBtn`,Vx=`messageFullscreenExportBtn`,Hx=`messageFullscreenExportDropdown`,Ux=null,Wx=null,Gx=null,Kx=!1,qx=null,Jx=!1;function Yx(){return Ux!==null}function Xx(e){return!e||Yx()?null:e.innerHTML}function Zx(){let e=document.querySelectorAll(`#chatContainer .message.assistant`);return e.length?e[e.length-1]:null}function Qx(){let e=document.createElement(`button`);return e.className=`fullscreen-btn`,e.title=r(`msgFullscreen.btnTitle`),e.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">`,`<path d="M6 2H2v4M10 2h4v4M6 14H2v-4M10 14h4v-4"/>`,`</svg>`,`<span>${r(`msgFullscreen.btnLabel`)}</span>`].join(``),e}function $x(){let e=document.getElementById(Ix),t=document.getElementById(Lx);return!e||!t?(i.warn(`[MsgFullscreen] overlay/body element missing`),null):{overlay:e,body:t,title:document.getElementById(Rx),copyBtn:document.getElementById(zx),closeBtn:document.getElementById(Bx)}}function eS(e){if(!e)return;let t=$x();if(t&&Ux!==e){if(!Ux){let e=document.getElementById(`chatContainer`);qx=e?e.scrollTop:null}Ux&&(Jx=!0,tS(),Jx=!1),Wx=document.createComment(`msg-fullscreen-anchor`),e.parentNode.insertBefore(Wx,e),e.dataset.fullscreen=`1`,t.body.appendChild(e),Ux=e,t.overlay.style.display=`flex`,document.body.classList.add(`message-fullscreen-viewing`),t.title&&(t.title.textContent=r(`msgFullscreen.title`)),t.copyBtn&&(t.copyBtn.title=r(`msgFullscreen.copyTitle`)),t.closeBtn&&(t.closeBtn.title=r(`msgFullscreen.closeTitle`)),dS(),rS(t.body)}}function tS(){if(!Ux)return;let e=$x();if(aS(),fS(),Wx&&Wx.parentNode)Wx.parentNode.insertBefore(Ux,Wx);else if(e){let e=document.getElementById(`chatContainer`);e&&e.appendChild(Ux)}if(Wx&&Wx.parentNode&&Wx.parentNode.removeChild(Wx),delete Ux.dataset.fullscreen,Ux=null,Wx=null,e){e.overlay.style.display=`none`,e.body.innerHTML=``;let t=e.overlay.querySelector(`.message-fullscreen-rail`);t&&t.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove())}if(document.body.classList.remove(`message-fullscreen-viewing`),!Jx&&qx!==null){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=qx),qx=null}}function nS(e){if(Ux&&Ux===e){tS();return}eS(e||Zx())}function rS(e){aS(),Kx=!1,e.scrollTop=e.scrollHeight,e.addEventListener(`scroll`,iS,{passive:!0}),typeof ResizeObserver<`u`&&(Gx=new ResizeObserver(()=>{Kx||(e.scrollTop=e.scrollHeight)}),Gx.observe(e.firstElementChild||e))}function iS(){let e=document.getElementById(Lx);e&&(Kx=e.scrollHeight-e.scrollTop-e.clientHeight>60)}function aS(){let e=document.getElementById(Lx);e&&e.removeEventListener(`scroll`,iS),Gx&&=(Gx.disconnect(),null)}function oS(e){if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyF`){e.preventDefault(),Ux?tS():eS(Zx());return}e.key===`Escape`&&Ux&&(e.preventDefault(),e.stopImmediatePropagation(),tS())}function sS(e){if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let t=e.target.closest?.(`#chatContainer .message.assistant`);t&&(e.preventDefault(),nS(t))}async function cS(e){if(!Ux)return;let{copyAssistantMessage:t}=await A(async()=>{let{copyAssistantMessage:e}=await Promise.resolve().then(()=>hS);return{copyAssistantMessage:e}},void 0);t(Ux,document.getElementById(zx),e)}var lS={docx:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6 8h4M6 10.5h4"/>`,pdf:`<path d="M4 1.5h6L13 4.5v10H4z"/><path d="M10 1.5v3h3"/><path d="M6.5 11.5c2-1 2.5-4 1-4s-1 4 2 4"/>`,image:`<rect x="2.5" y="3" width="11" height="10" rx="1.2"/><circle cx="6" cy="6.5" r="1"/><path d="M13.5 10 10 6.5 4.5 12.5"/>`,markdown:`<path d="M2.5 12V4l3 3 3-3v8"/><path d="M12.5 4v6m0 0 2-2.2m-2 2.2L10.5 7.8"/>`};function uS(){let e=document.createElement(`div`);e.className=`message-fullscreen-export`;let t=document.createElement(`button`);t.className=`message-fullscreen-icon-btn`,t.id=Vx,t.type=`button`,t.title=r(`msgFullscreen.exportTitle`),t.innerHTML=[`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" width="16" height="16">`,`<path d="M8 2v8m0 0 3-3M8 10 5 7M2.5 13.5h11"/>`,`</svg>`,`<span>${r(`msgFullscreen.export`)}</span>`,`<svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`].join(``);let n=document.createElement(`div`);n.className=`message-fullscreen-export-dropdown`,n.id=Hx;let i=e=>`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${lS[e]}</svg>`;n.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">${i(`docx`)}<span>${r(`msgFullscreen.exportWord`)}</span></button>`,`<button class="export-dropdown-item export-pdf-item" type="button">${i(`pdf`)}<span>${r(`msgFullscreen.exportPdf`)}</span></button>`,`<button class="export-dropdown-item export-image-item" type="button">${i(`image`)}<span>${r(`msgFullscreen.exportImage`)}</span></button>`,`<button class="export-dropdown-item export-md-item" type="button">${i(`markdown`)}<span>${r(`msgFullscreen.exportMarkdown`)}</span></button>`].join(``),t.addEventListener(`click`,e=>{e.stopPropagation(),n.classList.toggle(`show`)});let a=(e,t)=>{let r=n.querySelector(e);r.addEventListener(`click`,async e=>{e.stopPropagation(),Ux&&(n.classList.remove(`show`),(await A(()=>import(`./chat-export-DcDe1GQ_.js`),__vite__mapDeps([9,10,1,11,2,3,12,0])))[t](Ux,r,n))})};return a(`.export-docx-item`,`exportAssistantMessageToDocx`),a(`.export-pdf-item`,`exportAssistantMessageToPdf`),a(`.export-image-item`,`exportAssistantMessageToImage`),a(`.export-md-item`,`exportAssistantMessageToMarkdown`),e.appendChild(t),e.appendChild(n),e}function dS(){if(document.getElementById(Vx))return;let e=document.getElementById(Bx),t=e?e.parentNode:document.querySelector(`.message-fullscreen-actions`);t&&t.insertBefore(uS(),e||null)}function fS(){let e=document.getElementById(Hx);e&&e.classList.remove(`show`)}var pS=!1;function mS(){pS||(pS=!0,document.addEventListener(`click`,e=>{let t=document.getElementById(Hx);t&&t.classList.contains(`show`)&&!e.target.closest?.(`.message-fullscreen-export`)&&t.classList.remove(`show`);let n=e.target.closest?.(`.fullscreen-btn`);if(n){e.stopPropagation(),nS(n.closest(`.message`));return}if(e.target.closest?.(`#messageFullscreenCloseBtn`)){e.stopPropagation(),tS();return}e.target.closest?.(`#messageFullscreenCopyBtn`)&&(e.stopPropagation(),cS(e))},!0),document.addEventListener(`keydown`,oS,!0),document.addEventListener(`dblclick`,sS,!0))}var hS=t({copyAssistantMessage:()=>vS,copyMessage:()=>_S,copyRichText:()=>xS,fallbackCopyRichText:()=>CS,fallbackCopyText:()=>bS,quoteAndAsk:()=>ES,setQuoteContextInjector:()=>TS,showCopySuccess:()=>yS,wrapHtmlWithStyles:()=>SS});n(`zh`,{chatCopy:{copiedMarkdown:`已复制 Markdown`,copiedRich:`已复制富文本`,copyFailedManual:`复制失败,请手动复制`}}),n(`en`,{chatCopy:{copiedMarkdown:`Markdown copied`,copiedRich:`Rich text copied`,copyFailedManual:`Copy failed, please copy manually`}});function gS(e){let t=e.querySelectorAll(`.mermaid`),n=null;for(let e of t)try{if(!n&&e._pngDataUrl){let t=e._pngDataUrl.split(`,`)[1]||``,r=atob(t),i=r.length,a=new Uint8Array(i);for(let e=0;e<i;e++)a[e]=r.charCodeAt(e);n=new Blob([a],{type:`image/png`})}let t=e.getAttribute(`data-raw-code`),r=t?decodeURIComponent(t):e.dataset.rawMermaidCode||(e.textContent||``).trim();if(r){let t=r.split(`
|
|
1391
|
+
`),n=document.createElement(`pre`);n.appendChild(document.createTextNode(t[0]||``));for(let e=1;e<t.length;e++)n.appendChild(document.createElement(`br`)),n.appendChild(document.createTextNode(t[e]));e.parentNode.replaceChild(n,e)}else e.remove()}catch(t){i.warn(`[SidePanel] Mermaid chartprocessing failed,remove:`,t.message),e.remove()}return{html:e.innerHTML,firstPngBlob:n}}function _S(e,t){try{let n=e.dataset.textContent_||e.dataset.rawContent||``;navigator.clipboard.writeText(n).then(()=>{let e=t.innerHTML;t.innerHTML=`
|
|
1390
1392
|
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
|
|
1391
1393
|
<path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0z"/>
|
|
1392
1394
|
</svg>
|
|
@@ -1394,12 +1396,12 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1394
1396
|
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
|
|
1395
1397
|
<path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0z"/>
|
|
1396
1398
|
</svg>
|
|
1397
|
-
`,t.classList.add(`copied`),setTimeout(()=>{t.innerHTML=e,t.classList.remove(`copied`)},2e3)}catch{F(r(`chatCopy.copyFailed`),`error`)}document.body.removeChild(a)})}catch(e){i.error(`[SidePanel] copy failed:`,e),F(r(`chatCopy.copyFailed`),`error`)}}function
|
|
1399
|
+
`,t.classList.add(`copied`),setTimeout(()=>{t.innerHTML=e,t.classList.remove(`copied`)},2e3)}catch{F(r(`chatCopy.copyFailed`),`error`)}document.body.removeChild(a)})}catch(e){i.error(`[SidePanel] copy failed:`,e),F(r(`chatCopy.copyFailed`),`error`)}}function vS(e,t,n){try{let r=e.dataset.rawMarkdown||e.dataset.rawContent||``,i=``;if(!r){let t=C.messageHistory.find(e=>e.role===`assistant`);if(t)r=t.content;else{let t=e.querySelector(`.final-answer .markdown-body`)||e.querySelector(`.markdown-body`);t?(r=t.innerText,i=t.innerHTML):(r=e.innerText,i=e.innerHTML)}}if(!i){let t=e.querySelector(`.final-answer .markdown-body`)||e.querySelector(`.markdown-body`);t?i=t.innerHTML:r&&(i=tt(r))}if(n&&(n.ctrlKey||n.metaKey)&&i){let e=document.createElement(`div`);e.innerHTML=i,e.querySelectorAll(`table`).forEach(e=>{let t=at(e);e.parentNode.replaceChild(t,e)});let{html:n,firstPngBlob:a}=gS(e);xS(r,n,t,a)}else navigator.clipboard.writeText(r).then(()=>{t&&yS(t)}).catch(()=>{bS(r,t)})}catch(e){i.error(`[SidePanel] copy failed:`,e),F(r(`chatCopy.copyFailed`),`error`)}}function yS(e,t=!1){let n=e.innerHTML;e.innerHTML=`
|
|
1398
1400
|
<svg viewBox="0 0 16 16" fill="currentColor">
|
|
1399
1401
|
<path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0z"/>
|
|
1400
1402
|
</svg>
|
|
1401
1403
|
<span>${r(t?`chatCopy.copiedRich`:`chatCopy.copiedMarkdown`)}</span>
|
|
1402
|
-
`,e.classList.add(`copied`),setTimeout(()=>{e.innerHTML=n,e.classList.remove(`copied`)},2e3)}function
|
|
1404
|
+
`,e.classList.add(`copied`),setTimeout(()=>{e.innerHTML=n,e.classList.remove(`copied`)},2e3)}function bS(e,t){let n=document.createElement(`textarea`);n.value=e,n.style.position=`fixed`,n.style.left=`-999999px`,document.body.appendChild(n),n.select();try{document.execCommand(`copy`),yS(t)}catch{F(r(`chatCopy.copyFailedManual`),`error`)}document.body.removeChild(n)}function xS(e,t,n,r=null){let a=SS(t);if(n&&!document.hasFocus()&&n.focus(),typeof ClipboardItem<`u`){let t={"text/plain":new Blob([e],{type:`text/plain`}),"text/html":new Blob([a],{type:`text/html`})};r&&(t[`image/png`]=r);let o=new ClipboardItem(t);navigator.clipboard.write([o]).then(()=>{yS(n,!0)}).catch(t=>{i.warn(`[SidePanel] Clipboard API write failed,using fallback plan:`,t.message),CS(e,a,n)})}else CS(e,a,n)}function SS(e){return`<!DOCTYPE html><html><head>
|
|
1403
1405
|
<style>
|
|
1404
1406
|
h1 { font-size: 24px; font-weight: bold; margin: 16px 0 8px; }
|
|
1405
1407
|
h2 { font-size: 20px; font-weight: bold; margin: 14px 0 6px; }
|
|
@@ -1438,12 +1440,12 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1438
1440
|
a { color: #007bff; text-decoration: underline; }
|
|
1439
1441
|
img { max-width: 100%; }
|
|
1440
1442
|
</style>
|
|
1441
|
-
</head><body>${e}</body></html>`}function
|
|
1443
|
+
</head><body>${e}</body></html>`}function CS(e,t,n){n&&!document.hasFocus()&&n.focus();let r=document.createElement(`div`);r.style.position=`fixed`,r.style.left=`-999999px`,r.style.top=`-999999px`,r.innerHTML=t,document.body.appendChild(r);let i=document.createRange();i.selectNodeContents(r);let a=window.getSelection();a.removeAllRanges(),a.addRange(i);try{document.execCommand(`copy`),yS(n,!0)}catch{bS(e,n)}finally{a.removeAllRanges(),document.body.removeChild(r)}}var wS=null;function TS(e){wS=e}function ES(e){try{let t=e.dataset.rawMarkdown||e.dataset.rawContent||``;if(!t){i.warn(`[SidePanel] unable to getmessagecontent`);return}let n=document.getElementById(`userInput`);if(!n){i.warn(`[SidePanel] cannot find input box`);return}let a=e.querySelector(`.quote-btn`),o=a?a.innerHTML:``;wS&&wS(t),a&&(a.innerHTML=`
|
|
1442
1444
|
<svg viewBox="0 0 16 16" fill="currentColor">
|
|
1443
1445
|
<path d="M13.78 4.22a.75.75 0 0 1 0 1.06l-7.25 7.25a.75.75 0 0 1-1.06 0L2.22 9.28a.75.75 0 0 1 1.06-1.06L6 10.94l6.72-6.72a.75.75 0 0 1 1.06 0z"/>
|
|
1444
1446
|
</svg>
|
|
1445
1447
|
<span>${r(`chatCopy.quoted`)}</span>
|
|
1446
|
-
`,a.classList.add(`quoted`),setTimeout(()=>{a.innerHTML=o,a.classList.remove(`quoted`)},2e3)),n.focus(),i.debug(`[SidePanel] quote with messagecontent to prompt,input boxfocused`)}catch(e){i.error(`[SidePanel] quoted question failed:`,e),F(r(`chatCopy.quoteFailed`,{message:e.message}),`error`)}}n(`zh`,{chatPanels:{decisionPassed:`通过`,decisionRevised:`已修订`,decisionNeedsImprovement:`需改进`,dimAccuracy:`准确性`,dimCompleteness:`完整性`,dimRelevance:`相关性`,dimClarity:`清晰度`,dimUsefulness:`实用性`,dimSafety:`安全性`,dimEfficiency:`效率`,dimensionsTitle:`📊 评分维度`,issuesTitle:`❗ 发现的问题`,suggestionsTitle:`💡 改进建议`,roundsEvaluated:`评估 {rounds} 轮{revised}`,revisedTag:`(已修订)`,finalDecision:`最终决策:{label}`,resultUseful:`结果可用`,resultNeedsImprovement:`结果需改进`,processTitle:`🔄 评估过程`,scoreHighExplanation:`回答质量较高,内容准确、完整且清晰。`,scoreMidExplanation:`回答基本可用,但存在一些可以改进的地方。`,scoreLowExplanation:`回答质量较低,存在明显问题需要改进。`,reflectionTitle:`💡 质量评估详情`,overallScore:`综合评分`,scoreExplanationTitle:`📝 评分说明`,aboutTitle:`ℹ️ 关于质量评估`,aboutDesc:`质量评估由 AI 自动完成,从多个维度对回答进行打分,帮助判断回答的可靠程度。`,scoreStandard:`评分标准:8-10 分优秀,5-7 分良好,1-4 分需改进。`,executionLogTitle:`执行日志`,taskBreakdown:`任务拆解`,totalDurationTitle:`总耗时:{duration}`,totalDuration:`总耗时`,totalNodesTitle:`共 {count} 个执行节点`,totalNodes:`执行节点`,successCountTitle:`成功 {count} 个`,successLabel:`成功`,failedCountTitle:`失败 {count} 个`,failedLabel:`失败`,subtaskCountTitle:`子任务 {completed}/{total} 完成`,subtaskLabel:`子任务`,scoreTitle:`评分 {score}/10`,scoreLabel:`评分`,scoreUnavailable:`—`,tokenUsage:`Token 消耗`,tokenUsageTitle:`Token 消耗: {total} (Prompt: {prompt}, Completion: {completion})`,expandAll:`展开全部`,collapseAll:`收起全部`}}),n(`en`,{chatPanels:{decisionPassed:`Passed`,decisionRevised:`Revised`,decisionNeedsImprovement:`Needs Improvement`,dimAccuracy:`Accuracy`,dimCompleteness:`Completeness`,dimRelevance:`Relevance`,dimClarity:`Clarity`,dimUsefulness:`Usefulness`,dimSafety:`Safety`,dimEfficiency:`Efficiency`,dimensionsTitle:`📊 Scoring Dimensions`,issuesTitle:`❗ Issues Found`,suggestionsTitle:`💡 Suggestions`,roundsEvaluated:`Evaluated {rounds} rounds{revised}`,revisedTag:` (revised)`,finalDecision:`Final Decision: {label}`,resultUseful:`Result is useful`,resultNeedsImprovement:`Result needs improvement`,processTitle:`🔄 Evaluation Process`,scoreHighExplanation:`The answer is high quality, accurate, complete, and clear.`,scoreMidExplanation:`The answer is generally usable but has room for improvement.`,scoreLowExplanation:`The answer is low quality with obvious issues that need improvement.`,reflectionTitle:`💡 Quality Assessment Details`,overallScore:`Overall Score`,scoreExplanationTitle:`📝 Score Explanation`,aboutTitle:`ℹ️ About Quality Assessment`,aboutDesc:`Quality assessment is performed automatically by AI, scoring answers across multiple dimensions to help judge reliability.`,scoreStandard:`Scoring: 8-10 excellent, 5-7 good, 1-4 needs improvement.`,executionLogTitle:`Execution Log`,taskBreakdown:`Task Breakdown`,totalDurationTitle:`Total duration: {duration}`,totalDuration:`Duration`,totalNodesTitle:`{count} execution nodes`,totalNodes:`Nodes`,successCountTitle:`{count} succeeded`,successLabel:`Success`,failedCountTitle:`{count} failed`,failedLabel:`Failed`,subtaskCountTitle:`Subtasks {completed}/{total} done`,subtaskLabel:`Subtasks`,scoreTitle:`Score {score}/10`,scoreLabel:`Score`,scoreUnavailable:`—`,tokenUsage:`Token Usage`,tokenUsageTitle:`Token usage: {total} (Prompt: {prompt}, Completion: {completion})`,expandAll:`Expand All`,collapseAll:`Collapse All`}});function
|
|
1448
|
+
`,a.classList.add(`quoted`),setTimeout(()=>{a.innerHTML=o,a.classList.remove(`quoted`)},2e3)),n.focus(),i.debug(`[SidePanel] quote with messagecontent to prompt,input boxfocused`)}catch(e){i.error(`[SidePanel] quoted question failed:`,e),F(r(`chatCopy.quoteFailed`,{message:e.message}),`error`)}}n(`zh`,{chatPanels:{decisionPassed:`通过`,decisionRevised:`已修订`,decisionNeedsImprovement:`需改进`,dimAccuracy:`准确性`,dimCompleteness:`完整性`,dimRelevance:`相关性`,dimClarity:`清晰度`,dimUsefulness:`实用性`,dimSafety:`安全性`,dimEfficiency:`效率`,dimensionsTitle:`📊 评分维度`,issuesTitle:`❗ 发现的问题`,suggestionsTitle:`💡 改进建议`,roundsEvaluated:`评估 {rounds} 轮{revised}`,revisedTag:`(已修订)`,finalDecision:`最终决策:{label}`,resultUseful:`结果可用`,resultNeedsImprovement:`结果需改进`,processTitle:`🔄 评估过程`,scoreHighExplanation:`回答质量较高,内容准确、完整且清晰。`,scoreMidExplanation:`回答基本可用,但存在一些可以改进的地方。`,scoreLowExplanation:`回答质量较低,存在明显问题需要改进。`,reflectionTitle:`💡 质量评估详情`,overallScore:`综合评分`,scoreExplanationTitle:`📝 评分说明`,aboutTitle:`ℹ️ 关于质量评估`,aboutDesc:`质量评估由 AI 自动完成,从多个维度对回答进行打分,帮助判断回答的可靠程度。`,scoreStandard:`评分标准:8-10 分优秀,5-7 分良好,1-4 分需改进。`,executionLogTitle:`执行日志`,taskBreakdown:`任务拆解`,totalDurationTitle:`总耗时:{duration}`,totalDuration:`总耗时`,totalNodesTitle:`共 {count} 个执行节点`,totalNodes:`执行节点`,successCountTitle:`成功 {count} 个`,successLabel:`成功`,failedCountTitle:`失败 {count} 个`,failedLabel:`失败`,subtaskCountTitle:`子任务 {completed}/{total} 完成`,subtaskLabel:`子任务`,scoreTitle:`评分 {score}/10`,scoreLabel:`评分`,scoreUnavailable:`—`,tokenUsage:`Token 消耗`,tokenUsageTitle:`Token 消耗: {total} (Prompt: {prompt}, Completion: {completion})`,expandAll:`展开全部`,collapseAll:`收起全部`}}),n(`en`,{chatPanels:{decisionPassed:`Passed`,decisionRevised:`Revised`,decisionNeedsImprovement:`Needs Improvement`,dimAccuracy:`Accuracy`,dimCompleteness:`Completeness`,dimRelevance:`Relevance`,dimClarity:`Clarity`,dimUsefulness:`Usefulness`,dimSafety:`Safety`,dimEfficiency:`Efficiency`,dimensionsTitle:`📊 Scoring Dimensions`,issuesTitle:`❗ Issues Found`,suggestionsTitle:`💡 Suggestions`,roundsEvaluated:`Evaluated {rounds} rounds{revised}`,revisedTag:` (revised)`,finalDecision:`Final Decision: {label}`,resultUseful:`Result is useful`,resultNeedsImprovement:`Result needs improvement`,processTitle:`🔄 Evaluation Process`,scoreHighExplanation:`The answer is high quality, accurate, complete, and clear.`,scoreMidExplanation:`The answer is generally usable but has room for improvement.`,scoreLowExplanation:`The answer is low quality with obvious issues that need improvement.`,reflectionTitle:`💡 Quality Assessment Details`,overallScore:`Overall Score`,scoreExplanationTitle:`📝 Score Explanation`,aboutTitle:`ℹ️ About Quality Assessment`,aboutDesc:`Quality assessment is performed automatically by AI, scoring answers across multiple dimensions to help judge reliability.`,scoreStandard:`Scoring: 8-10 excellent, 5-7 good, 1-4 needs improvement.`,executionLogTitle:`Execution Log`,taskBreakdown:`Task Breakdown`,totalDurationTitle:`Total duration: {duration}`,totalDuration:`Duration`,totalNodesTitle:`{count} execution nodes`,totalNodes:`Nodes`,successCountTitle:`{count} succeeded`,successLabel:`Success`,failedCountTitle:`{count} failed`,failedLabel:`Failed`,subtaskCountTitle:`Subtasks {completed}/{total} done`,subtaskLabel:`Subtasks`,scoreTitle:`Score {score}/10`,scoreLabel:`Score`,scoreUnavailable:`—`,tokenUsage:`Token Usage`,tokenUsageTitle:`Token usage: {total} (Prompt: {prompt}, Completion: {completion})`,expandAll:`Expand All`,collapseAll:`Collapse All`}});function DS(e,t){let n=document.querySelector(`.reflection-info-overlay`);n&&n.remove();let i=document.createElement(`div`);i.className=`reflection-info-overlay`;let{overallScore:a,dimensions:o,issues:s,suggestions:c,decision:l,useful:u,reasoning:d,suggestion:f,rounds:p,wasRevised:m}=e,h=a>=8?`score-high`:a>=5?`score-mid`:`score-low`,g=a>=8?`✅`:a>=5?`🔍`:`⚠️`,_=l===`passed`?r(`chatPanels.decisionPassed`):l===`revised`?r(`chatPanels.decisionRevised`):l===`needs_improvement`?r(`chatPanels.decisionNeedsImprovement`):``,v={accuracy:r(`chatPanels.dimAccuracy`),completeness:r(`chatPanels.dimCompleteness`),relevance:r(`chatPanels.dimRelevance`),clarity:r(`chatPanels.dimClarity`),usefulness:r(`chatPanels.dimUsefulness`),safety:r(`chatPanels.dimSafety`),efficiency:r(`chatPanels.dimEfficiency`)},y=``;o&&Object.keys(o).length>0&&(y=`
|
|
1447
1449
|
<div class="ri-section">
|
|
1448
1450
|
<div class="ri-section-title">${r(`chatPanels.dimensionsTitle`)}</div>
|
|
1449
1451
|
<div class="ri-dimensions">
|
|
@@ -1498,7 +1500,7 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1498
1500
|
</div>
|
|
1499
1501
|
</div>
|
|
1500
1502
|
</div>
|
|
1501
|
-
`,document.body.appendChild(i),i.querySelector(`.ri-close`).addEventListener(`click`,()=>i.remove()),i.addEventListener(`click`,e=>{e.target===i&&i.remove()});let w=t.getBoundingClientRect(),T=i.querySelector(`.reflection-info-panel`),E=Math.min(window.innerHeight-40,560),D=w.right-380;D<10&&(D=10),D+380>window.innerWidth-10&&(D=window.innerWidth-380-10);let O=w.bottom+6;O+E>window.innerHeight-10&&(O=w.top-E-6),O<10&&(O=10),T.style.left=D+`px`,T.style.top=O+`px`,T.style.maxHeight=E+`px`}function
|
|
1503
|
+
`,document.body.appendChild(i),i.querySelector(`.ri-close`).addEventListener(`click`,()=>i.remove()),i.addEventListener(`click`,e=>{e.target===i&&i.remove()});let w=t.getBoundingClientRect(),T=i.querySelector(`.reflection-info-panel`),E=Math.min(window.innerHeight-40,560),D=w.right-380;D<10&&(D=10),D+380>window.innerWidth-10&&(D=window.innerWidth-380-10);let O=w.bottom+6;O+E>window.innerHeight-10&&(O=w.top-E-6),O<10&&(O=10),T.style.left=D+`px`,T.style.top=O+`px`,T.style.maxHeight=E+`px`}function OS(e){let t=document.querySelector(`.execution-log-panel`);t&&t.remove();let n=document.createElement(`div`);n.className=`execution-log-panel`;let i=e.reduce((e,t)=>e+(t.duration||0),0),a=e.filter(e=>e.status===`success`).length,o=e.filter(e=>e.status===`failed`).length,s=e.filter(e=>e.nodeType===`subtask`).length,c=e.filter(e=>e.nodeType===`subtask`&&e.status===`success`).length,l=e.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`plan_task`&&e.status===`success`).length,u=e.filter(e=>e.nodeType===`reflection`).find(e=>e.reflectionType===`post`),d=u&&u.overallScore!=null?`${u.overallScore}/10`:r(`chatPanels.scoreUnavailable`),f=Ge(e);n.innerHTML=`
|
|
1502
1504
|
<div class="log-container">
|
|
1503
1505
|
<div class="log-header">
|
|
1504
1506
|
<div class="log-title">
|
|
@@ -1577,19 +1579,19 @@ It is this session's directory or the agent default, so it stays accessible (wor
|
|
|
1577
1579
|
</div>
|
|
1578
1580
|
|
|
1579
1581
|
<div class="timeline">
|
|
1580
|
-
${
|
|
1582
|
+
${up(e)}
|
|
1581
1583
|
</div>
|
|
1582
1584
|
</div>
|
|
1583
|
-
`,document.body.appendChild(n)
|
|
1585
|
+
`,document.body.appendChild(n),rp(n),n.addEventListener(`click`,e=>{e.target===n&&n.remove()}),n.querySelector(`.log-close`).addEventListener(`click`,()=>{n.remove()});let p=n.querySelector(`.toggle-expand-btn`),m=n.querySelectorAll(`.timeline-content`),h=!1;p.addEventListener(`click`,()=>{h=!h,m.forEach(e=>{h?e.classList.add(`expanded`):e.classList.remove(`expanded`)});let e=p.querySelector(`svg`);h?(e.innerHTML=`<polyline points="17 11 12 6 7 11"></polyline><polyline points="17 18 12 13 7 18"></polyline>`,p.setAttribute(`title`,r(`chatPanels.collapseAll`))):(e.innerHTML=`<polyline points="7 13 12 18 17 13"></polyline><polyline points="7 6 12 11 17 6"></polyline>`,p.setAttribute(`title`,r(`chatPanels.expandAll`)))}),n.querySelectorAll(`.timeline-header`).forEach(e=>{e.addEventListener(`click`,()=>{e.parentElement.classList.toggle(`expanded`)})}),n.querySelectorAll(`.task-group-header`).forEach(e=>{e.addEventListener(`click`,()=>{e.parentElement.classList.toggle(`collapsed`)})});let g=n.querySelectorAll(`.combo-stat`),_=n.querySelectorAll(`.timeline-item`);g.forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.status,n=e.classList.contains(`active`);g.forEach(e=>e.classList.remove(`active`)),n?_.forEach(e=>{e.style.display=``}):(e.classList.add(`active`),_.forEach(e=>{if(t===`subtask`)e.classList.contains(`subtask-level`)?e.style.display=``:e.style.display=`none`;else{let n=e.querySelector(`.timeline-dot`);n&&n.classList.contains(t)?e.style.display=``:e.style.display=`none`}}))})})}n(`zh`,{chatResume:{title:`继续执行任务`,desc:`任务执行被中断,你可以提供补充说明帮助模型继续。`,budgetTitle:`执行预算已用完(部分完成)`,budgetDesc:`任务已到时间/轮数预算上限,以上回复是已完成部分与缺项清单。点击继续将在新的预算下接着未完成部分执行,可先补充说明调整目标。`,placeholder:`输入补充说明(可选)…`,continueBtn:`继续`,interruptedAgo:`({duration}前)`,taskInterrupted:`任务执行被中断{elapsed}`,checkpointNotFound:`检查点已失效,无法继续执行。请重新发送任务。`,taskCancelled:`任务已被用户停止`,swRestarted:`Service Worker 已重启,请重新发送任务`,resumeFailed:`恢复失败:{message}`,unknownError:`未知错误`}}),n(`en`,{chatResume:{title:`Continue Task`,desc:`The task was interrupted. You can provide additional guidance to help the model continue.`,budgetTitle:`Execution budget exhausted (partially complete)`,budgetDesc:`The task hit its time/round budget. The reply above lists what is completed and what remains. Press Continue to resume the unfinished parts with a fresh budget; you may add guidance first.`,placeholder:`Enter additional guidance (optional)…`,continueBtn:`Continue`,interruptedAgo:` ({duration} ago)`,taskInterrupted:`Task execution was interrupted{elapsed}`,checkpointNotFound:`The checkpoint has expired and the task cannot be resumed. Please resend the task.`,taskCancelled:`Task was stopped by user`,swRestarted:`Service Worker restarted. Please resend the task.`,resumeFailed:`Resume failed: {message}`,unknownError:`Unknown error`}});function kS(e={}){return new Promise(t=>{let n=document.createElement(`div`);n.className=`modal-overlay resume-dialog-overlay`,n.style.cssText=`display:flex;position:fixed;inset:0;background:var(--scrim);z-index:10000;align-items:center;justify-content:center;`;let i=document.createElement(`div`);i.className=`modal-container resume-dialog-container`,i.style.cssText=`background:var(--bg-surface);border-radius:8px;padding:24px;width:90%;max-width:480px;box-shadow:0 8px 32px var(--shadow-md);`;let a=document.createElement(`h3`);a.textContent=r(e.budgetEnded?`chatResume.budgetTitle`:`chatResume.title`),a.style.cssText=`margin:0 0 8px 0;font-size:16px;color:var(--text-primary);`;let o=document.createElement(`p`);o.textContent=r(e.budgetEnded?`chatResume.budgetDesc`:`chatResume.desc`),o.style.cssText=`margin:0 0 16px 0;font-size:13px;color:var(--text-secondary);line-height:1.5;`;let s=document.createElement(`textarea`);s.className=`resume-dialog-textarea`,s.placeholder=r(`chatResume.placeholder`),s.style.cssText=`width:100%;min-height:80px;padding:8px 12px;border:1px solid var(--border-default);border-radius:4px;font-size:13px;resize:vertical;box-sizing:border-box;font-family:inherit;line-height:1.5;`,s.rows=3;let c=document.createElement(`div`);c.style.cssText=`display:flex;justify-content:flex-end;gap:8px;margin-top:16px;`;let l=document.createElement(`button`);l.textContent=r(`common.cancel`),l.style.cssText=`padding:6px 16px;border:1px solid var(--border-default);background:var(--bg-surface);color:var(--text-secondary);border-radius:4px;cursor:pointer;font-size:13px;`;let u=document.createElement(`button`);u.textContent=r(`chatResume.continueBtn`),u.style.cssText=`padding:6px 16px;border:none;background:var(--info-500);color:var(--text-inverse);border-radius:4px;cursor:pointer;font-size:13px;font-weight:500;`,c.appendChild(l),c.appendChild(u),i.appendChild(a),i.appendChild(o),i.appendChild(s),i.appendChild(c),n.appendChild(i),document.body.appendChild(n),requestAnimationFrame(()=>s.focus());let d=()=>{n.remove(),document.removeEventListener(`keydown`,f)},f=e=>{e.key===`Escape`?(d(),t(null)):e.key===`Enter`&&(e.ctrlKey||e.metaKey)&&(d(),t(s.value.trim()))};l.addEventListener(`click`,()=>{d(),t(null)}),u.addEventListener(`click`,()=>{d(),t(s.value.trim())}),document.addEventListener(`keydown`,f)})}function AS(e){if(!e||e!==C.activeSessionId)return;let t=!1;for(let e of C.messageHistory)e.resumable&&(e.resumable=!1,t=!0);let n=document.getElementById(`chatContainer`);n&&n.querySelectorAll(`.message[data-resumable]:not([data-resumable="false"])`).forEach(e=>{e.removeAttribute(`data-resumable`);let t=e.querySelector(`.resume-task-btn`);t&&t.remove()}),t&&Rw()}async function jS(e,t){if(!(!e||!t))try{if(!(await chrome.runtime.sendMessage({type:`GET_CHECKPOINT`,sessionId:t}))?.exists){e.removeAttribute(`data-resumable`);let t=e.querySelector(`.resume-task-btn`);t&&t.remove();let n=e.dataset.messageId,r=C.messageHistory.find(e=>e.messageId===n);r&&r.resumable&&(r.resumable=!1,Rw())}}catch{}}function MS(e,t){if(!e||!t)return null;let n=e.querySelector(`:scope > .message-footer`);if(!n)return null;let i=n.querySelector(`.resume-task-btn`);if(i)return i;let a=t===`budget`,o=document.createElement(`button`);return o.className=`resume-task-btn`,o.type=`button`,o.title=r(a?`chatMsg.resumeTaskTitleBudget`:`chatMsg.resumeTaskTitle`),o.innerHTML=`
|
|
1584
1586
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1585
1587
|
<polygon points="5 3 19 12 5 21 5 3"></polygon>
|
|
1586
1588
|
</svg>
|
|
1587
1589
|
<span>${r(`chatMsg.resumeTaskBtn`)}</span>
|
|
1588
|
-
`,o.addEventListener(`click`,async e=>{if(e.stopPropagation(),o.disabled)return;let t=await
|
|
1590
|
+
`,o.addEventListener(`click`,async e=>{if(e.stopPropagation(),o.disabled)return;let t=await kS({budgetEnded:a});t!==null&&(o.disabled=!0,o.style.opacity=`0.6`,o.style.cursor=`not-allowed`,PS(C.activeSessionId,t).finally(()=>{o.disabled=!1,o.style.opacity=``,o.style.cursor=``}))}),n.appendChild(o),e.dataset.resumable=String(t),jS(e,C.activeSessionId),o}async function NS(){let e=C.activeSessionId;if(!e||C.pendingCallApiSessionIds&&C.pendingCallApiSessionIds.has(e))return;let t=C.messageHistory.some(e=>e.resumable),n=document.getElementById(`chatContainer`),a=n&&n.querySelector(`.resume-task-btn`);if(!(t&&a))try{let a=await chrome.runtime.sendMessage({type:`GET_CHECKPOINT`,sessionId:e});if(a?.running)return;if(a?.exists){i.debug(`[SidePanel] found abandoned checkpoint,auto addrestorehint card`),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:e}}));let o=a.checkpoint,s=o.updatedAt?Ve(Date.now()-o.updatedAt):``,c=r(`chatResume.taskInterrupted`,{elapsed:s?r(`chatResume.interruptedAgo`,{duration:s}):``});if(t){let e=C.messageHistory.find(e=>e.resumable);if(e&&(e.content=c,Rw()),n){let e=n.querySelector(`.message[data-resumable]:not([data-resumable="false"])`);if(!e){let t=n.querySelectorAll(`.message.assistant`);for(let n of t)if((n.textContent||``).includes(`任务执行被中断`)){e=n;break}}e&&e.remove()}}let{element:l,messageId:u}=_T(`assistant`,c,!0,[],null,!1,null,null,[],!0);t||(C.messageHistory.push({role:`assistant`,content:c,executionLog:[],messageId:u,resumable:!0,interrupted:!0}),Rw()),jS(l,e)}}catch(e){i.warn(`[SidePanel] check abandoned checkpoint failed:`,e.message)}}async function PS(e,t=``){if(!e)return i.warn(`[SidePanel] resumeTask: missing sessionId`),!1;if(C.activeSessionId!==e)return i.warn(`[SidePanel] resumeTask: currently activesessionwith targetsession not consistent,please switch firstto targetsession`),!1;if(C.pendingCallApiSessionIds&&C.pendingCallApiSessionIds.has(e))return i.warn(`[SidePanel] resumeTask: currentsession has ongoingtask`),!1;i.debug(`[SidePanel] resumeTask: startrestoretask, sessionId:`,e,`userGuidance:`,t?`"${t.substring(0,50)}..."`:`( no )`);try{let t=await chrome.runtime.sendMessage({type:`GET_CHECKPOINT`,sessionId:e});if(!t?.exists){i.warn(`[SidePanel] resumeTask: checkpoint not found, no way to restore, sessionId:`,e);let t=r(`chatResume.checkpointNotFound`),{messageId:n}=_T(`assistant`,t,!0,[]);return C.messageHistory.push({role:`assistant`,content:t,executionLog:[],messageId:n,resumable:!1,resumed:!0}),Rw(),AS(e),!1}i.debug(`[SidePanel] resumeTask: checkpoint verified, iteration:`,t.checkpoint?.iteration)}catch(e){i.warn(`[SidePanel] resumeTask: verify checkpoint hourcommunication failed,continue tryrestore:`,e.message)}let n=e,a=CT();C.isGenerating=!0;let o=``,s=[],c=null,l=!1,u=!1,d=!1,f=null,p=null;try{let e=await NT(null,null,!1,{},{resumeFromCheckpoint:!0,userGuidance:t,loadingId:a});o=e.content,s=e.executionLog||[],c=e.reflectionScore,l=e.wasRevised||!1,u=e.wasStreamed||!1,f=e.streamingHtml||null,e.streamingConnected!==void 0&&e.streamingConnected,p=e.streamingMsgId||null,d=e.budgetEnded===!0}catch(e){if(C.activeSessionId!==n){let t=e.message===r(`chatMsg.errTaskStopped`),i=!!e.checkpoint||e.swRestarted||t;return t?Pi(n,{role:`assistant`,content:r(`chatResume.taskCancelled`),executionLog:e.executionLog||[],resumable:i,resumed:!0}):e.swRestarted?Pi(n,{role:`assistant`,content:r(`chatResume.swRestarted`),executionLog:e.executionLog||[],resumable:i,resumed:!0}):Pi(n,{role:`assistant`,content:r(`chatResume.resumeFailed`,{message:e.message||r(`chatResume.unknownError`)}),executionLog:e.executionLog||[],resumable:!1,resumed:!0}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:n}})),wT(a),!1}if(e.message===r(`chatMsg.errTaskStopped`)){wT(a);let{messageId:t}=_T(`assistant`,r(`chatResume.taskCancelled`),!1,e.executionLog||[]);return C.messageHistory.push({role:`assistant`,content:r(`chatResume.taskCancelled`),executionLog:e.executionLog||[],messageId:t,resumable:!0,resumed:!0}),Rw(),!1}if(e.swRestarted){wT(a);let t=!!e.checkpoint,{messageId:n}=_T(`assistant`,r(`chatResume.swRestarted`),!1,e.executionLog||[]);return C.messageHistory.push({role:`assistant`,content:r(`chatResume.swRestarted`),executionLog:e.executionLog||[],messageId:n,resumable:t,resumed:!0}),Rw(),!1}wT(a);let t=r(`chatResume.resumeFailed`,{message:e.message||r(`chatResume.unknownError`)}),{element:i,messageId:o}=_T(`assistant`,t,!0,e.executionLog||[]);return C.messageHistory.push({role:`assistant`,content:t,executionLog:e.executionLog||[],messageId:o,resumable:!1,resumed:!0}),Rw(),!1}finally{Ql(n)}AS(n);let m=d?`budget`:!1;if(C.activeSessionId!==n){let e={role:`assistant`,content:o,executionLog:s,reflectionScore:c,wasRevised:l,resumable:m,resumed:!0};return u&&f&&(e.htmlContent=f),Pi(n,e),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:n}})),wT(a),!0}if(u&&f){let e=p;return C.messageHistory.push({role:`assistant`,content:o,executionLog:s,reflectionScore:c,wasRevised:l,resumable:m,messageId:e,resumed:!0,htmlContent:f}),Rw(),m&&MS(e?document.querySelector(`[data-message-id="${e}"]`):null,m),!0}wT(a);let{element:h,messageId:g}=_T(`assistant`,o,!0,s,c,l,null,null,[],m);return C.messageHistory.push({role:`assistant`,content:o,executionLog:s,reflectionScore:c,wasRevised:l,resumable:m,messageId:g,resumed:!0}),Rw(),h&<(h),!0}var FS=300*1024,IS=typeof TextEncoder<`u`?new TextEncoder:null;function LS(e){return e?IS?IS.encode(e).length:e.length*3:0}var RS=`streamSnap|`,zS=e=>`${RS}${e}`,BS=new Map,VS=null;function HS(){return typeof chrome<`u`&&chrome.storage&&chrome.storage.session&&typeof chrome.storage.session.set==`function`}function US(){if(VS||typeof window>`u`||!window.addEventListener||typeof document>`u`||!document.addEventListener)return;let e=()=>{qS()},t=()=>{document.visibilityState===`hidden`&&e()};VS={pagehide:e,onVisibility:t},window.addEventListener(`pagehide`,e),document.addEventListener(`visibilitychange`,t)}function WS(e,t,n){if(!e||!t||typeof n!=`function`||!HS())return;US();let r=BS.get(e)||{};r.callId!==t&&(r.oversizeLogged=!1),r.callId=t,r.read=n,r.timer||=setTimeout(()=>{let t=BS.get(e);t&&(t.timer=null,GS(e).catch(()=>{}))},700),BS.set(e,r)}async function GS(e){let t=BS.get(e);if(!t||(t.timer&&=(clearTimeout(t.timer),null),!HS()))return;let n;try{n=t.read()||{}}catch(e){i.debug(`[StreamSnapshot] 读取气泡内容失败(忽略):`,e?.message||e);return}let r=typeof n.html==`string`?n.html:``,a=typeof n.accumulated==`string`?n.accumulated:``,o=r,s=LS(r);s>307200&&(t.oversizeLogged||(t.oversizeLogged=!0,i.debug(`[StreamSnapshot] 快照 HTML ${s} 字节超过上限 ${FS},本次只存正文(接管后看不到工具卡片等富结构)`)),o=``);let c=`${o.length}|${a.length}|${o.slice(0,48)}|${o.slice(-48)}|${a.slice(-32)}`,l=Date.now();t.lastSig===c&&l-(t.lastWrittenAt||0)<3e4||(await chrome.storage.session.set({[zS(e)]:{sessionId:e,callId:t.callId,html:o,accumulated:a,ts:Date.now()}}),t.lastSig=c,t.lastWrittenAt=l)}function KS(e){let t=BS.get(e);t&&(t.timer&&clearTimeout(t.timer),BS.delete(e))}function qS(){return Promise.all([...BS.keys()].map(e=>GS(e).catch(e=>{i.debug(`[StreamSnapshot] 卸载前刷盘失败(忽略):`,e?.message||e)})))}async function JS(e){if(!e||!HS())return null;try{let t=await chrome.storage.session.get(zS(e)),n=t&&t[zS(e)];return!n||!n.callId?null:Date.now()-(n.ts||0)>18e5?(await YS(e),null):n}catch(e){return i.debug(`[StreamSnapshot] 读取快照失败(忽略):`,e?.message||e),null}}async function YS(e){let t=BS.get(e);if(t&&t.timer&&clearTimeout(t.timer),BS.delete(e),HS())try{await chrome.storage.session.remove(zS(e))}catch(e){i.debug(`[StreamSnapshot] 清除快照失败(忽略):`,e?.message||e)}}var XS=t({addStreamingMessage:()=>HC,appendThinkingIndicator:()=>KC,appendToolCallItems:()=>ow,appendToolResult:()=>bw,applyStreamSnapshot:()=>WC,attachAgentStreamChunk:()=>vw,autoScrollToBottom:()=>fC,bindProcessHeaderClick:()=>yC,cancelPendingAutoScroll:()=>pC,cancelStreamingTask:()=>Cw,createAgentStreamOutput:()=>cw,createCodeBlockHtml:()=>sw,createPreSelectCard:()=>xw,createStreamingElementAccessor:()=>OC,deleteStreamingState:()=>kC,finalizeCancelledStream:()=>ww,finalizeStreamingMessage:()=>Sw,flushPendingAgentStreams:()=>yw,getPendingPreselectLog:()=>MC,getProcessStartTime:()=>IC,getReasoningContent:()=>RC,getStreamedContent:()=>AC,getThinkingStartTime:()=>PC,initScrollToBottomBtn:()=>gC,markStreamingRetrying:()=>GC,mountStreamingElement:()=>JC,notifyNonStreamContentArrived:()=>_C,reconnectStreamingElement:()=>YC,refreshAgentNames:()=>bC,registerAgentStreamStore:()=>uw,renderStreamingContentFull:()=>iw,resetScrollState:()=>hC,resolveToolCallCard:()=>fw,scrollStreamingToBottom:()=>mC,setPendingPreselectLog:()=>NC,setProcessStartTime:()=>LC,setReasoningContent:()=>zC,setStreamedContent:()=>jC,setThinkingStartTime:()=>FC,updateScrollButtonState:()=>uC,updateStreamingMessage:()=>aw});n(`zh`,{chatStream:{thinking:`思考中...`,outputting:`输出中...`,retrying:`连接异常,正在重试 ({attempt}/{max})...`,stopGenerating:`停止生成`,thinkingResult:`思考结果`,toolActionOperate:`操作`,toolActionUpload:`上传`,toolActionDownload:`下载`,toolActionRequest:`请求`,toolActionInteract:`交互`,toolActionFill:`填写`,toolActionDispatch:`分派`,toolActionPreview:`预览`,toolActionRead:`读取`,toolActionWrite:`写入`,terminateCommand:`终止命令`,abortWaiting:`终止等待(跳过当前工具执行等待,不终止实际进程)`,executing:`执行中...`,terminating:`正在终止...`,copyCode:`复制代码`,truncatedTitle:`原始结果过大,已截断显示`,truncatedNote:`(输出过长已截断)`,noOutput:`(无输出)`,execFailed:`执行失败`,clickToExpand:`
|
|
1589
1591
|
... (点击展开查看完整输出)`,execResult:`执行结果`,statusFailed:`失败`,statusCompleted:`完成`,preselectFiltered:`从 {total} 个工具中筛选出 <strong>{count}</strong> 个:`,preselectSkippedAll:`跳过筛选({reason}),使用全部工具`,preselectSkippedCount:`跳过筛选({reason}),工具总数 {count}`,preselectDirectAnswer:`模型直接回答:`,toolPreselect:`工具预筛选`,toolsAfterFilter:`筛选后工具数:<strong>{count}</strong>`,listSeparator:`、`,totalNodes:`总节点`,successLabel:`成功`,failedLabel:`失败`,tokenLabel:`Token`,tokenUsageTitle:`Token 消耗: {total} (Prompt: {prompt}, Completion: {completion})`,thinkingProcess:`思考过程`,copyMarkdown:`复制 Markdown 内容 (Ctrl/Cmd + 点击复制富文本)`,copy:`复制`,quoteTitle:`引用该内容问答`,quote:`引用`,export:`导出`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,executionLog:`执行日志`,reflectionRoundsTag:` ({count}轮)`,qualityAssessmentTitle:`AI 质量评估: {score}/10{rounds}
|
|
1590
1592
|
点击查看评估详情`,reflectionFailedTitle:`反思评估失败(点击查看执行日志)`,reflectionFailedBadge:`⚠️ 反思失败`,prototypeOpenedLocal:`已在本地浏览器打开,点击可在面板内查看`,viewUiPrototype:`查看 UI 原型`,bookmarkMessage:`收藏消息`,removeBookmark:`取消收藏`,forkSession:`从此处分叉会话(仅复制到此条消息)`,deleteMessage:`删除消息`,stopping:`停止中...`,taskStopped:`任务已被用户停止`,cancelled:`已取消`}}),n(`en`,{chatStream:{thinking:`Thinking...`,outputting:`Outputting...`,retrying:`Connection unstable, retrying ({attempt}/{max})...`,stopGenerating:`Stop generating`,thinkingResult:`Thinking result`,toolActionOperate:`Operate`,toolActionUpload:`Upload`,toolActionDownload:`Download`,toolActionRequest:`Request`,toolActionInteract:`Interact`,toolActionFill:`Fill`,toolActionDispatch:`Dispatch`,toolActionPreview:`Preview`,toolActionRead:`Read`,toolActionWrite:`Write`,terminateCommand:`Terminate command`,abortWaiting:`Abort waiting (skip current tool wait, does not terminate the actual process)`,executing:`Executing...`,terminating:`Terminating...`,copyCode:`Copy code`,truncatedTitle:`Original result too large, truncated for display`,truncatedNote:`(output too long, truncated)`,noOutput:`(no output)`,execFailed:`Execution failed`,clickToExpand:`
|
|
1591
1593
|
... (click to expand and view full output)`,execResult:`Execution result`,statusFailed:`Failed`,statusCompleted:`Completed`,preselectFiltered:`Filtered <strong>{count}</strong> of {total} tools: `,preselectSkippedAll:`Skipped filtering ({reason}), using all tools`,preselectSkippedCount:`Skipped filtering ({reason}), total tools: {count}`,preselectDirectAnswer:`Model direct answer: `,toolPreselect:`Tool Pre-filter`,toolsAfterFilter:`Tools after filtering: <strong>{count}</strong>`,listSeparator:`, `,totalNodes:`Total nodes`,successLabel:`Success`,failedLabel:`Failed`,tokenLabel:`Token`,tokenUsageTitle:`Token usage: {total} (Prompt: {prompt}, Completion: {completion})`,thinkingProcess:`Thinking process`,copyMarkdown:`Copy Markdown content (Ctrl/Cmd + click to copy rich text)`,copy:`Copy`,quoteTitle:`Quote this content for Q&A`,quote:`Quote`,export:`Export`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,executionLog:`Execution log`,reflectionRoundsTag:` ({count} rounds)`,qualityAssessmentTitle:`AI quality assessment: {score}/10{rounds}
|
|
1592
|
-
Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection failed`,prototypeOpenedLocal:`Already opened in local browser, click to view in panel`,viewUiPrototype:`View UI prototype`,bookmarkMessage:`Bookmark message`,removeBookmark:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessage:`Delete message`,stopping:`Stopping...`,taskStopped:`Task stopped by user`,cancelled:`Cancelled`}});var
|
|
1594
|
+
Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection failed`,prototypeOpenedLocal:`Already opened in local browser, click to view in panel`,viewUiPrototype:`View UI prototype`,bookmarkMessage:`Bookmark message`,removeBookmark:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessage:`Delete message`,stopping:`Stopping...`,taskStopped:`Task stopped by user`,cancelled:`Cancelled`}});var ZS=new Map,QS=!1,$S=!1,eC=!1,tC=!1,nC=0,rC=null,iC=!1,aC=!1,oC=0,sC=0,cC=0,lC=0;function uC(){let e=document.getElementById(`scrollToBottomBtn`),t=document.getElementById(`scrollToBottomBadge`);if(!e)return;let n=document.getElementById(`chatContainer`);if(!n)return;let r=n.scrollHeight-n.scrollTop-n.clientHeight<80;r?(e.classList.remove(`visible`),tC=!1):e.classList.add(`visible`),t&&(tC&&!r?(t.classList.add(`active`),C.isGenerating?t.classList.add(`pulsing`):t.classList.remove(`pulsing`)):t.classList.remove(`active`,`pulsing`))}function dC(){if(eC)return;let e=document.getElementById(`chatContainer`);e&&(eC=!0,e.addEventListener(`scroll`,()=>{if(QS)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<80;$S=!t,t?tC=!1:C.isGenerating&&(tC=!0),uC()},{passive:!0}),document.addEventListener(`generating-state-changed`,()=>{C.isGenerating&&(tC=!0),requestAnimationFrame(()=>uC())}))}function fC(e,t={}){if(!e)return;dC();let{force:n=!1,smooth:r=!1}=t;if(!(!n&&Date.now()<lC)){if(!n&&$S){tC=!0,uC();return}rC=e,iC||=n,aC=r,!nC&&(QS=!0,nC=requestAnimationFrame(()=>{nC=0;let e=rC,t=iC,n=aC;if(rC=null,iC=!1,aC=!1,!e||!e.isConnected){QS=!1;return}if(!t&&$S){tC=!0,uC(),QS=!1;return}if(n){e.scrollTo({top:e.scrollHeight,behavior:`smooth`}),requestAnimationFrame(()=>{QS=!1});return}e.scrollTop=e.scrollHeight,sC&&cancelAnimationFrame(sC),sC=requestAnimationFrame(()=>{sC=0,e.isConnected&&!$S&&(e.scrollTop=e.scrollHeight),oC&&cancelAnimationFrame(oC),oC=requestAnimationFrame(()=>{oC=0,QS=!1})})}))}}function pC(){nC&&=(cancelAnimationFrame(nC),0),sC&&=(cancelAnimationFrame(sC),0),oC&&=(cancelAnimationFrame(oC),0),rC=null,iC=!1,aC=!1}function mC(e){if(!e||!e.isConnected)return;let t=document.getElementById(`chatContainer`);t&&fC(t)}function hC(){$S=!1,tC=!1,lC=0,C.isGenerating&&(tC=!0),uC()}function gC(){dC();let e=document.getElementById(`scrollToBottomBtn`);if(!e||e.dataset.bound)return;e.dataset.bound=`1`;let t=localStorage.getItem(`scrollBtnPosition`)||`center`;e.classList.add(`pos-${t}`);let n=!1,r=0,i=0,a=!1,o=0,s=!1;function c(){let t=document.getElementById(`chatContainer`);if(!t)return;let n=t.clientWidth,r={left:n/6,center:n/2,right:n*5/6},i=`center`,a=1/0;for(let[e,t]of Object.entries(r)){let n=Math.abs(o-t);n<a&&(a=n,i=e)}e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.classList.add(`pos-${i}`),e.style.left=``,e.style.marginLeft=``,e.style.right=``,localStorage.setItem(`scrollBtnPosition`,i)}function l(){let t=document.getElementById(`chatContainer`),n=e.getBoundingClientRect(),a=t?t.getBoundingClientRect():null,o=a?n.left-a.left+n.width/2:r;e.classList.remove(`pos-left`,`pos-center`,`pos-right`),e.style.left=`${o}px`,e.style.marginLeft=`0`,e.style.right=`auto`,e.classList.add(`dragging`),i=o,s=!0}function u(e){e.type===`mousedown`&&e.button!==0||(e.preventDefault(),n=!0,a=!1,s=!1,r=e.touches?e.touches[0].clientX:e.clientX)}function d(t){if(!n)return;let c=t.touches?t.touches[0].clientX:t.clientX;if(!s){if(Math.abs(c-r)<=3)return;a=!0,l()}let u=document.getElementById(`chatContainer`);if(!u)return;let d=u.getBoundingClientRect(),f=i+(c-r),p=e.offsetWidth/2;f=Math.max(p,Math.min(d.width-p,f)),o=f,e.style.left=`${f}px`}function f(){if(n){if(n=!1,a)e.classList.remove(`dragging`),c();else{s&&(e.classList.remove(`dragging`),e.style.left=``,e.style.marginLeft=``,e.style.right=``);let t=document.getElementById(`chatContainer`);t&&($S=!1,tC=!1,uC(),fC(t,{force:!0,smooth:!0}))}a=!1,s=!1}}e.addEventListener(`mousedown`,u),e.addEventListener(`touchstart`,u,{passive:!1}),document.addEventListener(`mousemove`,d),document.addEventListener(`touchmove`,d,{passive:!1}),document.addEventListener(`mouseup`,f),document.addEventListener(`touchend`,f),uC()}function _C(){dC();let e=document.getElementById(`chatContainer`);e&&(e.scrollHeight-e.scrollTop-e.clientHeight<80||(tC=!0),uC())}function vC(e,t){let n=e.querySelector(`.thinking-process-content`);if(!n)return;e.dataset.activeFilter=t,e.querySelectorAll(`.thinking-process-stat[data-filter]`).forEach(e=>{e.classList.toggle(`active`,e.dataset.filter===t)});let r=e=>t===`all`||e===t;n.querySelectorAll(`.tool-call-item`).forEach(e=>{e.classList.contains(`preselect-card`)||(e.style.display=r(e.dataset.status)?``:`none`)}),n.querySelectorAll(`.thinking-badge`).forEach(e=>{let t=r(e.dataset.status||`success`);e.style.display=t?``:`none`;let n=e.nextElementSibling;n&&n.classList.contains(`thinking-content`)&&(n.style.display=t?``:`none`)}),n.querySelectorAll(`.thinking-content`).forEach(e=>{let t=e.previousElementSibling;t&&t.classList.contains(`thinking-badge`)||(e.style.display=r(`success`)?``:`none`)})}function yC(e){if(!e||e._filterBound)return;e._filterBound=!0;let t=[``,`success`,`failed`];e.querySelectorAll(`.thinking-process-stat`).forEach((e,n)=>{t[n]&&(e.dataset.filter=t[n],e.classList.add(`filterable`))}),e.querySelectorAll(`.token-stat`).forEach(e=>{e.style.cursor=`pointer`}),e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=t.target.closest(`.thinking-process-stat`),r=e.closest(`.thinking-process`);if(r){if(n&&n.classList.contains(`token-stat`)){let e=r.closest(`.message`);if(e)try{let t=e.dataset.executionLog,r=Ge(t?JSON.parse(t):[]);r&&Ye(r,n)}catch{}return}n&&n.dataset.filter?vC(r,r.dataset.activeFilter===n.dataset.filter?`all`:n.dataset.filter):r.classList.toggle(`collapsed`)}});let n=e.closest(`.thinking-process`);n&&vC(n,n.dataset.activeFilter||`all`)}async function bC(){try{let{getAllAgents:e}=await A(async()=>{let{getAllAgents:e}=await import(`./agent-store-CeC2_dkP.js`).then(e=>e.t);return{getAllAgents:e}},__vite__mapDeps([0,1,2,3])),t=await e();ZS.clear();for(let e of t)ZS.set(e.id,e.name||e.id)}catch{}}function xC(e){return ZS.get(e)||e}var SC=new Map,CC=new Map,wC=null,TC=0,EC=0,DC=``;function OC(e){return t=>t===void 0?SC.get(e)||null:(SC.set(e,t),t)}function kC(e){SC.delete(e),CC.delete(e),YS(e)}function AC(e){return CC.get(e)||``}function jC(e,t){if(CC.set(e,t),!t){KS(e);return}UC(SC.get(e))}function MC(){return wC}function NC(e){wC=e}function PC(){return TC}function FC(e){TC=e}function IC(){return EC}function LC(e){EC=e}function RC(){return DC}function zC(e){DC=e}function BC(){return`
|
|
1593
1595
|
<svg class="thinking-icon pulse-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1594
1596
|
<path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/>
|
|
1595
1597
|
<circle cx="8" cy="12" r="1.5"/>
|
|
@@ -1604,15 +1606,15 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1604
1606
|
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
|
|
1605
1607
|
</svg>
|
|
1606
1608
|
</button>
|
|
1607
|
-
`}function
|
|
1609
|
+
`}function VC(e){e&&e.querySelectorAll(`.streaming-stop-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),Cw(e)})})}function HC(e){let t=document.getElementById(`chatContainer`),n=document.createElement(`div`);n.className=`message-wrapper assistant streaming`;let r=`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8);return n.dataset.messageId=r,n.dataset.sessionId=e||``,n.innerHTML=`
|
|
1608
1610
|
<div class="message-content">
|
|
1609
1611
|
<div class="stream-content"></div>
|
|
1610
|
-
<div class="thinking-indicator">${
|
|
1612
|
+
<div class="thinking-indicator">${BC()}</div>
|
|
1611
1613
|
<div class="stream-status hidden"></div>
|
|
1612
1614
|
</div>
|
|
1613
|
-
`,(!e||e===C.activeSessionId)&&t&&(t.appendChild(n),
|
|
1614
|
-
`,n),o=t===-1?e.length:t,s=e.slice(n,o),c=s.trim(),l=c.startsWith("```")||c.startsWith(`~~~`);if(l&&(r=!r),!r&&!l&&c===``){let n=``,r=t===-1?e.length:t+1;for(let t=0;t<
|
|
1615
|
-
`,r),i=t===-1?e.length:t,a=e.slice(r,i);if(a.trim()){n=a;break}if(r=i+1,t===-1)break}n
|
|
1615
|
+
`,(!e||e===C.activeSessionId)&&t&&(t.appendChild(n),hC(),uC(),requestAnimationFrame(()=>{fC(t,{force:!0})})),VC(n),n}function UC(e){let t=e?.dataset?.sessionId,n=e?.dataset?.callId;!t||!n||WS(t,n,()=>({html:e.innerHTML,accumulated:AC(t)}))}function WC(e,t){return!e||!t?!1:(e.innerHTML=t,VC(e),e.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{t.ctrlKey||t.metaKey||e.closest(`.tool-call-item`)?.classList.toggle(`expanded`)})}),e.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`),n=t?.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),it(),!0)}function GC(e,t,n){let i=e?.querySelector(`.thinking-indicator:not(.hidden) .thinking-label`);return i?(i.textContent=r(`chatStream.retrying`,{attempt:t,max:n}),i.dataset.retrying=`1`,!0):!1}function KC(e){let t=e?.querySelector(`.stream-content`);if(!t||e.querySelector(`.thinking-indicator:not(.hidden)`))return null;let n=document.createElement(`div`);return n.className=`thinking-indicator`,n.innerHTML=BC(),t.appendChild(n),VC(n),n}function qC(e,t,n){if(e.contains(n)){let r=n.previousElementSibling;r&&r.classList.contains(`thinking-content`)?e.insertBefore(t,r):e.insertBefore(t,n);return}let r=e.querySelectorAll(`.thinking-content`),i=r[r.length-1],a=i?i.nextElementSibling:null;i&&(!a||!a.classList.contains(`thinking-badge`))?e.insertBefore(t,i):e.appendChild(t)}function JC(e){let t=SC.get(e);if(!t||t.dataset.sessionId&&t.dataset.sessionId!==e)return!1;let n=document.getElementById(`chatContainer`);return n?(n.appendChild(t),requestAnimationFrame(()=>{n.scrollTop=n.scrollHeight}),!0):!1}function YC(e){let t=SC.get(e);if(!t||t.dataset.sessionId&&t.dataset.sessionId!==e)return;let n=document.getElementById(`chatContainer`);if(!n)return;n.appendChild(t);let i=CC.get(e)||``;if(i){aw(t,i);let e=t.querySelector(`.stream-content`);t.querySelectorAll(`.thinking-indicator:not(.hidden)`).forEach(t=>{if(t.classList.add(`hidden`),!e)return;let n=document.createElement(`span`);n.className=`thinking-badge`,n.dataset.status=`success`,n.innerHTML=`<svg class="thinking-icon-static" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/><circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/></svg>`+r(`chatStream.thinkingResult`),qC(e,n,t)})}requestAnimationFrame(()=>{n.scrollTop=n.scrollHeight})}var XC=new WeakMap,ZC=5;function QC(e){let t=e.querySelector(`.stream-content`);if(!t)return null;let n=t.querySelector(`.thinking-indicator:not(.hidden)`)||e.querySelector(`.thinking-indicator:not(.hidden)`);if(n){if(t.contains(n)){let e=n.previousElementSibling;if(e&&e.classList.contains(`thinking-content`))return e;let r=document.createElement(`div`);return r.className=`thinking-content`,t.insertBefore(r,n),r}let e=t.querySelectorAll(`.thinking-content`);if(e.length===0){let e=document.createElement(`div`);return e.className=`thinking-content`,t.appendChild(e),e}let r=e[e.length-1],i=r.nextElementSibling;if(!i||!i.classList.contains(`thinking-badge`))return r;let a=document.createElement(`div`);return a.className=`thinking-content`,t.appendChild(a),a}let r=t.querySelectorAll(`.thinking-badge`);if(r.length>0){let e=r[r.length-1],t=e.nextElementSibling;if(t&&t.classList.contains(`thinking-content`))return t;let n=document.createElement(`div`);return n.className=`thinking-content`,e.after(n),n}let i=document.createElement(`div`);return i.className=`thinking-content`,t.appendChild(i),i}function $C(e){let t=e.trim();return t?!!(/^(```|~~~)/.test(t)||/^([-*+]|\d+[.)])\s/.test(t)||/^>/.test(t)||/^\|/.test(t)||/^\s{2,}\S/.test(e)||t.startsWith(`<`)||/^\[[^\]]+\]:/.test(t)):!1}function ew(e,t){let n=t,r=!1,i=t,a=``;for(;n<=e.length;){let t=e.indexOf(`
|
|
1616
|
+
`,n),o=t===-1?e.length:t,s=e.slice(n,o),c=s.trim(),l=c.startsWith("```")||c.startsWith(`~~~`);if(l&&(r=!r),!r&&!l&&c===``){let n=``,r=t===-1?e.length:t+1;for(let t=0;t<ZC&&r<e.length;t++){let t=e.indexOf(`
|
|
1617
|
+
`,r),i=t===-1?e.length:t,a=e.slice(r,i);if(a.trim()){n=a;break}if(r=i+1,t===-1)break}n&&!$C(n)&&!$C(a)&&(i=t+1)}if(c&&(a=s),t===-1)break;n=t+1}return i}function tw(e){let t=document.createElement(`template`);return t.innerHTML=e,t.content}function nw(e,t){e.innerHTML=``;let n=document.createElement(`div`);n.className=`markdown-body`,e.appendChild(n);let r=ew(t,0);r>0&&n.appendChild(tw(tt(t.slice(0,r))));let i=null,a=t.slice(r);if(a){let e=tw(tt(a));i=e.firstChild,n.appendChild(e)}XC.set(e,{content:t,renderedChars:r,firstTailNode:i,body:n})}function rw(e,t){let n=t||``,r=XC.get(e);if(!r||!n.startsWith(r.content)){nw(e,n);return}let i=r.body;if(!i||i.parentNode!==e){nw(e,n);return}let a=r.firstTailNode;for(;a;){let e=a.nextSibling;a.remove(),a=e}r.firstTailNode=null;let o=ew(n,r.renderedChars);o>r.renderedChars&&(i.appendChild(tw(tt(n.slice(r.renderedChars,o)))),r.renderedChars=o);let s=n.slice(r.renderedChars);if(s){let e=tw(tt(s));r.firstTailNode=e.firstChild,i.appendChild(e)}r.content=n}function iw(e,t){if(!e||!t)return;let n=QC(e);n&&nw(n,t)}function aw(e,t){let n=e.querySelector(`.stream-content`);if(!n)return;let i=n.querySelector(`.thinking-indicator:not(.hidden)`)||e.querySelector(`.thinking-indicator:not(.hidden)`);if(i){let e=i.querySelector(`.thinking-label`);e&&(e.textContent===r(`chatStream.thinking`)||e.dataset.retrying===`1`)&&(e.textContent=r(`chatStream.outputting`),delete e.dataset.retrying)}let a=QC(e);a&&rw(a,t),UC(e),e.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&fC(e)})}function ow(e,t){if(!e||!t?.length)return;let n=e.querySelector(`.stream-content`);if(!n)return;let i=e.querySelector(`.thinking-indicator:not(.hidden)`);if(i){let e=TC>0?Ve(Date.now()-TC):``,t=document.createElement(`span`);t.className=`thinking-badge`,t.innerHTML=`<svg class="thinking-icon-static" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/><circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/></svg>${r(`chatStream.thinkingResult`)}${e?` <span class="thinking-duration">`+e+`</span>`:``}`,t.dataset.status=`success`,qC(n,t,i),i.classList.add(`hidden`),n.contains(i)||i.remove()}let a={execute_command:{metaType:`exec`},agent_exec:{metaType:`exec`},agent_file:{metaType:`file`,action:r(`chatStream.toolActionOperate`)},file_upload:{metaType:`file`,action:r(`chatStream.toolActionUpload`)},download_file:{metaType:`file`,action:r(`chatStream.toolActionDownload`)},fetch_url:{metaType:`web`,action:r(`chatStream.toolActionRequest`)},interact_element:{metaType:`web`,action:r(`chatStream.toolActionInteract`)},fill_form:{metaType:`web`,action:r(`chatStream.toolActionFill`)},manage_tab:{metaType:`web`,action:r(`chatStream.toolActionOperate`)},search_browser_data:{metaType:`search`},search_in_page:{metaType:`search`},dispatch_task:{metaType:`subagent`,action:r(`chatStream.toolActionDispatch`)},exec_log:{metaType:`search`},preview_ui:{metaType:`web`,action:r(`chatStream.toolActionPreview`)}};t.filter(e=>e&&typeof e==`object`).forEach(e=>{let t=e.function?.name||`unknown`,i=a[t]||{metaType:`other`},o;try{o=JSON.parse(e.function?.arguments||`{}`)}catch{o={raw:e.function?.arguments||``}}let s=JSON.stringify(o,null,2),c=``,l=``;if(i.metaType===`exec`){let e=o.command||o.cmd||JSON.stringify(o);l=e,c=`<code class="tool-call-cmd">$ ${L(e)}</code>`}else if(i.metaType===`file`){let e=o.file_path||o.filePath||o.path||o.filename||o.fileName||o.url||``,n=i.action===r(`chatStream.toolActionRead`)?`📖`:i.action===r(`chatStream.toolActionWrite`)?`📝`:i.action===r(`chatStream.toolActionUpload`)?`📤`:`📥`;l=e||t,c=`<span class="tool-call-file">${n} ${L(e)||L(t)}</span>`}else if(i.metaType===`web`){let e=o.url||o.href||o.selector||``;l=e||JSON.stringify(o),c=`<span class="tool-call-web">${L(i.action)}: ${L(e)||L(JSON.stringify(o).substring(0,80))}</span>`}else if(i.metaType===`search`){let e=o.query||o.keyword||o.text||``;l=e||t,c=`<span class="tool-call-search">🔍 ${L(e)||L(t)}</span>`}else if(i.metaType===`subagent`){let e=o.subAgentId||o.agent_id||``,t=e?xC(e):``,n=(o.task||``).substring(0,80);t&&t!==e?(l=`${t} (${e}): ${n}`,c=`<span class="tool-call-subagent">🤖 <strong>${L(t)}</strong> <span class="tool-call-subagent-id">(${L(e)})</span>: ${L(n)}</span>`):(l=`${e}: ${n}`,c=`<span class="tool-call-subagent">🤖 <strong>${L(e)}</strong>: ${L(n)}</span>`)}else{let e=Object.keys(o);if(e.length===0)l=t,c=`<span>${L(t)}</span>`;else if(e.length===1){let t=JSON.stringify(o[e[0]]);l=`${e[0]}: ${t}`,c=`<span>${L(e[0])}: ${L(t.substring(0,80))}</span>`}else l=e.map(e=>`${e}=${JSON.stringify(o[e])}`).join(`, `),c=`<span>${e.slice(0,2).map(e=>`${L(e)}=${L(JSON.stringify(o[e]).substring(0,30))}`).join(`, `)}${e.length>2?` ...`:``}</span>`}let u=i.metaType===`exec`?`<svg class="tool-call-icon exec" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1616
1618
|
<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>
|
|
1617
1619
|
</svg>`:i.metaType===`file`?`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1618
1620
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
@@ -1640,20 +1642,20 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1640
1642
|
<svg class="tool-call-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
|
|
1641
1643
|
</div>
|
|
1642
1644
|
<div class="tool-call-body">
|
|
1643
|
-
${
|
|
1645
|
+
${sw(L(s))}
|
|
1644
1646
|
</div>
|
|
1645
|
-
`,l){let e=d.querySelector(`.tool-call-summary`);e&&(e.title=l)}if(it(),f){let e=d.querySelector(`.tool-call-terminate-btn`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),
|
|
1647
|
+
`,l){let e=d.querySelector(`.tool-call-summary`);e&&(e.title=l)}if(it(),f){let e=d.querySelector(`.tool-call-terminate-btn`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),OT(C.activeSessionId)})}let h=d.querySelector(`.tool-call-abort-btn`);h&&h.addEventListener(`click`,e=>{e.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:C.activeSessionId}),h.disabled=!0,h.title=r(`chatStream.terminating`)}),d.querySelector(`.tool-call-header`).addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||d.classList.toggle(`expanded`)}),n.appendChild(d)}),yw(null,e),UC(e),e.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&fC(e)})}function sw(e,t=``){let n=t?` class="${t}"`:``;return`<div class="code-block-container" style="position: relative;">
|
|
1646
1648
|
<button class="code-copy-btn" title="${r(`chatStream.copyCode`)}">
|
|
1647
1649
|
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
|
1648
1650
|
<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>
|
|
1649
1651
|
</svg>
|
|
1650
1652
|
</button>
|
|
1651
1653
|
<pre${n}><code>${e}</code></pre>
|
|
1652
|
-
</div>`}function
|
|
1654
|
+
</div>`}function cw(e,t){let n=document.createElement(`div`);n.className=`agent-stream-output`,n.innerHTML=`
|
|
1653
1655
|
<div class="tool-result-title">${r(`chatMsg.toolResultTitle`)}</div>
|
|
1654
|
-
${
|
|
1655
|
-
`;let i=(e?e.querySelector(`.tool-call-body`)||e:null)||t;return i&&i.appendChild(n),n}var
|
|
1656
|
-
`);r.appendChild(t),e.stderrSeparator=t}r.appendChild(i)}else e.stderrSeparator?r.insertBefore(i,e.stderrSeparator):r.appendChild(i);e.textLength=(e.textLength||0)+n.length,e.textLength>
|
|
1656
|
+
${sw(``,`agent-stream-content`)}
|
|
1657
|
+
`;let i=(e?e.querySelector(`.tool-call-body`)||e:null)||t;return i&&i.appendChild(n),n}var lw=new WeakMap;function uw(e,t){e&&t&&lw.set(e,t)}function dw(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(String(e)):String(e).replace(/["\\]/g,`\\$&`)}function fw(e,t){if(!t)return null;let n=`.tool-call-item[data-tool-call-id="${dw(t)}"]`,r=e&&typeof e.querySelector==`function`?e.querySelector(n):null;if(r)return r;if(typeof document>`u`)return null;let i=document.querySelectorAll(n);return i.length?i[i.length-1]:null}function pw(e){let t=e.querySelector(`.agent-stream-output`),n=t?t.querySelector(`code`):null;if(t&&n)return{element:t,codeEl:n,textLength:(n.textContent||``).length};let r=cw(e,null);return{element:r,codeEl:r.querySelector(`code`),textLength:0}}var mw=2e5,hw=15e4;function gw(e){let t=e&&e.codeEl;if(!t)return;let n=t.textContent||``;if(n.length<=hw){e.textLength=n.length;return}let r=n.slice(n.length-hw),i=`… 已省略前 ${n.length-r.length} 字符(仅保留最近 ${hw} 字符)\n`;e.stderrSeparator=null,t.textContent=i+r,e.textLength=i.length+r.length}function _w(e,t,n){let r=e.codeEl;if(!r||!n)return;let i=document.createTextNode(n);if(t===`stderr`){if(!e.stderrSeparator){let t=document.createTextNode(`
|
|
1658
|
+
`);r.appendChild(t),e.stderrSeparator=t}r.appendChild(i)}else e.stderrSeparator?r.insertBefore(i,e.stderrSeparator):r.appendChild(i);e.textLength=(e.textLength||0)+n.length,e.textLength>mw&&gw(e)}function vw(e,t,n){if(!e||!n||!n.execId)return null;let r=typeof e.get==`function`?e.get(n.execId):e[n.execId];if(!r){let i=fw(t,n.toolCallId);if(i){let{element:e,codeEl:t,textLength:a}=pw(i);r={element:e,codeEl:t,stderrSeparator:null,toolCallId:n.toolCallId||``,pending:null,textLength:a},it()}else if(n.toolCallId)r={element:null,codeEl:null,stderrSeparator:null,toolCallId:n.toolCallId,pending:{stdout:``,stderr:``}};else{let e=cw(null,t?t.querySelector(`.stream-content`):null);r={element:e,codeEl:e.querySelector(`code`),stderrSeparator:null,toolCallId:``,pending:null},it()}typeof e.set==`function`?e.set(n.execId,r):e[n.execId]=r}let i=n.data||``;if(r.codeEl){_w(r,n.streamType,i);let e=r.codeEl.parentElement;e&&(e.scrollTop=e.scrollHeight)}else if(r.pending&&i){let e=n.streamType===`stderr`?`stderr`:`stdout`,t=r.pending[e]+i;r.pending[e]=t.length>mw?t.slice(t.length-hw):t}return r}function yw(e,t){let n=e||(t?lw.get(t):null);if(!n)return;let r=typeof n.values==`function`?[...n.values()]:Object.values(n);for(let e of r){if(!e||e.codeEl||!e.pending)continue;let n=fw(t,e.toolCallId);if(!n)continue;let{element:r,codeEl:i,textLength:a}=pw(n),{stdout:o,stderr:s}=e.pending;e.element=r,e.codeEl=i,e.stderrSeparator=null,e.pending=null,e.textLength=a,o&&_w(e,`stdout`,o),s&&_w(e,`stderr`,s);let c=i.parentElement;c&&(c.scrollTop=c.scrollHeight),it()}}function bw(e,t){if(!e?.toolCallId)return;let n=t;if(!n)return;let i=n.querySelector(`.tool-call-item[data-tool-call-id="${e.toolCallId}"]`);if(!i)return;i.classList.add(`has-result`),i.dataset.status=e.success?`success`:`failed`,yw(null,n);let a=parseInt(i.getAttribute(`data-created-at`),10),o=Date.now()-a,s=o<400&&o>=0?400-o:0,c=()=>{let n=i.querySelector(`.tool-call-executing`);n&&n.remove();let a=i.querySelector(`.tool-call-terminate-btn`);a&&(a.style.display=`none`);let o=i.querySelector(`.tool-call-abort-btn`);o&&(o.style.display=`none`);let s=i.querySelector(`.tool-call-result`);s&&s.remove();let c=e.truncated?`<span class="tool-result-truncated" title="${r(`chatStream.truncatedTitle`)}">${r(`chatStream.truncatedNote`)}</span>`:``,l=i.getAttribute(`data-meta-type`)===`exec`,u=i.querySelector(`.tool-call-header`),d=`
|
|
1657
1659
|
<span class="tool-result-status ${e.success?`success`:`fail`}">
|
|
1658
1660
|
${e.success?`<svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>`:`<svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/></svg>`}
|
|
1659
1661
|
</span>
|
|
@@ -1662,9 +1664,9 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1662
1664
|
`,f=u.querySelector(`.tool-call-chevron`);f?f.insertAdjacentHTML(`beforebegin`,d):u.insertAdjacentHTML(`beforeend`,d);let p=i.querySelector(`.agent-stream-output code`),m=!!(p&&p.textContent.trim());if(!l||!e.success&&!m){let t=e.content||(e.success?r(`chatStream.noOutput`):r(`chatStream.execFailed`)),n=t.length>500?t.substring(0,500)+r(`chatStream.clickToExpand`):t,a=t,o=document.createElement(`div`);if(o.className=`tool-call-result`,o.innerHTML=`
|
|
1663
1665
|
<div class="tool-result-title">${r(`chatStream.execResult`)}</div>
|
|
1664
1666
|
<div class="tool-result-content">
|
|
1665
|
-
${
|
|
1667
|
+
${sw(L(n))}
|
|
1666
1668
|
</div>
|
|
1667
|
-
`,a.length>500){let e=o.querySelector(`code`);e.dataset.fullContent=a;let t=!1;o.style.cursor=`pointer`,o.addEventListener(`click`,r=>{r.ctrlKey||r.metaKey||(t=!t,e.textContent=t?a:n)})}let s=i.querySelector(`.tool-call-body`);s?s.appendChild(o):i.appendChild(o)}it(),
|
|
1669
|
+
`,a.length>500){let e=o.querySelector(`code`);e.dataset.fullContent=a;let t=!1;o.style.cursor=`pointer`,o.addEventListener(`click`,r=>{r.ctrlKey||r.metaKey||(t=!t,e.textContent=t?a:n)})}let s=i.querySelector(`.tool-call-body`);s?s.appendChild(o):i.appendChild(o)}it(),UC(t),t.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&fC(e)})};s>0?setTimeout(c,s):c()}function xw(e){let t=document.createElement(`div`);t.className=`tool-call-item preselect-card`+(C.chatConfig?.streamExpandTools?` expanded`:``);let n=e.status===`failed`,i=``,a=``;if(e.action?.params?.selected){let t=e.action.params.selected;i=`<div class="tool-call-summary"><span>${r(`chatStream.preselectFiltered`,{total:e.apiRequest?.toolCount||`?`,count:t.length})}</span></div>`,a=`<span class="preselect-summary">${t.map(e=>`<code>${L(e)}</code>`).join(r(`chatStream.listSeparator`))}</span>`}else e.action?.name===`all_tools`?(i=`<div class="tool-call-summary"><span>${L(e.action.params.reason||``)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectSkippedAll`,{reason:L(e.action.params.reason||``)})}</span>`):e.action?.name===`skip`?(i=`<div class="tool-call-summary"><span>${L(e.action.params.reason||``)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectSkippedCount`,{reason:L(e.action.params.reason||``),count:e.action.params.toolCount||`?`})}</span>`):e.error?(i=`<div class="tool-call-summary"><span style="color:var(--danger-500);">${L(e.error)}</span></div>`,a=`<span class="preselect-summary" style="color:var(--danger-500);">${L(e.error)}</span>`):e.thought&&(i=`<div class="tool-call-summary"><span>${r(`chatStream.preselectDirectAnswer`)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectDirectAnswer`)}${L(e.thought).substring(0,200)}</span>`);let o=e.duration?Ve(e.duration):``,s=n?`<svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z"/></svg>`:`<svg viewBox="0 0 24 24" fill="currentColor" width="16" height="16"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/></svg>`;return t.innerHTML=`
|
|
1668
1670
|
<div class="tool-call-header">
|
|
1669
1671
|
<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1670
1672
|
<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
|
|
@@ -1679,7 +1681,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1679
1681
|
${a}
|
|
1680
1682
|
${e.apiResponse?.toolCountAfter===void 0?``:`<div class="preselect-meta">${r(`chatStream.toolsAfterFilter`,{count:e.apiResponse.toolCountAfter})}</div>`}
|
|
1681
1683
|
</div>
|
|
1682
|
-
`,t.querySelector(`.tool-call-header`).addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||t.classList.toggle(`expanded`)}),t}function
|
|
1684
|
+
`,t.querySelector(`.tool-call-header`).addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||t.classList.toggle(`expanded`)}),t}function Sw(e,t,n=[],a=null,o=null,s=!1){if(!e)return;e.dataset.sessionId&&YS(e.dataset.sessionId);let c=e.querySelector(`.message-content`),l=e.querySelector(`.stream-content`),u=e.querySelector(`.thinking-indicator:not(.hidden)`);if(u&&l){let e=TC>0?Ve(Date.now()-TC):``,t=document.createElement(`span`);if(t.className=`thinking-badge`,t.innerHTML=`<svg class="thinking-icon-static" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/><circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/></svg>${r(`chatStream.thinkingResult`)}${e?` <span class="thinking-duration">`+e+`</span>`:``}`,t.dataset.status=`success`,l.contains(u)){let e=u.previousElementSibling;e&&e.classList.contains(`thinking-content`)?l.insertBefore(t,e):l.insertBefore(t,u),u.classList.add(`hidden`)}else{let e=l.querySelectorAll(`.thinking-content`);if(e.length>0){let n=e[e.length-1],r=n.nextElementSibling;!r||!r.classList.contains(`thinking-badge`)?l.insertBefore(t,n):l.appendChild(t)}else l.appendChild(t);u.classList.add(`hidden`),u.remove()}}e.querySelectorAll(`.thinking-indicator`).forEach(e=>e.classList.add(`hidden`));let d=e.querySelector(`.stream-status`);if(d&&d.remove(),e.classList.remove(`streaming`),c&&c.querySelector(`.tool-call-item`)||l&&l.querySelector(`.tool-call-item`)){let e=EC>0?Ve(Date.now()-EC):``,a=(n||[]).filter(e=>e.nodeType===`api_call`||e.nodeType===`tool_exec`),o=a.filter(e=>e.status===`success`).length,u=a.filter(e=>e.status===`failed`).length,d=a.length,f=Ge(n),p=document.createElement(`div`);p.className=`thinking-process collapsed`;let m=document.createElement(`div`);m.className=`thinking-process-header`;let h=d>0?`
|
|
1683
1685
|
<span class="thinking-process-stat">
|
|
1684
1686
|
<span class="stat-icon node-icon">◉</span>
|
|
1685
1687
|
<span class="stat-label">${r(`chatStream.totalNodes`)}</span>
|
|
@@ -1714,7 +1716,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1714
1716
|
<svg class="thinking-process-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1715
1717
|
<polyline points="6 9 12 15 18 9"/>
|
|
1716
1718
|
</svg>
|
|
1717
|
-
`,f){let e=m.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ye(f,e)}))}let _=document.createElement(`div`);_.className=`thinking-process-body`;let v=document.createElement(`div`);if(v.className=`thinking-process-content`,_.appendChild(v),l)for(;l.firstChild;)v.appendChild(l.firstChild);c.querySelectorAll(`.tool-call-item`).forEach(e=>v.appendChild(e)),v.querySelectorAll(`.preselect-card`).forEach(e=>e.remove());let y=(n||[]).filter(e=>e.nodeType===`preselect`);i.debug(`[finalizeStreamingMessage] executionLog length:`,(n||[]).length,`preselectEntries:`,y.length),y.forEach(e=>{i.debug(`[finalizeStreamingMessage] creating preselect card for entry:`,e);let t=
|
|
1719
|
+
`,f){let e=m.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ye(f,e)}))}let _=document.createElement(`div`);_.className=`thinking-process-body`;let v=document.createElement(`div`);if(v.className=`thinking-process-content`,_.appendChild(v),l)for(;l.firstChild;)v.appendChild(l.firstChild);c.querySelectorAll(`.tool-call-item`).forEach(e=>v.appendChild(e)),v.querySelectorAll(`.preselect-card`).forEach(e=>e.remove());let y=(n||[]).filter(e=>e.nodeType===`preselect`);i.debug(`[finalizeStreamingMessage] executionLog length:`,(n||[]).length,`preselectEntries:`,y.length),y.forEach(e=>{i.debug(`[finalizeStreamingMessage] creating preselect card for entry:`,e);let t=xw(e);v.insertBefore(t,v.firstChild)});let b=v.querySelectorAll(`.thinking-content`),x=kw(t).trim();if(b.length>0){let e=b[b.length-1],t=e.textContent.trim();if(!s||s&&t===x){let t=e.previousElementSibling;for(;t;){if(t.classList.contains(`thinking-badge`)){t.remove();break}t=t.previousElementSibling}e.remove()}}if(v.children.length>0&&v.textContent.trim()){p.appendChild(m),p.appendChild(_);let e=document.createElement(`div`);e.className=`final-answer`;let n=kw(t);n&&n.trim()&&(e.innerHTML=et(n));let r=c.querySelector(`.thinking-indicator`);r&&r.remove(),l&&(l.innerHTML=``),c.appendChild(p),c.appendChild(e),yC(m)}else{let e=c.querySelector(`.thinking-indicator`);if(e&&e.remove(),l){let e=kw(t);e&&e.trim()&&(l.innerHTML=et(e))}}}else if(l){let e=kw(t);if(l.querySelector(`.thinking-content`)){let t=EC>0?Ve(Date.now()-EC):``,i=(n||[]).filter(e=>e.nodeType===`api_call`||e.nodeType===`tool_exec`),a=i.filter(e=>e.status===`success`).length,o=i.filter(e=>e.status===`failed`).length,u=i.length,d=Ge(n),f=document.createElement(`div`);f.className=`thinking-process collapsed`;let p=document.createElement(`div`);p.className=`thinking-process-header`;let m=u>0?`
|
|
1718
1720
|
<span class="thinking-process-stat">
|
|
1719
1721
|
<span class="stat-icon node-icon">◉</span>
|
|
1720
1722
|
<span class="stat-label">${r(`chatStream.totalNodes`)}</span>
|
|
@@ -1749,7 +1751,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1749
1751
|
<svg class="thinking-process-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1750
1752
|
<polyline points="6 9 12 15 18 9"/>
|
|
1751
1753
|
</svg>
|
|
1752
|
-
`,d){let e=p.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ye(d,e)}))}let g=document.createElement(`div`);g.className=`thinking-process-body`;let _=document.createElement(`div`);for(_.className=`thinking-process-content`,g.appendChild(_);l.firstChild;)_.appendChild(l.firstChild);let v=_.querySelectorAll(`.thinking-content`),y=e.trim();if(v.length>0){let e=v[v.length-1],t=e.textContent.trim();if(!s||s&&t===y){let t=e.previousElementSibling;for(;t;){if(t.classList.contains(`thinking-badge`)){t.remove();break}t=t.previousElementSibling}e.remove()}}if(_.children.length>0&&_.textContent.trim()){f.appendChild(p),f.appendChild(g);let t=document.createElement(`div`);t.className=`final-answer`,e&&e.trim()&&(t.innerHTML=et(e));let n=c.querySelector(`.thinking-indicator`);n&&n.remove(),c.appendChild(f),c.appendChild(t),pC(p)}else{let t=c.querySelector(`.thinking-indicator`);t&&t.remove(),e&&e.trim()&&(l.innerHTML=et(e))}}else e&&e.trim()&&(l.innerHTML=et(e))}e.classList.add(`assistant`,`message`),e.dataset.rawContent=typeof t==`string`?dt(t):JSON.stringify(t),e.dataset.textContent_=dt(Cw(t)),e.dataset.executionLog=JSON.stringify(n);let f=document.createElement(`div`);f.className=`message-footer`;let p=document.createElement(`button`);p.className=`copy-btn`,p.title=r(`chatStream.copyMarkdown`),p.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>`+r(`chatStream.copy`)+`</span>`].join(``),p.addEventListener(`click`,t=>{t.stopPropagation(),fS(e,p,t)}),f.appendChild(p);let m=document.createElement(`button`);m.className=`quote-btn`,m.title=r(`chatStream.quoteTitle`),m.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>`+r(`chatStream.quote`)+`</span>`].join(``),m.addEventListener(`click`,t=>{t.stopPropagation(),bS(e)}),f.appendChild(m),f.appendChild(Kx());let h=document.createElement(`div`);h.className=`export-menu-container`;let g=document.createElement(`button`);g.className=`export-trigger-btn`,g.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>`+r(`chatStream.export`)+`</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let _=document.createElement(`div`);_.className=`export-dropdown`,_.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>`+r(`chatStream.exportWord`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>`+r(`chatStream.exportPdf`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>`+r(`chatStream.exportImage`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>`+r(`chatStream.exportMarkdown`)+`</span>`,`</button>`].join(``);let v=_.querySelector(`.export-docx-item`);v.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToDocx:n}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DRUG3mwM.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(e,v,_)});let y=_.querySelector(`.export-md-item`);y.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToMarkdown:n}=await A(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DRUG3mwM.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(e,y,_)});let b=_.querySelector(`.export-pdf-item`);b.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToPdf:n}=await A(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DRUG3mwM.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(e,b,_)});let x=_.querySelector(`.export-image-item`);x.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToImage:n}=await A(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DRUG3mwM.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(e,x,_)}),g.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.toggle(`show`)});let S=null;h.addEventListener(`mouseenter`,()=>{S=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.add(`show`)},300)}),h.addEventListener(`mouseleave`,()=>{S&&=(clearTimeout(S),null),setTimeout(()=>{!h.matches(`:hover`)&&!_.matches(`:hover`)&&_.classList.remove(`show`)},100)}),h.appendChild(g),h.appendChild(_),f.appendChild(h);let w=document.createElement(`div`);w.className=`footer-right-actions`,w.style.marginLeft=`auto`,w.style.display=`flex`,w.style.alignItems=`center`,w.style.gap=`8px`;let T=Ge(n);if(T){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:I(T.totalTokens),prompt:I(T.promptTokens),completion:I(T.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${I(T.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ye(T,e)}),w.appendChild(e)}let E=ub(t),D=pb(n,t);if(E.length&&(e.dataset.declaredArtifacts=JSON.stringify(E)),jb(D),D.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:D.length}),e.innerHTML=`
|
|
1754
|
+
`,d){let e=p.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ye(d,e)}))}let g=document.createElement(`div`);g.className=`thinking-process-body`;let _=document.createElement(`div`);for(_.className=`thinking-process-content`,g.appendChild(_);l.firstChild;)_.appendChild(l.firstChild);let v=_.querySelectorAll(`.thinking-content`),y=e.trim();if(v.length>0){let e=v[v.length-1],t=e.textContent.trim();if(!s||s&&t===y){let t=e.previousElementSibling;for(;t;){if(t.classList.contains(`thinking-badge`)){t.remove();break}t=t.previousElementSibling}e.remove()}}if(_.children.length>0&&_.textContent.trim()){f.appendChild(p),f.appendChild(g);let t=document.createElement(`div`);t.className=`final-answer`,e&&e.trim()&&(t.innerHTML=et(e));let n=c.querySelector(`.thinking-indicator`);n&&n.remove(),c.appendChild(f),c.appendChild(t),yC(p)}else{let t=c.querySelector(`.thinking-indicator`);t&&t.remove(),e&&e.trim()&&(l.innerHTML=et(e))}}else e&&e.trim()&&(l.innerHTML=et(e))}e.classList.add(`assistant`,`message`),e.dataset.rawContent=typeof t==`string`?dt(t):JSON.stringify(t),e.dataset.textContent_=dt(kw(t)),e.dataset.executionLog=JSON.stringify(n);let f=document.createElement(`div`);f.className=`message-footer`;let p=document.createElement(`button`);p.className=`copy-btn`,p.title=r(`chatStream.copyMarkdown`),p.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>`+r(`chatStream.copy`)+`</span>`].join(``),p.addEventListener(`click`,t=>{t.stopPropagation(),vS(e,p,t)}),f.appendChild(p);let m=document.createElement(`button`);m.className=`quote-btn`,m.title=r(`chatStream.quoteTitle`),m.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>`+r(`chatStream.quote`)+`</span>`].join(``),m.addEventListener(`click`,t=>{t.stopPropagation(),ES(e)}),f.appendChild(m),f.appendChild(Qx());let h=document.createElement(`div`);h.className=`export-menu-container`;let g=document.createElement(`button`);g.className=`export-trigger-btn`,g.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>`+r(`chatStream.export`)+`</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let _=document.createElement(`div`);_.className=`export-dropdown`,_.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>`+r(`chatStream.exportWord`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>`+r(`chatStream.exportPdf`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>`+r(`chatStream.exportImage`)+`</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>`+r(`chatStream.exportMarkdown`)+`</span>`,`</button>`].join(``);let v=_.querySelector(`.export-docx-item`);v.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToDocx:n}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(e,v,_)});let y=_.querySelector(`.export-md-item`);y.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToMarkdown:n}=await A(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(e,y,_)});let b=_.querySelector(`.export-pdf-item`);b.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToPdf:n}=await A(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(e,b,_)});let x=_.querySelector(`.export-image-item`);x.addEventListener(`click`,async t=>{t.stopPropagation();let{exportAssistantMessageToImage:n}=await A(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(e,x,_)}),g.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.toggle(`show`)});let S=null;h.addEventListener(`mouseenter`,()=>{S=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==_&&e.classList.remove(`show`)}),_.classList.add(`show`)},300)}),h.addEventListener(`mouseleave`,()=>{S&&=(clearTimeout(S),null),setTimeout(()=>{!h.matches(`:hover`)&&!_.matches(`:hover`)&&_.classList.remove(`show`)},100)}),h.appendChild(g),h.appendChild(_),f.appendChild(h);let w=document.createElement(`div`);w.className=`footer-right-actions`,w.style.marginLeft=`auto`,w.style.display=`flex`,w.style.alignItems=`center`,w.style.gap=`8px`;let T=Ge(n);if(T){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:I(T.totalTokens),prompt:I(T.promptTokens),completion:I(T.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${I(T.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ye(T,e)}),w.appendChild(e)}let E=mb(t),D=_b(n,t);if(E.length&&(e.dataset.declaredArtifacts=JSON.stringify(E)),Fb(D),D.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:D.length}),e.innerHTML=`
|
|
1753
1755
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1754
1756
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
1755
1757
|
<polyline points="14 2 14 8 20 8"/>
|
|
@@ -1757,57 +1759,57 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1757
1759
|
<line x1="9" y1="15" x2="15" y2="15"/>
|
|
1758
1760
|
</svg>
|
|
1759
1761
|
<span class="artifacts-btn-count">${D.length}</span>
|
|
1760
|
-
`,e.addEventListener(`click`,t=>{t.stopPropagation(),
|
|
1762
|
+
`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ib(D,e)}),w.appendChild(e),Pb(D,e)}if($e(e,D.map(e=>e.path)).catch(()=>{}),n&&n.length>0&&C.chatConfig?.enableExecutionLog){let e=document.createElement(`button`);e.className=`execution-log-btn`,e.type=`button`,e.title=r(`chatStream.executionLog`),e.innerHTML=[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<circle cx="12" cy="12" r="10"></circle>`,`<polyline points="12 6 12 12 16 14"></polyline>`,`</svg>`].join(``),w.appendChild(e)}let O=a!=null,k=n?n.filter(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.status===`success`).length:0,j=n?.find(e=>e.nodeType===`reflection`&&e.reflectionType===`post`);if(O&&C.chatConfig?.enableExecutionLog){let e=a>=8?`score-high`:a>=5?`score-mid`:`score-low`,t=a>=8?`✅`:a>=5?`🔍`:`⚠️`,n=k>1?r(`chatStream.reflectionRoundsTag`,{count:k}):``,i=document.createElement(`button`);i.className=`reflection-score-btn`,i.type=`button`,i.title=r(`chatStream.qualityAssessmentTitle`,{score:a,rounds:n}),i.innerHTML=`<span class="reflection-badge ${e}"><span class="reflection-badge-emoji">${t}</span> ${a}/10</span>`,i.dataset.reflectionData=JSON.stringify({overallScore:j?.overallScore??a,dimensions:j?.dimensions||null,issues:j?.issues||null,suggestions:j?.suggestions||null,decision:j?.action?.decision||null,useful:j?.useful??null,reasoning:j?.reasoning||null,suggestion:j?.suggestion||null,rounds:k,wasRevised:!1}),w.appendChild(i)}else if(!O&&j&&j.status===`failed`&&C.chatConfig?.enableExecutionLog){let e=document.createElement(`button`);e.className=`reflection-score-btn`,e.type=`button`,e.title=r(`chatStream.reflectionFailedTitle`),e.innerHTML=`<span class="reflection-badge score-low">${r(`chatStream.reflectionFailedBadge`)}</span>`,w.appendChild(e)}let M=n?.slice().reverse().find(e=>e.nodeType===`tool_exec`&&(e.action?.name===`preview_ui`||e.action?.name===`preview_ui_prototype`)&&e.status===`success`);if(M){let e=!1;if(M.observation)try{e=(typeof M.observation==`string`?JSON.parse(M.observation):M.observation)?.localOpened===!0}catch{}let t=document.createElement(`button`);t.className=`prototype-btn-small`,t.type=`button`,t.title=r(e?`chatStream.prototypeOpenedLocal`:`chatStream.viewUiPrototype`),t.innerHTML=Dc,t.addEventListener(`click`,()=>{let e=M.prototypeId;if(!e&&M.observation)try{e=(typeof M.observation==`string`?JSON.parse(M.observation):M.observation)?.prototypeId}catch{}e?Wc(e):i.error(`[SidePanel] not found prototypeId,entry keys:`,Object.keys(M),`observation:`,M.observation)}),w.appendChild(t)}let N=document.createElement(`button`);N.className=`bookmark-btn`,N.title=r(`chatStream.bookmarkMessage`),N.innerHTML=`
|
|
1761
1763
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1762
1764
|
<path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>
|
|
1763
1765
|
</svg>
|
|
1764
|
-
`,
|
|
1766
|
+
`,ih(C.activeSessionId,e.dataset.messageId)&&(N.classList.add(`bookmarked`),N.title=r(`chatStream.removeBookmark`),N.querySelector(`svg`).setAttribute(`fill`,`currentColor`)),N.addEventListener(`click`,async t=>{t.stopPropagation();let n=C.activeSessionId,r=e.dataset.messageId;if(N.classList.contains(`bookmarked`)){await oh(n,r),vh(N,n,r);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>uh);return{refreshBookmarkPanel:e}},void 0);e()}else{await ah(n,r,e.dataset.textContent_||``,C.sessions.find(e=>e.id===n)?.title||``),vh(N,n,r);let{refreshBookmarkPanel:t}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>uh);return{refreshBookmarkPanel:e}},void 0);t()}}),w.appendChild(N);let ee=document.createElement(`button`);ee.className=`fork-btn`,ee.title=r(`chatStream.forkSession`),ee.innerHTML=`
|
|
1765
1767
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1766
1768
|
<circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/>
|
|
1767
1769
|
<path d="M6 8.5v7"/><path d="M6 12h8a4 4 0 0 0 4-4V6"/>
|
|
1768
1770
|
</svg>
|
|
1769
|
-
`,ee.addEventListener(`click`,async t=>{t.stopPropagation();let n=e.dataset.messageId;n&&await
|
|
1771
|
+
`,ee.addEventListener(`click`,async t=>{t.stopPropagation();let n=e.dataset.messageId;n&&await _c(C.activeSessionId,n)}),w.appendChild(ee);let te=document.createElement(`button`);te.className=`delete-btn`,te.title=r(`chatStream.deleteMessage`),te.innerHTML=`
|
|
1770
1772
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1771
1773
|
<polyline points="3 6 5 6 21 6"></polyline>
|
|
1772
1774
|
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
|
1773
1775
|
</svg>
|
|
1774
|
-
`,te.addEventListener(`click`,t=>{t.stopPropagation(),
|
|
1776
|
+
`,te.addEventListener(`click`,t=>{t.stopPropagation(),AT(e)}),w.appendChild(te),f.appendChild(w),e.querySelector(`.message-content`).appendChild(f),bT(),ST(),it(),lt(e),requestAnimationFrame(()=>{if(dC(),!$S){let t=document.getElementById(`chatContainer`);t&&e.offsetHeight>t.clientHeight*.6&&(pC(),lC=Date.now()+1e3,QS=!0,e.scrollIntoView({behavior:`smooth`,block:`start`}),clearTimeout(cC),cC=setTimeout(()=>{QS=!1},450))}uC()})}function Cw(e){if(!e||e.disabled)return!1;try{document.dispatchEvent(new CustomEvent(`task-stop-requested`,{detail:{sessionId:C.activeSessionId}}))}catch{}e.disabled=!0,e.style.opacity=`0.4`,e.style.cursor=`not-allowed`;let t=document.querySelector(`.loading-message .stop-task-btn`);if(t){t.disabled=!0,t.style.opacity=`0.6`,t.style.cursor=`not-allowed`;let e=document.querySelector(`.loading-message .loading-text`);e&&(e.textContent=r(`chatStream.stopping`))}return chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:null,sessionId:C.activeSessionId}),C.pendingCancelApi&&C.pendingCancelApi({message:r(`chatStream.taskStopped`),executionLog:C.currentExecutionStatus?.executionLog||[]}),!0}function ww(e){if(!e)return;e.querySelectorAll(`.thinking-indicator`).forEach(e=>e.classList.add(`hidden`));let t=e.querySelector(`.stream-status`);t&&(t.textContent=``),e.querySelectorAll(`.tool-call-executing`).forEach(e=>{e.textContent=r(`chatStream.cancelled`),e.classList.add(`tool-call-cancelled`)}),e.querySelectorAll(`.subtask-status-label`).forEach(e=>{let t=e.querySelector(`.subtask-spinner`);t&&t.remove(),e.textContent.includes(r(`chatStream.executing`))&&(e.textContent=r(`chatStream.cancelled`))}),e.querySelectorAll(`.subtask-progress-active`).forEach(e=>e.classList.remove(`subtask-progress-active`)),e.querySelectorAll(`.subtask-node-spinner`).forEach(e=>e.replaceWith(`○`)),e.querySelectorAll(`.subtask-spinner, .thinking-spinner, .loading-dots`).forEach(e=>e.remove()),e.classList.remove(`streaming`),e.classList.add(`stream-cancelled`),e.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>e.style.display=`none`),e.querySelectorAll(`.tool-call-terminate-btn`).forEach(e=>e.style.display=`none`)}var Tw=t({_checkForAbandonedCheckpoint:()=>NS,addContextBubble:()=>pT,addLoadingMessage:()=>CT,addMessage:()=>_T,applyNodeFilter:()=>Zw,bindExecutionLogDelegate:()=>bT,bindReflectionBadgeDelegate:()=>ST,bindSubtaskProgressClicks:()=>nT,buildKnowledgeContextText:()=>Ww,buildUserContent:()=>pm,callApi:()=>NT,cancelStreamingTask:()=>Cw,classifySubtaskNodeStats:()=>qw,classifySubtaskOutcome:()=>Kw,clearChatHistory:()=>Bw,clearSelectedContext:()=>Mw,deleteMessage:()=>AT,directSend:()=>fT,editAndResendMessage:()=>PT,extractSubtaskPlan:()=>eT,extractTextContent:()=>kw,fillSidePanelInput:()=>dT,hideModal:()=>Hw,insertSubtaskRowInOrder:()=>rT,isSubtaskReplaySkipped:()=>Yw,loadChatHistory:()=>Iw,mapApiErrorToUserMessage:()=>oT,openImagePreview:()=>rm,rebindAllMessages:()=>DT,reconcileSubtaskRowStates:()=>aT,refreshSelectionIndicatorFromState:()=>jw,removeLoadingMessage:()=>wT,renderImagePreviewsFromChat:()=>fm,renderKnowledgeContextBubbles:()=>Gw,renderMessageMermaid:()=>lt,renderPendingSubtaskRow:()=>tT,resolveRunningNodeLabel:()=>Jw,restoreMessageFromHtml:()=>ET,restorePendingSessionsFromStorage:()=>Ow,saveChatHistory:()=>Rw,saveChatHistoryAsync:()=>zw,sendMessage:()=>lT,setMessageTimestampVisible:()=>vT,setQuoteContext:()=>Aw,showCommandTerminateDialog:()=>OT,showModal:()=>Vw,stripImagesFromContent:()=>mm,syncPendingSessionsToStorage:()=>Dw,toggleNodeFilter:()=>Xw,triggerSelectionSearch:()=>uT});TS(Aw),n(`zh`,{chatMsg:{searchPrompt:`搜索一下`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,executionLogTitle:`执行日志`,revisedTag:`已修订`,roundsTag:` ({count}轮)`,revisedSuffix:`(已修订)`,scoreBadgeTitle:`AI 质量评估: {score}/10{rounds}{revised}
|
|
1775
1777
|
点击查看评估详情`,reflectionFailedTitle:`反思评估失败(点击查看执行日志)`,reflectionFailedBadge:`⚠️ 反思失败`,prototypeLocalOpened:`已在本地浏览器打开,点击可在面板内查看`,prototypeView:`查看 UI 原型`,bookmarkMessage:`收藏消息`,unbookmarkMessage:`取消收藏`,forkSession:`从此处分叉会话(仅复制到此条消息)`,deleteMessageTitle:`删除消息`,resumeTaskTitle:`从上次中断处继续执行任务`,resumeTaskTitleBudget:`执行预算已用完(部分完成):点击后可在新的预算下接着未完成的部分继续`,resumeTaskBtn:`继续执行`,clickToEnlarge:`点击查看大图`,fileExtracting:` 提取中...`,fileFailed:` 失败`,fileExtractFailed:`提取失败`,copyMessageTitle:`复制消息内容`,editAndResend:`编辑后重新发送`,thinking:`思考中...`,stopTask:`停止任务`,viewExecutionLog:`查看执行日志`,preparing:`准备中...`,emptyModelReply:`模型未返回任何内容。若你发送了图片,请确认所选模型支持视觉识别(图片识别需选择支持多模态视觉的模型),或更换模型后重试。`,stopping:`停止中...`,copyCode:`复制代码`,aborting:`正在终止...`,terminateCommandTitle:`终止命令执行`,terminateCommandPrompt:`请选择终止方式:`,terminateWaitTitle:`终止等待`,terminateWaitDesc:`仅停止等待命令输出,后台进程继续运行。<br/>适用于挂起型服务(如 npm run dev)。`,terminateCommandBtnTitle:`终止命令`,terminateCommandBtnDesc:`直接终止后台命令进程,释放资源。`,confirmDeleteMessage:`确认删除消息`,deleteMessageWarning:`删除后消息将从对话历史中移除,且无法恢复。`,confirmDelete:`确认删除`,quotedContextLabel:`💬 已引用: {text}`,selectedContextLabel:`📌 已选中: {text}`,subtaskDone:`完成`,subtaskFailed:`失败`,subtaskPartial:`部分完成`,subtaskFailReason:`中断原因:{error}`,subtaskExecuting:`执行中...`,subtaskPending:`待执行`,subtaskDescLabel:`任务描述:`,subtaskResultLabel:`产出摘要:`,subtaskAllDone:`✓ 全部完成`,subtaskReplaySkipped:`已跳过重放`,subtaskReplaySkippedHint:`中断前已成功完成,本轮未重复执行,写操作不会二次生效`,subtaskFilterEmpty:`当前过滤下无匹配节点`,subtaskFilterHint:`点击按此状态过滤节点,再点取消`,subtaskStatOtherHint:`已取消 / 未完成节点(用户拒绝确认、任务终止时仍在执行等),点击过滤`,subtaskPartialFail:`✗ {success}/{total} 完成,{fail} 个节点失败`,unknownNode:`未知`,stopGeneration:`停止生成`,toolResultTitle:`执行结果`,reflectionInProgress:`质量评估中...`,cannotGetMessageContent:`无法获取消息内容`,editFailed:`编辑失败: {message}`,errTaskStopped:`任务已被用户停止`,errTaskReplaced:`任务已被新请求替代`,errSwRestarted:`后台服务异常重启,API 调用已中断`,errTimeout:`请求超时({seconds}秒)`,cancelBtn:`取消`}}),n(`en`,{chatMsg:{searchPrompt:`Search`,exportWord:`Export Word`,exportPdf:`Export PDF`,exportImage:`Export Image`,exportMarkdown:`Export Markdown`,executionLogTitle:`Execution Log`,revisedTag:`Revised`,roundsTag:` ({count} rounds)`,revisedSuffix:` (Revised)`,scoreBadgeTitle:`AI Quality Assessment: {score}/10{rounds}{revised}
|
|
1776
|
-
Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection Failed`,prototypeLocalOpened:`Opened in local browser, click to view in panel`,prototypeView:`View UI Prototype`,bookmarkMessage:`Bookmark message`,unbookmarkMessage:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessageTitle:`Delete message`,resumeTaskTitle:`Resume task from last interruption`,resumeTaskTitleBudget:`Execution budget exhausted (partially complete): click to continue the unfinished parts with a fresh budget`,resumeTaskBtn:`Resume`,clickToEnlarge:`Click to view full size`,fileExtracting:` extracting...`,fileFailed:` failed`,fileExtractFailed:`Extraction failed`,copyMessageTitle:`Copy message content`,editAndResend:`Edit and resend`,thinking:`Thinking...`,stopTask:`Stop task`,viewExecutionLog:`View execution log`,preparing:`Preparing...`,emptyModelReply:`The model returned no content. If you sent an image, make sure the selected model supports vision (image recognition requires a multimodal vision model), or switch model and retry.`,stopping:`Stopping...`,copyCode:`Copy code`,aborting:`Aborting...`,terminateCommandTitle:`Terminate Command Execution`,terminateCommandPrompt:`Please select a termination method:`,terminateWaitTitle:`Stop Waiting`,terminateWaitDesc:`Only stop waiting for command output; the background process continues running.<br/>Suitable for hanging services (e.g. npm run dev).`,terminateCommandBtnTitle:`Terminate Command`,terminateCommandBtnDesc:`Directly terminate the background command process and release resources.`,confirmDeleteMessage:`Confirm Delete Message`,deleteMessageWarning:`After deletion, the message will be removed from the conversation history and cannot be recovered.`,confirmDelete:`Confirm Delete`,quotedContextLabel:`💬 Quoted: {text}`,selectedContextLabel:`📌 Selected: {text}`,subtaskDone:`Done`,subtaskFailed:`Failed`,subtaskPartial:`Partial`,subtaskFailReason:`Interrupted: {error}`,subtaskExecuting:`Executing...`,subtaskPending:`Pending`,subtaskDescLabel:`Description: `,subtaskResultLabel:`Output summary: `,subtaskAllDone:`✓ All done`,subtaskReplaySkipped:`replay skipped`,subtaskReplaySkippedHint:`Already completed before the interruption; not re-run this round, so side effects do not apply twice`,subtaskFilterEmpty:`No nodes match this filter`,subtaskFilterHint:`Click to filter nodes by this status, click again to clear`,subtaskStatOtherHint:`Cancelled / unfinished nodes (denied confirmations, still running when the task ended). Click to filter`,subtaskPartialFail:`✗ {success}/{total} done, {fail} nodes failed`,unknownNode:`Unknown`,stopGeneration:`Stop generation`,toolResultTitle:`Execution Result`,reflectionInProgress:`Assessing quality...`,cannotGetMessageContent:`Cannot get message content`,editFailed:`Edit failed: {message}`,errTaskStopped:`Task stopped by user`,errTaskReplaced:`Task replaced by new request`,errSwRestarted:`Background service restarted unexpectedly, API call interrupted`,errTimeout:`Request timeout ({seconds}s)`,cancelBtn:`Cancel`}});var
|
|
1778
|
+
Click to view assessment details`,reflectionFailedTitle:`Reflection assessment failed (click to view execution log)`,reflectionFailedBadge:`⚠️ Reflection Failed`,prototypeLocalOpened:`Opened in local browser, click to view in panel`,prototypeView:`View UI Prototype`,bookmarkMessage:`Bookmark message`,unbookmarkMessage:`Remove bookmark`,forkSession:`Fork session from here (copy up to this message only)`,deleteMessageTitle:`Delete message`,resumeTaskTitle:`Resume task from last interruption`,resumeTaskTitleBudget:`Execution budget exhausted (partially complete): click to continue the unfinished parts with a fresh budget`,resumeTaskBtn:`Resume`,clickToEnlarge:`Click to view full size`,fileExtracting:` extracting...`,fileFailed:` failed`,fileExtractFailed:`Extraction failed`,copyMessageTitle:`Copy message content`,editAndResend:`Edit and resend`,thinking:`Thinking...`,stopTask:`Stop task`,viewExecutionLog:`View execution log`,preparing:`Preparing...`,emptyModelReply:`The model returned no content. If you sent an image, make sure the selected model supports vision (image recognition requires a multimodal vision model), or switch model and retry.`,stopping:`Stopping...`,copyCode:`Copy code`,aborting:`Aborting...`,terminateCommandTitle:`Terminate Command Execution`,terminateCommandPrompt:`Please select a termination method:`,terminateWaitTitle:`Stop Waiting`,terminateWaitDesc:`Only stop waiting for command output; the background process continues running.<br/>Suitable for hanging services (e.g. npm run dev).`,terminateCommandBtnTitle:`Terminate Command`,terminateCommandBtnDesc:`Directly terminate the background command process and release resources.`,confirmDeleteMessage:`Confirm Delete Message`,deleteMessageWarning:`After deletion, the message will be removed from the conversation history and cannot be recovered.`,confirmDelete:`Confirm Delete`,quotedContextLabel:`💬 Quoted: {text}`,selectedContextLabel:`📌 Selected: {text}`,subtaskDone:`Done`,subtaskFailed:`Failed`,subtaskPartial:`Partial`,subtaskFailReason:`Interrupted: {error}`,subtaskExecuting:`Executing...`,subtaskPending:`Pending`,subtaskDescLabel:`Description: `,subtaskResultLabel:`Output summary: `,subtaskAllDone:`✓ All done`,subtaskReplaySkipped:`replay skipped`,subtaskReplaySkippedHint:`Already completed before the interruption; not re-run this round, so side effects do not apply twice`,subtaskFilterEmpty:`No nodes match this filter`,subtaskFilterHint:`Click to filter nodes by this status, click again to clear`,subtaskStatOtherHint:`Cancelled / unfinished nodes (denied confirmations, still running when the task ended). Click to filter`,subtaskPartialFail:`✗ {success}/{total} done, {fail} nodes failed`,unknownNode:`Unknown`,stopGeneration:`Stop generation`,toolResultTitle:`Execution Result`,reflectionInProgress:`Assessing quality...`,cannotGetMessageContent:`Cannot get message content`,editFailed:`Edit failed: {message}`,errTaskStopped:`Task stopped by user`,errTaskReplaced:`Task replaced by new request`,errSwRestarted:`Background service restarted unexpectedly, API call interrupted`,errTimeout:`Request timeout ({seconds}s)`,cancelBtn:`Cancel`}});var Ew=`pendingCallApiSessions`;function Dw(){chrome.storage.session.set({[Ew]:[...C.pendingCallApiSessionIds]}).catch(()=>{})}async function Ow(){try{let e=await chrome.storage.session.get([Ew]);e[Ew]&&Array.isArray(e[Ew])&&(C.pendingCallApiSessionIds=new Set(e[Ew]))}catch{}}function kw(e){if(Array.isArray(e))return e.filter(e=>e.type===`text`).map(e=>e.text).join(``);if(typeof e==`string`&&e.startsWith(`[`))try{let t=JSON.parse(e);if(Array.isArray(t))return t.filter(e=>e.type===`text`).map(e=>e.text).join(``)}catch{}return e}function Aw(e){let t=kw(e);C.quotedContextText=t;let n=document.getElementById(`selectionIndicator`),i=document.getElementById(`selectionText`),a=document.getElementById(`userInput`);if(n&&i&&a){let e;e=t.length>100?t.substring(0,100)+`...`:t.length>50?t.substring(0,50)+`...`:t,i.textContent=r(`chat.quotedPrefix`,{text:e}),n.classList.add(`show`)}}function jw(){let e=document.getElementById(`selectionIndicator`),t=document.getElementById(`selectionText`);if(!e||!t)return;let n=(C.quotedContextText||``).trim(),i=(C.selectedContextText||``).trim(),a=n||i;if(!a){e.classList.remove(`show`);return}let o;o=a.length>100?a.substring(0,100)+`...`:a.length>50?a.substring(0,50)+`...`:a,t.textContent=r(n?`chatMsg.quotedContextLabel`:`chatMsg.selectedContextLabel`,{text:o}),e.classList.add(`show`)}function Mw(){i.debug(`[SidePanel] clear selectedcontenttext `),C.selectedContextText=``,C.quotedContextText=``;let e=document.getElementById(`selectionIndicator`),t=document.getElementById(`userInput`);if(e&&(e.classList.remove(`show`),i.debug(`[SidePanel] hiddenselected contentprompt`)),typeof window.hideFloatingMenu==`function`&&window.hideFloatingMenu(),t&&t.value.startsWith(`[选中内容]`)){let e=t.value.split(`
|
|
1777
1779
|
`),n=e.findIndex(e=>e.startsWith(`[用户问题]`));n===-1?t.value=``:t.value=e.slice(n+1).join(`
|
|
1778
|
-
`).trim()}}var
|
|
1780
|
+
`).trim()}}var Nw,Pw=new Promise(e=>{Nw=e});function Fw(){C.activeSessionId&&document.dispatchEvent(new CustomEvent(`session-hydrated`,{detail:{sessionId:C.activeSessionId,workdir:C.sessionWorkdir||null}}))}async function Iw(){try{await Lw()}finally{Nw(),document.dispatchEvent(new CustomEvent(`chat-history-rendered`,{detail:{sessionId:C.activeSessionId||null}}))}}async function Lw(){let e=await vi();if(e.activeSessionId&&e.list.length>0){C.activeSessionId=e.activeSessionId,C.sessions=e.list;let t=e.list.find(t=>t.id===e.activeSessionId);if(t){if(C.messageHistory=t.messageHistory||[],C.activeCompaction=t.contextCompaction||null,bi(t),Fw(),C.currentModel=t.model||C.currentModel,C.useTools=t.useTools===void 0?C.useTools:t.useTools,C.temperature=t.temperature===void 0?C.temperature:t.temperature,C.topP=t.topP===void 0?C.topP:t.topP,C.activeAgentId=t.agentId||null,C.activeAgentId&&C.activeAgentId!=="default"){try{let{getAgent:e}=await A(async()=>{let{getAgent:e}=await import(`./agent-store-CeC2_dkP.js`).then(e=>e.t);return{getAgent:e}},__vite__mapDeps([0,1,2,3])),t=await e(C.activeAgentId);t&&(C.activeAgentMcpExcludedServerIds=t.mcpExcludedServerIds??null,t.model&&(C.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(C.temperature=t.temperature,C.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`)))}catch{}C.activeAgentMcpExcludedServerIds=null}else{C.activeAgentMcpExcludedServerIds=null;try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(C.currentModel=e.modelName),e.temperature!==void 0&&(C.temperature=e.temperature),e.topP!==void 0&&(C.topP=e.topP)}catch{}document.dispatchEvent(new CustomEvent(`agent-model-changed`))}let e=`agentMcpClosedServers_${C.activeAgentId||`default`}`;C.mcpClosedServers=(await chrome.storage.local.get([e]))[e]||[]}let n=document.getElementById(`chatContainer`);n&&n.querySelectorAll(`.message, .user-context-bubble`).forEach(e=>e.remove()),C.messageHistory.forEach(e=>{let t=e.wasRevised;if(!t&&e.executionLog)try{t=(typeof e.executionLog==`string`?JSON.parse(e.executionLog):e.executionLog).some(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.action?.decision===`revised`)}catch{}if(e.role===`user`&&e.contextBubbles&&Array.isArray(e.contextBubbles)&&e.contextBubbles.forEach(e=>{let t=``;switch(e.type){case`skill`:t=r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``});break;case`mcp`:t=r(`contextBubble.bubbleMcp`,{name:e.serverName});break;case`page`:t=r(`contextBubble.bubblePage`,{title:e.title,url:e.url});break;case`file`:t=`${e.name} (${Rm(e.size||0)})`;break;case`knowledge`:{let t=Array.isArray(e.refs)?e.refs:[];t.length>0&&Gw(t,e.failed===!0);break}}t&&e.type!==`file`&&pT(e.type,t,!1)}),e.htmlContent)ET(e.htmlContent,e.messageId,e.resumable);else{let n=(e.contextBubbles||[]).filter(e=>e.type===`file`).map(e=>({name:e.name,size:e.size||0,type:e.fileType||``}));_T(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,t,null,e.messageId,n,e.resumable,e.timestamp??null)}}),bT(),ST(),st();let i=document.querySelector(`.welcome-message`);i&&C.messageHistory.length>0&&i.remove(),Xe(),it(),ZO(),e.activeSessionId===C.activeSessionId?Bo(e):Bo(),await NS();let a=`scrollPosition_`+(C.activeSessionId||`default`);chrome.storage.local.get([a],e=>{e[a]!==void 0&&setTimeout(()=>{let t=document.getElementById(`chatContainer`);t.scrollTop=e[a]},100)})}else{await Si();let e=await vi();e.activeSessionId&&(C.activeSessionId=e.activeSessionId,C.sessions=e.list,bi(e.list.find(t=>t.id===e.activeSessionId)),Fw()),Bo(e)}}function Rw(){try{yi().catch(e=>{i.error(`[SidePanel] save currentsession failed:`,e)})}catch(e){i.error(`[SidePanel] save conversationhistory exception:`,e)}}async function zw(){try{await yi()}catch(e){i.error(`[SidePanel] save conversationhistory exception:`,e)}}function Bw(){C.messageHistory&&C.messageHistory.length>0&&Di().then(()=>{C.messageHistory=[],C.activeCompaction=null;let e=document.getElementById(`chatContainer`);if(e){e.innerHTML=``;let t=document.createElement(`div`);t.className=`welcome-message`,t.innerHTML=`
|
|
1779
1781
|
<div class="icon-wrapper">
|
|
1780
1782
|
<div class="icon">💬</div>
|
|
1781
1783
|
</div>
|
|
1782
1784
|
<h2>${r(`chat.welcomeTitle`)}</h2>
|
|
1783
1785
|
<p>${r(`chat.welcomeSubtitle`)}</p>
|
|
1784
|
-
`,e.appendChild(t)}chrome.storage.local.remove(`scrollPosition_`+(C.activeSessionId||`default`)),
|
|
1786
|
+
`,e.appendChild(t)}chrome.storage.local.remove(`scrollPosition_`+(C.activeSessionId||`default`)),Bo()})}function Vw(){document.getElementById(`confirmModal`).classList.add(`show`)}function Hw(){document.getElementById(`confirmModal`).classList.remove(`show`)}var Uw=1500;async function Ww(e,t){if(!t||t.length===0)return null;let{ragEnabled:n}=await chrome.storage.local.get(`ragEnabled`);if(n!==!0)return i.debug(`[SidePanel] RAG global switch off, skip knowledge context`),null;let a=await new Promise(n=>{try{chrome.runtime.sendMessage({type:`RAG_SEARCH`,params:{query:e,collectionIds:t.map(e=>e.id).filter(Boolean),topK:5}},e=>{if(chrome.runtime.lastError){n(null);return}n(e&&e.success?e:null)})}catch{n(null)}}),o=!a,s=a&&a.results||[],c=new Map(t.filter(e=>e.id).map(e=>[e.id,e.name])),l=new Map;s.forEach(e=>{let t=e.collectionId||``,n=l.get(t);n||(n={id:t,name:c.get(t)||t||r(`contextBubble.labelKnowledge`),hitCount:0,items:[]},l.set(t,n)),n.items.push(e),n.hitCount++});let u=Array.from(l.values()),d=s.length,f=e=>e.map(e=>{let t=String(e.content||``).trim();return{score:typeof e.score==`number`?e.score:Number(e.score)||0,content:t.slice(0,Uw),truncated:t.length>Uw,fullLength:t.length}}),p=t.map(e=>({id:e.id,name:e.name,hitCount:e.id&&l.get(e.id)?.hitCount||0,hits:e.id?f(l.get(e.id)?.items||[]):[]}));u.forEach(e=>{p.some(t=>t.id&&t.id===e.id)||p.push({id:e.id,name:e.name,hitCount:e.hitCount,hits:f(e.items)})});let m=[`[知识库检索结果](引用: ${t.map(e=>e.name).join(`、`)})`];return o?m.push(`知识库检索失败:检索服务暂时不可用(这不代表知识库中没有相关内容)。`):d===0?m.push(`未找到与问题相关的内容。`):u.forEach(e=>{m.push(``),m.push(`【${e.name}】`),e.items.forEach(e=>{let t=typeof e.score==`number`?e.score.toFixed(3):String(e.score??``);m.push(`· 相关度 ${t}`),m.push(String(e.content||``).trim().slice(0,Uw)),m.push(``)})}),m.push(`[/知识库检索结果]`),{text:m.join(`
|
|
1785
1787
|
`)+`
|
|
1786
1788
|
|
|
1787
|
-
`,refs:p,failed:o}}function
|
|
1789
|
+
`,refs:p,failed:o}}function Gw(e,t=!1){if(!Array.isArray(e)||e.length===0)return;let n=e.reduce((e,t)=>e+(t.hitCount||0),0);if(t){pT(`knowledge`,r(`contextBubble.bubbleKnowledgeFailed`,{name:e.map(e=>e.name).join(`、`)}),!1);return}if(n===0){pT(`knowledge`,r(`contextBubble.bubbleKnowledgeMiss`,{name:e.map(e=>e.name).join(`、`)}),!1);return}e.forEach(e=>{(e.hitCount||0)>0?pT(`knowledge`,r(`contextBubble.bubbleKnowledge`,{name:e.name,count:e.hitCount}),!1,Array.isArray(e.hits)?e.hits:null):pT(`knowledge`,r(`contextBubble.bubbleKnowledgeMiss`,{name:e.name}),!1)})}function Kw(e,t,n,r=.8){return e===`failed`?!n||n<=0?`failed`:t/n>=r?`partial`:`failed`:e}function qw(e){let t=Array.isArray(e)?e:[],n=0,r=0;for(let e of t)e&&e.status===`success`?n++:e&&e.status===`failed`&&r++;return{total:t.length,success:n,failed:r,other:t.length-n-r}}function Jw(e){let t=e&&e.nodeName?e.nodeName:r(`chatMsg.subtaskExecuting`);return L(String(t))}function Yw(e,t){return(Array.isArray(e)?e:[]).some(e=>!!e&&e.nodeType===`subtask`&&e.subtaskIndex===t&&e.skippedReplay===!0)}function Xw(e,t){return t!==`success`&&t!==`failed`&&t!==`other`?e||null:e===t?null:t}function Zw(e,t){let n=Array.isArray(e)?e:[];return t!==`success`&&t!==`failed`&&t!==`other`?n:t===`other`?n.filter(e=>!e||e.status!==`success`&&e.status!==`failed`):n.filter(e=>e&&e.status===t)}var Qw=`<svg class="subtask-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="17" rx="2"/><line x1="8" y1="2" x2="8" y2="4"/><line x1="16" y1="2" x2="16" y2="4"/><line x1="3" y1="10" x2="21" y2="10"/></svg>`,$w=`<svg class="subtask-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>`;function eT(e){let t=Array.isArray(e)?e:[],n=null,r=-1;for(let e=0;e<t.length;e++){let i=t[e];!i||i.nodeType!==`subtask_plan`||!Array.isArray(i.items)||(!n||new Date(i.timestamp||0)>=new Date(n.timestamp||0))&&(n=i,r=e)}if(!n)return null;let i=n.items,a=i.filter(e=>e&&typeof e.index==`number`);return{total:n.subtaskTotal||i.length,items:a,timestamp:n.timestamp,logIndex:r}}function tT(e,t){let n=e.description?String(e.description).replace(/\s+/g,` `).trim():``,i=n?`<div class="subtask-detail-desc"><span class="subtask-detail-label">${r(`chatMsg.subtaskDescLabel`)}</span>${L(n)}</div>`:``;return`
|
|
1788
1790
|
<div class="subtask-header">
|
|
1789
|
-
${
|
|
1791
|
+
${$w}${Qw}${`<span class="subtask-badge">${e.index+1}/${t}</span>`}<span class="subtask-name" title="${P(n)}">${L(e.name||``)}</span><span class="subtask-status-pending">${r(`chatMsg.subtaskPending`)}</span>
|
|
1790
1792
|
</div>
|
|
1791
1793
|
<div class="subtask-detail-body">${i}</div>
|
|
1792
|
-
`}function
|
|
1794
|
+
`}function nT(e){!e||e._clickDelegated||(e._clickDelegated=!0,e.addEventListener(`click`,t=>{let n=t.target.closest(`[data-node-filter]`);if(n){t.stopPropagation(),e._nodeFilter=Xw(e._nodeFilter||null,n.dataset.nodeFilter),e._nodeFilter&&e.classList.add(`subtask-expanded`),e._renderNodes?.();return}t.target.closest(`.subtask-header`)&&e.classList.toggle(`subtask-expanded`)}))}function rT(e,t){let n=Number(t.dataset.subtaskIndex),r=Array.from(e.querySelectorAll(`.subtask-progress[data-subtask-index]`)).find(e=>Number(e.dataset.subtaskIndex)>n);r?e.insertBefore(t,r):e.appendChild(t)}function iT(e,t,n,i,a,o){let s=t.index,c=qw(o),l=n.total||s+1,u=a&&(a.status===`success`||a.status===`failed`)?a.status:null;u||=c.failed>0?`failed`:`success`;let d=Kw(u,c.success,c.total),f=u===`success`,p=t.description?String(t.description).replace(/\s+/g,` `).trim():``,m=Yw(i,s)?`<span class="subtask-replay-skipped" title="${P(r(`chatMsg.subtaskReplaySkippedHint`))}">${r(`chatMsg.subtaskReplaySkipped`)}</span>`:``,h=``,g=``;if(f)h=`<span class="subtask-status-done">${r(`chatMsg.subtaskDone`)}</span>`,g=`<span>${r(`chatMsg.subtaskAllDone`)}</span>`;else if(d===`partial`)h=`<span class="subtask-status-partial">${r(`chatMsg.subtaskPartial`)}</span>`,g=`<span>${r(`chatMsg.subtaskPartialFail`,{success:c.success,total:c.total,fail:c.failed})}</span>`;else{h=`<span class="subtask-status-failed">${r(`chatMsg.subtaskFailed`)}</span>`;let e=a&&a.error?String(a.error).replace(/\s+/g,` `).trim().slice(0,120):``;g=`<span>${r(`chatMsg.subtaskPartialFail`,{success:c.success,total:c.total,fail:c.failed})}</span>${e?`<span class="subtask-fail-reason">${L(r(`chatMsg.subtaskFailReason`,{error:e}))}</span>`:``}`}let _=`
|
|
1793
1795
|
<span class="subtask-node-stats">
|
|
1794
1796
|
<span class="subtask-stat-done${e._nodeFilter===`success`?` subtask-stat-active`:``}" data-node-filter="success" title="${r(`chatMsg.subtaskFilterHint`)}">✓ ${c.success}</span>
|
|
1795
1797
|
${c.failed>0?`<span class="subtask-stat-fail${e._nodeFilter===`failed`?` subtask-stat-active`:``}" data-node-filter="failed" title="${r(`chatMsg.subtaskFilterHint`)}">✗ ${c.failed}</span>`:``}
|
|
1796
1798
|
${c.other>0?`<span class="subtask-stat-other${e._nodeFilter===`other`?` subtask-stat-active`:``}" data-node-filter="other" title="${r(`chatMsg.subtaskStatOtherHint`)}">⊘ ${c.other}</span>`:``}
|
|
1797
1799
|
</span>`,v=e.classList.contains(`subtask-expanded`);e.classList.remove(`subtask-progress-active`,`subtask-progress-pending`),e.classList.add(f?`subtask-progress-done`:`subtask-progress-failed`),e.dataset.terminal=`1`,e.innerHTML=`
|
|
1798
1800
|
<div class="subtask-header">
|
|
1799
|
-
${
|
|
1801
|
+
${$w}${Qw}<span class="subtask-badge">${s+1}/${l}</span><span class="subtask-name" title="${P(p)}">${L(t.name||``)}</span>${m}${h}
|
|
1800
1802
|
</div>
|
|
1801
1803
|
<div class="subtask-progress-line ${f?`done`:`failed`}">${g}${_}</div>
|
|
1802
1804
|
<div class="subtask-detail-body"></div>
|
|
1803
|
-
`,v&&e.classList.add(`subtask-expanded`);let y=e.querySelector(`.subtask-detail-body`);e._renderNodes=()=>{if(!y)return;let t=[];p&&t.push(`<div class="subtask-detail-desc"><span class="subtask-detail-label">${r(`chatMsg.subtaskDescLabel`)}</span>${L(p)}</div>`);let n=a&&a.result?String(a.result).trim():``;n&&t.push(`<div class="subtask-detail-result"><span class="subtask-detail-label">${r(`chatMsg.subtaskResultLabel`)}</span>${L(n)}</div>`);let i=
|
|
1805
|
+
`,v&&e.classList.add(`subtask-expanded`);let y=e.querySelector(`.subtask-detail-body`);e._renderNodes=()=>{if(!y)return;let t=[];p&&t.push(`<div class="subtask-detail-desc"><span class="subtask-detail-label">${r(`chatMsg.subtaskDescLabel`)}</span>${L(p)}</div>`);let n=a&&a.result?String(a.result).trim():``;n&&t.push(`<div class="subtask-detail-result"><span class="subtask-detail-label">${r(`chatMsg.subtaskResultLabel`)}</span>${L(n)}</div>`);let i=Zw(o,e._nodeFilter),s=``;o.length>0&&i.length===0?s=`<div class="subtask-node-empty">${L(r(`chatMsg.subtaskFilterEmpty`))}</div>`:i.length>0&&(s=i.map(e=>{let t=e.nodeType===`tool_exec`?`🔧`:e.nodeType===`api_call`?`📡`:e.nodeType===`reflection`?`🎯`:e.nodeType===`preselect`?`🔍`:`○`,n=e.status===`success`?`✓`:e.status===`failed`?`✗`:`○`,i=e.status===`success`?`done`:e.status===`failed`?`failed`:`processing`,a=e.duration?Ve(e.duration):``,o=L(e.nodeName||r(`chatMsg.unknownNode`)),s=``;if(e.nodeType===`tool_exec`){let t=ap(e);t&&(s=`<span class="subtask-node-cmd" title="${P(t)}">${L(t)}</span>`)}return`<div class="subtask-node ${i}">
|
|
1804
1806
|
<span class="subtask-node-icon">${t}</span>
|
|
1805
1807
|
<span class="subtask-node-status">${n}</span>
|
|
1806
1808
|
<span class="subtask-node-name">${o}${s}</span>
|
|
1807
1809
|
${a?`<span class="subtask-node-dur">${a}</span>`:``}
|
|
1808
|
-
</div>`}).join(``)),y.innerHTML=t.join(``)+s},e._renderNodes(),
|
|
1810
|
+
</div>`}).join(``)),y.innerHTML=t.join(``)+s},e._renderNodes(),nT(e)}function aT(e,t,n,r=null){let i=r||eT(t);i&&[...i.items].sort((e,t)=>e.index-t.index).forEach(r=>{if(r.index===n)return;let a=e.querySelector(`.subtask-progress[data-subtask-index="${r.index}"]`);if(!a||a.dataset.terminal===`1`)return;let o=r.index,s=t.filter(e=>e.subtaskIndex===o&&e.nodeType!==`subtask`),c=t.find(e=>e.subtaskIndex===o&&e.nodeType===`subtask`),l=!!c&&(c.status===`success`||c.status===`failed`),u=s.length>0&&!s.some(e=>e.status===`processing`);!l&&!u||iT(a,r,i,t,c,s)})}function oT(e){let t=e||r(`chatResume.unknownError`),n=t.toLowerCase();return n.includes(`network`)||n.includes(`failed to fetch`)||n.includes(`load failed`)?r(`chat.networkError`):n.includes(`timeout`)||t.includes(`超时`)?r(`chat.timeoutError`,{message:t}):r(`chat.requestFailed`,{message:t})}var sT=Object.freeze({quotedContextText:``,selectedContextText:``,selectedSkills:[],selectedMcpServices:[],knowledgeRefs:[],selectedPage:null,attachedFiles:[],attachedImages:[]});function cT(){return{quotedContextText:C.quotedContextText||``,selectedContextText:C.selectedContextText||``,selectedSkills:(C.selectedSkills||[]).slice(),selectedMcpServices:(C.selectedMcpServices||[]).slice(),knowledgeRefs:(C.knowledgeRefs||[]).slice(),selectedPage:C.selectedPage||null,attachedFiles:(C.attachedFiles||[]).slice(),attachedImages:(C.attachedImages||[]).slice()}}async function lT(e={}){await Pw;let t=document.getElementById(`userInput`),n=document.getElementById(`chatContainer`),a=e.sessionId||C.activeSessionId,o=a===C.activeSessionId,l=o?null:e.sessionState||{},u=o?C.messageHistory:l.messageHistory||[],d=e.context||(o?cT():sT),f=!e.context,h=o?C.currentModel:l.model||C.currentModel,g=o||l.useTools===void 0?C.useTools:l.useTools,_=o?C.enabledTools:l.enabledTools||C.enabledTools,v=o?C.activeCompaction:l.contextCompaction||null,y=String(e.text==null?t?.value||``:e.text).trim(),x=y||Dd(d);if(!x)return{ok:!1,reason:`empty`};if(o&&f&&Md())return F(r(`queue.filesStillExtracting`),`warning`,4e3),{ok:!1,reason:`files_extracting`};if(e.fromQueue||ud(),C.generatingSessionIds.has(a))return{ok:!1,reason:`generating`};try{let e=await chrome.runtime.sendMessage({type:`QUERY_SESSION_RUNNING`,sessionId:a});if(e?.running===!0||Array.isArray(e?.activeSessionIds)&&e.activeSessionIds.includes(a)||e?.activeCallIds&&e.activeCallIds[a])return{ok:!1,reason:`generating`}}catch{}if(AS(a),chrome.runtime.sendMessage({type:`DELETE_CHECKPOINT`,sessionId:a}),o&&await _l({state:C,getRatio:()=>IO().usage?.ratio??0,compact:GO}),o){let e=n?.querySelector(`.welcome-message`);e&&e.remove()}let S=x,w=d.selectedContextText&&d.selectedContextText.trim(),T=d.quotedContextText&&d.quotedContextText.trim(),D=[];if(T){let e=d.quotedContextText.trim(),{compressed:t,wasCompressed:n}=m(e);S=`[引用内容${n?`摘要`:``}]\n${t}\n\n[用户问题]\n${x}`,o&&pT(`quoted`,e,!1),D.push({type:`quoted`,text:e}),o&&f&&C.quotedContextText===d.quotedContextText&&(C.quotedContextText=``)}else if(w){let e=d.selectedContextText.trim(),{compressed:t,wasCompressed:n}=m(e);S=`[选中内容${n?`摘要`:``}]\n${t}\n\n[用户问题]\n${x}`,o&&pT(`selected`,e,!1),D.push({type:`selected`,text:e}),o&&f&&C.selectedContextText===d.selectedContextText&&(C.selectedContextText=``)}let O=await wE(d.selectedSkills);if(O){S=O+S;for(let e of d.selectedSkills||[])o&&pT(`skill`,r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``}),!1),D.push({type:`skill`,name:e.name,description:e.description||``});if(o){let e=new Set(d.selectedSkills||[]),t=C.selectedSkills.filter(t=>!e.has(t));t.length!==C.selectedSkills.length&&(C.selectedSkills=t,C.selectedSkillIndex=-1,vE(),yE())}}let k=null,A=ME(d.selectedMcpServices);if(A){let e=(d.selectedMcpServices||[]).map(e=>e.serverId).filter(Boolean);k=e.length>0?e:null,S=A+S;for(let e of d.selectedMcpServices||[])o&&pT(`mcp`,r(`contextBubble.bubbleMcp`,{name:e.serverName}),!1),D.push({type:`mcp`,serverName:e.serverName,serverId:e.serverId||``});if(o){let e=new Set(d.selectedMcpServices||[]),t=C.selectedMcpServices.filter(t=>!e.has(t));t.length!==C.selectedMcpServices.length&&(C.selectedMcpServices=t,C.selectedMcpServiceIndex=-1,NE(),PE())}}if((d.knowledgeRefs||[]).length>0){let e=d.knowledgeRefs.slice();o&&(C.isGenerating=!0);let t=o?pT(`knowledge`,r(`contextBubble.bubbleKnowledgeSearching`),!0):null,n=null;try{n=await Ww(y||r(`sidePanel.defaultKnowledgeQuery`),e)}catch(e){i.warn(`[SidePanel] knowledge search failed:`,e)}if(t&&t.parentNode&&t.remove(),n&&(S=n.text+S,o&&Gw(n.refs,n.failed===!0),D.push({type:`knowledge`,refs:n.refs,failed:n.failed||void 0})),o){let t=new Set(e),n=C.knowledgeRefs.filter(e=>!t.has(e));n.length!==C.knowledgeRefs.length&&(C.knowledgeRefs=n,dx(),vx())}}if(d.selectedPage){let e=d.selectedPage;S=`[网页上下文]\n标题: ${e.title}\nURL: ${e.url}\ntabId: ${e.id}\n`+S,o&&pT(`page`,r(`contextBubble.bubblePage`,{title:e.title,url:e.url}),!1),D.push({type:`page`,title:e.title,url:e.url}),o&&C.selectedPage===d.selectedPage&&Mx()}let M=!1,N=(d.attachedFiles||[]).slice();if(N.length>0){let e=nh(N);e&&(S+=e),N.forEach(e=>{e.status===`done`&&D.push({type:`file`,name:e.name,size:e.size,fileType:e.type})})}let ee=(d.attachedImages||[]).slice(),te=null;if(N.length>0||ee.length>0)try{te=await j(a,N,ee)}catch(e){i.warn(`[Chat] save doc image snapshot failed:`,e.message)}let ne=De(te?.chatStart,te?.chatCount);ne&&(S+=ne);let re=`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8),ie=new Date().toISOString(),ae={role:`user`,content:pm(S,d.attachedImages),messageId:re,timestamp:ie,contextBubbles:D};o?(_T(`user`,pm(x,d.attachedImages),!0,[],null,!1,S,re,N,!1,ie),C.messageHistory.push(ae),Rw(),y&&ln(y),C.inputHistoryIndex=-1):u.push(ae),M=!0,o&&!e.fromQueue&&(t.value=``,t.style.height=`auto`),o&&(w||T)&&(!C.quotedContextText&&!C.selectedContextText?Mw():jw()),C.generatingSessionIds.add(a),document.dispatchEvent(new CustomEvent(`generating-state-changed`));let oe=o?CT():null,se=C.enableImageInput&&(d.attachedImages||[]).length>0&&C.imageModelName||h;if(o&&(d.attachedImages||[]).length>0){let e=new Set(d.attachedImages),t=C.attachedImages.filter(t=>!e.has(t));t.length!==C.attachedImages.length&&(C.attachedImages=t,fm())}if(o&&N.length>0){let e=new Set(N),t=C.attachedFiles.filter(t=>!e.has(t));if(t.length!==C.attachedFiles.length){for(let t of C.attachedFiles)e.has(t)&&t.dataUrl&&URL.revokeObjectURL(t.dataUrl);C.attachedFiles=t,th()}}let ce=e=>{if(!o){u.push(e);return}if(C.activeSessionId!==a){Pi(a,e);return}C.messageHistory.push(e)};try{await rt();let e=await DO(o?C.activeAgentId:l.agentId||null),t=OO(e),n=e?.skillIds??null;o&&(C.activeAgentToolIds=t,C.activeAgentSkillIds=n,C.activeAgentMcpExcludedServerIds=e?e.mcpExcludedServerIds??null:null);let f={agentId:o?C.activeAgentId:l.agentId||null,agentToolIds:t,agentSkillIds:n,agentMcpExcludedServerIds:e?e.mcpExcludedServerIds??null:null};i.debug(`[SidePanel] sendmessagedebuginfo:`),i.debug(` - agent:`,e?e.name:`default assistant`),i.debug(` - agentToolIds:`,t),i.debug(` - isolateChat:`,C.isolateChat),i.debug(` - chatConfig:`,C.chatConfig),i.debug(` - messageHistory.length:`,u.length);let m=[{role:`system`,content:await Ke(e,{sessionId:a})}];if(C.isolateChat){let e=s(m[0]?.content||``),t=p(se,0,C.customModelMap)-e-4096-2e3;Math.floor(t*.7);let n=u[u.length-1],r=rn(u.slice(0,-1),{isolateChat:!0,maxMemoryMessages:C.chatConfig.maxMemoryMessages,compaction:v,currentMessage:n});on(m,r,v,i),r.historySummaryText&&(m[0]={...m[0],content:m[0].content+`
|
|
1809
1811
|
|
|
1810
|
-
`+r.historySummaryText}),i.debug(`[SidePanel] history selection: keep ${r.keptHistory.length}/${u.length-1}, trimmed ${r.trimmedCount}, compactionApplied: ${r.compactionApplied}`),m=[...m,...r.messages];for(let e=0;e<m.length-1;e++)m[e]={...m[e],content:
|
|
1812
|
+
`+r.historySummaryText}),i.debug(`[SidePanel] history selection: keep ${r.keptHistory.length}/${u.length-1}, trimmed ${r.trimmedCount}, compactionApplied: ${r.compactionApplied}`),m=[...m,...r.messages];for(let e=0;e<m.length-1;e++)m[e]={...m[e],content:mm(m[e].content)}}else{let e=pm(S,d.attachedImages);m.push({role:`user`,content:e})}let h=await Pe(o?null:{temperature:l.temperature,topP:l.topP});if(o&&(h._loadingId=oe),o)try{let e=await Hf({sessionId:a,text:x,attachments:Uf(d)});e&&(h.goal=e)}catch(e){i.warn(`[SidePanel] prepare goal for send failed:`,e?.message)}let y=E(m),w=p(se,0,C.customModelMap),T=c(y,w);if(i.debug(`[SidePanel] send context: ${y} tokens (message: ${m.length} ), pressure: ${T.level}(${Math.round(T.ratio*100)}%)`),T.level===`critical`){i.warn(`[SidePanel] context pressure too high,maindynamictrimming...`);let e=s(m[0]?.content||``),t=await jT(k),n=(_.length+t)*200,r=w-e-n-4096-2e3,a=b(m,Math.max(r,2e3),{generateSummary:!1});m=a.messages,i.warn(`[SidePanel] proactively trimmed: ${y} → ${E(m)} tokens (${a.trimmedCount} )`)}let D,O,A,j=!1,M=!1,N=null,ee=!0,te=null,ne=!1;try{let e=await NT(m,se,g,h,{forcedMcpServerIds:k,sessionId:a,agent:f});D=e.content,O=e.executionLog||[],A=e.reflectionScore,j=e.wasRevised||!1,M=e.wasStreamed||!1,N=e.streamingHtml||null,ee=e.streamingConnected===void 0?!0:e.streamingConnected,te=e.streamingMsgId||null,ne=e.budgetEnded===!0}catch(e){if(!o||C.activeSessionId!==a){let t=!!e.checkpoint||e.swRestarted||e.message===r(`chatMsg.errTaskStopped`);return ce({role:`assistant`,content:e.message===r(`chatMsg.errTaskStopped`)?r(`chatResume.taskCancelled`):e.swRestarted?r(`chat.taskInterruptedSwRestart`):oT(e.message),executionLog:e.executionLog||[],resumable:t}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:a}})),oe&&wT(oe),C.substituteLoadingIds.delete(a),{ok:!1,delivered:!0,reason:`inactive`}}if(e.message===r(`chatMsg.errTaskStopped`)){oe&&wT(oe),C.substituteLoadingIds.delete(a);let{messageId:t}=_T(`assistant`,r(`chatResume.taskCancelled`),!1,e.executionLog||[],null,!1,null,null,[],!0);return C.messageHistory.push({role:`assistant`,content:r(`chatResume.taskCancelled`),executionLog:e.executionLog||[],messageId:t,resumable:!0}),Rw(),{ok:!1,delivered:!0,reason:`cancelled`}}if(e.swRestarted){oe&&wT(oe),C.substituteLoadingIds.delete(a);let t=!!e.checkpoint,{messageId:n}=_T(`assistant`,r(`chat.taskInterruptedSwRestart`),!1,e.executionLog||[],null,!1,null,null,[],t);return C.messageHistory.push({role:`assistant`,content:r(`chat.taskInterruptedSwRestart`),executionLog:e.executionLog||[],messageId:n,resumable:t}),Rw(),Yl(a,r(`chat.taskInterruptedSwRestart`),x),{ok:!1,delivered:!0,reason:`sw_restarted`}}oe&&wT(oe),C.substituteLoadingIds.delete(a),D=oT(e.message),O=e.executionLog||[];let{messageId:t}=_T(`assistant`,D,!0,O,A,!1,null,null,[],!0);return C.messageHistory.push({role:`assistant`,content:D,executionLog:O,reflectionScore:A,messageId:t,resumable:!0}),Yl(a,D,x),{ok:!1,delivered:!0,reason:`error`}}if(!o||C.activeSessionId!==a){let e={role:`assistant`,content:D,executionLog:O,reflectionScore:A,wasRevised:j,resumable:ne?`budget`:!1,messageId:te||`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8)};return M&&N&&(e.htmlContent=N),ce(e),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:a}})),oe&&wT(oe),C.substituteLoadingIds.delete(a),{ok:!0,delivered:!0}}let re=null;if(!M||!N)if(oe&&wT(oe),C.substituteLoadingIds.has(a)&&(wT(C.substituteLoadingIds.get(a)),C.substituteLoadingIds.delete(a)),M)C.substituteLoadingIds.has(a)&&(wT(C.substituteLoadingIds.get(a)),C.substituteLoadingIds.delete(a)),re=te;else{let{element:e,messageId:t}=_T(`assistant`,D,!0,O,A,j,null,null,[],ne?`budget`:!1);re=t,await lt(e),_C()}else re=te;ne&&MS(re?document.querySelector(`[data-message-id="${re}"]`):null,`budget`);let ie={role:`assistant`,content:D,executionLog:O,reflectionScore:A,wasRevised:j,resumable:ne?`budget`:!1,messageId:re};if(M&&N&&(ie.htmlContent=N,!ee&&!document.querySelector(`[data-message-id="${re}"]`))){ET(N,re,ne?`budget`:!1),bT(),ST();let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}return C.messageHistory.push(ie),Jl(a,x),{ok:!0,delivered:!0}}catch(e){return i.error(`[SidePanel] sendMessage exception:`,e?.message||e),{ok:!1,delivered:M,reason:e?.message||`exception`}}finally{o?Rw():(await xi(a,{messageHistory:u,model:l.model,useTools:l.useTools,enabledTools:l.enabledTools,agentId:l.agentId,temperature:l.temperature,topP:l.topP,activeCompaction:l.contextCompaction,workdir:l.workdir,workdirAgentId:l.workdirAgentId,goalMode:l.goalMode}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:a}}))),Ql(a),o&&t.focus()}}function uT(e,t){let n=document.getElementById(`userInput`);if(!t||C.isGenerating){i.debug(`[SidePanel] triggerSelectionSearch skip:`,{hasText:!!t,isGenerating:C.isGenerating});return}C.selectedContextText=t,C.quotedContextText=``,n.value=r(`chatMsg.searchPrompt`),n.dispatchEvent(new Event(`input`)),lT()}function dT(e){let t=document.getElementById(`userInput`);!t||!e||(t.value=e,t.dispatchEvent(new Event(`input`)),t.focus())}async function fT(e,t=``){await Pw;let n=document.getElementById(`userInput`);if(!(!n||!e)){if(t&&(C.selectedContextText=t,C.quotedContextText=``),C.isGenerating){n.value=e,n.dispatchEvent(new Event(`input`)),await Id();return}n.value=e,n.dispatchEvent(new Event(`input`)),n.focus(),lT()}}function pT(e,t,n=!0,i=null){let a=document.getElementById(`chatContainer`),o=document.createElement(`div`);o.className=`user-context-bubble`,o.dataset.role=`context`;let s=e===`quoted`?`💬`:e===`skill`?`🧩`:e===`mcp`?`🔌`:e===`page`?`🌐`:e===`file`?`📎`:e===`knowledge`?`📚`:`📌`,c=r(e===`quoted`?`contextBubble.labelQuoted`:e===`skill`?`contextBubble.labelSkill`:e===`mcp`?`contextBubble.labelMcp`:e===`page`?`contextBubble.labelPage`:e===`file`?`contextBubble.labelFile`:e===`knowledge`?`contextBubble.labelKnowledge`:`contextBubble.labelSelection`),l=L(t);if(e===`knowledge`&&Array.isArray(i)&&i.length>0){let e=i.map(e=>{let t=typeof e.score==`number`?e.score.toFixed(3):``,n=t?`<span class="kb-bubble-hit-score">${t}</span>`:``,i=e.truncated?`<span class="kb-bubble-hit-truncated" title="${r(`contextBubble.kbHitTruncatedTitle`)}">${r(`contextBubble.kbHitTruncated`,{total:e.fullLength||0,kept:Uw})}</span>`:``;return`<div class="kb-bubble-hit"><div class="kb-bubble-hit-text" title="${r(`contextBubble.kbHitToggle`)}">${n}${L(e.content||``)}</div>${i}</div>`}).join(``),n=i.filter(e=>e.truncated).length,a=n>0?`<span class="kb-bubble-truncated-badge">${r(`contextBubble.kbHitTruncatedBadge`,{count:n})}</span>`:``;l=`<div class="kb-bubble-summary">${L(t)}${a}</div>${e}`}o.innerHTML=`
|
|
1811
1813
|
<div class="context-bubble-inner">
|
|
1812
1814
|
<div class="context-bubble-header" title="${r(`contextBubble.clickToExpand`)}">
|
|
1813
1815
|
<span class="context-icon">${s}</span>
|
|
@@ -1815,7 +1817,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1815
1817
|
</div>
|
|
1816
1818
|
<div class="context-bubble-content">${l}</div>
|
|
1817
1819
|
</div>
|
|
1818
|
-
`;let u=o.querySelector(`.context-bubble-header`),d=o.querySelector(`.context-bubble-content`);return u.addEventListener(`click`,e=>{e.stopPropagation(),d.classList.toggle(`expanded`)}),e===`knowledge`&&o.querySelectorAll(`.kb-bubble-hit-text`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),e.classList.toggle(`expanded`)})}),a.appendChild(o),n&&(a.scrollTop=a.scrollHeight),o}function cT(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n[\s\S]*?(?:请根据上述技能说明[\s\S]*?处理以下问题[::]|Please use the relevant tools[\s\S]*?handle the following problem[.:])\s*\n/,``).replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n(?:请|Please)[^\n]*(?:处理以下问题|handle the following problem)[^。\n]*。?\s*\n/,``);while(t!==n);return t}function lT(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选MCP服务|Selected MCP service):\s*[^\]]+\]\n(?:请使用「[^」]+」MCP服务来处理以下问题:|Please use the "[^"]+" MCP service to handle the following problem:)\s*\n/,``);while(t!==n);return t}var uT=e=>!!e&&e.dataset.resumable===`budget`;function dT(e,t,n=!0,a=[],o=null,s=!1,c=null,l=null,u=[],d=!1,f=void 0){let p=document.getElementById(`chatContainer`),m=document.createElement(`div`);m.className=`message ${e}`;let h=f===void 0?new Date().toISOString():f||null;h&&(m.dataset.timestamp=h);let g=l||`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8);m.dataset.messageId=g;let _=Array.isArray(t)?t.filter(e=>e.type===`text`).map(e=>e.text).join(``):t,v=e===`user`?pe(_):_,y=Array.isArray(t)&&t.some(e=>e.type===`image_url`);m.dataset.rawContent=Array.isArray(t)?JSON.stringify(t):dt(t),m.dataset.textContent_=dt(e===`user`?pe(c||v):c||v);let b=v;if(m.dataset.executionLog=JSON.stringify(a),s&&(m.dataset.wasRevised=`true`),e===`assistant`){m.innerHTML=et(t);let e=document.createElement(`div`);e.className=`message-footer`;let n=document.createElement(`button`);n.className=`copy-btn`,n.title=r(`chatStream.copyMarkdown`),n.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>${r(`common.copy`)}</span>`].join(``),n.addEventListener(`click`,e=>{e.stopPropagation(),fS(m,n,e)}),e.appendChild(n);let c=document.createElement(`button`);c.className=`quote-btn`,c.title=r(`chat.quoteTitle`),c.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>${r(`chat.quote`)}</span>`].join(``),c.addEventListener(`click`,e=>{e.stopPropagation(),bS(m)}),e.appendChild(c),e.appendChild(Kx());let l=document.createElement(`div`);l.className=`export-menu-container`;let u=document.createElement(`button`);u.className=`export-trigger-btn`,u.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>${r(`chat.export`)}</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let f=document.createElement(`div`);f.className=`export-dropdown`,f.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>${r(`chatMsg.exportWord`)}</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>${r(`chatMsg.exportPdf`)}</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>${r(`chatMsg.exportImage`)}</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>${r(`chatMsg.exportMarkdown`)}</span>`,`</button>`].join(``);let p=f.querySelector(`.export-docx-item`);p.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToDocx:t}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DRUG3mwM.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));t(m,p,f)});let h=f.querySelector(`.export-md-item`);h.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToMarkdown:t}=await A(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DRUG3mwM.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));t(m,h,f)});let _=f.querySelector(`.export-pdf-item`);_.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToPdf:t}=await A(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DRUG3mwM.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));t(m,_,f)});let v=f.querySelector(`.export-image-item`);v.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToImage:t}=await A(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DRUG3mwM.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));t(m,v,f)}),u.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.toggle(`show`)});let y=null;l.addEventListener(`mouseenter`,()=>{y=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.add(`show`)},300)}),l.addEventListener(`mouseleave`,()=>{y&&=(clearTimeout(y),null),setTimeout(()=>{!l.matches(`:hover`)&&!f.matches(`:hover`)&&f.classList.remove(`show`)},100)}),l.appendChild(u),l.appendChild(f),e.appendChild(l);let b=document.createElement(`div`);b.className=`footer-right-actions`,b.style.marginLeft=`auto`,b.style.display=`flex`,b.style.alignItems=`center`,b.style.gap=`8px`;let x=Ge(a);if(x){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:I(x.totalTokens),prompt:I(x.promptTokens),completion:I(x.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${I(x.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ye(x,e)}),b.appendChild(e)}let S=a&&a.length>0,w=o!=null,T=a?a.filter(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.status===`success`).length:0;mT(),gT(),st();let E=a?.find(e=>e.nodeType===`reflection`&&e.reflectionType===`post`),D=ub(t),O=pb(a,t);if(D.length&&(m.dataset.declaredArtifacts=JSON.stringify(D)),jb(O),console.log(`[addMessage] executionLog entries:`,a?.length,`| agent_file entries:`,a?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length,`| artifacts:`,O.length),O.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:O.length}),e.innerHTML=`
|
|
1820
|
+
`;let u=o.querySelector(`.context-bubble-header`),d=o.querySelector(`.context-bubble-content`);return u.addEventListener(`click`,e=>{e.stopPropagation(),d.classList.toggle(`expanded`)}),e===`knowledge`&&o.querySelectorAll(`.kb-bubble-hit-text`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),e.classList.toggle(`expanded`)})}),a.appendChild(o),n&&(a.scrollTop=a.scrollHeight),o}function mT(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n[\s\S]*?(?:请根据上述技能说明[\s\S]*?处理以下问题[::]|Please use the relevant tools[\s\S]*?handle the following problem[.:])\s*\n/,``).replace(/^\[(?:已选技能|Selected skill): [^\]]+\]\n(?:请|Please)[^\n]*(?:处理以下问题|handle the following problem)[^。\n]*。?\s*\n/,``);while(t!==n);return t}function hT(e){let t=e,n;do n=t,t=t.replace(/^\[(?:已选MCP服务|Selected MCP service):\s*[^\]]+\]\n(?:请使用「[^」]+」MCP服务来处理以下问题:|Please use the "[^"]+" MCP service to handle the following problem:)\s*\n/,``);while(t!==n);return t}var gT=e=>!!e&&e.dataset.resumable===`budget`;function _T(e,t,n=!0,a=[],o=null,s=!1,c=null,l=null,u=[],d=!1,f=void 0){let p=document.getElementById(`chatContainer`),m=document.createElement(`div`);m.className=`message ${e}`;let h=f===void 0?new Date().toISOString():f||null;h&&(m.dataset.timestamp=h);let g=l||`msg_`+Date.now().toString(36)+`_`+Math.random().toString(36).substring(2,8);m.dataset.messageId=g;let _=Array.isArray(t)?t.filter(e=>e.type===`text`).map(e=>e.text).join(``):t,v=e===`user`?pe(_):_,y=Array.isArray(t)&&t.some(e=>e.type===`image_url`);m.dataset.rawContent=Array.isArray(t)?JSON.stringify(t):dt(t),m.dataset.textContent_=dt(e===`user`?pe(c||v):c||v);let b=v;if(m.dataset.executionLog=JSON.stringify(a),s&&(m.dataset.wasRevised=`true`),e===`assistant`){m.innerHTML=et(t);let e=document.createElement(`div`);e.className=`message-footer`;let n=document.createElement(`button`);n.className=`copy-btn`,n.title=r(`chatStream.copyMarkdown`),n.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`,`<span>${r(`common.copy`)}</span>`].join(``),n.addEventListener(`click`,e=>{e.stopPropagation(),vS(m,n,e)}),e.appendChild(n);let c=document.createElement(`button`);c.className=`quote-btn`,c.title=r(`chat.quoteTitle`),c.innerHTML=[`<svg t="1781246498458" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="9645" width="14" height="14"><path d="M156.09136 606.57001a457.596822 457.596822 0 0 1 221.680239-392.516385 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z m406.752731 0a457.596822 457.596822 0 0 1 221.680239-392.007944 50.844091 50.844091 0 1 1 50.844091 86.943396 355.90864 355.90864 0 0 0-138.804369 152.532274h16.77855a152.532274 152.532274 0 1 1-152.532274 152.532274z" fill="#8a8a8a" p-id="9646"></path></svg>`,`<span>${r(`chat.quote`)}</span>`].join(``),c.addEventListener(`click`,e=>{e.stopPropagation(),ES(m)}),e.appendChild(c),e.appendChild(Qx());let l=document.createElement(`div`);l.className=`export-menu-container`;let u=document.createElement(`button`);u.className=`export-trigger-btn`,u.innerHTML=`<svg t="1781245244396" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5115" width="14" height="14"><path d="M496.213333 739.84c2.133333 2.133333 4.693333 3.84 7.68 5.12 0.853333 0.426667 2.133333 0.426667 2.986667 0.853333 1.706667 0.426667 2.986667 0.853333 4.693333 0.853334 5.546667 0 11.093333-2.133333 14.933334-6.4l256-256c8.533333-8.533333 8.533333-21.76 0-30.293334s-21.76-8.533333-30.293334 0L533.333333 674.133333V128c0-11.946667-9.386667-21.333333-21.333333-21.333333s-21.333333 9.386667-21.333333 21.333333v545.706667l-219.306667-219.306667c-8.533333-8.533333-21.76-8.533333-30.293333 0s-8.533333 21.76 0 30.293333l255.146666 255.146667zM768 874.666667H256c-11.946667 0-21.333333 9.386667-21.333333 21.333333s9.386667 21.333333 21.333333 21.333333h512c11.946667 0 21.333333-9.386667 21.333333-21.333333s-9.386667-21.333333-21.333333-21.333333z" fill="#8a8a8a" p-id="5116"></path></svg><span>${r(`chat.export`)}</span><svg class="dropdown-arrow" width="8" height="6" viewBox="0 0 8 6" fill="currentColor"><path d="M0 0l4 6 4-6z"/></svg>`;let f=document.createElement(`div`);f.className=`export-dropdown`,f.innerHTML=[`<button class="export-dropdown-item export-docx-item" type="button">`,`<svg t="1781245550030" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6544" width="32" height="32"><path d="M747.936 901.171H276.819c-72.2 0-130.953-55.224-130.953-123.078V244.721c0-67.854 58.752-123.078 130.953-123.078h383.525c6.597 0 12.937 2.505 17.795 6.954l192.363 178.046c5.317 4.96 8.386 11.914 8.386 19.227v452.223c0 67.854-58.752 123.078-130.952 123.078zM276.819 174.004c-43.31 0-78.592 31.703-78.592 70.717v533.372c0 39.015 35.282 70.718 78.592 70.718h471.117c43.31 0 78.592-31.703 78.592-70.718V337.324l-176.461-163.32H276.819z" fill="#8a8a8a" p-id="6545"></path><path d="M830.567 331.546H669.446c-14.471 0-26.18-11.71-26.18-26.181V156.209c0-14.471 11.709-26.18 26.18-26.18s26.181 11.709 26.181 26.18v122.976h134.94c14.471 0 26.181 11.709 26.181 26.18s-11.711 26.181-26.181 26.181z" fill="#8a8a8a" p-id="6546"></path><path d="M730.214 428.749l-92.04 343.616h-53.179L511.363 498.29l-75.677 274.074h-53.179l-92.04-343.616h49.088l69.542 255.667 69.541-255.667h63.406l69.541 255.667 69.541-255.667h49.088z" fill="#8a8a8a" p-id="6547"></path></svg>`,`<span>${r(`chatMsg.exportWord`)}</span>`,`</button>`,`<button class="export-dropdown-item export-pdf-item" type="button">`,`<svg t="1781245863206" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8152" width="32" height="32"><path d="M582.4 864H170.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V170.666667c0-6.4 4.266667-10.666667 10.666667-10.666667h309.333333V320c0 40.533333 34.133333 74.666667 74.666667 74.666667h160v38.4c0 17.066667 14.933333 32 32 32s32-14.933333 32-32V298.666667c0-8.533333-4.266667-17.066667-8.533334-23.466667l-170.666666-170.666667c-6.4-6.4-14.933333-8.533333-23.466667-8.533333H170.666667C130.133333 96 96 130.133333 96 170.666667v682.666666c0 40.533333 34.133333 74.666667 74.666667 74.666667h411.733333c17.066667 0 32-14.933333 32-32s-14.933333-32-32-32z m132.266667-550.4v17.066667H554.666667c-6.4 0-10.666667-4.266667-10.666667-10.666667V160h19.2l151.466667 153.6z" fill="#8a8a8a" p-id="8153"></path><path d="M332.8 533.333333c-12.8 0-19.2 2.133333-25.6 6.4-6.4 4.266667-8.533333 12.8-8.533333 23.466667v206.933333c0 6.4 2.133333 12.8 6.4 19.2 4.266667 4.266667 10.666667 8.533333 21.333333 8.533334s17.066667-4.266667 21.333333-8.533334c4.266667-4.266667 6.4-10.666667 6.4-19.2v-64h32c57.6 0 89.6-29.866667 89.6-87.466666 0-27.733333-8.533333-51.2-23.466666-64-14.933333-14.933333-36.266667-21.333333-66.133334-21.333334h-53.333333z m87.466667 85.333334c0 12.8-2.133333 23.466667-8.533334 27.733333-4.266667 4.266667-14.933333 8.533333-27.733333 8.533333h-32v-70.4H384c12.8 0 21.333333 2.133333 27.733333 8.533334 6.4 4.266667 8.533333 12.8 8.533334 25.6zM667.733333 571.733333c-8.533333-12.8-21.333333-21.333333-34.133333-29.866666-14.933333-4.266667-32-8.533333-51.2-8.533334h-61.866667c-8.533333 0-17.066667 0-23.466666 8.533334-2.133333 4.266667-4.266667 10.666667-4.266667 19.2V768c0 8.533333 2.133333 14.933333 4.266667 19.2 6.4 8.533333 14.933333 8.533333 23.466666 8.533333h64c19.2 0 34.133333-4.266667 49.066667-10.666666 12.8-6.4 25.6-17.066667 34.133333-29.866667 8.533333-12.8 14.933333-25.6 19.2-42.666667 4.266667-14.933333 6.4-32 6.4-49.066666 0-17.066667-2.133333-34.133333-6.4-49.066667-4.266667-14.933333-10.666667-29.866667-19.2-42.666667z m-42.666666 153.6c-8.533333 12.8-21.333333 19.2-38.4 19.2h-38.4v-160H576c21.333333 0 38.4 6.4 46.933333 19.2 10.666667 12.8 14.933333 34.133333 14.933334 59.733334 2.133333 27.733333-4.266667 46.933333-12.8 61.866666zM851.2 533.333333h-106.666667c-8.533333 0-17.066667 2.133333-21.333333 6.4-6.4 4.266667-8.533333 12.8-8.533333 21.333334v209.066666c0 6.4 2.133333 12.8 6.4 17.066667 4.266667 6.4 10.666667 8.533333 21.333333 8.533333 8.533333 0 17.066667-2.133333 21.333333-8.533333 2.133333-4.266667 6.4-8.533333 6.4-19.2v-85.333333h72.533334c12.8 0 23.466667-6.4 25.6-17.066667 2.133333-8.533333 2.133333-14.933333 0-17.066667-2.133333-4.266667-6.4-17.066667-25.6-17.066666H768v-49.066667h81.066667c8.533333 0 14.933333-2.133333 19.2-4.266667 4.266667-2.133333 8.533333-8.533333 8.533333-21.333333 2.133333-12.8-8.533333-23.466667-25.6-23.466667z" fill="#8a8a8a" p-id="8154"></path></svg>`,`<span>${r(`chatMsg.exportPdf`)}</span>`,`</button>`,`<button class="export-dropdown-item export-image-item" type="button">`,`<svg t="1784207887308" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5993" width="32" height="32"><path d="M400.696 268.795c-17.249 0-31.233 13.986-31.233 31.233v30.471c0 17.249 13.986 31.233 31.233 31.233s31.233-13.986 31.233-31.233v-30.471c0-17.249-13.985-31.233-31.233-31.233z" fill="#8a8a8a" p-id="5994"></path><path d="M623.649 361.734c17.249 0 31.234-13.986 31.234-31.233v-30.471c0-17.249-13.986-31.233-31.234-31.233s-31.233 13.986-31.233 31.233v30.471c-0.001 17.248 13.985 31.233 31.233 31.233z" fill="#8a8a8a" p-id="5995"></path><path d="M438.295 388.804c-14.656 9.104-19.155 28.362-10.050 43.013 11.209 18.047 41.976 48.59 86.157 48.59 43.958 0 75.1-30.313 86.574-48.223 9.303-14.529 5.068-33.847-9.455-43.15-14.539-9.298-33.852-5.068-43.15 9.455-0.122 0.199-13.38 19.45-33.969 19.45-20.009 0-32.444-18.128-33.278-19.373-9.166-14.423-28.28-18.805-42.829-9.761z" fill="#8a8a8a" p-id="5996"></path><path d="M824.508503 116.690676 571.592236 116.690676c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c40.181141 0 72.878844 32.692586 72.878844 72.878844l0 396.966057-189.334159-165.29465c-12.20088-10.655687-30.517037-10.207479-42.173518 0.9967L468.578048 674.16231 309.521472 517.519714c-11.895935-11.70253-30.903847-12.002358-43.154869-0.645706L126.957507 646.163629l0-394.126382c0-40.186258 32.692586-72.878844 72.878844-72.878844l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352S470.000444 116.690676 452.751594 116.690676L199.836351 116.690676c-74.632791 0-135.346571 60.71378-135.346571 135.346571l0 520.56405c0 74.632791 60.71378 135.346571 135.346571 135.346571l252.916267 0c17.248849 0 31.233352-13.985526 31.233352-31.233352s-13.985526-31.233352-31.233352-31.233352L199.836351 845.481164c-40.186258 0-72.878844-32.692586-72.878844-72.878844l0-41.23924 160.003134-148.385539 159.428036 157.007917c12.048407 11.865235 31.361265 11.981892 43.546795 0.274246l198.576661-190.68697 208.876238 182.346001 0 40.683585c0 40.186258-32.697703 72.878844-72.878844 72.878844L571.592236 845.481164c-17.248849 0-31.233352 13.985526-31.233352 31.233352s13.985526 31.233352 31.233352 31.233352l252.916267 0c74.627674 0 135.346571-60.71378 135.346571-135.346571L959.855074 252.037247C959.855074 177.404456 899.136178 116.690676 824.508503 116.690676z" fill="#8a8a8a" p-id="5997"></path></svg>`,`<span>${r(`chatMsg.exportImage`)}</span>`,`</button>`,`<button class="export-dropdown-item export-md-item" type="button">`,`<svg t="1784038824502" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1666" width="32" height="32"><path d="M601.216 85.333333a42.666667 42.666667 0 0 1 30.485333 12.821334l209.450667 213.973333a42.666667 42.666667 0 0 1 12.181333 29.866667V853.333333a85.333333 85.333333 0 0 1-85.333333 85.333334H256a85.333333 85.333333 0 0 1-85.333333-85.333334V170.666667a85.333333 85.333333 0 0 1 85.333333-85.333334h345.216z m-35.584 64H256a21.333333 21.333333 0 0 0-21.333333 21.333334v682.666666a21.333333 21.333333 0 0 0 21.333333 21.333334h512a21.333333 21.333333 0 0 0 21.333333-21.333334V395.413333h-191.68a32 32 0 0 1-32-32L565.632 149.333333z m64 38.186667v143.893333h140.821333L629.632 187.52z" fill="#8a8a8a" p-id="1667"></path><path d="M384.341333 800l-3.072-0.106667a32 32 0 0 1-29.162666-34.624l21.973333-256c2.752-32.256 46.165333-40.490667 60.544-11.477333l77.290667 156.010667 78.805333-156.224c14.08-27.925333 55.082667-20.906667 60.074667 8.789333l0.384 3.050667 20.714666 256a32 32 0 0 1-63.786666 5.162666l-11.541334-142.549333-56.341333 111.722667c-11.413333 22.613333-42.88 23.381333-55.744 2.517333l-1.493333-2.730667-54.912-110.826666-12.181334 142.016a32 32 0 0 1-31.552 29.269333z" fill="#8a8a8a" p-id="1668"></path></svg>`,`<span>${r(`chatMsg.exportMarkdown`)}</span>`,`</button>`].join(``);let p=f.querySelector(`.export-docx-item`);p.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToDocx:t}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));t(m,p,f)});let h=f.querySelector(`.export-md-item`);h.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToMarkdown:t}=await A(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));t(m,h,f)});let _=f.querySelector(`.export-pdf-item`);_.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToPdf:t}=await A(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));t(m,_,f)});let v=f.querySelector(`.export-image-item`);v.addEventListener(`click`,async e=>{e.stopPropagation();let{exportAssistantMessageToImage:t}=await A(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));t(m,v,f)}),u.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.toggle(`show`)});let y=null;l.addEventListener(`mouseenter`,()=>{y=setTimeout(()=>{document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==f&&e.classList.remove(`show`)}),f.classList.add(`show`)},300)}),l.addEventListener(`mouseleave`,()=>{y&&=(clearTimeout(y),null),setTimeout(()=>{!l.matches(`:hover`)&&!f.matches(`:hover`)&&f.classList.remove(`show`)},100)}),l.appendChild(u),l.appendChild(f),e.appendChild(l);let b=document.createElement(`div`);b.className=`footer-right-actions`,b.style.marginLeft=`auto`,b.style.display=`flex`,b.style.alignItems=`center`,b.style.gap=`8px`;let x=Ge(a);if(x){let e=document.createElement(`span`);e.className=`token-usage-tag`,e.title=r(`chatStream.tokenUsageTitle`,{total:I(x.totalTokens),prompt:I(x.promptTokens),completion:I(x.completionTokens)}),e.innerHTML=`<span class="token-tag-icon">⬤</span><span class="token-tag-value">${I(x.totalTokens)}</span>`,e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ye(x,e)}),b.appendChild(e)}let S=a&&a.length>0,w=o!=null,T=a?a.filter(e=>e.nodeType===`reflection`&&e.reflectionType===`post`&&e.status===`success`).length:0;bT(),ST(),st();let E=a?.find(e=>e.nodeType===`reflection`&&e.reflectionType===`post`),D=mb(t),O=_b(a,t);if(D.length&&(m.dataset.declaredArtifacts=JSON.stringify(D)),Fb(O),console.log(`[addMessage] executionLog entries:`,a?.length,`| agent_file entries:`,a?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length,`| artifacts:`,O.length),O.length>0){let e=document.createElement(`button`);e.className=`artifacts-btn`,e.type=`button`,e.title=r(`artifacts.btnTitle`,{count:O.length}),e.innerHTML=`
|
|
1819
1821
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1820
1822
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
1821
1823
|
<polyline points="14 2 14 8 20 8"/>
|
|
@@ -1823,26 +1825,26 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1823
1825
|
<line x1="9" y1="15" x2="15" y2="15"/>
|
|
1824
1826
|
</svg>
|
|
1825
1827
|
<span class="artifacts-btn-count">${O.length}</span>
|
|
1826
|
-
`,e.addEventListener(`click`,t=>{t.stopPropagation(),
|
|
1828
|
+
`,e.addEventListener(`click`,t=>{t.stopPropagation(),Ib(O,e)}),b.appendChild(e),Pb(O,e)}if($e(m,O.map(e=>e.path)).catch(()=>{}),S&&C.chatConfig.enableExecutionLog){let e=document.createElement(`button`);e.className=`execution-log-btn`,e.type=`button`,e.title=r(`chatMsg.executionLogTitle`),e.innerHTML=[`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">`,`<circle cx="12" cy="12" r="10"></circle>`,`<polyline points="12 6 12 12 16 14"></polyline>`,`</svg>`].join(``),b.appendChild(e)}if(w&&C.chatConfig.enableExecutionLog){let e=o>=8?`score-high`:o>=5?`score-mid`:`score-low`,t=o>=8?`✅`:o>=5?`🔍`:`⚠️`,n=s?` <span class="reflection-revised-tag">${r(`chatMsg.revisedTag`)}</span>`:``,i=T>1?r(`chatMsg.roundsTag`,{count:T}):``,a=document.createElement(`button`);a.className=`reflection-score-btn`,a.type=`button`,a.title=r(`chatMsg.scoreBadgeTitle`,{score:o,rounds:i,revised:s?r(`chatMsg.revisedSuffix`):``}),a.innerHTML=`<span class="reflection-badge ${e}"><span class="reflection-badge-emoji">${t}</span> ${o}/10${n}</span>`,a.dataset.reflectionData=JSON.stringify({overallScore:E?.overallScore??o,dimensions:E?.dimensions||null,issues:E?.issues||null,suggestions:E?.suggestions||null,decision:E?.action?.decision||null,useful:E?.useful??null,reasoning:E?.reasoning||null,suggestion:E?.suggestion||null,rounds:T,wasRevised:s}),b.appendChild(a)}else if(!w&&E&&E.status===`failed`&&C.chatConfig?.enableExecutionLog){let e=document.createElement(`button`);e.className=`reflection-score-btn`,e.type=`button`,e.title=r(`chatMsg.reflectionFailedTitle`),e.innerHTML=`<span class="reflection-badge score-low">${r(`chatMsg.reflectionFailedBadge`)}</span>`,b.appendChild(e)}let k=a?.slice().reverse().find(e=>e.nodeType===`tool_exec`&&e.action?.name===`preview_ui`||e.action?.name===`preview_preview_ui`&&e.status===`success`);if(k){let e=!1;if(k.observation)try{e=(typeof k.observation==`string`?JSON.parse(k.observation):k.observation)?.localOpened===!0}catch{}let t=document.createElement(`button`);t.className=`prototype-btn-small`,t.type=`button`,t.title=r(e?`chatMsg.prototypeLocalOpened`:`chatMsg.prototypeView`),t.innerHTML=Dc,t.addEventListener(`click`,()=>{let e=k.prototypeId;if(!e&&k.observation)try{e=(typeof k.observation==`string`?JSON.parse(k.observation):k.observation)?.prototypeId}catch{}e?Wc(e):i.error(`[SidePanel] not found prototypeId,entry keys:`,Object.keys(k),`observation:`,k.observation)}),b.appendChild(t)}let j=document.createElement(`button`);j.className=`bookmark-btn`,j.title=r(`chatMsg.bookmarkMessage`),j.innerHTML=`
|
|
1827
1829
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1828
1830
|
<path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>
|
|
1829
1831
|
</svg>
|
|
1830
|
-
`,
|
|
1832
|
+
`,ih(C.activeSessionId,g)&&(j.classList.add(`bookmarked`),j.title=r(`chatMsg.unbookmarkMessage`),j.querySelector(`svg`).setAttribute(`fill`,`currentColor`)),j.addEventListener(`click`,async e=>{e.stopPropagation();let t=C.activeSessionId,n=m.dataset.messageId;if(j.classList.contains(`bookmarked`)){await oh(t,n),vh(j,t,n);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>uh);return{refreshBookmarkPanel:e}},void 0);e()}else{await ah(t,n,m.dataset.textContent_||``,C.sessions.find(e=>e.id===t)?.title||``),vh(j,t,n);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>uh);return{refreshBookmarkPanel:e}},void 0);e()}}),b.appendChild(j);let M=document.createElement(`button`);M.className=`fork-btn`,M.title=r(`chatMsg.forkSession`),M.innerHTML=`
|
|
1831
1833
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1832
1834
|
<circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/>
|
|
1833
1835
|
<path d="M6 8.5v7"/><path d="M6 12h8a4 4 0 0 0 4-4V6"/>
|
|
1834
1836
|
</svg>
|
|
1835
|
-
`,M.addEventListener(`click`,async e=>{e.stopPropagation();let t=m.dataset.messageId;t&&await
|
|
1837
|
+
`,M.addEventListener(`click`,async e=>{e.stopPropagation();let t=m.dataset.messageId;t&&await _c(C.activeSessionId,t)}),b.appendChild(M);let N=document.createElement(`button`);N.className=`delete-btn`,N.title=r(`chatMsg.deleteMessageTitle`),N.innerHTML=`
|
|
1836
1838
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1837
1839
|
<polyline points="3 6 5 6 21 6"></polyline>
|
|
1838
1840
|
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
|
1839
1841
|
</svg>
|
|
1840
|
-
`,N.addEventListener(`click`,e=>{e.stopPropagation(),
|
|
1842
|
+
`,N.addEventListener(`click`,e=>{e.stopPropagation(),AT(m)}),b.appendChild(N),e.appendChild(b),m.appendChild(e),d&&MS(m,d)}else{let e=b;e=e.replace(/^\[网页上下文\]\n标题: .+\nURL: .+\ntabId: \d+\n/,``),e=e.replace(/\[知识库检索结果\][^\n]*\n[\s\S]*?\[\/知识库检索结果\]\n\n?/,``),e=hT(e),e=mT(e);let n=e.match(/^\[引用内容(?:摘要)?\]\n([\s\S]+?)\n\n\[用户问题\]\n([\s\S]*)$/),i=e.match(/^\[选中内容(?:摘要)?\]\n([\s\S]+?)\n\n\[用户问题\]\n([\s\S]*)$/),a=n||i;if(a){let e=n?`quoted`:`selected`,t=a[1].trim(),r=a[2].trim();if(u&&u.length>0){let e=r.search(/\n\n\[(?:工作目录)?文件(?:内容)?:/);e!==-1&&(r=r.substring(0,e))}r=r.replace(/^\[网页上下文\]\n标题: .+\nURL: .+\ntabId: \d+\n/,``),r=hT(r),r=mT(r),r=r.replace(/\[工作目录文件: [^\]]+\]/g,``),m._pendingContext={type:e,contextText:t,userQuestion:r},m.textContent=r}else{let e=b;if(u&&u.length>0){let t=e.search(/\n\n\[(?:工作目录)?文件(?:内容)?:/);t!==-1&&(e=e.substring(0,t))}e=e.replace(/^\[网页上下文\]\n标题: .+\nURL: .+\ntabId: \d+\n/,``),e=e.replace(/\[知识库检索结果\][^\n]*\n[\s\S]*?\[\/知识库检索结果\]\n\n?/,``),e=hT(e),e=mT(e),e=e.replace(/\[工作目录文件: [^\]]+\]/g,``),m.textContent=e}if(y){let e=document.createElement(`div`);e.className=`user-message-images`,t.filter(e=>e.type===`image_url`).forEach((t,n)=>{let i=document.createElement(`img`),a=t.image_url.original_url||t.image_url.url;i.src=a,i.className=`user-message-image`,i.title=r(`chatMsg.clickToEnlarge`),i.addEventListener(`click`,()=>{rm(a,i)}),e.appendChild(i)}),m.appendChild(e)}if(u&&u.length>0){m.dataset.attachedFiles=JSON.stringify(u.map(e=>({name:e.name,size:e.size,type:e.type,text:e.text,status:e.status,agentPath:e.agentPath||``})));let e=document.createElement(`div`);e.className=`user-message-files`;let t=u.filter(e=>e.status===`done`),n=u.filter(e=>e.status!==`done`);[...t,...n].forEach(t=>{let n=document.createElement(`span`);n.className=`user-message-file-tag ${t.status}`,n.textContent=`${Lm(t.name)} ${t.name} (${Rm(t.size)})`,t.status===`extracting`?n.textContent+=r(`chatMsg.fileExtracting`):t.status===`error`&&(n.textContent+=r(`chatMsg.fileFailed`),n.title=t.error||r(`chatMsg.fileExtractFailed`)),e.appendChild(n)}),m.appendChild(e)}let o=document.createElement(`div`);o.className=`message-toolbar`;let s=document.createElement(`button`);s.className=`message-toolbar-btn copy-btn`,s.title=r(`chatMsg.copyMessageTitle`),s.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>`,`</svg>`].join(``),s.addEventListener(`click`,e=>{e.stopPropagation(),_S(m,s)});let c=document.createElement(`button`);c.className=`message-toolbar-btn edit-btn`,c.title=r(`chatMsg.editAndResend`),c.innerHTML=[`<svg viewBox="0 0 16 16" fill="currentColor">`,`<path d="M12.146.146a.5.5 0 0 1 .708 0l2.5 2.5a.5.5 0 0 1 0 .708l-10 10a.5.5 0 0 1-.168.11l-5 2a.5.5 0 0 1-.65-.65l2-5a.5.5 0 0 1 .11-.168l10-10zM11.207 2.5 13.5 4.793 14.793 3.5 12.5 1.207 11.207 2.5zm1.586 3L10.5 3.207 4 9.707V10h.5a.5.5 0 0 1 .5.5v.5h.5a.5.5 0 0 1 .5.5v.5h.293l6.5-6.5zm-9.761 5.175-.106.106-1.528 3.821 3.821-1.528.106-.106A.5.5 0 0 1 5 12h.5a.5.5 0 0 1 .5.5v.5a.5.5 0 0 1-.5.5h-.5a.5.5 0 0 1-.468-.325z"/>`,`</svg>`].join(``),c.addEventListener(`click`,e=>{e.stopPropagation(),PT(m)}),o.appendChild(s),o.appendChild(c);let l=document.createElement(`button`);if(l.className=`message-toolbar-btn delete-btn`,l.title=r(`chatMsg.deleteMessageTitle`),l.innerHTML=`
|
|
1841
1843
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1842
1844
|
<polyline points="3 6 5 6 21 6"></polyline>
|
|
1843
1845
|
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
|
|
1844
1846
|
</svg>
|
|
1845
|
-
`,l.addEventListener(`click`,e=>{e.stopPropagation(),
|
|
1847
|
+
`,l.addEventListener(`click`,e=>{e.stopPropagation(),AT(m)}),o.appendChild(l),m.appendChild(o),h){m.classList.add(`has-time`);let e=document.createElement(`time`);e.className=`message-time`,e.dateTime=h,e.textContent=Le(h),e.title=Be(h),m.appendChild(e)}}if(p.appendChild(m),m._pendingContext){let{type:e,contextText:t}=m._pendingContext,n=pT(e,t,!1);p.insertBefore(n,m),delete m._pendingContext}return n&&fC(p,{smooth:!0}),e===`assistant`&&it(),{element:m,messageId:g,timestamp:h}}function vT(e){let t=document.getElementById(`chatContainer`);t&&t.classList.toggle(`timestamps-hidden`,e===!1)}var yT=!1;function bT(){if(yT)return;let e=document.getElementById(`chatContainer`);e&&(e.addEventListener(`click`,e=>{let t=e.target.closest(`.execution-log-btn`);if(!t)return;let n=t.closest(`.message`);if(!n)return;e.preventDefault(),e.stopPropagation();let r=n.dataset.executionLog;if(r)try{let e=JSON.parse(r);i.debug(`[chat-manager] exec log buttonclick(delegate), entries:`,e.length),OS(e)}catch(e){i.error(`[chat-manager] parse executionLog failed:`,e)}}),yT=!0)}var xT=!1;function ST(){if(xT)return;let e=document.getElementById(`chatContainer`);e&&(e.addEventListener(`click`,e=>{let t=e.target.closest(`.reflection-score-btn`);if(!t)return;e.preventDefault(),e.stopPropagation();let n=t.dataset.reflectionData;if(n)try{DS(JSON.parse(n),t)}catch(e){i.error(`[chat-manager] parse reflectionData failed:`,e)}}),xT=!0)}function CT(){let e=document.getElementById(`chatContainer`),t=`loading-`+Date.now(),n=document.createElement(`div`);n.className=`loading-message`,n.id=t,n.innerHTML=`
|
|
1846
1848
|
<div class="loading-content">
|
|
1847
1849
|
<div class="loading-dots">
|
|
1848
1850
|
<span></span>
|
|
@@ -1866,7 +1868,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1866
1868
|
<span class="current-node-name">${r(`chatMsg.preparing`)}</span>
|
|
1867
1869
|
</div>
|
|
1868
1870
|
</div>
|
|
1869
|
-
`,e.appendChild(n),requestAnimationFrame(()=>{e.scrollTop=e.scrollHeight});let a=n.querySelector(`.stop-task-btn`),o=n.querySelector(`.loading-text`);a&&a.addEventListener(`click`,e=>{e.stopPropagation(),a.disabled=!0,a.style.opacity=`0.6`,a.style.cursor=`not-allowed`,o&&(o.textContent=r(`chatMsg.stopping`)),chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:null,sessionId:C.activeSessionId}),C.pendingCancelApi&&C.pendingCancelApi({message:r(`chatMsg.errTaskStopped`),executionLog:C.currentExecutionStatus?.executionLog||[]})});let s=C.activeSessionId;if(C.executionLogListener=(e,n,r)=>e.sessionId&&e.sessionId!==s?!1:e.type===`EXECUTION_STATUS_UPDATE`?(i.debug(`[SidePanel] recei to execution statusupdate:`,e.nodeName,e.status,`log count:`,e.executionLog?.length),
|
|
1871
|
+
`,e.appendChild(n),requestAnimationFrame(()=>{e.scrollTop=e.scrollHeight});let a=n.querySelector(`.stop-task-btn`),o=n.querySelector(`.loading-text`);a&&a.addEventListener(`click`,e=>{e.stopPropagation(),a.disabled=!0,a.style.opacity=`0.6`,a.style.cursor=`not-allowed`,o&&(o.textContent=r(`chatMsg.stopping`)),chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:null,sessionId:C.activeSessionId}),C.pendingCancelApi&&C.pendingCancelApi({message:r(`chatMsg.errTaskStopped`),executionLog:C.currentExecutionStatus?.executionLog||[]})});let s=C.activeSessionId;if(C.executionLogListener=(e,n,r)=>e.sessionId&&e.sessionId!==s?!1:e.type===`EXECUTION_STATUS_UPDATE`?(i.debug(`[SidePanel] recei to execution statusupdate:`,e.nodeName,e.status,`log count:`,e.executionLog?.length),Sp(t,e.nodeName,e.status,e.executionLog),!1):!1,chrome.runtime.onMessage.addListener(C.executionLogListener),C.chatConfig.enableExecutionLog){let e=n.querySelector(`.execution-status-container`);e&&(e.style.display=`flex`)}let c=n.querySelector(`.execution-log-toggle-btn`);return c&&c.addEventListener(`click`,e=>{e.stopPropagation(),bp(t)}),t}function wT(e){let t=document.getElementById(e);if(t){let e=t.querySelector(`.loading-text`);e&&(e.textContent=r(`chatMsg.thinking`)),t.remove()}C.executionLogListener&&=(chrome.runtime.onMessage.removeListener(C.executionLogListener),null),C.currentExecutionStatus=null;let n=document.querySelector(`.execution-log-panel.realtime-mode`);n&&n.remove()}function TT(e){if(!e)return;let t=pb((()=>{try{let t=e.dataset.executionLog;return t?JSON.parse(t):[]}catch{return[]}})()),n=[];try{n=JSON.parse(e.dataset.declaredArtifacts||`[]`)}catch{n=[]}let i=n.length?gb(t,n):t;if(Fb(i),$e(e,i.map(e=>e.path)).catch(()=>{}),i.length===0)return;let a=e.querySelector(`.artifacts-btn`);if(!a){let t=e.querySelector(`.footer-right-actions`);if(!t)return;a=document.createElement(`button`),a.className=`artifacts-btn`,a.type=`button`,a.title=r(`artifacts.btnTitle`,{count:i.length}),a.innerHTML=`
|
|
1870
1872
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1871
1873
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
1872
1874
|
<polyline points="14 2 14 8 20 8"/>
|
|
@@ -1874,15 +1876,15 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1874
1876
|
<line x1="9" y1="15" x2="15" y2="15"/>
|
|
1875
1877
|
</svg>
|
|
1876
1878
|
<span class="artifacts-btn-count">${i.length}</span>
|
|
1877
|
-
`;let n=t.querySelector(`.execution-log-btn`);n?t.insertBefore(a,n):t.prepend(a)}a._artifactsBound||(a.addEventListener(`click`,e=>{e.stopPropagation(),
|
|
1879
|
+
`;let n=t.querySelector(`.execution-log-btn`);n?t.insertBefore(a,n):t.prepend(a)}a._artifactsBound||(a.addEventListener(`click`,e=>{e.stopPropagation(),Ib(i,a)}),a._artifactsBound=!0,Pb(i,a))}function ET(e,t=null,n=!1){let a=document.getElementById(`chatContainer`);if(!a||!e)return;let o=document.createElement(`div`);o.innerHTML=e;let s=o.firstElementChild;if(!s)return;t&&(s.dataset.messageId=t),n&&MS(s,n),s.classList.remove(`streaming`);let c=s.querySelector(`.thinking-process-header`);c&&yC(c),s.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{t.ctrlKey||t.metaKey||e.closest(`.tool-call-item`).classList.toggle(`expanded`)})}),s.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`);if(!t)return;let n=t.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),s.querySelectorAll(`.tool-call-body > pre, .tool-result-content > pre, .agent-stream-output > pre`).forEach(e=>{if(e.parentElement.classList.contains(`code-block-container`))return;let t=document.createElement(`div`);t.className=`code-block-container`,t.style.position=`relative`,t.innerHTML=`<button class="code-copy-btn" title="${r(`chatMsg.copyCode`)}">
|
|
1878
1880
|
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
|
1879
1881
|
<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>
|
|
1880
1882
|
</svg>
|
|
1881
|
-
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),s.querySelectorAll(`.subtask-progress`).forEach(e=>{
|
|
1883
|
+
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),s.querySelectorAll(`.subtask-progress`).forEach(e=>{nT(e)}),s.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),OT(C.activeSessionId)})}),s.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:C.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})});let l=s.querySelector(`.message-footer`);if(l){let e=l.querySelector(`.copy-btn`);e&&e.addEventListener(`click`,t=>{t.stopPropagation(),vS(s,e,t)});let t=l.querySelector(`.quote-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),ES(s)});let n=l.querySelector(`.export-trigger-btn`),r=l.querySelector(`.export-dropdown`);n&&r&&(n.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==r&&e.classList.remove(`show`)}),r.classList.toggle(`show`)}),r.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToDocx:n}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(s,t,r)}),r.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToMarkdown:n}=await A(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(s,t,r)}),r.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToPdf:n}=await A(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(s,t,r)}),r.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let t=e.currentTarget,{exportAssistantMessageToImage:n}=await A(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));n(s,t,r)}));let a=l.querySelector(`.prototype-btn-small`);if(a){let e=(()=>{try{let e=s.dataset.executionLog;return e?JSON.parse(e):[]}catch{return[]}})().find(e=>e.nodeType===`tool_exec`&&e.action?.name===`preview_ui`||e.action?.name===`preview_preview_ui`&&e.status===`success`);e&&a.addEventListener(`click`,()=>{let t=e.prototypeId;if(!t&&e.observation)try{t=(typeof e.observation==`string`?JSON.parse(e.observation):e.observation)?.prototypeId}catch{}t?Wc(t):i.error(`[SidePanel] not found prototypeId,entry keys:`,Object.keys(e),`observation:`,e.observation)})}let o=l.querySelector(`.bookmark-btn`);o&&(vh(o,C.activeSessionId,s.dataset.messageId),o.addEventListener(`click`,async e=>{e.stopPropagation();let t=C.activeSessionId,n=s.dataset.messageId;if(o.classList.contains(`bookmarked`)){await oh(t,n),vh(o,t,n);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>uh);return{refreshBookmarkPanel:e}},void 0);e()}else{await ah(t,n,s.dataset.textContent_||``,C.sessions.find(e=>e.id===t)?.title||``),vh(o,t,n);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>uh);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=l.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),AT(s)});let u=l.querySelector(`.fork-btn`);u&&u.addEventListener(`click`,async e=>{e.stopPropagation();let t=s.dataset.messageId;t&&await _c(C.activeSessionId,t)});let d=l.querySelector(`.resume-task-btn`);d&&d.addEventListener(`click`,async e=>{if(e.stopPropagation(),d.disabled)return;let t=await kS({budgetEnded:gT(s)});t!==null&&(d.disabled=!0,d.style.opacity=`0.6`,d.style.cursor=`not-allowed`,PS(C.activeSessionId,t).finally(()=>{d.disabled=!1,d.style.opacity=``,d.style.cursor=``}))}),TT(s);let f=l.querySelector(`.token-usage-tag`);f&&!f._clickBound&&(f._clickBound=!0,f.style.cursor=`pointer`,f.addEventListener(`click`,e=>{e.stopPropagation();try{let e=s.dataset.executionLog,t=Ge(e?JSON.parse(e):[]);t&&Ye(t,f)}catch{}}))}let u=s.querySelector(`.message-toolbar`);if(u){let e=u.querySelector(`.edit-btn`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),PT(s)});let t=u.querySelector(`.copy-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),_S(s,t)});let n=u.querySelector(`.delete-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),AT(s)})}s.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{rm(e.src,e)})}),a.appendChild(s),ZO()}function DT(e){e.querySelectorAll(`.tool-call-body > pre, .tool-result-content > pre, .agent-stream-output > pre`).forEach(e=>{if(e.parentElement.classList.contains(`code-block-container`))return;let t=document.createElement(`div`);t.className=`code-block-container`,t.style.position=`relative`,t.innerHTML=`<button class="code-copy-btn" title="${r(`chatMsg.copyCode`)}">
|
|
1882
1884
|
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
|
1883
1885
|
<path d="M0 6.75C0 5.784.784 5 1.75 5h1.5a.75.75 0 0 1 0 1.5h-1.5a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-1.5a.75.75 0 0 1 1.5 0v1.5A1.75 1.75 0 0 1 9.25 16h-7.5A1.75 1.75 0 0 1 0 14.25zM5 1.75C5 .784 5.784 0 6.75 0h7.5C15.216 0 16 .784 16 1.75v7.5A1.75 1.75 0 0 1 14.25 11h-7.5A1.75 1.75 0 0 1 5 9.25zm1.75-.25a.25.25 0 0 0-.25.25v7.5c0 .138.112.25.25.25h7.5a.25.25 0 0 0 .25-.25v-7.5a.25.25 0 0 0-.25-.25z"/>
|
|
1884
1886
|
</svg>
|
|
1885
|
-
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),e.querySelectorAll(`.thinking-process-header`).forEach(e=>{
|
|
1887
|
+
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),e.querySelectorAll(`.thinking-process-header`).forEach(e=>{yC(e)}),e.querySelectorAll(`.tool-call-header`).forEach(e=>{e.addEventListener(`click`,t=>{if(t.ctrlKey||t.metaKey)return;let n=e.closest(`.tool-call-item`);n&&n.classList.toggle(`expanded`)})}),e.querySelectorAll(`.tool-call-result`).forEach(e=>{let t=e.querySelector(`code`);if(!t)return;let n=t.dataset.fullContent;if(!n||n.length<=500)return;let r=t.textContent||``,i=!1;e.style.cursor=`pointer`,e.addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||(e.stopPropagation(),i=!i,t.textContent=i?n:r)})}),e.querySelectorAll(`.subtask-progress`).forEach(e=>{nT(e)}),e.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),OT(C.activeSessionId)})}),e.querySelectorAll(`.tool-call-abort-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),chrome.runtime.sendMessage({type:`ABORT_CURRENT_TOOL`,sessionId:C.activeSessionId}),e.disabled=!0,e.title=r(`chatMsg.aborting`)})}),e.querySelectorAll(`.message-footer`).forEach(e=>{let t=e.closest(`.message`);if(!t)return;let n=e.querySelector(`.copy-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),vS(t,n,e)});let r=e.querySelector(`.quote-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),ES(t)});let i=e.querySelector(`.export-trigger-btn`),a=e.querySelector(`.export-dropdown`);i&&a&&(i.addEventListener(`click`,e=>{e.stopPropagation(),document.querySelectorAll(`.export-dropdown.show`).forEach(e=>{e!==a&&e.classList.remove(`show`)}),a.classList.toggle(`show`)}),a.querySelector(`.export-docx-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToDocx:r}=await A(async()=>{let{exportAssistantMessageToDocx:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));r(t,n,a)}),a.querySelector(`.export-md-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToMarkdown:r}=await A(async()=>{let{exportAssistantMessageToMarkdown:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));r(t,n,a)}),a.querySelector(`.export-pdf-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToPdf:r}=await A(async()=>{let{exportAssistantMessageToPdf:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));r(t,n,a)}),a.querySelector(`.export-image-item`)?.addEventListener(`click`,async e=>{e.stopPropagation();let n=e.currentTarget,{exportAssistantMessageToImage:r}=await A(async()=>{let{exportAssistantMessageToImage:e}=await import(`./chat-export-DcDe1GQ_.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,12,0]));r(t,n,a)}));let o=e.querySelector(`.prototype-btn-small`);if(o){let e=(()=>{try{let e=t.dataset.executionLog;return e?JSON.parse(e):[]}catch{return[]}})().find(e=>e.nodeType===`tool_exec`&&e.action?.name===`preview_ui`||e.action?.name===`preview_preview_ui`&&e.status===`success`);e&&o.addEventListener(`click`,()=>{let t=e.prototypeId;if(!t&&e.observation)try{t=(typeof e.observation==`string`?JSON.parse(e.observation):e.observation)?.prototypeId}catch{}t&&Wc(t)})}let s=e.querySelector(`.bookmark-btn`);s&&(vh(s,C.activeSessionId,t.dataset.messageId),s.addEventListener(`click`,async e=>{e.stopPropagation();let n=C.activeSessionId,r=t.dataset.messageId;if(s.classList.contains(`bookmarked`)){await oh(n,r),vh(s,n,r);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>uh);return{refreshBookmarkPanel:e}},void 0);e()}else{await ah(n,r,t.dataset.textContent_||``,C.sessions.find(e=>e.id===n)?.title||``),vh(s,n,r);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>uh);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=e.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),AT(t)});let l=e.querySelector(`.fork-btn`);l&&l.addEventListener(`click`,async e=>{e.stopPropagation();let n=t.dataset.messageId;n&&await _c(C.activeSessionId,n)});let u=e.querySelector(`.resume-task-btn`);u&&u.addEventListener(`click`,async e=>{if(e.stopPropagation(),u.disabled)return;let n=await kS({budgetEnded:gT(t)});n!==null&&(u.disabled=!0,u.style.opacity=`0.6`,u.style.cursor=`not-allowed`,PS(C.activeSessionId,n).finally(()=>{u.disabled=!1,u.style.opacity=``,u.style.cursor=``}))}),TT(t);let d=e.querySelector(`.token-usage-tag`);d&&!d._clickBound&&(d._clickBound=!0,d.style.cursor=`pointer`,d.addEventListener(`click`,e=>{e.stopPropagation();try{let e=t.dataset.executionLog,n=Ge(e?JSON.parse(e):[]);n&&Ye(n,d)}catch{}}))}),e.querySelectorAll(`.message-toolbar`).forEach(e=>{let t=e.closest(`.message`);if(!t)return;let n=e.querySelector(`.edit-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),PT(t)});let r=e.querySelector(`.copy-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),_S(t,r)});let i=e.querySelector(`.delete-btn`);i&&i.addEventListener(`click`,e=>{e.stopPropagation(),AT(t)})}),e.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{rm(e.src,e)})}),e.querySelectorAll(`.mermaid-controls`).forEach(e=>e.remove()),Qe(),bT(),ST(),ZO()}function OT(e){return new Promise(t=>{let n=document.querySelector(`.command-terminate-overlay`);n&&n.remove();let i=document.createElement(`div`);i.className=`command-terminate-overlay`,i.innerHTML=`
|
|
1886
1888
|
<div class="command-terminate-modal">
|
|
1887
1889
|
<div class="command-terminate-header">
|
|
1888
1890
|
<div class="command-terminate-icon">⏹</div>
|
|
@@ -1911,7 +1913,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1911
1913
|
<button class="command-terminate-cancel">${r(`common.cancel`)}</button>
|
|
1912
1914
|
</div>
|
|
1913
1915
|
</div>
|
|
1914
|
-
`,document.body.appendChild(i);let a=()=>{i.remove()};i.querySelector(`.command-terminate-cancel`).addEventListener(`click`,()=>{a(),t(null)}),i.querySelector(`.wait-btn`).addEventListener(`click`,()=>{a(),chrome.runtime.sendMessage({type:`TERMINATE_COMMAND`,sessionId:e,mode:`wait`}),t(`wait`)}),i.querySelector(`.kill-btn`).addEventListener(`click`,()=>{a(),chrome.runtime.sendMessage({type:`TERMINATE_COMMAND`,sessionId:e,mode:`kill`}),t(`kill`)})})}function
|
|
1916
|
+
`,document.body.appendChild(i);let a=()=>{i.remove()};i.querySelector(`.command-terminate-cancel`).addEventListener(`click`,()=>{a(),t(null)}),i.querySelector(`.wait-btn`).addEventListener(`click`,()=>{a(),chrome.runtime.sendMessage({type:`TERMINATE_COMMAND`,sessionId:e,mode:`wait`}),t(`wait`)}),i.querySelector(`.kill-btn`).addEventListener(`click`,()=>{a(),chrome.runtime.sendMessage({type:`TERMINATE_COMMAND`,sessionId:e,mode:`kill`}),t(`kill`)})})}function kT(e){return new Promise(t=>{let n=document.querySelector(`.delete-confirm-overlay`);n&&n.remove();let i=document.createElement(`div`);i.className=`delete-confirm-overlay`;let a=e.length>50?e.substring(0,50)+`...`:e;i.innerHTML=`
|
|
1915
1917
|
<div class="delete-confirm-modal">
|
|
1916
1918
|
<div class="delete-confirm-header">
|
|
1917
1919
|
<div class="delete-confirm-icon">🗑️</div>
|
|
@@ -1926,7 +1928,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1926
1928
|
<button class="delete-confirm-confirm">${r(`chatMsg.confirmDelete`)}</button>
|
|
1927
1929
|
</div>
|
|
1928
1930
|
</div>
|
|
1929
|
-
`,document.body.appendChild(i);let o=i.querySelector(`.delete-confirm-cancel`),s=i.querySelector(`.delete-confirm-confirm`);o.addEventListener(`click`,()=>{i.remove(),t(!1)}),s.addEventListener(`click`,()=>{i.remove(),t(!0)}),i.addEventListener(`click`,e=>{e.target})})}async function
|
|
1931
|
+
`,document.body.appendChild(i);let o=i.querySelector(`.delete-confirm-cancel`),s=i.querySelector(`.delete-confirm-confirm`);o.addEventListener(`click`,()=>{i.remove(),t(!1)}),s.addEventListener(`click`,()=>{i.remove(),t(!0)}),i.addEventListener(`click`,e=>{e.target})})}async function AT(e,t=!1){let n=e.dataset.messageId,a=e.classList.contains(`user`)?`user`:`assistant`,o=``;if(o=a===`user`?e.textContent.trim():e.dataset.textContent_||``,!t&&!await kT(o))return;if(n){let e=C.messageHistory.findIndex(e=>e.messageId===n);e!==-1&&C.messageHistory.splice(e,1)}else{let t=e.dataset.timestamp,n=C.messageHistory.findIndex(e=>e.timestamp===t);n!==-1&&C.messageHistory.splice(n,1)}let s=e.previousElementSibling;s&&s.classList.contains(`user-context-bubble`)&&s.remove(),e.remove();let c=document.getElementById(`chatContainer`);c.querySelectorAll(`.message`).length===0&&(c.innerHTML=`
|
|
1930
1932
|
<div class="welcome-message">
|
|
1931
1933
|
<div class="icon-wrapper">
|
|
1932
1934
|
<div class="icon">💬</div>
|
|
@@ -1934,7 +1936,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1934
1936
|
<h2>${r(`chat.welcomeTitle`)}</h2>
|
|
1935
1937
|
<p>${r(`chat.welcomeSubtitle`)}</p>
|
|
1936
1938
|
</div>
|
|
1937
|
-
`),await
|
|
1939
|
+
`),await zw(),n&&C.activeSessionId&&y(C.activeSessionId,n).then(e=>{e||i.warn(`[SidePanel] IndexedDB messagecleanup failed, messageId:`,n)}).catch(e=>{i.error(`[SidePanel] IndexedDB messagecleanup exception:`,e)}),i.debug(`[SidePanel] deletedmessage: ${a}, messageId: ${n}`)}async function jT(e=null){try{let{mcpTools:t}=await chrome.storage.local.get([`mcpTools`]),n=t||[],r=new Set(Array.isArray(C.mcpClosedServers)?C.mcpClosedServers:[]),i=new Set(Array.isArray(C.activeAgentMcpExcludedServerIds)?C.activeAgentMcpExcludedServerIds:[]),a=new Set(Array.isArray(e)?e:[]);return n.filter(e=>{let t=e.serverId||`unknown`;return a.has(t)?!0:!r.has(t)&&!i.has(t)}).length}catch{return 0}}var MT=new Set([`STREAM_START`,`STREAM_CHUNK`,`STREAM_TOOL_CALL`,`STREAM_TOOL_RESULT`,`STREAM_DONE`,`AGENT_STREAM`,`AGENT_STREAM_DONE`,`API_RETRYING`,`API_COMPLETE`,`API_ERROR`]);async function NT(e,t,n=!1,a={},o={}){let{resumeFromCheckpoint:s=!1,userGuidance:c=``,loadingId:l=null,forcedMcpServerIds:u=null,sessionId:d=null,agent:f=null}=o,p=f?f.agentId:C.activeAgentId,m=f?f.agentToolIds:C.activeAgentToolIds,h=f?f.agentSkillIds:C.activeAgentSkillIds,g=f?f.agentMcpExcludedServerIds:C.activeAgentMcpExcludedServerIds,_=await ze(),v=(_.toolTimeout||0)+3*(_.apiTimeout||0)+6e4,y=_.loopTimeout+v,b=await new Promise(e=>{chrome.storage.local.get(`reflectionConfig`,t=>{e(t.reflectionConfig||{enabled:!1})})}),x=d||C.activeSessionId,S=s?`resume_${Date.now()}_${Math.random().toString(36).substring(2,8)}`:`call_${Date.now()}_${Math.random().toString(36).substring(2,8)}`;if(i.debug(`[SidePanel] callApi: generating callId: ${S}${s?` (restoremode)`:``}`),s&&l&&(a={...a,_loadingId:l}),C.pendingCancelApiMap&&C.pendingCancelApiMap.has(x)){i.debug(`[SidePanel] callApi: detectedsession has ongoing API call with , first cancelold`);let e=C.pendingCancelApiMap.get(x);e&&e({message:r(`chatMsg.errTaskReplaced`),executionLog:[]})}C.pendingCallApiSessionIds&&C.pendingCallApiSessionIds.has(x)&&(C.pendingCallApiSessionIds.delete(x),Dw());let w=OC(x),T=null,E=[],D=chrome.runtime.connect({name:`keepalive-`+x});i.debug(`[SidePanel] keepalive portconnected, sessionId:`,x),Cl(x);try{let e=Sl();D.postMessage({type:`KEEPALIVE_IDENTITY`,identity:e==null?null:{windowId:e}})}catch{}let O={restarted:!1,rejectFn:null,cleanup:null,checkpoint:null};D.onMessage.addListener(e=>{if(e&&MT.has(e.type)){T?T(e):E.length<200&&E.push(e);return}if(e.type===`HOST_TAB_RESOLVED`&&e.sessionId===x){wl(x,e.hostTabId);return}e.type===`SW_RESTARTED`&&e.sessionId===x&&(i.warn(`[SidePanel] ⚠️ recei to SW_RESTARTED notification,background re started,API call lost`),O.restarted=!0,O.checkpoint=e.checkpoint||null,O.rejectFn&&O.cleanup&&(O.cleanup(),O.rejectFn({message:r(`chatMsg.errSwRestarted`),executionLog:[],checkpoint:O.checkpoint,swRestarted:!0}))),e.type===`SHOW_CLARIFY_DIALOG`?oo(e.data):e.type===`CLARIFY_TIMEOUT`?po(e):e.type===`CLARIFY_EXTENDED`?Xa(e):e.type===`SHOW_CONFIRM_DIALOG`?Ao(e.data):e.type===`DISMISS_CONFIRM_DIALOG`&&No(e.data)});let k={timeoutId:null,removeListener:()=>{}},A=()=>{T=null,E.length=0;try{D.disconnect()}catch{}k.timeoutId&&=(clearTimeout(k.timeoutId),null),k.removeListener(),C.pendingCancelApiMap.delete(x),C.pendingCallApiSessionIds.delete(x),kC(x),Dw()};return new Promise((o,l)=>{if(O.cleanup=A,O.rejectFn=l,O.restarted){A(),l({message:r(`chatMsg.errSwRestarted`),executionLog:[],checkpoint:O.checkpoint,swRestarted:!0});return}let d=[],f=Math.round(_.loopTimeout/1e3);w(null),NC(null),LC(0);let v=``,D=new Map,j=e=>{w()&&(iw(w(),v),ww(w())),A(),(!e.executionLog||e.executionLog.length===0||d.length>0)&&(e.executionLog=d),l(e)};C.pendingCancelApiMap.set(x,j),C.pendingCallApiSessionIds.add(x),Dw(),i.debug(`[SidePanel] callApi: add pendingCallApiSessionIds, mySessionId =`,x,`, set:`,[...C.pendingCallApiSessionIds]),k.timeoutId=setTimeout(()=>{j({message:r(`chatMsg.errTimeout`,{seconds:f}),executionLog:d}),chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:C.currentTabId,sessionId:x}).catch(e=>{i.debug(`[SidePanel] sendcancelrequest failed:`,e.message)})},y);let M=Date.now(),N=0,ee=null,te=()=>{ee===null&&k.timeoutId!==null&&(ee=Date.now(),clearTimeout(k.timeoutId),k.timeoutId=null,i.debug(`[SidePanel] before sidetimeoutpaused (waitinguser response:clarification/sensitive toolconfirm)`))},ne=()=>{if(ee!==null){let e=Date.now()-ee;N+=e,ee=null;let t=Date.now()-M,n=y+N-t;if(n<=0){j({message:r(`chatMsg.errTimeout`,{seconds:f}),executionLog:d});return}k.timeoutId=setTimeout(()=>{j({message:r(`chatMsg.errTimeout`,{seconds:f}),executionLog:d}),chrome.runtime.sendMessage({type:`CANCEL_REACT`,tabId:C.currentTabId,sessionId:x}).catch(e=>{i.debug(`[SidePanel] sendcancelrequest failed:`,e.message)})},n),i.debug(`[SidePanel] before sidetimeoutrestored,pause duration:`,Math.round(e/1e3),`s,remaining time:`,Math.round(n/1e3),`s`)}},re=e=>{if(e.sessionId&&e.sessionId!==x||e.callId&&e.callId!==S)return!1;if(e.type===`EXECUTION_STATUS_UPDATE`){let t=e.executionLog||[];if(t.length>0&&t.forEach(e=>{let t=d.findIndex(t=>t.id===e.id);t===-1?d.push(e):d[t]=xp(d[t],e)}),e.subtaskTotal&&e.subtaskTotal>0){let t=w();if(t){let n=t.querySelector(`.stream-content`);if(n){let t=e.subtaskIndex??0,i=eT(d),a=i&&i.logIndex>0?d.slice(i.logIndex):d;if(i){let e=String(i.timestamp||i.logIndex);n.dataset.planStamp!==e&&(n.dataset.planStamp=e,n.querySelectorAll(`.subtask-progress`).forEach(e=>e.remove()))}i&&[...i.items].sort((e,t)=>e.index-t.index).forEach(r=>{if(r.index===t)return;let a=`.subtask-progress[data-subtask-index="${r.index}"]`;if(n.querySelector(a))return;let o=document.createElement(`div`);o.className=`subtask-progress subtask-progress-pending`,o.dataset.subtaskIndex=r.index,o.innerHTML=tT(r,i.total||e.subtaskTotal),rT(n,o),nT(o)});let o=`.subtask-progress[data-subtask-index="${t}"]`,s=n.querySelector(o),c=s?s.classList.contains(`subtask-expanded`):!1;s||(s=document.createElement(`div`),s.className=`subtask-progress`,s.dataset.subtaskIndex=t,rT(n,s));let l=Qw,u=t+1,f=e.subtaskTotal,p=e.subtaskName||``,m=`<span class="subtask-badge">${u}/${f}</span>`,h=$w,g=e.status!==`success`&&e.status!==`failed`,_=a.filter(e=>e.subtaskIndex===t&&e.nodeType!==`subtask`),v=qw(_),y=v.total,b=v.success,x=v.failed,S=v.other,C=_.find(e=>e.status===`processing`),w=Kw(e.status,b,y),T=i?i.items.find(e=>e.index===t):null,E=T&&T.description?String(T.description).replace(/\s+/g,` `).trim():``,D=a.find(e=>e.subtaskIndex===t&&e.nodeType===`subtask`),O=Yw(a,t)?`<span class="subtask-replay-skipped" title="${P(r(`chatMsg.subtaskReplaySkippedHint`))}">${r(`chatMsg.subtaskReplaySkipped`)}</span>`:``;s.classList.remove(`subtask-progress-pending`);let k=``;e.status===`success`?(k=`<span class="subtask-status-done">${r(`chatMsg.subtaskDone`)}</span>`,s.classList.add(`subtask-progress-done`),s.classList.remove(`subtask-progress-active`),s.dataset.terminal=`1`):w===`partial`?(k=`<span class="subtask-status-partial">${r(`chatMsg.subtaskPartial`)}</span>`,s.classList.add(`subtask-progress-failed`),s.classList.remove(`subtask-progress-active`),s.dataset.terminal=`1`):e.status===`failed`?(k=`<span class="subtask-status-failed">${r(`chatMsg.subtaskFailed`)}</span>`,s.classList.add(`subtask-progress-failed`),s.classList.remove(`subtask-progress-active`),s.dataset.terminal=`1`):(k=`<span class="subtask-status-label"><span class="subtask-spinner"></span>${r(`chatMsg.subtaskExecuting`)}</span>`,s.classList.add(`subtask-progress-active`),delete s.dataset.terminal);let A=``;if(g&&y>0){let e=C?C.nodeType===`tool_exec`?`🔧`:C.nodeType===`api_call`?`📡`:C.nodeType===`reflection`?`🎯`:C.nodeType===`preselect`?`🔍`:`○`:`○`,t=Jw(C),n=C?ap(C):``;A=`<div class="subtask-progress-line">
|
|
1938
1940
|
<span class="subtask-current-node"><span class="subtask-current-spinner"></span><span class="node-label">${e} ${t}</span>${n?` <span class="subtask-current-cmd" title="${P(n)}">${L(n)}</span>`:``}</span>
|
|
1939
1941
|
<span class="subtask-node-stats">
|
|
1940
1942
|
<span class="subtask-stat-total">${y}</span>
|
|
@@ -1962,12 +1964,12 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1962
1964
|
</div>
|
|
1963
1965
|
${A}
|
|
1964
1966
|
<div class="subtask-detail-body"></div>
|
|
1965
|
-
`,c&&s.classList.add(`subtask-expanded`);let j=s.querySelector(`.subtask-detail-body`);s._renderNodes=()=>{if(!j)return;let e=[];E&&e.push(`<div class="subtask-detail-desc"><span class="subtask-detail-label">${r(`chatMsg.subtaskDescLabel`)}</span>${L(E)}</div>`);let n=D&&D.result?String(D.result).trim():``;n&&e.push(`<div class="subtask-detail-result"><span class="subtask-detail-label">${r(`chatMsg.subtaskResultLabel`)}</span>${L(n)}</div>`);let i=a.filter(e=>e.subtaskIndex===t&&e.nodeType!==`subtask`),o=
|
|
1967
|
+
`,c&&s.classList.add(`subtask-expanded`);let j=s.querySelector(`.subtask-detail-body`);s._renderNodes=()=>{if(!j)return;let e=[];E&&e.push(`<div class="subtask-detail-desc"><span class="subtask-detail-label">${r(`chatMsg.subtaskDescLabel`)}</span>${L(E)}</div>`);let n=D&&D.result?String(D.result).trim():``;n&&e.push(`<div class="subtask-detail-result"><span class="subtask-detail-label">${r(`chatMsg.subtaskResultLabel`)}</span>${L(n)}</div>`);let i=a.filter(e=>e.subtaskIndex===t&&e.nodeType!==`subtask`),o=Zw(i,s._nodeFilter),c=``;i.length>0&&o.length===0?c=`<div class="subtask-node-empty">${L(r(`chatMsg.subtaskFilterEmpty`))}</div>`:o.length>0&&(c=o.map(e=>{let t=e.nodeType===`tool_exec`?`🔧`:e.nodeType===`api_call`?`📡`:e.nodeType===`reflection`?`🎯`:e.nodeType===`preselect`?`🔍`:`○`,n=e.status===`success`?`✓`:e.status===`failed`?`✗`:g?`<span class="subtask-node-spinner"></span>`:`○`,i=e.status===`success`?`done`:e.status===`failed`?`failed`:`processing`,a=e.duration?Ve(e.duration):``,o=L(e.nodeName||r(`chatMsg.unknownNode`)),s=``;if(e.nodeType===`tool_exec`){let t=ap(e);t&&(s=`<span class="subtask-node-cmd" title="${P(t)}">${L(t)}</span>`)}return`<div class="subtask-node ${i}">
|
|
1966
1968
|
<span class="subtask-node-icon">${t}</span>
|
|
1967
1969
|
<span class="subtask-node-status">${n}</span>
|
|
1968
1970
|
<span class="subtask-node-name">${o}${s}</span>
|
|
1969
1971
|
${a?`<span class="subtask-node-dur">${a}</span>`:``}
|
|
1970
|
-
</div>`}).join(``)),j.innerHTML=e.join(``)+c},s._renderNodes(),
|
|
1972
|
+
</div>`}).join(``)),j.innerHTML=e.join(``)+c},s._renderNodes(),nT(s),e.status===`success`&&u>=f&&n.querySelectorAll(`.subtask-progress`).forEach(e=>e.classList.add(`subtask-progress-all-done`)),aT(n,a,t,i)}}}return!1}if(e.type===`CLARIFY_START`)return te(),!1;if(e.type===`CLARIFY_END`)return ne(),!1;if(e.type===`TOOL_CONFIRM_START`)return te(),!1;if(e.type===`TOOL_CONFIRM_END`)return ne(),!1;if(e.type===`STREAM_PRESELECT`){if(i.debug(`[SidePanel] received pre-filterlog,:`,e.preselectLog?.length),NC(e.preselectLog||null),w()&&MC()&&MC().length>0){let e=w().querySelector(`.message-content`);e&&(MC().forEach(t=>{let n=xw(t);e.insertBefore(n,e.firstChild)}),NC(null),i.debug(`[SidePanel] pre-filtercard imageappended to existingstreamingelement`))}return!1}if(e.type===`API_RETRYING`){let t=w();if(t)GC(t,e.attempt,e.maxRetries);else{let t=document.querySelector(`.loading-message .loading-text`);t&&(t.textContent=r(`chatStream.retrying`,{attempt:e.attempt,max:e.maxRetries}))}return!1}if(e.type===`STREAM_START`){i.debug(`[SidePanel] streamingoutput start`);let e=a._loadingId,t=e?document.getElementById(e):document.querySelector(`.loading-message`);if(t&&t.remove(),C.executionLogListener&&=(chrome.runtime.onMessage.removeListener(C.executionLogListener),null),C.currentExecutionStatus=null,w()){let e=w().querySelector(`.stream-content`);if(e){let t=e.querySelector(`.thinking-indicator:not(.hidden)`);if(t&&i.warn(`[STREAM_START] has can seen thinking indicator,skipcreate:`,t),!t){let t=document.createElement(`div`);t.className=`thinking-indicator`,t.innerHTML=`
|
|
1971
1973
|
<svg class="thinking-icon pulse-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1972
1974
|
<path d="M12 2a3 3 0 0 0-3 3v1a3 3 0 0 0 3 3 3 3 0 0 1 3 3v1a3 3 0 0 1-3 3 3 3 0 0 0-3 3v1a3 3 0 0 0 3 3"/>
|
|
1973
1975
|
<circle cx="8" cy="12" r="1.5"/>
|
|
@@ -1980,16 +1982,16 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
1980
1982
|
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
|
|
1981
1983
|
</svg>
|
|
1982
1984
|
</button>
|
|
1983
|
-
`;let n=t.querySelector(`.streaming-stop-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),
|
|
1985
|
+
`;let n=t.querySelector(`.streaming-stop-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),Cw(n)}),e.appendChild(t)}}}else if(w(HC(x)),LC(Date.now()),MC()&&MC().length>0){let e=w().querySelector(`.message-content`);MC().forEach(t=>{let n=xw(t);e.insertBefore(n,e.firstChild)}),NC(null)}return w().dataset.callId=S,v=``,jC(x,``),FC(Date.now()),zC(``),mC(w()),!1}if(e.type===`STREAM_CHUNK`)return w()&&(v+=e.delta,jC(x,v),w().isConnected&&aw(w(),v)),!1;if(e.type===`STREAM_TOOL_CALL`)return w()||(w(HC(x)),LC(Date.now())),w()&&e.toolCalls?.length>0&&(iw(w(),e.thinkingContent||v),ow(w(),e.toolCalls)),!1;if(e.type===`STREAM_TOOL_RESULT`)return w()&&e.result&&bw(e.result,w()),!1;if(e.type===`AGENT_STREAM`){if(w()&&e.execId){let t=w();uw(t,D),vw(D,t,e)}return!1}if(e.type===`AGENT_STREAM_DONE`){if(e.execId){let t=D.get(e.execId);t&&t.element&&e.exitCode!==0&&t.element.classList.add(`agent-stream-error`)}return!1}if(e.type===`STREAM_DONE`){if(w()){let e=w().querySelector(`.stream-status`);e&&(b?.enabled?e.textContent=r(`chatMsg.reflectionInProgress`):e.textContent=``)}return!1}if(e.type===`API_COMPLETE`){let t=e.content&&String(e.content).trim()?e.content:r(`chatMsg.emptyModelReply`);w()&&Sw(w(),t,e.executionLog||[],e.reflectionScore,e.reasoningContent,e.wasRevised);let n=w(),i=!!n,a=n?n.dataset.htmlContent||n.outerHTML:null,s=n?n.isConnected:!1,c=n?n.dataset.messageId:null;return A(),console.log(`[callApi API_COMPLETE] wasStreamed:`,i,`| message.executionLog entries:`,e.executionLog?.length||0,`| local executionLog entries:`,d.length,`| agent_file entries:`,(e.executionLog||d)?.filter(e=>e.nodeType===`tool_exec`&&e.action?.name===`agent_file`).length||0),o({content:t,executionLog:e.executionLog||d,reflectionScore:e.reflectionScore,wasStreamed:i,wasRevised:e.wasRevised,streamingHtml:a,streamingConnected:s,streamingMsgId:c,budgetEnded:e.budgetEnded===!0}),!1}else if(e.type===`API_ERROR`){let t=w();return t&&t.isConnected&&t.remove(),A(),l({message:e.error,executionLog:e.executionLog||d}),!1}return!1};for(chrome.runtime.onMessage.addListener(re),T=e=>re(e);E.length>0;)T(E.shift());if(k.removeListener=()=>{chrome.runtime.onMessage.removeListener(re)},s)i.debug(`[SidePanel] send RESUME_REACT message,sessionId:`,x,`userGuidance:`,c?`"${c.substring(0,50)}..."`:`( no )`,`timeout:`,y),chrome.runtime.sendMessage({type:`RESUME_REACT`,sessionId:x,callId:S,userGuidance:c||``});else{let r=e.some(e=>Array.isArray(e.content)&&e.content.some(e=>e&&e.type===`image_url`));i.debug(`[SidePanel] send CALL_API message,useTools:`,n,`tabId:`,C.currentTabId,`sessionId:`,x,`apiParams:`,a,`timeout:`,y),chrome.runtime.sendMessage({type:`CALL_API`,sessionId:x,messages:e,model:t,useTools:n,tabId:C.currentTabId,apiParams:a,agentId:p,agentToolIds:m,agentSkillIds:h,forcedMcpServerIds:Array.isArray(u)&&u.length>0?u:null,agentMcpExcludedServerIds:g??null,callId:S,imageApiBase:C.enableImageInput&&r&&C.imageApiBase||``,imageApiKey:C.enableImageInput&&r&&C.imageApiKey||``})}})}function PT(e){try{let t=e.dataset.rawContent||``,n=e.dataset.textContent_||``;if(!n&&!t){F(r(`chatMsg.cannotGetMessageContent`),`error`);return}let a=[];if(t.startsWith(`[`))try{let e=JSON.parse(t);if(Array.isArray(e)){let t=e.filter(e=>e.type===`image_url`);for(let e of t){let t=e.image_url.original_url||e.image_url.url;a.push({originalUrl:t,compressedUrl:e.image_url.url,width:e.image_url.width,height:e.image_url.height})}}}catch{}a.length>0&&(C.attachedImages=a,fm());let o=[];if(e.dataset.attachedFiles)try{let t=JSON.parse(e.dataset.attachedFiles);for(let e of t)o.push({name:e.name,size:e.size,type:e.type,text:e.text||``,status:e.status||`done`,agentPath:e.agentPath||``})}catch{}o.length>0&&(C.attachedFiles=o,A(()=>Promise.resolve().then(()=>Pm).then(e=>{e.renderFilePreviews()}),void 0));let s=n.match(/^\[网页上下文\]\n标题: (.+)\nURL: (.+)\ntabId: (\d+)\n/);if(s){Mx(),C.selectedPage={id:parseInt(s[3]),title:s[1],url:s[2],favIconUrl:``};let e=document.getElementById(`pageIndicator`),t=document.getElementById(`pageIndicatorName`);if(e&&t){let n=s[1],r=s[2];n&&n!==`无标题`&&r?t.textContent=`${n} · ${r}`:t.textContent=n||r,e.style.display=`flex`}}let c=n.match(/\[知识库检索结果\](引用: ([^)]+))/);if(c){let e=c[1].split(`、`).map(e=>e.trim()).filter(Boolean);e.length>0&&(_x(),C.knowledgeRefs=e.map(e=>({id:``,name:e})),vx(),Sx().then(e=>{if(e&&e.ok){let t=new Map((e.collections||[]).map(e=>[e.name,e]));C.knowledgeRefs=C.knowledgeRefs.map(e=>{if(e.id)return e;let n=t.get(e.name);return{id:n?.id||``,name:e.name,enabled:n?n.enabled!==!1:!0}}),vx()}}).catch(()=>{}))}let l=Array.from(new Set([...n.matchAll(/\[(?:已选技能|Selected skill):\s*([^\n\]]+)\]/g)].map(e=>e[1].split(` - `)[0].trim()).filter(Boolean)));l.length>0&&(_E(),C.selectedSkills=l.map(e=>({name:e,description:``,type:`agent`})),vE());let u=Array.from(new Set([...n.matchAll(/\[(?:已选MCP服务|Selected MCP service):\s*([^\n\]]+)\]/g)].map(e=>e[1].split(` - `)[0].trim()).filter(Boolean)));u.length>0&&(jE(),C.selectedMcpServices=u.map(e=>({serverId:``,serverName:e,toolCount:0})),NE(),chrome.storage.local.get([`mcpTools`],e=>{let t=e.mcpTools||[];u.forEach(e=>{let n=C.selectedMcpServices.find(t=>t.serverName===e);if(!n||n.serverId)return;let r=t.find(t=>(t.serverName||``)===e)||t.find(t=>(t.serverName||``).startsWith(e));r&&(n.serverId=r.serverId||``,n.toolCount=t.filter(e=>e.serverId===r.serverId).length)}),NE()}));let d=n;s&&(d=d.replace(/^\[网页上下文\]\n标题: .+\nURL: .+\ntabId: \d+\n/,``)),c&&(d=d.replace(/\[知识库检索结果\][^\n]*\n[\s\S]*?\[\/知识库检索结果\]\n\n?/,``)),u.length>0&&(d=hT(d)),l.length>0&&(d=mT(d));let f=C.quotedContextText,p=C.selectedContextText;C.quotedContextText=``,C.selectedContextText=``;let m=d.match(/^\[引用内容(?:摘要)?\]\n([\s\S]+?)\n\n\[用户问题\]\n([\s\S]*)$/),h=d.match(/^\[选中内容(?:摘要)?\]\n([\s\S]+?)\n\n\[用户问题\]\n([\s\S]*)$/),g=m||h,_=d;if(g){let e=m?`quoted`:`selected`,t=g[1].trim(),n=g[2].trim();if(o.length>0){let e=n.search(/\n\n\[(?:工作目录)?文件(?:内容)?:/);e!==-1&&(n=n.substring(0,e).trim())}let i=document.getElementById(`selectionIndicator`),a=document.getElementById(`selectionText`);if(i&&a){let n;n=t.length>100?t.substring(0,100)+`...`:t.length>50?t.substring(0,50)+`...`:t,e===`quoted`?(C.quotedContextText=t,C.selectedContextText=p,a.textContent=r(`chatMsg.quotedContextLabel`,{text:n})):(C.selectedContextText=t,C.quotedContextText=f,a.textContent=r(`chatMsg.selectedContextLabel`,{text:n})),i.classList.add(`show`)}_=n}else if(C.quotedContextText=f,C.selectedContextText=p,o.length>0){let e=_.search(/\n\n\[(?:工作目录)?文件(?:内容)?:/);e!==-1&&(_=_.substring(0,e).trim())}let v=document.getElementById(`userInput`);v.value=_,ut(),v.focus(),v.selectionStart=v.selectionEnd=v.value.length,i.debug(`[SidePanel] loadedmessagecontent to input box,waitingafter user editsend`)}catch(e){i.error(`[SidePanel] editmessage failed:`,e),F(r(`chatMsg.editFailed`,{message:e.message}),`error`)}}n(`zh`,{promptMgr:{promptsTabCount:`提示词 ({count})`,skillsTabCount:`技能 ({count})`,mcpTabCount:`MCP ({count})`,noMatchPrompt:`暂无匹配的提示词`,mergedHeaderHint:`方向键切换 · Enter发送/选中并关闭 · Ctrl+Enter带入/多选反选 · Esc取消`,noMatchResult:`暂无匹配结果`,requestFailed:`❌ 请求失败:{message}`,emptyPromptHint:`暂无提示词,请添加`,menuEnableTooltip:`加入右键菜单`,menuDisableTooltip:`移出右键菜单`,codeAndContentRequired:`请填写编码和内容`,codeExists:`编码已存在`,saveChanges:`保存修改`,confirmDeletePrompt:`确定要删除提示词 "/{code}" 吗?`}}),n(`en`,{promptMgr:{promptsTabCount:`Prompts ({count})`,skillsTabCount:`Skills ({count})`,mcpTabCount:`MCP ({count})`,noMatchPrompt:`No matching prompts`,mergedHeaderHint:`Arrow keys to switch · Enter to send / select & close · Ctrl+Enter to insert / multi-select · Esc to cancel`,noMatchResult:`No matching results`,requestFailed:`❌ Request failed: {message}`,emptyPromptHint:`No prompts yet, please add one`,menuEnableTooltip:`Add to right-click menu`,menuDisableTooltip:`Remove from right-click menu`,codeAndContentRequired:`Please fill in both code and content`,codeExists:`Code already exists`,saveChanges:`Save changes`,confirmDeletePrompt:`Are you sure you want to delete prompt "/{code}"?`}});var FT=`<svg viewBox="0 0 1024 1024" width="12" height="12" fill="currentColor"><path d="M674.56 231.552l101.568 56.96-56.896-101.632 56.96-101.568-101.632 56.896-101.632-56.896 56.96 101.568-56.896 101.632 101.568-56.96zM186.944 629.76l-101.504-56.896 56.832 101.632-56.832 101.568 101.504-56.96 101.632 56.96-56.896-101.568 56.896-101.568-101.568 56.832zM85.44 85.312l56.832 101.568-56.832 101.632 101.504-56.96 101.632 56.96L231.68 186.88l56.896-101.568-101.568 56.896-101.568-56.896z m351.872 438.016l-99.2-99.136L424.32 337.984l99.072 99.264-86.08 86.144m-41.856-223.04L300.352 395.392a40.448 40.448 0 0 0 0 57.28l474.24 474.112a40.448 40.448 0 0 0 57.344 0l94.912-95.04a40.448 40.448 0 0 0 0-57.344L452.736 300.288a40.448 40.448 0 0 0-57.28 0z"/></svg>`;function IT(){i.debug(`[SidePanel] clear selectedcontenttext `),C.selectedContextText=``,C.quotedContextText=``;let e=document.getElementById(`selectionIndicator`),t=document.getElementById(`userInput`);if(e&&(e.classList.remove(`show`),i.debug(`[SidePanel] hiddenselected contentprompt`)),typeof window.hideFloatingMenu==`function`&&window.hideFloatingMenu(),t&&t.value.startsWith(`[选中内容]`)){let e=t.value.split(`
|
|
1984
1986
|
`),n=0;for(let t=0;t<e.length;t++)if(e[t].startsWith(`[用户问题]`)){n=t;break}n>0&&(t.value=e.slice(n).join(`
|
|
1985
|
-
`),t.dispatchEvent(new Event(`input`)),i.debug(`[SidePanel] removedinput box selected content before suffix`))}C.lastSelectedText=``,C.currentSelectionRange=null}function
|
|
1987
|
+
`),t.dispatchEvent(new Event(`input`)),i.debug(`[SidePanel] removedinput box selected content before suffix`))}C.lastSelectedText=``,C.currentSelectionRange=null}function LT(){let e=document.getElementById(`promptManageList`).querySelectorAll(`.prompt-manage-item`);e.forEach(t=>{t.addEventListener(`dragstart`,e=>{C.draggedItemIndex=parseInt(t.dataset.index),t.classList.add(`dragging`),e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,C.draggedItemIndex)}),t.addEventListener(`dragend`,()=>{t.classList.remove(`dragging`),e.forEach(e=>e.classList.remove(`drag-over`)),C.draggedItemIndex=null}),t.addEventListener(`dragover`,e=>{e.preventDefault(),e.dataTransfer.dropEffect=`move`,t.classList.add(`drag-over`)}),t.addEventListener(`dragleave`,()=>{t.classList.remove(`drag-over`)}),t.addEventListener(`drop`,e=>{e.stopPropagation(),e.preventDefault();let n=parseInt(t.dataset.index);if(C.draggedItemIndex!==null&&C.draggedItemIndex!==n){let e=C.customPrompts[C.draggedItemIndex];C.customPrompts.splice(C.draggedItemIndex,1),C.customPrompts.splice(n,0,e),chrome.storage.local.set({customPrompts:C.customPrompts}),XT()}t.classList.remove(`drag-over`)})})}function RT(){let e=document.querySelector(`#promptDropdown .prompt-dropdown-header`);if(!e||e.querySelector(`.prompt-manage-btn`))return;let t=document.createElement(`button`);t.className=`prompt-manage-btn`,t.title=r(`promptManager.title`),t.style.fontSize=`13px`,t.innerHTML=`✚`,t.addEventListener(`click`,e=>{e.stopPropagation(),JT()}),e.appendChild(t)}async function zT(e=``,t=null){let n=document.getElementById(`promptSelector`),r=document.getElementById(`promptDropdown`);Je(),n.style.display=`block`,r.classList.add(`show`);let i=document.getElementById(`skillsTab`),a=document.getElementById(`mcpTab`),o=i?await lE():!1,s=a?await TE():!1;if(i&&(i.style.display=o?`block`:`none`),a&&(a.style.display=s?`block`:`none`),VT(o,s),e)await WT(e);else{let n=t||C.lastActiveDropdownTab||`prompts`,r=document.querySelector(`#promptDropdownTabs .prompt-tab[data-tab="${n}"]`),i=`prompts`;if(r&&r.style.display!==`none`)i=n;else{let e=document.querySelectorAll(`#promptDropdownTabs .prompt-tab`);for(let t of e)if(t.style.display!==`none`){i=t.dataset.tab;break}}await xE(i),UT(e)}}function BT(){let e=document.getElementById(`promptSelector`),t=document.getElementById(`promptDropdown`);e.style.display=`none`,t.classList.remove(`show`),C.selectedPromptIndex=-1,C.showMergedList=!1;let n=document.getElementById(`promptDropdownTabs`);n&&n.classList.remove(`merged-mode`)}async function VT(e,t){try{let n=C.customPrompts.length,i=document.querySelector(`#promptDropdownTabs .prompt-tab[data-tab="prompts"]`);if(i&&(i.textContent=r(`promptMgr.promptsTabCount`,{count:n})),e){let e=await dE(),t=document.getElementById(`skillsTab`);t&&(t.textContent=r(`promptMgr.skillsTabCount`,{count:e.length}))}if(t){let e=await EE(),t=document.getElementById(`mcpTab`);t&&(t.textContent=r(`promptMgr.mcpTabCount`,{count:e.length}))}}catch{}}function HT(e=``){e?WT(e):UT(e)}function UT(e=``){let t=document.getElementById(`promptList`),n=e.toLowerCase(),i=C.customPrompts.filter(t=>e?t.code.toLowerCase().includes(n)||t.content.toLowerCase().includes(n):!0);if(i.length===0){t.innerHTML=`<div class="prompt-empty">${r(`promptMgr.noMatchPrompt`)}</div>`,C.selectedPromptIndex=-1;return}C.selectedPromptIndex=0,t.innerHTML=i.map((e,t)=>`
|
|
1986
1988
|
<div class="prompt-item ${t===C.selectedPromptIndex?`selected`:``}" data-index="${t}" data-code="${e.code}">
|
|
1987
1989
|
<span class="prompt-item-index">${t+1}</span>
|
|
1988
|
-
<span class="prompt-item-icon">${
|
|
1990
|
+
<span class="prompt-item-icon">${FT}</span>
|
|
1989
1991
|
<span class="prompt-item-content">${e.content}</span>
|
|
1990
1992
|
<span class="prompt-item-code">/${e.code}</span>
|
|
1991
1993
|
</div>
|
|
1992
|
-
`).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{let n=e.dataset.code;t.ctrlKey||t.metaKey?
|
|
1994
|
+
`).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{let n=e.dataset.code;t.ctrlKey||t.metaKey?KT(n):qT(n)})})}async function WT(e=``){let t=document.getElementById(`promptList`),n=document.getElementById(`skillList`),i=document.getElementById(`mcpList`),a=document.getElementById(`promptDropdownTabs`),o=document.querySelector(`#promptDropdownHeader .prompt-dropdown-header-text`),s=document.querySelector(`#promptDropdownHeader .prompt-manage-btn`),c=document.querySelector(`#promptDropdownHeader .skill-manage-btn`),l=document.querySelector(`#promptDropdownHeader .mcp-manage-btn`);a&&a.classList.add(`merged-mode`),n&&(n.style.display=`none`),i&&(i.style.display=`none`),t&&(t.style.display=`block`),o&&(o.textContent=r(`promptMgr.mergedHeaderHint`)),s&&(s.style.display=``),c&&(c.style.display=`none`),l&&(l.style.display=`none`),C.showMergedList=!0,C.activeDropdownTab=`prompts`;let u=e.toLowerCase(),d=C.customPrompts.filter(t=>e?t.code.toLowerCase().includes(u)||t.content.toLowerCase().includes(u):!0),f=[];await lE()&&(f=(await dE()).filter(t=>e?(t.name||``).toLowerCase().includes(u)||(t.description||``).toLowerCase().includes(u):!0));let p=[];await TE()&&(p=(await EE()).filter(t=>e?(t.serverName||``).toLowerCase().includes(u)||(t.serverId||``).toLowerCase().includes(u):!0));let m=d.length+f.length+p.length,h=document.getElementById(`promptMergedTitle`);if(h&&(h.textContent=r(`promptSelector.mergedTitleCount`,{count:m})),m===0){t.innerHTML=`<div class="prompt-empty">${r(`promptMgr.noMatchResult`)}</div>`,C.selectedPromptIndex=-1;return}C.selectedPromptIndex=0;let g=0,_=d.map(e=>{let t=`
|
|
1993
1995
|
<div class="prompt-item ${g===0?`selected`:``}" data-index="${g}" data-type="prompt" data-code="${e.code}">
|
|
1994
1996
|
<span class="prompt-item-index">${g+1}</span>
|
|
1995
1997
|
<span class="prompt-item-icon">📋</span>
|
|
@@ -2007,14 +2009,13 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
2007
2009
|
<span class="prompt-item-content">🔌 ${L(e.serverName)}</span>
|
|
2008
2010
|
${t?`<span class="merged-item-badge badge-mcp-inactive">${r(`skillSelector.mcpInactiveBadge`)}</span>`:``}
|
|
2009
2011
|
<span class="merged-item-badge badge-mcp">MCP</span>
|
|
2010
|
-
</div>`;return g++,n}).join(``);t.innerHTML=_+v+y,t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=e.dataset.type;if(n===`skill`){let n=e.dataset.skillName;
|
|
2011
|
-
`){e=t;break}s=e===-1?a.substring(0,o).trimEnd():a.substring(0,e+1).trimEnd()}r.value=s+(s&&!s.endsWith(`
|
|
2012
|
+
</div>`;return g++,n}).join(``);t.innerHTML=_+v+y,t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=e.dataset.type;if(n===`skill`){let n=e.dataset.skillName;hE(n,await dE()),(t.ctrlKey||t.metaKey)&&BT()}else if(n===`mcp`){let n=e.dataset.serverId,r=e.dataset.serverName;kE(n,r,await EE()),(t.ctrlKey||t.metaKey)&&BT()}else{let n=e.dataset.code;t.ctrlKey||t.metaKey?KT(n):qT(n)}})}),yE(),PE()}function GT(e){e.forEach((e,t)=>{t===C.selectedPromptIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function KT(e,{skipTriggerStrip:t=!1}={}){let n=C.customPrompts.find(t=>t.code===e);if(!n)return;let r=document.getElementById(`userInput`),a=r.value,o=r.selectionStart,s,c;if(t)s=a+(a&&!a.endsWith(`
|
|
2012
2013
|
`)?`
|
|
2013
2014
|
|
|
2014
|
-
`:``)+n.content,r.focus(),r.selectionStart=r.selectionEnd=
|
|
2015
|
+
`:``)+n.content,c=s.length;else{let e=Ta(a,o,`slash`,n.content);e?(s=e.value,c=e.caret):(s=a.substring(0,o)+n.content+a.substring(o),c=o+n.content.length)}r.value=s,r.focus(),r.selectionStart=r.selectionEnd=c,BT(),ut(),i.debug(`[SidePanel] trackaddpromptword to input box:`,n.code,n.content)}async function qT(e){let t=C.customPrompts.find(t=>t.code===e);if(!t)return;if(C.isGenerating){i.debug(`[SidePanel] generating,please wait...`);return}let n=document.getElementById(`userInput`)?.value||``,a={quotedContextText:C.quotedContextText||``,selectedContextText:C.selectedContextText||``,selectedSkills:C.selectedSkills.slice(),selectedMcpServices:C.selectedMcpServices.slice(),knowledgeRefs:C.knowledgeRefs.slice(),selectedPage:C.selectedPage,attachedImages:C.attachedImages.slice(),attachedFiles:C.attachedFiles.slice()};await _l({state:C,getRatio:()=>IO().usage?.ratio??0,compact:GO}),BT();let o=document.getElementById(`chatContainer`).querySelector(`.welcome-message`);o&&o.remove();let s=t.content,c=a.selectedContextText&&a.selectedContextText.trim(),l=a.quotedContextText&&a.quotedContextText.trim(),u=[];if(l){let e=a.quotedContextText.trim(),{compressed:n,wasCompressed:r}=m(e);s=`[引用内容${r?`摘要`:``}]\n${n}\n\n[用户问题]\n${t.content}`,pT(`quoted`,e,!1),u.push({type:`quoted`,text:e}),C.quotedContextText===a.quotedContextText&&(C.quotedContextText=``)}else if(c){let e=a.selectedContextText.trim(),{compressed:n,wasCompressed:r}=m(e);s=`[选中内容${r?`摘要`:``}]\n${n}\n\n[用户问题]\n${t.content}`,pT(`selected`,e,!1),u.push({type:`selected`,text:e}),C.selectedContextText===a.selectedContextText&&(C.selectedContextText=``)}let d=a.selectedSkills,f=await wE(d);if(f){s=f+s;for(let e of d)pT(`skill`,r(`contextBubble.bubbleSkill`,{name:e.name,desc:e.description?`:`+e.description:``}),!1),u.push({type:`skill`,name:e.name,description:e.description||``});let e=new Set(d),t=C.selectedSkills.filter(t=>!e.has(t));t.length!==C.selectedSkills.length&&(C.selectedSkills=t,C.selectedSkillIndex=-1,vE(),yE())}let p=null,h=a.selectedMcpServices,_=ME(h);if(_){let e=h.map(e=>e.serverId).filter(Boolean);p=e.length>0?e:null,s=_+s;for(let e of h)pT(`mcp`,r(`contextBubble.bubbleMcp`,{name:e.serverName}),!1),u.push({type:`mcp`,serverName:e.serverName,serverId:e.serverId||``});let t=new Set(h),n=C.selectedMcpServices.filter(e=>!t.has(e));n.length!==C.selectedMcpServices.length&&(C.selectedMcpServices=n,C.selectedMcpServiceIndex=-1,NE(),PE())}let v=a.knowledgeRefs;if(v.length>0){let e=pT(`knowledge`,r(`contextBubble.bubbleKnowledgeSearching`),!1),n=null;try{n=await Ww(t.content,v)}catch(e){i.warn(`[SidePanel] knowledge search failed:`,e)}e&&e.parentNode&&e.remove(),n&&(s=n.text+s,Gw(n.refs,n.failed===!0),u.push({type:`knowledge`,refs:n.refs,failed:n.failed||void 0}));let a=new Set(v),o=C.knowledgeRefs.filter(e=>!a.has(e));o.length!==C.knowledgeRefs.length&&(C.knowledgeRefs=o,dx(),vx())}let y=a.selectedPage;y&&(s=`[网页上下文]\n标题: ${y.title}\nURL: ${y.url}\ntabId: ${y.id}\n`+s,pT(`page`,r(`contextBubble.bubblePage`,{title:y.title,url:y.url}),!1),u.push({type:`page`,title:y.title,url:y.url}),C.selectedPage===y&&Mx()),(c||l)&&(!C.quotedContextText&&!C.selectedContextText?IT():jw());let b=a.attachedFiles,x=(a.attachedImages||[]).slice();if(b.length>0){let e=nh(b);e&&(s+=e),b.forEach(e=>{e.status===`done`&&u.push({type:`file`,name:e.name,size:e.size,fileType:e.type})})}let S=null;if(b.length>0||x.length>0)try{S=await j(C.activeSessionId,b,x)}catch(e){i.warn(`[Prompt] save doc image snapshot failed:`,e.message)}let w=De(S?.chatStart,S?.chatCount);w&&(s+=w);let T=pm(s,x),{messageId:E,timestamp:D}=_T(`user`,pm(t.content,x),!0,[],null,!1,s,null,b);C.messageHistory.push({role:`user`,content:T,messageId:E,timestamp:D,contextBubbles:u}),Rw(),ln(t.content);let O=document.getElementById(`userInput`);O.value===n&&(O.value=``,O.style.height=`auto`),C.isGenerating=!0;let k=CT(),A=C.activeSessionId,M=C.enableImageInput&&x.length>0&&C.imageModelName||C.currentModel;if(x.length>0){let e=new Set(x),t=C.attachedImages.filter(t=>!e.has(t));t.length!==C.attachedImages.length&&(C.attachedImages=t,fm())}if(b.length>0){let e=new Set(b),t=C.attachedFiles.filter(t=>!e.has(t));if(t.length!==C.attachedFiles.length){for(let t of C.attachedFiles)e.has(t)&&t.dataUrl&&URL.revokeObjectURL(t.dataUrl);C.attachedFiles=t,th()}}try{await rt(),i.debug(`[SidePanel] sendmessagedebuginfo:`),i.debug(` - isolateChat:`,C.isolateChat),i.debug(` - chatConfig:`,C.chatConfig),i.debug(` - messageHistory.length:`,C.messageHistory.length);let e=[{role:`system`,content:await Ke(null,{sessionId:A})}];if(C.isolateChat){let t=g(M,C.enabledTools.length||50,0,C.customModelMap),n=Math.floor(t*.7),r=C.messageHistory[C.messageHistory.length-1],a=rn(C.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:C.chatConfig.maxMemoryMessages,compaction:C.activeCompaction,historyBudget:n,currentMessage:r});on(e,a,C.activeCompaction,i),a.historySummaryText&&(e[0]={...e[0],content:e[0].content+`
|
|
2015
2016
|
|
|
2016
|
-
`+a.historySummaryText}),e=[...e,...a.messages];for(let t=0;t<e.length-1;t++)e[t]={...e[t],content:
|
|
2017
|
-
<div class="prompt-manage-item" draggable="true" data-index="${t}">
|
|
2017
|
+
`+a.historySummaryText}),e=[...e,...a.messages];for(let t=0;t<e.length-1;t++)e[t]={...e[t],content:mm(e[t].content)}}else e.push({role:`user`,content:T});let n=await Pe(),a,o,s=!1,c=null,l=null;try{let t=await NT(e,M,C.useTools,n,{forcedMcpServerIds:p});a=t.content,o=t.executionLog||[],s=t.wasStreamed||!1,c=t.streamingHtml||null,t.streamingConnected!==void 0&&t.streamingConnected,l=t.streamingMsgId||null}catch(e){wT(k),a=r(`promptMgr.requestFailed`,{message:e.message||r(`agentConfig.unknownError`)}),o=e.executionLog||[];let{element:n,messageId:i}=_T(`assistant`,a,!0,o);throw C.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:i}),Rw(),e.message!==r(`chatMsg.errTaskStopped`)&&Yl(A,a,t.content),e}let u=null;if(!s||!c)if(wT(k),s)u=l;else{let{element:e,messageId:t}=_T(`assistant`,a,!0,o);u=t,await lt(e)}else u=l;C.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:u}),Rw(),Jl(A,t.content)}catch{}finally{Ql(A),O.focus()}}function JT(){document.getElementById(`promptManageModal`).classList.add(`show`),XT()}function YT(){document.getElementById(`promptManageModal`).classList.remove(`show`);let e=document.getElementById(`editPromptIndex`),t=document.getElementById(`newPromptCode`),n=document.getElementById(`newPromptContent`),i=document.getElementById(`promptManageAddBtn`);e&&(e.value=``),t&&(t.value=``),n&&(n.value=``),i&&(i.textContent=r(`promptManager.addPrompt`),i.style.background=`var(--brand-500)`)}function XT(){let e=document.getElementById(`promptManageList`);if(C.customPrompts.length===0){e.innerHTML=`<div class="prompt-empty">${r(`promptMgr.emptyPromptHint`)}</div>`;return}e.innerHTML=C.customPrompts.map((e,t)=>{let n=e.enabledInMenu===!0;return`
|
|
2018
|
+
<div class="prompt-manage-item ${n?`in-menu`:``}" draggable="true" data-index="${t}">
|
|
2018
2019
|
<div class="prompt-manage-item-left">
|
|
2019
2020
|
<span class="prompt-drag-handle" title="${r(`toolbar.dragSort`)}">⋮⋮</span>
|
|
2020
2021
|
<span class="prompt-manage-item-content">${e.content}</span>
|
|
@@ -2023,7 +2024,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
2023
2024
|
<div class="prompt-manage-item-actions">
|
|
2024
2025
|
<button class="prompt-sort-btn move-up-btn" data-index="${t}" title="${r(`toolbar.moveUp`)}" ${t===0?`disabled`:``}>↑</button>
|
|
2025
2026
|
<button class="prompt-sort-btn move-down-btn" data-index="${t}" title="${r(`toolbar.moveDown`)}" ${t===C.customPrompts.length-1?`disabled`:``}>↓</button>
|
|
2026
|
-
<button class="prompt-sort-btn menu-toggle-btn ${
|
|
2027
|
+
<button class="prompt-sort-btn menu-toggle-btn ${n?`active`:``}" data-index="${t}" title="${r(n?`promptMgr.menuDisableTooltip`:`promptMgr.menuEnableTooltip`)}" aria-pressed="${n}">
|
|
2027
2028
|
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
|
|
2028
2029
|
<path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0z"/>
|
|
2029
2030
|
</svg>
|
|
@@ -2041,7 +2042,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
2041
2042
|
</button>
|
|
2042
2043
|
</div>
|
|
2043
2044
|
</div>
|
|
2044
|
-
`).join(``),e.querySelectorAll(`.move-up-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=parseInt(e.dataset.index);if(n>0){let e=C.customPrompts[n];C.customPrompts[n]=C.customPrompts[n-1],C.customPrompts[n-1]=e,chrome.storage.local.set({customPrompts:C.customPrompts}),
|
|
2045
|
+
`}).join(``),e.querySelectorAll(`.move-up-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=parseInt(e.dataset.index);if(n>0){let e=C.customPrompts[n];C.customPrompts[n]=C.customPrompts[n-1],C.customPrompts[n-1]=e,chrome.storage.local.set({customPrompts:C.customPrompts}),XT()}})}),e.querySelectorAll(`.move-down-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=parseInt(e.dataset.index);if(n<C.customPrompts.length-1){let e=C.customPrompts[n];C.customPrompts[n]=C.customPrompts[n+1],C.customPrompts[n+1]=e,chrome.storage.local.set({customPrompts:C.customPrompts}),XT()}})}),e.querySelectorAll(`.menu-toggle-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation();let n=parseInt(e.dataset.index);C.customPrompts[n].enabledInMenu=!C.customPrompts[n].enabledInMenu,chrome.storage.local.set({customPrompts:C.customPrompts}),XT()})}),e.querySelectorAll(`.edit-btn`).forEach(e=>{e.addEventListener(`click`,()=>{eE(parseInt(e.dataset.index))})}),e.querySelectorAll(`.delete-btn`).forEach(e=>{e.addEventListener(`click`,()=>{tE(parseInt(e.dataset.index))})}),LT()}function ZT(e){let t=document.getElementById(`promptErrorModal`),n=document.getElementById(`promptErrorMessage`);n.textContent=e,t.classList.add(`show`)}function QT(){document.getElementById(`promptErrorModal`).classList.remove(`show`)}function $T(){let e=document.getElementById(`editPromptIndex`),t=document.getElementById(`newPromptCode`),n=document.getElementById(`newPromptContent`),i=t.value.trim(),a=n.value.trim();if(!i||!a){ZT(r(`promptMgr.codeAndContentRequired`));return}let o=e?parseInt(e.value):-1,s=C.customPrompts.findIndex(e=>e.code===i);if(s!==-1&&s!==o){ZT(r(`promptMgr.codeExists`));return}o>=0&&o<C.customPrompts.length?C.customPrompts[o]={...C.customPrompts[o],code:i,content:a}:C.customPrompts.push({code:i,content:a,enabledInMenu:!1}),chrome.storage.local.set({customPrompts:C.customPrompts}),t.value=``,n.value=``,e&&(e.value=``);let c=document.getElementById(`promptManageAddBtn`);c.textContent=r(`promptManager.addPrompt`),c.style.background=`var(--brand-500)`,XT()}function eE(e){let t=C.customPrompts[e];if(!t)return;let n=document.getElementById(`editPromptIndex`),i=document.getElementById(`newPromptCode`),a=document.getElementById(`newPromptContent`),o=document.getElementById(`promptManageAddBtn`);n&&(n.value=e),i.value=t.code,a.value=t.content,o.textContent=r(`promptMgr.saveChanges`),o.style.background=`var(--warning-500)`,i.scrollIntoView({behavior:`smooth`})}function tE(e){let t=C.customPrompts[e];if(!t)return;C.pendingDeleteIndex=e;let n=document.getElementById(`deleteConfirmModal`),i=document.getElementById(`deleteConfirmMessage`);i.textContent=r(`promptMgr.confirmDeletePrompt`,{code:t.code}),n.classList.add(`show`)}function nE(){document.getElementById(`deleteConfirmModal`).classList.remove(`show`),C.pendingDeleteIndex=-1}function rE(e){C.customPrompts.splice(e,1),chrome.storage.local.set({customPrompts:C.customPrompts}),XT()}function iE(){let e=document.getElementById(`promptManageCancelBtn`),t=document.getElementById(`promptManageAddBtn`),n=document.getElementById(`promptModalCloseBtn`);e&&e.addEventListener(`click`,YT),t&&t.addEventListener(`click`,$T),n&&n.addEventListener(`click`,YT);let r=document.getElementById(`deleteCancelBtn`),i=document.getElementById(`deleteConfirmBtn`);r&&r.addEventListener(`click`,nE),i&&i.addEventListener(`click`,()=>{C.pendingDeleteIndex>=0&&rE(C.pendingDeleteIndex),nE()});let a=document.getElementById(`deleteConfirmModal`);a&&a.addEventListener(`click`,e=>{e.target===a&&nE()});let o=document.getElementById(`promptErrorConfirmBtn`);o&&o.addEventListener(`click`,QT);let s=document.getElementById(`promptErrorModal`);s&&s.addEventListener(`click`,e=>{e.target===s&&QT()});let c=document.getElementById(`promptDropdown`);c&&c.addEventListener(`mousedown`,e=>{e.target.closest(`.prompt-item, .prompt-tab, .skill-list-item, .mcp-list-item`)&&e.preventDefault()})}n(`zh`,{promptSelector:{noMatchSkill:`暂无匹配的技能`,skillManageTitle:`管理技能`,noMatchMcp:`暂无匹配的 MCP 服务`,toolCount:`{count} 个工具`,mcpManageTitle:`管理 MCP 服务`}}),n(`en`,{promptSelector:{noMatchSkill:`No matching skills`,skillManageTitle:`Manage skills`,noMatchMcp:`No matching MCP services`,toolCount:`{count} tools`,mcpManageTitle:`Manage MCP services`}}),n(`zh`,{skillSelector:{selectedSkillStart:`[已选技能: {name}`,useSkillToolsHint:`请根据上述技能说明,使用相关工具处理以下问题:
|
|
2045
2046
|
`,loadSkillHint:"请使用 `agent_skill`(action=load)加载「{name}」的完整说明,然后根据说明自主调用相关工具处理以下问题。\n",runSkillHint:"请使用 `agent_skill`(action=run)执行「{name}」技能来处理以下问题",requiredParam:`必填`,optionalParam:`可选`,callParamsPrefix:`,调用参数:`,paramItem:`({flag},{type}:{desc})`,paramJoin:`、`,sentenceEnd:`。
|
|
2046
2047
|
`,selectedMcpContext:`[已选MCP服务: {name}]
|
|
2047
2048
|
请使用「{name}」MCP服务来处理以下问题:
|
|
@@ -2049,7 +2050,7 @@ Click to view assessment details`,reflectionFailedTitle:`Reflection assessment f
|
|
|
2049
2050
|
`,loadSkillHint:'Please use `agent_skill` (action=load) to load the full description of "{name}", then autonomously call relevant tools to handle the following problem.\n',runSkillHint:'Please use `agent_skill` (action=run) to execute the "{name}" skill to handle the following problem',requiredParam:`required`,optionalParam:`optional`,callParamsPrefix:`, parameters: `,paramItem:`({flag}, {type}: {desc})`,paramJoin:`, `,sentenceEnd:`.
|
|
2050
2051
|
`,selectedMcpContext:`[Selected MCP service: {name}]
|
|
2051
2052
|
Please use the "{name}" MCP service to handle the following problem:
|
|
2052
|
-
`,disabledBadge:`Disabled`,disabledTooltip:`Not enabled (won't be auto-injected into the AI prompt), but you can still select and use it manually`,mcpInactiveBadge:`Inactive`,mcpInactiveTooltip:`This service is currently inactive (closed or excluded by the current agent). Selecting it will force-enable it for this request.`,manualUseSuffix:`Manual`}});var
|
|
2053
|
+
`,disabledBadge:`Disabled`,disabledTooltip:`Not enabled (won't be auto-injected into the AI prompt), but you can still select and use it manually`,mcpInactiveBadge:`Inactive`,mcpInactiveTooltip:`This service is currently inactive (closed or excluded by the current agent). Selecting it will force-enable it for this request.`,manualUseSuffix:`Manual`}});var aE=[],oE=0,sE=3e4;async function cE(e=!1){let t=Date.now();return!e&&aE.length>0&&t-oE<sE?aE:new Promise(e=>{chrome.runtime.sendMessage({type:`GET_SKILL_LIST`},t=>{if(chrome.runtime.lastError||!t?.success){e(aE);return}aE=t.skills||[],oE=Date.now(),e(aE)})})}async function lE(){if(!C.agentPlatform?.connected||(await new Promise(e=>{chrome.storage.local.get([`skillsEnabled`],e)})).skillsEnabled===!1)return!1;try{return(await dE()).length>0}catch{return!1}}async function uE(e=!1){return(await cE(e)).filter(e=>e.enabled!==!1)}async function dE(e=!1){let t=[...await cE(e)];return t.sort((e,t)=>(e.enabled===!1)-+(t.enabled===!1)),t}async function fE(e=``){let t=document.getElementById(`skillList`);if(!t)return;let n=await dE(!0),i=e.toLowerCase(),a=n.filter(t=>e?(t.name||``).toLowerCase().includes(i)||(t.description||``).toLowerCase().includes(i):!0);if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`promptSelector.noMatchSkill`)}</div>`,C.selectedSkillIndex=-1;return}C.selectedSkillIndex=0,t.innerHTML=a.map((e,t)=>{let n=e.type===`agent`?`Agent`:`Workflow`,i=e.description||``,a=e.enabled===!1,o=a?`${e.name}\n${r(`skillSelector.disabledTooltip`)}`:e.name;return`
|
|
2053
2054
|
<div class="skill-list-item ${t===0?`selected`:``} ${a?`skill-list-item-disabled`:``}" data-index="${t}" data-skill-name="${L(e.name)}" title="${P(o)}">
|
|
2054
2055
|
<span class="skill-list-item-index">${t+1}</span>
|
|
2055
2056
|
<span class="skill-list-item-icon">🧩</span>
|
|
@@ -2060,15 +2061,15 @@ Please use the "{name}" MCP service to handle the following problem:
|
|
|
2060
2061
|
<span class="skill-list-item-badge">${n}</span>
|
|
2061
2062
|
${a?`<span class="skill-list-item-badge badge-disabled">${r(`skillSelector.disabledBadge`)}</span>`:``}
|
|
2062
2063
|
</div>
|
|
2063
|
-
`}).join(``),t.querySelectorAll(`.skill-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.skillName;
|
|
2064
|
+
`}).join(``),t.querySelectorAll(`.skill-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.skillName;hE(r,n),(t.ctrlKey||t.metaKey)&&BT()})}),yE()}function pE(e){e.forEach((e,t)=>{t===C.selectedSkillIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function mE(){let e=document.getElementById(`userInput`);if(!e)return;let t=Ea(e.value,e.selectionStart,`slash`);t&&(e.value=t.value,e.selectionStart=e.selectionEnd=t.caret),e.focus(),ut()}function hE(e,t,{clearTrigger:n=!0,toggle:r=!0}={}){let a=t.find(t=>t.name===e);if(!a)return;let o=C.selectedSkills.findIndex(t=>t.name===e);if(o>=0?r&&C.selectedSkills.splice(o,1):C.selectedSkills.push({name:a.name,description:a.description||``,type:a.type||`agent`,stepCount:a.stepCount||0,parameters:a.parameters||{},enabled:a.enabled!==!1}),yE(),vE(),n)mE();else{let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length),ut()}i.debug(`[SidePanel] skill toggled:`,a.name,`count:`,C.selectedSkills.length)}async function gE(e,{multi:t=!1}={}){hE(e,await dE(),{toggle:t}),t||BT()}function _E(){C.selectedSkills=[],C.selectedSkillIndex=-1,vE(),yE(),i.debug(`[SidePanel] skill clearedselect`)}function vE(){let e=document.getElementById(`skillIndicator`);if(e){if(C.selectedSkills.length===0){e.style.display=`none`,e.innerHTML=``;return}e.innerHTML=C.selectedSkills.map(e=>{let t=e.enabled===!1,n=t?`${e.name} (${r(`skillSelector.manualUseSuffix`)})`:e.name,i=t?r(`skillSelector.disabledTooltip`):e.name;return`
|
|
2064
2065
|
<span class="ref-chip skill-ref-chip${t?` skill-ref-chip-manual`:``}">
|
|
2065
2066
|
<span class="ref-chip-name" title="${P(i)}">🧩 ${L(n)}</span>
|
|
2066
2067
|
<button class="ref-chip-close" data-skill-name="${P(e.name)}" title="${r(`common.delete`)}">✕</button>
|
|
2067
2068
|
</span>
|
|
2068
|
-
`}).join(``),e.querySelectorAll(`.ref-chip-close`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),C.selectedSkills=C.selectedSkills.filter(t=>t.name!==e.dataset.skillName),
|
|
2069
|
+
`}).join(``),e.querySelectorAll(`.ref-chip-close`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),C.selectedSkills=C.selectedSkills.filter(t=>t.name!==e.dataset.skillName),vE(),yE()})}),e.style.display=`flex`}}function yE(){let e=new Set(C.selectedSkills.map(e=>e.name));document.querySelectorAll(`.skill-list-item, .merged-skill-item`).forEach(t=>{t.classList.toggle(`picked`,e.has(t.dataset.skillName))})}function bE(){let e=document.getElementById(`skillIndicatorClose`);e&&e.addEventListener(`click`,_E)}async function xE(e){C.activeDropdownTab=e,C.lastActiveDropdownTab=e,C.showMergedList=!1;let t=document.getElementById(`promptList`),n=document.getElementById(`skillList`),i=document.getElementById(`mcpList`),a=document.getElementById(`promptDropdownTabs`),o=document.querySelectorAll(`#promptDropdownTabs .prompt-tab`),s=document.querySelector(`#promptDropdownHeader .prompt-dropdown-header-text`);a&&a.classList.remove(`merged-mode`),o.forEach(t=>{t.classList.toggle(`active`,t.dataset.tab===e)}),e===`skills`?(t&&(t.style.display=`none`),n&&(n.style.display=`block`),i&&(i.style.display=`none`),s&&(s.textContent=r(`promptSelector.switchHintMulti`)),C.selectedPromptIndex=-1,C.selectedMcpServiceIndex=-1,await fE()):e===`mcp`?(t&&(t.style.display=`none`),n&&(n.style.display=`none`),i&&(i.style.display=`block`),s&&(s.textContent=r(`promptSelector.switchHintMulti`)),C.selectedPromptIndex=-1,C.selectedSkillIndex=-1,await DE()):(t&&(t.style.display=`block`),n&&(n.style.display=`none`),i&&(i.style.display=`none`),s&&(s.textContent=r(`promptSelector.switchHint`)),C.selectedSkillIndex=-1,C.selectedMcpServiceIndex=-1);let c=document.querySelector(`#promptDropdownHeader .prompt-manage-btn`),l=document.querySelector(`#promptDropdownHeader .skill-manage-btn`),u=document.querySelector(`#promptDropdownHeader .mcp-manage-btn`);c&&(c.style.display=e===`prompts`?``:`none`),l&&(l.style.display=e===`skills`?``:`none`),u&&(u.style.display=e===`mcp`?``:`none`);let d=document.getElementById(`userInput`);d&&d.focus()}function SE(){let e=document.getElementById(`promptDropdownHeader`);if(!e||e.querySelector(`.skill-manage-btn`))return;let t=document.createElement(`button`);t.className=`skill-manage-btn`,t.title=r(`promptSelector.skillManageTitle`),t.style.display=`none`,t.style.fontSize=`13px`,t.innerHTML=`✚`,t.addEventListener(`click`,e=>{e.stopPropagation(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`toolbox`})}),e.appendChild(t)}function CE(){let e=document.getElementById(`promptDropdownTabs`);e&&(SE(),IE(),e.addEventListener(`click`,e=>{let t=e.target.closest(`.prompt-tab`);if(!t)return;let n=t.dataset.tab;n!==C.activeDropdownTab&&xE(n)}))}async function wE(e){let t=e||C.selectedSkills||[];if(t.length===0)return``;let n=[];for(let e of t){let t=e.type===`agent`,i=r(`skillSelector.selectedSkillStart`,{name:e.name});if(e.description&&(i+=` - ${e.description}`),i+=`]
|
|
2069
2070
|
`,t)try{let t=await new Promise(t=>{chrome.runtime.sendMessage({type:`GET_AGENT_SKILL_PROMPT`,name:e.name},e=>{if(chrome.runtime.lastError||!e?.success){t(null);return}t(e)})});t&&t.prompt?i+=`${t.prompt}\n\n${r(`skillSelector.useSkillToolsHint`)}`:i+=r(`skillSelector.loadSkillHint`,{name:e.name})}catch{i+=r(`skillSelector.loadSkillHint`,{name:e.name})}else{i+=r(`skillSelector.runSkillHint`,{name:e.name});let t=e.parameters;if(t&&t.properties&&Object.keys(t.properties).length>0){let e=t.required||[],n=Object.entries(t.properties).map(([t,n])=>r(`skillSelector.paramItem`,{flag:e.includes(t)?r(`skillSelector.requiredParam`):r(`skillSelector.optionalParam`),type:n.type||`string`,desc:n.description||``})).join(r(`skillSelector.paramJoin`));i+=r(`skillSelector.callParamsPrefix`)+n}i+=r(`skillSelector.sentenceEnd`)}n.push(i)}return n.join(`
|
|
2070
2071
|
|
|
2071
|
-
`)}async function
|
|
2072
|
+
`)}async function TE(){return!C.agentPlatform?.connected||!await new Promise(e=>{chrome.storage.local.get([`mcpEnabled`],t=>e(t.mcpEnabled))})?!1:(await EE()).length>0}async function EE(){return new Promise(e=>{chrome.storage.local.get([`mcpTools`],t=>{let n=t.mcpTools||[],r=new Set(Array.isArray(C.mcpClosedServers)?C.mcpClosedServers:[]),i=new Set(Array.isArray(C.activeAgentMcpExcludedServerIds)?C.activeAgentMcpExcludedServerIds:[]),a=new Map;n.forEach(e=>{let t=e.serverId||`unknown`;a.has(t)||a.set(t,{serverId:t,serverName:e.serverName||t,toolCount:0,effectiveOpen:!r.has(t)&&!i.has(t)}),a.get(t).toolCount++});let o=Array.from(a.values());e([...o.filter(e=>e.effectiveOpen),...o.filter(e=>!e.effectiveOpen)])})})}async function DE(e=``){let t=document.getElementById(`mcpList`);if(!t)return;let n=await EE(),i=e.toLowerCase(),a=n.filter(t=>e?(t.serverName||``).toLowerCase().includes(i)||(t.serverId||``).toLowerCase().includes(i):!0);if(a.length===0){t.innerHTML=`<div class="prompt-empty">${r(`promptSelector.noMatchMcp`)}</div>`,C.selectedMcpServiceIndex=-1;return}C.selectedMcpServiceIndex=0,t.innerHTML=a.map((e,t)=>{let n=e.effectiveOpen===!1,i=n?`${e.serverName}\n${r(`skillSelector.mcpInactiveTooltip`)}`:e.serverName;return`
|
|
2072
2073
|
<div class="mcp-list-item ${t===0?`selected`:``} ${n?`mcp-list-item-inactive`:``}" data-index="${t}" data-server-id="${L(e.serverId)}" data-server-name="${L(e.serverName)}" title="${P(i)}">
|
|
2073
2074
|
<span class="mcp-list-item-index">${t+1}</span>
|
|
2074
2075
|
<span class="mcp-list-item-icon">🔌</span>
|
|
@@ -2079,15 +2080,15 @@ Please use the "{name}" MCP service to handle the following problem:
|
|
|
2079
2080
|
${n?`<span class="mcp-list-item-badge mcp-badge-inactive">${r(`skillSelector.mcpInactiveBadge`)}</span>`:``}
|
|
2080
2081
|
<span class="mcp-list-item-badge">${r(`promptSelector.toolCount`,{count:e.toolCount})}</span>
|
|
2081
2082
|
</div>
|
|
2082
|
-
`}).join(``),t.querySelectorAll(`.mcp-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.serverId,i=e.dataset.serverName;
|
|
2083
|
-
`)}function
|
|
2083
|
+
`}).join(``),t.querySelectorAll(`.mcp-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.serverId,i=e.dataset.serverName;kE(r,i,n),(t.ctrlKey||t.metaKey)&&BT()})}),PE()}function OE(e){e.forEach((e,t)=>{t===C.selectedMcpServiceIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function kE(e,t,n,{clearTrigger:r=!0,toggle:a=!0}={}){let o=n?.find(t=>t.serverId===e)?.toolCount||0,s=t||e,c=C.selectedMcpServices.findIndex(e=>e.serverName===s);if(c>=0?a&&C.selectedMcpServices.splice(c,1):C.selectedMcpServices.push({serverId:e,serverName:s,toolCount:o}),PE(),NE(),r)mE();else{let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length),ut()}i.debug(`[SidePanel] MCP service toggled:`,s,`count:`,C.selectedMcpServices.length)}async function AE(e,t,{multi:n=!1}={}){kE(e,t,await EE(),{toggle:n}),n||BT()}function jE(){C.selectedMcpServices=[],C.selectedMcpServiceIndex=-1,NE(),PE(),i.debug(`[SidePanel] cleared MCP serviceselect`)}function ME(e){let t=e||C.selectedMcpServices||[];return t.length===0?``:t.map(e=>r(`skillSelector.selectedMcpContext`,{name:e.serverName})).join(`
|
|
2084
|
+
`)}function NE(){let e=document.getElementById(`mcpIndicator`);if(e){if(C.selectedMcpServices.length===0){e.style.display=`none`,e.innerHTML=``;return}e.innerHTML=C.selectedMcpServices.map(e=>`
|
|
2084
2085
|
<span class="ref-chip mcp-ref-chip">
|
|
2085
2086
|
<span class="ref-chip-name" title="${P(e.serverName)}">🔌 ${L(e.serverName)}</span>
|
|
2086
2087
|
<button class="ref-chip-close" data-server-name="${P(e.serverName)}" title="${r(`common.delete`)}">✕</button>
|
|
2087
2088
|
</span>
|
|
2088
|
-
`).join(``),e.querySelectorAll(`.ref-chip-close`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),C.selectedMcpServices=C.selectedMcpServices.filter(t=>t.serverName!==e.dataset.serverName),
|
|
2089
|
-
`)}function
|
|
2090
|
-
`):t===`en`?`(no skills available)`:`(当前没有可用技能)`}function
|
|
2089
|
+
`).join(``),e.querySelectorAll(`.ref-chip-close`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),C.selectedMcpServices=C.selectedMcpServices.filter(t=>t.serverName!==e.dataset.serverName),NE(),PE()})}),e.style.display=`flex`}}function PE(){let e=new Set(C.selectedMcpServices.map(e=>e.serverName));document.querySelectorAll(`.mcp-list-item, .merged-mcp-item`).forEach(t=>{t.classList.toggle(`picked`,e.has(t.dataset.serverName))})}function FE(){let e=document.getElementById(`mcpIndicatorClose`);e&&e.addEventListener(`click`,jE)}function IE(){let e=document.getElementById(`promptDropdownHeader`);if(!e||e.querySelector(`.mcp-manage-btn`))return;let t=document.createElement(`button`);t.className=`mcp-manage-btn`,t.title=r(`promptSelector.mcpManageTitle`),t.style.display=`none`,t.style.fontSize=`13px`,t.innerHTML=`✚`,t.addEventListener(`click`,e=>{e.stopPropagation(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`toolbox`})}),e.appendChild(t)}function LE({builtinTools:e=[],ragTools:t=[],agentConnected:n=!1,skillsEnabled:r=!0}={}){let i=[...e,...t||[]];return n||(i=i.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),r===!1&&(i=i.filter(e=>e.id!==`agent_skill`)),i}function RE(e=[]){let t=new Map;for(let n of e){let e=n.serverId||`unknown`;t.has(e)||t.set(e,{serverId:e,serverName:n.serverName||e,tools:[]}),t.get(e).tools.push(n)}return Array.from(t.values())}async function zE(){let e=[];try{e=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[]}catch{}let t=!1,n=!0,r=[];try{let e=await chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`ragTools`]);t=e.mcpEnabled===!0,n=e.skillsEnabled!==!1,r=e.ragTools||[]}catch{}let i=C.agentPlatform?.connected===!0,a=LE({builtinTools:f,ragTools:r,agentConnected:i,skillsEnabled:n}),o=[];if(n!==!1)try{o=await uE()}catch{}return{tools:a.map(e=>({id:e.id,name:e.name||e.id,description:Ri(e),category:e.category||`other`})),skills:o.map(e=>({name:e.name,description:e.description||``})),mcpServices:t&&i?RE(e):[],meta:{agentConnected:i,skillsEnabled:n,mcpEnabled:t}}}var BE=24,VE=60,HE=4e3,UE=60;function WE(e){return typeof e==`string`?e.trim():``}function GE(e,t){let n=Array.from(e);return n.length>t?n.slice(0,t).join(``):e}function KE(e,t){if(!e.length)return t===`en`?`(no tools available)`:`(当前没有可用工具)`;let n=[...e].sort((e,t)=>{let n=e.category||``,r=t.category||``;return n===r?String(e.id).localeCompare(String(t.id)):n.localeCompare(r)}),r=n.length>80?40:UE;return n.map(e=>`- ${e.id}|${e.name}|${GE(e.description||``,r)}`).join(`
|
|
2090
|
+
`)}function qE(e,t){return e.length?[...e].sort((e,t)=>String(e.name).localeCompare(String(t.name))).map(e=>`- ${e.name}|${GE(e.description||``,UE)}`).join(`
|
|
2091
|
+
`):t===`en`?`(no skills available)`:`(当前没有可用技能)`}function JE({language:e=`zh`,tools:t=[],skills:n=[],currentAgent:r=null}={}){let i=KE(t,e),a=qE(n,e),o=``;if(r){let t=JSON.stringify({name:r.name||``,icon:r.icon||``,description:r.description||``,systemPrompt:r.systemPrompt||``,toolIds:r.toolIds??null,skillIds:r.skillIds??null,allowSubDispatch:r.allowSubDispatch===!0},null,2);o=e===`en`?`\n## Current assistant (edit mode)\nThe user is editing an existing assistant. Change ONLY what the user explicitly asks for; keep every unmentioned field as-is. Minimally edit systemPrompt instead of rewriting it. Still output the complete done configuration, and use message to describe what changed in one sentence.\n${t}\n`:`\n## 当前助手(编辑模式)\n用户是在现有助手基础上做修改:只调整用户明确提到的部分,未提及的字段必须原样保留;systemPrompt 请在原文基础上最小改动,不要整段重写;最终仍输出完整的 done 配置,并用 message 用一句话说明本次改了什么。\n${t}\n`}return e===`en`?`You are the "Assistant Creation Advisor". Through a short conversation, turn the user's vague need into a ready-to-use assistant configuration (role prompt + tools + skills).
|
|
2091
2092
|
|
|
2092
2093
|
## Capability catalog (choose ONLY from here)
|
|
2093
2094
|
Tools (id | name | description):
|
|
@@ -2185,17 +2186,17 @@ ${o}
|
|
|
2185
2186
|
2. 标注风险与待办,给出下周建议。
|
|
2186
2187
|
3. 统一输出为 Markdown。
|
|
2187
2188
|
流程:先确认时间范围与受众,再整理要点,最后成稿。
|
|
2188
|
-
边界:不编造未提供的数据;信息不足时先追问;默认控制在 800 字以内。"`}function
|
|
2189
|
+
边界:不编造未提供的数据;信息不足时先追问;默认控制在 800 字以内。"`}function YE(e){return String(e||``).replace(/^\uFEFF/,``).replace(/[\u200B-\u200D\u2060]/g,``).trim()}function XE(e,t){if(e[t]!==`{`)return null;let n=0,r=!1,i=!1;for(let a=t;a<e.length;a+=1){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`)r=!0;else if(o===`{`)n+=1;else if(o===`}`&&(--n,n===0))return e.slice(t,a+1)}return e.slice(t)}function ZE(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(n){t+=a,r?r=!1:a===`\\`?r=!0:a===`"`&&(n=!1);continue}if(a===`"`){n=!0,t+=a;continue}if(a===`/`&&e[i+1]===`/`){for(;i<e.length&&e[i]!==`
|
|
2189
2190
|
`;)i+=1;i<e.length&&(t+=`
|
|
2190
|
-
`);continue}if(a===`/`&&e[i+1]===`*`){for(i+=2;i<e.length&&!(e[i]===`*`&&e[i+1]===`/`);)i+=1;i+=1;continue}t+=a}return t}function
|
|
2191
|
-
`){t+=`\\n`;continue}if(i===`\r`){t+=`\\r`;continue}if(i===` `){t+=`\\t`;continue}let e=i.codePointAt(0);if(e!==void 0&&e<32){t+=`\\u${e.toString(16).padStart(4,`0`)}`;continue}t+=i;continue}i===`"`&&(n=!0),t+=i}return t}function GE(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(n){t+=a,r?r=!1:a===`\\`?r=!0:a===`"`&&(n=!1);continue}if(a===`"`){n=!0,t+=a;continue}if(a===`,`){let t=i+1;for(;t<e.length&&/\s/.test(e[t]);)t+=1;if(e[t]===`}`||e[t]===`]`)continue}t+=a}return t}function KE(e){let t=e.match(/```(?:json|JSON)?\s*([\s\S]*?)```/);return t?t[1].trim():``}function qE(e){let t=[],n=KE(e);n&&t.push(n),t.push(e);for(let e of t){let t=UE(e),n=[t.trim()],r=0;for(let e=0;e<3;e+=1){let e=t.indexOf(`{`,r);if(e===-1)break;let i=HE(t,e);if(!i)break;n.push(i),r=e+i.length}for(let e of n){if(!e)continue;let t=[e,GE(WE(e))];for(let e of t)try{let t=JSON.parse(e);if(typeof t==`string`&&(t=JSON.parse(t)),t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}}throw Error(`invalid_json`)}function JE(e){let t=VE(e);if(!t)throw Error(`empty_reply`);if(!t.includes(`{`))throw Error(`no_json_object`);let n=qE(t),r=n.action,i=LE(IE(n.message),500);if(r===`ask`){let e=n.question||{},t=IE(e.text),a=Array.isArray(e.options)?e.options.map(IE).filter(Boolean).slice(0,4):[];if(!t||a.length===0)throw Error(`invalid_question`);let o=Number.isInteger(e.recommended)?e.recommended:0;return{action:r,message:i,question:{text:t,options:a,recommended:Math.min(Math.max(o,0),a.length-1),allowCustom:e.allowCustom!==!1}}}if(r===`done`){if(!n.agent||typeof n.agent!=`object`)throw Error(`invalid_agent`);return{action:r,message:i,agent:n.agent}}throw Error(`invalid_action`)}function YE(e={},{tools:t=[],skills:n=[],language:r=`zh`,baseAgent:i=null}={}){let a=[],o=i||null,s=LE(IE(e.name),ME)||LE(IE(o?.name),ME);s||=r===`en`?`New Assistant`:`未命名助手`;let c=IE(e.icon)||IE(o?.icon);(!c||Array.from(c).length>6)&&(c=`🤖`,IE(e.icon)&&a.push({code:`iconFallback`}));let l=LE(IE(e.description)||IE(o?.description),NE),u=LE(IE(e.systemPrompt)||IE(o?.systemPrompt),PE);Array.from(u).length<60&&a.push({code:`promptShort`});let d=Array.isArray(o?.toolIds)&&o.toolIds.length>0?[...o.toolIds]:null,f=new Set([...t.map(e=>e.id),...d||[]]),p=d;if(e.toolIds===null)p=null;else if(Array.isArray(e.toolIds))if(e.toolIds.length===0)p=null;else{let t=[...new Set(e.toolIds.filter(e=>typeof e==`string`&&e))],n=t.filter(e=>f.has(e)),r=t.filter(e=>!f.has(e));r.length&&a.push({code:n.length>0?`toolsDropped`:`toolsAllDropped`,count:r.length,names:r.slice(0,5)}),p=n.length>0?n:d}let m=Array.isArray(o?.skillIds)&&o.skillIds.length>0?[...o.skillIds]:null,h=new Set([...n.map(e=>e.name),...m||[]]),g=m;if(e.skillIds===null)g=null;else if(Array.isArray(e.skillIds))if(e.skillIds.length===0)g=null;else{let t=[...new Set(e.skillIds.filter(e=>typeof e==`string`&&e))],n=t.filter(e=>h.has(e)),r=t.filter(e=>!h.has(e));r.length&&a.push({code:n.length>0?`skillsDropped`:`skillsAllDropped`,count:r.length,names:r.slice(0,5)}),g=n.length>0?n:m}return{draft:{name:s,icon:c,description:l,systemPrompt:u,toolIds:p,skillIds:g,allowSubDispatch:e.allowSubDispatch===void 0?o?.allowSubDispatch===!0:e.allowSubDispatch===!0,model:o?.model??null,temperature:o?.temperature??null,topP:o?.topP??null,mcpExcludedServerIds:Array.isArray(o?.mcpExcludedServerIds)?[...o.mcpExcludedServerIds]:null},warnings:a}}n(`zh`,{agentBuilder:{title:`AI 创建助手`,subtitle:`描述你的需求,AI 会通过几个问题帮你生成配置`,entry:`AI 帮我创建`,editorBanner:`不知道怎么填?让 AI 问几个问题 →`,editBanner:`让 AI 调整这个助手 →`,editConfirmTitle:`用 AI 调整助手`,editConfirmMessage:`AI 将基于已保存的配置进行修改,当前未保存的修改不会带入。是否继续?`,greeting:`告诉我你想让这个助手做什么,我会问几个关键问题,然后直接帮你创建。`,editGreeting:`已载入「{name}」,想调整什么?可以直接说,例如:更简洁、只保留网页工具、输出改成英文。`,editExample1:`更简洁一点`,editExample2:`只保留网页相关工具`,editExample3:`输出改成英文`,example1:`帮我汇总周报`,example2:`帮我审查代码`,example3:`帮我抓取网页表格数据`,placeholder:`描述你的需求,例如:帮我每天汇总科技新闻…`,send:`发送`,hint:`最多 3 轮澄清,信息够了会自动创建`,restart:`重新开始`,thinking:`正在理解你的需求…`,recommended:`推荐`,customHint:`也可以直接在下方输入你的答案`,noConfig:`请先在设置中配置 API 地址和模型`,requestFailed:`生成失败:{message}`,protocolError:`AI 返回的配置格式不正确,请重试或换个说法。`,timeout:`请求超时`,repairInstruction:`你上一次的输出不是合法 JSON。请严格按协议只输出一个 JSON 对象;所有键和字符串使用英文双引号,字符串内换行写成 \\n,不要代码块和解释。`,created:`助手「{name}」已创建并切换`,updated:`助手「{name}」已更新`,saveFailed:`保存失败:{message}`,changedTitle:`本次修改`,fieldName:`名称`,fieldIcon:`图标`,fieldDescription:`描述`,fieldPrompt:`系统提示词`,fieldTools:`工具`,fieldSkills:`技能`,fieldSubDispatch:`子任务分发`,noChanges:`配置没有变化,已跳过保存。`,undo:`撤销本次修改`,undone:`已撤销本次修改`,undoFailed:`撤销失败:{message}`,promptLabel:`系统提示词`,toolsLabel:`工具`,skillsLabel:`技能`,inheritTools:`继承全局(全部工具)`,inheritSkills:`继承全部启用技能`,continueAdjust:`继续调整`,editInEditor:`在编辑器中微调`,finish:`完成`,adjustHint:`可以直接说想改什么,例如:把输出改成英文、只保留网页相关工具。`,warnIconFallback:`图标不可用,已使用默认图标`,warnPromptShort:`提示词偏短,建议在编辑器中补充`,warnToolsDropped:`已忽略 {count} 个不可用的工具:{names}`,warnSkillsDropped:`已忽略 {count} 个不可用的技能:{names}`,warnToolsAllDropped:`所有推荐工具都不可用,已继承全部工具,请在编辑器中确认权限范围`,warnSkillsAllDropped:`所有推荐技能都不可用,已继承全部启用技能`,roundCapHint:`澄清轮数已达上限,本轮必须直接输出 done,不要再提问。`}}),n(`en`,{agentBuilder:{title:`Create assistant with AI`,subtitle:`Describe your need; AI asks a few questions and builds the config`,entry:`Create with AI`,editorBanner:`Not sure what to fill in? Let AI ask a few questions →`,editBanner:`Adjust this assistant with AI →`,editConfirmTitle:`Adjust with AI`,editConfirmMessage:`AI will modify the saved configuration. Unsaved edits in this form will not be carried over. Continue?`,greeting:`Tell me what you want this assistant to do. I will ask a few key questions and then create it.`,editGreeting:`Loaded "{name}". What would you like to change? For example: make it more concise, keep only web tools, or output in English.`,editExample1:`Make it more concise`,editExample2:`Keep only web tools`,editExample3:`Output in English`,example1:`Summarize my weekly report`,example2:`Review my code`,example3:`Scrape table data from a page`,placeholder:`Describe your need, e.g. summarize tech news every day…`,send:`Send`,hint:`Up to 3 clarification rounds, then it creates automatically`,restart:`Restart`,thinking:`Understanding your need…`,recommended:`Recommended`,customHint:`You can also type your answer below`,noConfig:`Please configure the API base and model in settings first`,requestFailed:`Generation failed: {message}`,protocolError:`AI returned an invalid configuration. Please retry or rephrase.`,timeout:`Request timed out`,repairInstruction:`Your previous output was not valid JSON. Output exactly one JSON object; use English double quotes and escape line breaks inside strings as \\n. No code fences or explanation.`,created:`Assistant "{name}" created and activated`,updated:`Assistant "{name}" updated`,saveFailed:`Save failed: {message}`,changedTitle:`Changed in this update`,fieldName:`Name`,fieldIcon:`Icon`,fieldDescription:`Description`,fieldPrompt:`System prompt`,fieldTools:`Tools`,fieldSkills:`Skills`,fieldSubDispatch:`Sub-task dispatch`,noChanges:`No configuration changes detected; save skipped.`,undo:`Undo this change`,undone:`Change undone`,undoFailed:`Undo failed: {message}`,promptLabel:`System prompt`,toolsLabel:`Tools`,skillsLabel:`Skills`,inheritTools:`Inherit global (all tools)`,inheritSkills:`Inherit all enabled skills`,continueAdjust:`Keep adjusting`,editInEditor:`Fine-tune in editor`,finish:`Done`,adjustHint:`Just say what to change, e.g. output in English, or keep only web tools.`,warnIconFallback:`Icon was invalid; default icon applied`,warnPromptShort:`Prompt is short; consider enriching it in the editor`,warnToolsDropped:`Ignored {count} unavailable tool(s): {names}`,warnSkillsDropped:`Ignored {count} unavailable skill(s): {names}`,warnToolsAllDropped:`None of the suggested tools were available; all global tools are inherited. Review permissions in the editor.`,warnSkillsAllDropped:`None of the suggested skills were available; all enabled skills are inherited.`,roundCapHint:`Clarification limit reached. Output done now without asking more questions.`}});var XE=8,Z={open:!1,catalog:null,catalogPromise:null,messages:[],askCount:0,pending:!1,controller:null,runId:0,createdAgentId:null,draft:null,callbacks:null,sessionMode:`create`,editingAgent:null,previousAgent:null},ZE=!1;function QE(e){return document.getElementById(e)}function Q(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=n),r}function $E(e,t=300){let n=String(e||``).replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t)}…`:n}function eD(){let e=QE(`agentBuilderChat`);e&&(e.scrollTop=e.scrollHeight)}function tD(e,t){let n=QE(`agentBuilderChat`);if(!n)return;let r=Q(`div`,`agent-builder-msg ${e}`,t);n.appendChild(r),eD()}function nD(e){let t=QE(`agentBuilderChat`);if(!t)return;let n=Q(`div`,`agent-builder-examples`);for(let t of e){let e=Q(`button`,`agent-builder-example`,t);e.type=`button`,e.dataset.example=t,n.appendChild(e)}t.appendChild(n),eD()}function rD(e){Z.pending=e;let t=QE(`agentBuilderSendBtn`);t&&(t.disabled=e);let n=QE(`agentBuilderChat`);if(!n)return;let i=n.querySelector(`.agent-builder-typing`);e&&!i?(n.appendChild(Q(`div`,`agent-builder-msg assistant agent-builder-typing`,r(`agentBuilder.thinking`))),eD()):!e&&i&&i.remove()}function iD(e){let t=QE(`agentBuilderComposer`);t&&(t.style.display=e?`flex`:`none`)}function aD(){let e=QE(`agentBuilderPanel`);e&&(e.innerHTML=``)}function oD(){if(Z.runId+=1,Z.controller){try{Z.controller.abort()}catch{}Z.controller=null}}async function sD(){let e={};try{e=await chrome.storage.local.get([`apiBase`,`apiKey`,`modelName`])}catch{}let t=String(e.apiBase||``).trim().replace(/\/+$/,``),n=String(e.modelName||``).trim();if(!t||!n)return F(r(`agentBuilder.noConfig`),`warning`),null;let i=k(e.apiKey),a={"Content-Type":`application/json`};return i&&(a.Authorization=`Bearer ${i}`),{apiBase:t,model:n,headers:a}}function cD(e,t=XE){if(e.length<=t)return e;let n=e[0]?.role===`user`?[e[0]]:[];return[...n,...e.slice(-(t-n.length))]}function lD(){let e=BE({language:a(),tools:Z.catalog?.tools||[],skills:Z.catalog?.skills||[],currentAgent:Z.editingAgent});return Z.askCount>=3&&(e+=`\n\n${r(`agentBuilder.roundCapHint`)}`),[{role:`system`,content:e},...cD(Z.messages)]}async function uD(){if(Z.catalogPromise)try{await Z.catalogPromise}catch{}}async function dD(e,t,n){let r=new AbortController;Z.controller=r;let i=setTimeout(()=>r.abort(),9e4);try{let i={model:e.model,temperature:t,max_tokens:2e3,messages:lD()};return n&&(i.response_format={type:`json_object`}),await se(`${e.apiBase}/chat/completions`,{headers:e.headers,body:i,useStream:await ye(),signal:r.signal})}finally{clearTimeout(i),Z.controller===r&&(Z.controller=null)}}async function fD(e=.3){let t=await sD();if(!t)throw Error(r(`agentBuilder.noConfig`));let n=await dD(t,e,!0);if(!n.ok&&[400,422].includes(n.status)&&(i.debug(`[AgentBuilder] json mode unsupported, retrying without response_format`),n=await dD(t,e,!1)),!n.ok)throw Error(`HTTP ${n.status}${n.errorText?`: ${n.errorText}`:``}`);return n.data?.choices?.[0]?.message?.content||``}function pD(e){let t=QE(`agentBuilderPanel`);if(!t)return;t.innerHTML=``;let n=Q(`div`,`agent-builder-q`);n.appendChild(Q(`div`,`agent-builder-q-text`,e.text));let i=Q(`div`,`agent-builder-options`);e.options.forEach((t,n)=>{let a=n===e.recommended,o=Q(`button`,`agent-builder-option${a?` recommended`:``}`,t);o.type=`button`,o.dataset.optionIndex=String(n),o.dataset.answer=t,a&&o.appendChild(Q(`span`,`agent-builder-badge`,r(`agentBuilder.recommended`))),i.appendChild(o)}),n.appendChild(i),e.allowCustom&&n.appendChild(Q(`div`,`agent-builder-custom-hint`,r(`agentBuilder.customHint`))),t.appendChild(n);let a=QE(`agentBuilderInput`);a&&a.focus()}function mD(e){switch(e.code){case`iconFallback`:return r(`agentBuilder.warnIconFallback`);case`promptShort`:return r(`agentBuilder.warnPromptShort`);case`toolsDropped`:return r(`agentBuilder.warnToolsDropped`,{count:e.count,names:(e.names||[]).join(`, `)});case`skillsDropped`:return r(`agentBuilder.warnSkillsDropped`,{count:e.count,names:(e.names||[]).join(`, `)});case`toolsAllDropped`:return r(`agentBuilder.warnToolsAllDropped`);case`skillsAllDropped`:return r(`agentBuilder.warnSkillsAllDropped`);default:return``}}function hD(e){return Z.catalog?.tools.find(t=>t.id===e)?.name||e}function gD(e,t){let n=Q(`div`,`agent-builder-tags`);if(!e||e.length===0)return n.appendChild(Q(`span`,`agent-builder-tag`,t)),n;for(let t of e)n.appendChild(Q(`span`,`agent-builder-tag`,t));return n}function _D(e){return{name:e.name,icon:e.icon,description:e.description,systemPrompt:e.systemPrompt,toolIds:e.toolIds??null,skillIds:e.skillIds??null,allowSubDispatch:e.allowSubDispatch===!0,model:e.model??null,temperature:e.temperature??null,topP:e.topP??null,mcpExcludedServerIds:Array.isArray(e.mcpExcludedServerIds)?e.mcpExcludedServerIds:null}}function vD(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function yD(e,t){let n=[];return(e.name||``)!==(t.name||``)&&n.push(`name`),(e.icon||``)!==(t.icon||``)&&n.push(`icon`),(e.description||``)!==(t.description||``)&&n.push(`description`),(e.systemPrompt||``)!==(t.systemPrompt||``)&&n.push(`prompt`),vD(e.toolIds,t.toolIds)||n.push(`tools`),vD(e.skillIds,t.skillIds)||n.push(`skills`),e.allowSubDispatch===!0!=(t.allowSubDispatch===!0)&&n.push(`subDispatch`),n}function bD(e){let t={name:`fieldName`,icon:`fieldIcon`,description:`fieldDescription`,prompt:`fieldPrompt`,tools:`fieldTools`,skills:`fieldSkills`,subDispatch:`fieldSubDispatch`}[e];return t?r(`agentBuilder.${t}`):e}async function xD(){let e=Z.createdAgentId,t=Z.previousAgent;if(!(!e||!t))try{let n=await mt(e,_D(t));if(!n)throw Error(`agent_not_found`);if(Z.editingAgent={...t},Z.previousAgent=null,Z.callbacks?.onAgentSaved)try{await Z.callbacks.onAgentSaved(n,{updated:!0})}catch(e){i.warn(`[AgentBuilder] onAgentSaved failed:`,e?.message||e)}F(r(`agentBuilder.undone`),`success`),SD(t,[],{changeSummary:r(`agentBuilder.undone`),changedFields:[],canUndo:!1}),iD(!1)}catch(e){i.warn(`[AgentBuilder] undo failed:`,e?.message||e),tD(`assistant error`,r(`agentBuilder.undoFailed`,{message:e?.message||``}))}}function SD(e,t,n={}){let i=QE(`agentBuilderPanel`);if(!i)return;i.innerHTML=``;let o=Q(`div`,`agent-builder-result`),s=Q(`div`,`agent-builder-result-head`);s.appendChild(Q(`span`,`agent-builder-result-icon`,e.icon));let c=Q(`div`,`agent-builder-result-info`);if(c.appendChild(Q(`div`,`agent-builder-result-name`,e.name)),c.appendChild(Q(`div`,`agent-builder-result-desc`,e.description||``)),s.appendChild(c),o.appendChild(s),n.changedFields&&n.changedFields.length>0||n.changeSummary){let e=Q(`div`,`agent-builder-section`);if(e.appendChild(Q(`div`,`agent-builder-section-title`,r(`agentBuilder.changedTitle`))),n.changedFields&&n.changedFields.length>0){let t=Q(`div`,`agent-builder-tags`);for(let e of n.changedFields)t.appendChild(Q(`span`,`agent-builder-tag`,bD(e)));e.appendChild(t)}n.changeSummary&&e.appendChild(Q(`div`,`agent-builder-change-note`,n.changeSummary)),o.appendChild(e)}let l=Q(`div`,`agent-builder-section`);l.appendChild(Q(`div`,`agent-builder-section-title`,r(`agentBuilder.promptLabel`))),l.appendChild(Q(`div`,`agent-builder-prompt`,e.systemPrompt||``)),o.appendChild(l);let u=Q(`div`,`agent-builder-section`);u.appendChild(Q(`div`,`agent-builder-section-title`,r(`agentBuilder.toolsLabel`)));let d=e.toolIds?e.toolIds.map(hD):null;u.appendChild(gD(d,r(`agentBuilder.inheritTools`))),o.appendChild(u);let f=Q(`div`,`agent-builder-section`);f.appendChild(Q(`div`,`agent-builder-section-title`,r(`agentBuilder.skillsLabel`))),f.appendChild(gD(e.skillIds,r(`agentBuilder.inheritSkills`))),o.appendChild(f);let p=(t||[]).map(mD).filter(Boolean);if(p.length>0){let e=a()===`en`?`; `:`;`;o.appendChild(Q(`div`,`agent-builder-warn`,p.join(e)))}let m=Q(`div`,`agent-builder-actions`);if(n.canUndo){let e=Q(`button`,`modal-btn cancel`,r(`agentBuilder.undo`));e.type=`button`,e.dataset.action=`undo`,m.appendChild(e)}let h=Q(`button`,`modal-btn cancel`,r(`agentBuilder.continueAdjust`));h.type=`button`,h.dataset.action=`continue`;let g=Q(`button`,`modal-btn cancel`,r(`agentBuilder.editInEditor`));g.type=`button`,g.dataset.action=`edit`;let _=Q(`button`,`modal-btn confirm`,r(`agentBuilder.finish`));_.type=`button`,_.dataset.action=`finish`,m.append(h,g,_),o.appendChild(m),i.appendChild(o)}async function CD(e,t=``){let n=Z.editingAgent,{draft:o,warnings:s}=YE(e,{tools:Z.catalog?.tools||[],skills:Z.catalog?.skills||[],language:a(),baseAgent:n});Z.draft=o;let c=!!Z.createdAgentId,l=n?yD(n,o):[];if(c&&n&&l.length===0){tD(`assistant`,r(`agentBuilder.noChanges`)),iD(!0);return}let u=null;try{if(c){if(u=await mt(Z.createdAgentId,o),!u)throw Error(`agent_not_found`);Z.previousAgent=n?{...n}:null,Z.editingAgent={...u},F(r(`agentBuilder.updated`,{name:o.name}),`success`)}else u=await gt(o),Z.createdAgentId=u.id,Z.editingAgent={...u},F(r(`agentBuilder.created`,{name:u.name}),`success`)}catch(e){i.error(`[AgentBuilder] save failed:`,e),tD(`assistant error`,r(`agentBuilder.saveFailed`,{message:e?.message||``}));return}if(Z.callbacks?.onAgentSaved)try{await Z.callbacks.onAgentSaved(u,{updated:c})}catch(e){i.warn(`[AgentBuilder] onAgentSaved failed:`,e?.message||e)}SD(o,s,{changeSummary:c&&n?t:``,changedFields:c&&n?l:[],canUndo:c&&!!Z.previousAgent}),iD(!1)}async function wD(e){let t=String(e||``).trim();if(!t||Z.pending)return;aD(),QE(`agentBuilderChat`)?.querySelector(`.agent-builder-examples`)?.remove(),tD(`user`,t),Z.messages.push({role:`user`,content:t}),rD(!0);let n=++Z.runId;try{if(await uD(),n!==Z.runId||!Z.open)return;let e=await fD();if(n!==Z.runId||!Z.open)return;let t;try{t=JE(e)}catch(a){if(i.warn(`[AgentBuilder] invalid reply, retrying once:`,a?.message,`| raw:`,$E(e)),Z.messages.push({role:`assistant`,content:e||``}),Z.messages.push({role:`user`,content:r(`agentBuilder.repairInstruction`)}),e=await fD(0),n!==Z.runId||!Z.open)return;t=JE(e)}Z.messages.push({role:`assistant`,content:e}),t.message&&tD(`assistant`,t.message),t.action===`ask`?(Z.askCount+=1,pD(t.question)):await CD(t.agent,t.message)}catch(e){if(n!==Z.runId)return;i.warn(`[AgentBuilder] request failed:`,e?.message||e);let t=new Set([`empty_reply`,`no_json_object`,`invalid_json`,`invalid_action`,`invalid_question`,`invalid_agent`]),a=e?.message||``;e?.name===`AbortError`?a=r(`agentBuilder.timeout`):t.has(a)&&(a=r(`agentBuilder.protocolError`)),tD(`assistant error`,r(`agentBuilder.requestFailed`,{message:a}))}finally{n===Z.runId&&rD(!1)}}function TD(){if(Z.editingAgent){tD(`assistant`,r(`agentBuilder.editGreeting`,{name:Z.editingAgent.name})),nD([r(`agentBuilder.editExample1`),r(`agentBuilder.editExample2`),r(`agentBuilder.editExample3`)]);return}tD(`assistant`,r(`agentBuilder.greeting`)),nD([r(`agentBuilder.example1`),r(`agentBuilder.example2`),r(`agentBuilder.example3`)])}function ED(){oD(),Z.messages=[],Z.askCount=0,Z.draft=null,Z.pending=!1,Z.previousAgent=null,Z.sessionMode===`edit`&&Z.editingAgent?Z.createdAgentId=Z.editingAgent.id||null:(Z.editingAgent=null,Z.createdAgentId=null);let e=QE(`agentBuilderChat`);e&&(e.innerHTML=``),aD(),iD(!0),rD(!1);let t=QE(`agentBuilderInput`);t&&(t.value=``),TD()}async function DD({agent:e=null,onAgentSaved:t,onEditAgent:n}={}){let r=QE(`agentBuilderModal`);if(!r)return;Z.sessionMode=e?`edit`:`create`,Z.editingAgent=e?{...e}:null,Z.callbacks={onAgentSaved:t,onEditAgent:n},Z.open=!0,r.style.display=`flex`,ED(),Z.catalogPromise=(async()=>{try{Z.catalog=await jE()}catch(e){i.warn(`[AgentBuilder] load catalog failed:`,e?.message||e),Z.catalog={tools:[],skills:[]}}})();let a=QE(`agentBuilderInput`);a&&a.focus()}function OD(){oD(),Z.open=!1,Z.pending=!1;let e=QE(`agentBuilderModal`);e&&(e.style.display=`none`)}function kD(){ZE||QE(`agentBuilderModal`)&&(ZE=!0,QE(`agentBuilderCloseBtn`)?.addEventListener(`click`,OD),QE(`agentBuilderRestartBtn`)?.addEventListener(`click`,ED),QE(`agentBuilderSendBtn`)?.addEventListener(`click`,()=>{let e=QE(`agentBuilderInput`),t=e?.value||``;e&&(e.value=``),wD(t)}),QE(`agentBuilderInput`)?.addEventListener(`keydown`,e=>{if(e.key===`Enter`&&!e.shiftKey&&!e.isComposing){e.preventDefault();let t=e.target,n=t.value||``;t.value=``,wD(n)}}),QE(`agentBuilderChat`)?.addEventListener(`click`,e=>{let t=e.target.closest(`[data-example]`);!t||Z.pending||wD(t.dataset.example||``)}),QE(`agentBuilderPanel`)?.addEventListener(`click`,e=>{let t=e.target.closest(`[data-option-index]`);if(t){if(Z.pending)return;wD(t.dataset.answer||``);return}let n=e.target.closest(`[data-action]`);if(!n)return;let i=n.dataset.action;if(i===`undo`)xD();else if(i===`continue`)aD(),Z.askCount=0,tD(`assistant`,r(`agentBuilder.adjustHint`)),iD(!0),QE(`agentBuilderInput`)?.focus();else if(i===`edit`){let e=Z.createdAgentId,t=Z.callbacks?.onEditAgent;OD(),e&&t&&t(e)}else i===`finish`&&OD()}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&Z.open&&OD()}))}var AD=[[`🀄`,`mahjong tile red dragon`,`symbols`,`麻将,红中`],[`🃏`,`playing card black joker`,`symbols`,``],[`🅰`,`negative squared latin capital letter a`,`symbols`,``],[`🅱`,`negative squared latin capital letter b`,`symbols`,``],[`🅾`,`negative squared latin capital letter o`,`symbols`,``],[`🅿`,`negative squared latin capital letter p`,`symbols`,``],[`🆎`,`negative squared ab`,`symbols`,``],[`🆑`,`squared cl`,`symbols`,``],[`🆒`,`squared cool`,`symbols`,``],[`🆓`,`squared free`,`symbols`,``],[`🆔`,`squared id`,`symbols`,``],[`🆕`,`squared new`,`symbols`,``],[`🆖`,`squared ng`,`symbols`,``],[`🆗`,`squared ok`,`symbols`,``],[`🆘`,`squared sos`,`symbols`,``],[`🆙`,`squared up with exclamation mark`,`symbols`,``],[`🆚`,`squared vs`,`symbols`,``],[`🇨🇩`,`regional indicator symbol letter c`,`flags`,``],[`🇬🇭`,`regional indicator symbol letter g`,`flags`,``],[`🇲🇳`,`regional indicator symbol letter m`,`flags`,``],[`🇷🇸`,`regional indicator symbol letter r`,`flags`,``],[`🈁`,`squared katakana koko`,`symbols`,``],[`🈂`,`squared katakana sa`,`symbols`,``],[`🈚`,`squared cjk unified ideograph-7121`,`symbols`,``],[`🈯`,`squared cjk unified ideograph-6307`,`symbols`,``],[`🈲`,`squared cjk unified ideograph-7981`,`symbols`,``],[`🈳`,`squared cjk unified ideograph-7a7a`,`symbols`,``],[`🈴`,`squared cjk unified ideograph-5408`,`symbols`,``],[`🈵`,`squared cjk unified ideograph-6e80`,`symbols`,``],[`🈶`,`squared cjk unified ideograph-6709`,`symbols`,``],[`🈷`,`squared cjk unified ideograph-6708`,`symbols`,``],[`🈸`,`squared cjk unified ideograph-7533`,`symbols`,``],[`🈹`,`squared cjk unified ideograph-5272`,`symbols`,``],[`🈺`,`squared cjk unified ideograph-55b6`,`symbols`,``],[`🉐`,`circled ideograph advantage`,`symbols`,``],[`🉑`,`circled ideograph accept`,`symbols`,``],[`🌀`,`cyclone`,`symbols`,`台风,龙卷风,旋风`],[`🌁`,`foggy`,`symbols`,`雾,雾霾,朦胧`],[`🌂`,`closed umbrella`,`symbols`,``],[`🌃`,`night with stars`,`symbols`,`夜晚,星空,城市`],[`🌄`,`sunrise over mountains`,`symbols`,`日出,山,早晨`],[`🌅`,`sunrise`,`symbols`,`日出,太阳,早晨`],[`🌆`,`cityscape at dusk`,`symbols`,`黄昏,傍晚,城市`],[`🌇`,`sunset over buildings`,`symbols`,`日落,黄昏`],[`🌈`,`rainbow`,`symbols`,`彩虹,雨后`],[`🌉`,`bridge at night`,`symbols`,`桥,大桥`],[`🌊`,`water wave`,`symbols`,`海浪,波浪,海`],[`🌋`,`volcano`,`symbols`,`火山,爆发`],[`🌌`,`milky way`,`symbols`,``],[`🌍`,`earth globe europe-africa`,`symbols`,``],[`🌎`,`earth globe americas`,`symbols`,`地球,美洲`],[`🌏`,`earth globe asia-australia`,`symbols`,`地球,亚洲`],[`🌐`,`globe with meridians`,`symbols`,``],[`🌑`,`new moon symbol`,`symbols`,``],[`🌒`,`waxing crescent moon symbol`,`symbols`,``],[`🌓`,`first quarter moon symbol`,`symbols`,``],[`🌔`,`waxing gibbous moon symbol`,`symbols`,``],[`🌕`,`full moon symbol`,`symbols`,``],[`🌖`,`waning gibbous moon symbol`,`symbols`,``],[`🌗`,`last quarter moon symbol`,`symbols`,``],[`🌘`,`waning crescent moon symbol`,`symbols`,``],[`🌙`,`crescent moon`,`symbols`,``],[`🌚`,`new moon with face`,`symbols`,``],[`🌛`,`first quarter moon with face`,`symbols`,``],[`🌜`,`last quarter moon with face`,`symbols`,``],[`🌝`,`full moon with face`,`symbols`,``],[`🌞`,`sun with face`,`symbols`,``],[`🌟`,`glowing star`,`symbols`,`星星,闪光,闪耀`],[`🌠`,`shooting star`,`symbols`,``],[`🌡`,`thermometer`,`symbols`,``],[`🌤`,`white sun with small cloud`,`symbols`,``],[`🌥`,`white sun behind cloud`,`symbols`,``],[`🌦`,`white sun behind cloud with rain`,`symbols`,``],[`🌧`,`cloud with rain`,`symbols`,``],[`🌨`,`cloud with snow`,`symbols`,``],[`🌩`,`cloud with lightning`,`symbols`,``],[`🌪`,`cloud with tornado`,`symbols`,``],[`🌫`,`fog`,`symbols`,``],[`🌬`,`wind blowing face`,`symbols`,``],[`🌭`,`hot dog`,`food`,`热狗`],[`🌮`,`taco`,`food`,`墨西哥卷饼`],[`🌯`,`burrito`,`food`,`墨西哥卷,卷饼`],[`🌰`,`chestnut`,`food`,`栗子,坚果`],[`🌱`,`seedling`,`food`,``],[`🌲`,`evergreen tree`,`food`,`松树,树`],[`🌳`,`deciduous tree`,`food`,`树,大树`],[`🌴`,`palm tree`,`food`,`棕榈树,热带,度假`],[`🌵`,`cactus`,`food`,`仙人掌,沙漠`],[`🌶`,`hot pepper`,`food`,``],[`🌷`,`tulip`,`food`,`郁金香,花`],[`🌸`,`cherry blossom`,`food`,`樱花,花,春天`],[`🌹`,`rose`,`food`,`玫瑰,花,爱情`],[`🌺`,`hibiscus`,`food`,`花,芙蓉`],[`🌻`,`sunflower`,`food`,`向日葵,花,太阳`],[`🌼`,`blossom`,`food`,`雏菊,花`],[`🌽`,`ear of maize`,`food`,`玉米`],[`🌾`,`ear of rice`,`food`,``],[`🌿`,`herb`,`food`,`草,植物,草药`],[`🍀`,`four leaf clover`,`food`,`四叶草,幸运,好运`],[`🍁`,`maple leaf`,`food`,`枫叶,秋天,红叶`],[`🍂`,`fallen leaf`,`food`,`落叶,秋天`],[`🍃`,`leaf fluttering in wind`,`food`,`树叶,风`],[`🍄`,`mushroom`,`food`,`蘑菇,菌`],[`🍅`,`tomato`,`food`,`番茄,西红柿`],[`🍆`,`aubergine`,`food`,`茄子`],[`🍇`,`grapes`,`food`,`葡萄`],[`🍈`,`melon`,`food`,`哈密瓜,甜瓜`],[`🍉`,`watermelon`,`food`,`西瓜`],[`🍊`,`tangerine`,`food`,`橙子,橘子`],[`🍋`,`lemon`,`food`,`柠檬`],[`🍌`,`banana`,`food`,`香蕉`],[`🍍`,`pineapple`,`food`,`菠萝`],[`🍎`,`red apple`,`food`,`苹果`],[`🍏`,`green apple`,`food`,``],[`🍐`,`pear`,`food`,`梨`],[`🍑`,`peach`,`food`,`桃子,蜜桃`],[`🍒`,`cherries`,`food`,`樱桃,车厘子`],[`🍓`,`strawberry`,`food`,`草莓`],[`🍔`,`hamburger`,`food`,`汉堡,汉堡包`],[`🍕`,`slice of pizza`,`food`,`披萨,比萨`],[`🍖`,`meat on bone`,`food`,`骨头,肉,排骨`],[`🍗`,`poultry leg`,`food`,`鸡腿,炸鸡`],[`🍘`,`rice cracker`,`food`,`米饼,仙贝`],[`🍙`,`rice ball`,`food`,`饭团`],[`🍚`,`cooked rice`,`food`,`米饭,饭`],[`🍛`,`curry and rice`,`food`,`咖喱,咖喱饭`],[`🍜`,`steaming bowl`,`food`,`面条,拉面,面`],[`🍝`,`spaghetti`,`food`,`意大利面,意面`],[`🍞`,`bread`,`food`,`面包`],[`🍟`,`french fries`,`food`,`薯条,炸薯条`],[`🍠`,`roasted sweet potato`,`food`,`红薯,地瓜`],[`🍡`,`dango`,`food`,`团子,丸子`],[`🍢`,`oden`,`food`,`关东煮,串`],[`🍣`,`sushi`,`food`,`寿司,三文鱼`],[`🍤`,`fried shrimp`,`food`,`炸虾,天妇罗`],[`🍥`,`fish cake with swirl design`,`food`,`鱼板,鸣门卷`],[`🍦`,`soft ice cream`,`food`,`冰淇淋,甜筒`],[`🍧`,`shaved ice`,`food`,`刨冰,冰沙`],[`🍨`,`ice cream`,`food`,`冰淇淋,圣代`],[`🍩`,`doughnut`,`food`,``],[`🍪`,`cookie`,`food`,``],[`🍫`,`chocolate bar`,`food`,`巧克力`],[`🍬`,`candy`,`food`,`糖果,糖`],[`🍭`,`lollipop`,`food`,`棒棒糖`],[`🍮`,`custard`,`food`,`布丁,焦糖`],[`🍯`,`honey pot`,`food`,`蜂蜜,蜜`],[`🍰`,`shortcake`,`food`,`蛋糕,奶油蛋糕`],[`🍱`,`bento box`,`food`,`便当,盒饭`],[`🍲`,`pot of food`,`food`,`火锅,汤锅,炖菜`],[`🍳`,`cooking`,`food`,`煎蛋,鸡蛋`],[`🍴`,`fork and knife`,`food`,`刀叉,餐具`],[`🍵`,`teacup without handle`,`food`,`绿茶,茶,抹茶`],[`🍶`,`sake bottle and cup`,`food`,`清酒,日本酒`],[`🍷`,`wine glass`,`food`,`红酒,葡萄酒,酒`],[`🍸`,`cocktail glass`,`food`,`鸡尾酒,马提尼`],[`🍹`,`tropical drink`,`food`,`果汁,鸡尾酒`],[`🍺`,`beer mug`,`food`,`啤酒,啤酒杯`],[`🍻`,`clinking beer mugs`,`food`,`干杯,碰杯,啤酒`],[`🍼`,`baby bottle`,`food`,`奶瓶,婴儿,奶粉`],[`🍽`,`fork and knife with plate`,`food`,``],[`🍾`,`bottle with popping cork`,`food`,`香槟,起泡酒,庆祝`],[`🍿`,`popcorn`,`food`,``],[`🎀`,`ribbon`,`activity`,`蝴蝶结,礼物,装饰`],[`🎁`,`wrapped present`,`activity`,`礼物,礼盒,生日`],[`🎂`,`birthday cake`,`activity`,`生日蛋糕,生日,蛋糕`],[`🎃`,`jack-o-lantern`,`activity`,``],[`🎄`,`christmas tree`,`activity`,``],[`🎅`,`father christmas`,`activity`,`圣诞老人,圣诞,圣诞节`],[`🎆`,`fireworks`,`activity`,``],[`🎇`,`firework sparkler`,`activity`,``],[`🎈`,`balloon`,`activity`,`气球,庆祝,派对`],[`🎉`,`party popper`,`activity`,`彩带,庆祝,派对,欢呼`],[`🎊`,`confetti ball`,`activity`,`庆祝`],[`🎋`,`tanabata tree`,`activity`,``],[`🎌`,`crossed flags`,`flags`,`旗,日本,交叉旗`],[`🎍`,`pine decoration`,`activity`,``],[`🎎`,`japanese dolls`,`activity`,`人偶,日本人偶`],[`🎏`,`carp streamer`,`activity`,`鲤鱼旗,日本,端午节`],[`🎐`,`wind chime`,`activity`,`风铃,夏天`],[`🎑`,`moon viewing ceremony`,`activity`,``],[`🎒`,`school satchel`,`activity`,`书包,背包`],[`🎓`,`graduation cap`,`activity`,`学士帽,毕业,学位`],[`🎖`,`military medal`,`activity`,``],[`🎗`,`reminder ribbon`,`activity`,``],[`🎙`,`studio microphone`,`activity`,``],[`🎚`,`level slider`,`activity`,``],[`🎛`,`control knobs`,`activity`,``],[`🎞`,`film frames`,`activity`,``],[`🎟`,`admission tickets`,`activity`,``],[`🎠`,`carousel horse`,`activity`,`旋转木马,游乐园`],[`🎡`,`ferris wheel`,`activity`,`摩天轮,游乐园`],[`🎢`,`roller coaster`,`activity`,`过山车,游乐园`],[`🎣`,`fishing pole and fish`,`activity`,`钓鱼`],[`🎤`,`microphone`,`activity`,`麦克风,唱歌,K歌`],[`🎥`,`movie camera`,`activity`,`摄影机,电影,拍摄`],[`🎦`,`cinema`,`activity`,``],[`🎧`,`headphone`,`activity`,`耳机,听歌,音乐,戴`],[`🎨`,`artist palette`,`activity`,`调色板,画画,美术,艺术`],[`🎩`,`top hat`,`activity`,`礼帽,魔术帽,帽子`],[`🎪`,`circus tent`,`activity`,`马戏团`],[`🎫`,`ticket`,`activity`,`门票,票,入场券`],[`🎬`,`clapper board`,`activity`,`场记板,电影,拍戏,导演`],[`🎭`,`performing arts`,`activity`,`面具,戏剧,表演,舞台`],[`🎮`,`video game`,`activity`,`游戏机,游戏,手柄,玩`],[`🎯`,`direct hit`,`activity`,`目标`],[`🎰`,`slot machine`,`activity`,``],[`🎱`,`billiards`,`activity`,`台球`],[`🎲`,`game die`,`activity`,`骰子,赌博,游戏`],[`🎳`,`bowling`,`activity`,`保龄球,球`],[`🎴`,`flower playing cards`,`activity`,`花牌,卡牌,纸牌`],[`🎵`,`musical note`,`activity`,`音符,音乐,歌`],[`🎶`,`multiple musical notes`,`activity`,`音符,音乐,唱歌`],[`🎷`,`saxophone`,`activity`,`萨克斯,爵士,乐器`],[`🎸`,`guitar`,`activity`,`吉他,弹吉他,摇滚`],[`🎹`,`musical keyboard`,`activity`,`钢琴,键盘,弹琴`],[`🎺`,`trumpet`,`activity`,`小号,喇叭,乐器`],[`🎻`,`violin`,`activity`,`小提琴,弦乐`],[`🎼`,`musical score`,`activity`,`乐谱,音乐,谱`],[`🎽`,`running shirt with sash`,`activity`,`背心`],[`🎾`,`tennis racquet and ball`,`activity`,`网球,球`],[`🎿`,`ski and ski boot`,`activity`,`滑雪`],[`🏀`,`basketball and hoop`,`activity`,`篮球,球`],[`🏁`,`chequered flag`,`flags`,`终点,旗帜,赛车,比赛`],[`🏂`,`snowboarder`,`activity`,``],[`🏃`,`runner`,`activity`,`跑步,跑,奔跑`],[`🏄`,`surfer`,`activity`,``],[`🏅`,`sports medal`,`activity`,`奖牌,奖章,荣誉`],[`🏆`,`trophy`,`activity`,``],[`🏇`,`horse racing`,`activity`,``],[`🏈`,`american football`,`activity`,`橄榄球,美式足球`],[`🏉`,`rugby football`,`activity`,`橄榄球,英式`],[`🏊`,`swimmer`,`activity`,``],[`🏋`,`weight lifter`,`activity`,``],[`🏌`,`golfer`,`activity`,``],[`🏍`,`racing motorcycle`,`activity`,``],[`🏎`,`racing car`,`activity`,``],[`🏏`,`cricket bat and ball`,`activity`,``],[`🏐`,`volleyball`,`activity`,`排球,球`],[`🏑`,`field hockey stick and ball`,`activity`,``],[`🏒`,`ice hockey stick and puck`,`activity`,``],[`🏓`,`table tennis paddle and ball`,`activity`,`乒乓球,乒乓,球`],[`🏔`,`snow capped mountain`,`activity`,``],[`🏕`,`camping`,`activity`,``],[`🏖`,`beach with umbrella`,`activity`,``],[`🏗`,`building construction`,`activity`,``],[`🏘`,`house buildings`,`activity`,``],[`🏙`,`cityscape`,`activity`,``],[`🏚`,`derelict house building`,`activity`,``],[`🏛`,`classical building`,`activity`,``],[`🏜`,`desert`,`activity`,``],[`🏝`,`desert island`,`activity`,``],[`🏞`,`national park`,`activity`,``],[`🏟`,`stadium`,`activity`,``],[`🏠`,`house building`,`travel`,`房子,家,住宅`],[`🏡`,`house with garden`,`travel`,`房子,家,花园`],[`🏢`,`office building`,`travel`,`办公楼,大楼,写字楼`],[`🏣`,`japanese post office`,`travel`,`邮局,邮政`],[`🏤`,`european post office`,`travel`,`邮局`],[`🏥`,`hospital`,`travel`,`医院,医疗`],[`🏦`,`bank`,`travel`,`银行,金融`],[`🏧`,`automated teller machine`,`travel`,``],[`🏨`,`hotel`,`travel`,`酒店,旅馆`],[`🏩`,`love hotel`,`travel`,`爱情旅馆,酒店`],[`🏪`,`convenience store`,`travel`,`便利店,商店`],[`🏫`,`school`,`travel`,`学校,校园`],[`🏬`,`department store`,`travel`,`商场,百货,购物`],[`🏭`,`factory`,`travel`,`工厂,工业`],[`🏮`,`izakaya lantern`,`travel`,``],[`🏯`,`japanese castle`,`objects`,`城堡,日本城堡`],[`🏰`,`european castle`,`travel`,`城堡,童话`],[`🏳`,`waving white flag`,`flags`,``],[`🏴`,`waving black flag`,`flags`,`黑旗`],[`🏵`,`rosette`,`objects`,``],[`🏷`,`label`,`objects`,``],[`🏸`,`badminton racquet and shuttlecock`,`activity`,`羽毛球,球`],[`🏹`,`bow and arrow`,`activity`,`射箭,弓箭,弓`],[`🏺`,`amphora`,`activity`,`陶罐,花瓶,双耳瓶`],[`🏻`,`emoji modifier fitzpatrick type-1-2`,`symbols`,``],[`🏼`,`emoji modifier fitzpatrick type-3`,`symbols`,``],[`🏽`,`emoji modifier fitzpatrick type-4`,`symbols`,``],[`🏾`,`emoji modifier fitzpatrick type-5`,`symbols`,``],[`🏿`,`emoji modifier fitzpatrick type-6`,`symbols`,``],[`🐀`,`rat`,`animals`,`老鼠,鼠`],[`🐁`,`mouse`,`animals`,`老鼠,鼠`],[`🐂`,`ox`,`animals`,`公牛,牛`],[`🐃`,`water buffalo`,`animals`,`水牛,牛`],[`🐄`,`cow`,`animals`,`奶牛,牛`],[`🐅`,`tiger`,`animals`,``],[`🐆`,`leopard`,`animals`,``],[`🐇`,`rabbit`,`animals`,`兔子,兔`],[`🐈`,`cat`,`animals`,`猫,猫咪`],[`🐉`,`dragon`,`animals`,`龙,中国龙`],[`🐊`,`crocodile`,`animals`,`鳄鱼,短吻鳄`],[`🐋`,`whale`,`animals`,`鲸鱼`],[`🐌`,`snail`,`animals`,``],[`🐍`,`snake`,`animals`,`蛇,爬行动物`],[`🐎`,`horse`,`animals`,``],[`🐏`,`ram`,`animals`,`羊,公羊`],[`🐐`,`goat`,`animals`,`山羊,羊`],[`🐑`,`sheep`,`animals`,`羊,绵羊`],[`🐒`,`monkey`,`animals`,``],[`🐓`,`rooster`,`animals`,`公鸡,鸡`],[`🐔`,`chicken`,`animals`,`鸡,母鸡`],[`🐕`,`dog`,`animals`,`狗,小狗`],[`🐖`,`pig`,`animals`,`猪`],[`🐗`,`boar`,`animals`,`野猪,猪`],[`🐘`,`elephant`,`animals`,`大象`],[`🐙`,`octopus`,`animals`,`章鱼,八爪鱼`],[`🐚`,`spiral shell`,`animals`,``],[`🐛`,`bug`,`animals`,``],[`🐜`,`ant`,`animals`,``],[`🐝`,`honeybee`,`animals`,``],[`🐞`,`lady beetle`,`animals`,``],[`🐟`,`fish`,`animals`,`鱼,鱼`],[`🐠`,`tropical fish`,`animals`,`热带鱼,鱼`],[`🐡`,`blowfish`,`animals`,`河豚,鱼`],[`🐢`,`turtle`,`animals`,`乌龟,慢`],[`🐣`,`hatching chick`,`animals`,`小鸡,破壳,孵化`],[`🐤`,`baby chick`,`animals`,`小鸡,黄,可爱`],[`🐥`,`front-facing baby chick`,`animals`,`小鸡,正面`],[`🐦`,`bird`,`animals`,`鸟`],[`🐧`,`penguin`,`animals`,`企鹅,南极`],[`🐨`,`koala`,`animals`,`考拉,无尾熊`],[`🐩`,`poodle`,`animals`,`贵宾犬,狗`],[`🐪`,`dromedary camel`,`animals`,`骆驼`],[`🐫`,`bactrian camel`,`animals`,`骆驼,双峰`],[`🐬`,`dolphin`,`animals`,`海豚,海洋`],[`🐭`,`mouse face`,`animals`,`老鼠,鼠`],[`🐮`,`cow face`,`animals`,`牛,奶牛`],[`🐯`,`tiger face`,`animals`,``],[`🐰`,`rabbit face`,`animals`,`兔子,兔,可爱`],[`🐱`,`cat face`,`animals`,``],[`🐲`,`dragon face`,`animals`,`龙,龙头`],[`🐳`,`spouting whale`,`animals`,`鲸鱼,喷水`],[`🐴`,`horse face`,`animals`,`马`],[`🐵`,`monkey face`,`animals`,``],[`🐶`,`dog face`,`animals`,``],[`🐷`,`pig face`,`animals`,`猪,猪头`],[`🐸`,`frog face`,`animals`,`青蛙,蛙`],[`🐹`,`hamster face`,`animals`,`仓鼠`],[`🐺`,`wolf face`,`animals`,``],[`🐻`,`bear face`,`animals`,`熊,泰迪熊`],[`🐼`,`panda face`,`animals`,``],[`🐽`,`pig nose`,`animals`,`猪鼻子,猪`],[`🐾`,`paw prints`,`animals`,`爪印,脚印`],[`🐿`,`chipmunk`,`animals`,``],[`👀`,`eyes`,`people`,``],[`👁`,`eye`,`people`,``],[`👂`,`ear`,`people`,`耳朵,听`],[`👃`,`nose`,`people`,`鼻子,闻`],[`👄`,`mouth`,`people`,`嘴巴,嘴唇,吻`],[`👅`,`tongue`,`people`,`舌头,舔`],[`👆`,`white up pointing backhand index`,`people`,`指,上面,向上`],[`👇`,`white down pointing backhand index`,`people`,`指,下面,向下`],[`👈`,`white left pointing backhand index`,`people`,`指,左边,指向`],[`👉`,`white right pointing backhand index`,`people`,`指,右边,指向`],[`👊`,`fisted hand sign`,`people`,`拳头,打,战斗`],[`👋`,`waving hand sign`,`people`,`挥手,再见,你好`],[`👌`,`ok hand sign`,`people`,`OK,好,可以`],[`👍`,`thumbs up sign`,`people`,`点赞,好,赞,棒`],[`👎`,`thumbs down sign`,`people`,`差评,不好,踩`],[`👏`,`clapping hands sign`,`people`,`鼓掌,拍手,掌声`],[`👐`,`open hands sign`,`people`,`张开,手,开放`],[`👑`,`crown`,`people`,`皇冠,王冠,国王,女王`],[`👒`,`womans hat`,`people`,`帽子,草帽,遮阳帽`],[`👓`,`eyeglasses`,`people`,`眼镜`],[`👔`,`necktie`,`people`,`领带,西装,工作`],[`👕`,`t-shirt`,`people`,`衣服,T恤`],[`👖`,`jeans`,`people`,`裤子,牛仔裤`],[`👗`,`dress`,`people`,`裙子,连衣裙`],[`👘`,`kimono`,`people`,`和服`],[`👙`,`bikini`,`people`,`比基尼,泳装`],[`👚`,`womans clothes`,`people`,`女装,衣服`],[`👛`,`purse`,`people`,`钱包,小包`],[`👜`,`handbag`,`people`,`手提包,包包`],[`👝`,`pouch`,`people`,`手拿包,包包`],[`👞`,`mans shoe`,`people`,`皮鞋,鞋`],[`👟`,`athletic shoe`,`people`,`运动鞋,跑鞋`],[`👠`,`high-heeled shoe`,`people`,`高跟鞋,鞋`],[`👡`,`womans sandal`,`people`,`凉鞋,鞋`],[`👢`,`womans boots`,`people`,`靴子,长靴`],[`👣`,`footprints`,`people`,`脚印,脚步,足迹`],[`👤`,`bust in silhouette`,`people`,`人,剪影,用户`],[`👥`,`busts in silhouette`,`people`,`人群,人,多个人`],[`👦`,`boy`,`people`,`男孩,小男孩`],[`👧`,`girl`,`people`,`女孩,小女孩`],[`👨`,`man`,`people`,`男人,男士`],[`👩`,`woman`,`people`,`女人,女士`],[`👪`,`family`,`people`,`家庭`],[`👫`,`woman and man holding hands`,`people`,``],[`👬`,`men holding hands`,`people`,``],[`👭`,`women holding hands`,`people`,``],[`👮`,`police officer`,`people`,`警察,警官`],[`👯`,`woman with bunny ears`,`people`,`兔子舞,蹦迪,派对`],[`👰`,`bride with veil`,`people`,`新娘,婚纱,结婚`],[`👱`,`person with blond hair`,`people`,``],[`👲`,`man with gua pi mao`,`people`,`中国人`],[`👳`,`man with turban`,`people`,`包头巾,印度,阿拉伯`],[`👴`,`older man`,`people`,`老人,老爷爷`],[`👵`,`older woman`,`people`,`老人,老奶奶`],[`👶`,`baby`,`people`,`婴儿,宝宝,小孩`],[`👷`,`construction worker`,`people`,`工人`],[`👸`,`princess`,`people`,`公主,女王`],[`👹`,`japanese ogre`,`people`,`妖怪,鬼,怪物`],[`👺`,`japanese goblin`,`people`,`天狗,怪物,鬼`],[`👻`,`ghost`,`people`,`幽灵,鬼,万圣节`],[`👼`,`baby angel`,`people`,`天使,婴儿,可爱`],[`👽`,`extraterrestrial alien`,`people`,`外星人,ET,飞碟`],[`👾`,`alien monster`,`people`,`外星人,怪兽,游戏`],[`👿`,`imp`,`people`,`恶魔,愤怒`],[`💀`,`skull`,`people`,`骷髅,死亡,骨头`],[`💁`,`information desk person`,`people`,``],[`💂`,`guardsman`,`people`,`卫兵,士兵`],[`💃`,`dancer`,`people`,`跳舞,舞女,跳舞`],[`💄`,`lipstick`,`people`,`口红,化妆`],[`💅`,`nail polish`,`people`,`美甲,指甲,涂`],[`💆`,`face massage`,`people`,`按摩,放松,头部`],[`💇`,`haircut`,`people`,`理发,剪发,发型`],[`💈`,`barber pole`,`people`,`理发店,理发`],[`💉`,`syringe`,`people`,`注射器,针,疫苗`],[`💊`,`pill`,`people`,`药丸,药,胶囊`],[`💋`,`kiss mark`,`people`,`吻,口红印,亲亲`],[`💌`,`love letter`,`people`,`情书,信,爱情`],[`💍`,`ring`,`people`,`戒指,钻戒,结婚`],[`💎`,`gem stone`,`people`,`钻石,宝石,珠宝`],[`💏`,`kiss`,`people`,``],[`💐`,`bouquet`,`smileys`,`花束,花,礼物`],[`💑`,`couple with heart`,`smileys`,``],[`💒`,`wedding`,`smileys`,`教堂,婚礼,教堂婚礼`],[`💓`,`beating heart`,`smileys`,`爱心,跳动,心跳`],[`💔`,`broken heart`,`smileys`,`心碎,伤心,破碎`],[`💕`,`two hearts`,`smileys`,`爱心,两个,喜欢`],[`💖`,`sparkling heart`,`smileys`,`爱心,闪光,喜欢`],[`💗`,`growing heart`,`smileys`,`爱心,跳动,喜欢`],[`💘`,`heart with arrow`,`smileys`,`爱心,箭,丘比特`],[`💙`,`blue heart`,`smileys`,``],[`💚`,`green heart`,`smileys`,``],[`💛`,`yellow heart`,`smileys`,``],[`💜`,`purple heart`,`smileys`,``],[`💝`,`heart with ribbon`,`smileys`,`爱心,礼物,蝴蝶结`],[`💞`,`revolving hearts`,`smileys`,`爱心,旋转,轮回`],[`💟`,`heart decoration`,`smileys`,`爱心,符号`],[`💠`,`diamond shape with a dot inside`,`objects`,``],[`💡`,`electric light bulb`,`objects`,``],[`💢`,`anger symbol`,`objects`,`生气,怒气`],[`💣`,`bomb`,`objects`,`炸弹,爆炸`],[`💤`,`sleeping symbol`,`objects`,`睡觉,打呼,困`],[`💥`,`collision symbol`,`objects`,``],[`💦`,`splashing sweat symbol`,`objects`,`汗,水,泪`],[`💧`,`droplet`,`objects`,`水滴,水,眼泪`],[`💨`,`dash symbol`,`objects`,`风,跑,快,烟雾`],[`💩`,`pile of poo`,`objects`,`大便,屎,狗屎`],[`💪`,`flexed biceps`,`people`,`肌肉,力量,加油,强壮`],[`💫`,`dizzy symbol`,`objects`,`星星,旋转`],[`💬`,`speech balloon`,`objects`,`对话,聊天`],[`💭`,`thought balloon`,`objects`,`想法,思考,气泡`],[`💮`,`white flower`,`objects`,``],[`💯`,`hundred points symbol`,`objects`,``],[`💰`,`money bag`,`objects`,`钱袋,钱,金钱`],[`💱`,`currency exchange`,`objects`,``],[`💲`,`heavy dollar sign`,`objects`,``],[`💳`,`credit card`,`objects`,`信用卡,银行卡,支付`],[`💴`,`banknote with yen sign`,`objects`,`日元,日圆,钱`],[`💵`,`banknote with dollar sign`,`objects`,`美元,美金,钱`],[`💶`,`banknote with euro sign`,`objects`,`欧元,钱`],[`💷`,`banknote with pound sign`,`objects`,`英镑,钱`],[`💸`,`money with wings`,`objects`,`钱,飞钱,花钱`],[`💹`,`chart with upwards trend and yen sign`,`objects`,`股票,上涨,图表,增长`],[`💺`,`seat`,`objects`,`座位,椅子,飞机座位`],[`💻`,`personal computer`,`objects`,`电脑,笔记本,笔记本电脑`],[`💼`,`briefcase`,`objects`,`公文包,工作,商务`],[`💽`,`minidisc`,`objects`,`光盘,磁盘`],[`💾`,`floppy disk`,`objects`,`软盘,保存`],[`💿`,`optical disc`,`objects`,`光盘,CD`],[`📀`,`dvd`,`objects`,`光盘,DVD`],[`📁`,`file folder`,`objects`,`文件夹`],[`📂`,`open file folder`,`objects`,`文件夹,打开`],[`📃`,`page with curl`,`objects`,`文件,文档`],[`📄`,`page facing up`,`objects`,`文件,文档,纸`],[`📅`,`calendar`,`objects`,`日历`],[`📆`,`tear-off calendar`,`objects`,`日历,日历页`],[`📇`,`card index`,`objects`,`名片,索引卡`],[`📈`,`chart with upwards trend`,`objects`,``],[`📉`,`chart with downwards trend`,`objects`,``],[`📊`,`bar chart`,`objects`,``],[`📋`,`clipboard`,`objects`,`剪贴板,清单,列表`],[`📌`,`pushpin`,`objects`,``],[`📍`,`round pushpin`,`objects`,``],[`📎`,`paperclip`,`objects`,``],[`📏`,`straight ruler`,`objects`,``],[`📐`,`triangular ruler`,`objects`,``],[`📑`,`bookmark tabs`,`objects`,`书签,标签,文件`],[`📒`,`ledger`,`objects`,``],[`📓`,`notebook`,`objects`,``],[`📔`,`notebook with decorative cover`,`objects`,``],[`📕`,`closed book`,`objects`,``],[`📖`,`open book`,`objects`,``],[`📗`,`green book`,`objects`,``],[`📘`,`blue book`,`objects`,``],[`📙`,`orange book`,`objects`,``],[`📚`,`books`,`objects`,``],[`📛`,`name badge`,`objects`,``],[`📜`,`scroll`,`objects`,``],[`📝`,`memo`,`objects`,`笔记,备忘录,写作,文档`],[`📞`,`telephone receiver`,`objects`,`电话`],[`📟`,`pager`,`objects`,`寻呼机,传呼机`],[`📠`,`fax machine`,`objects`,`传真机,传真`],[`📡`,`satellite antenna`,`objects`,`天线,卫星,信号`],[`📢`,`public address loudspeaker`,`objects`,``],[`📣`,`cheering megaphone`,`objects`,``],[`📤`,`outbox tray`,`objects`,`发送,输出,上传`],[`📥`,`inbox tray`,`objects`,`接收,下载,收件箱`],[`📦`,`package`,`objects`,`包裹,快递,箱子`],[`📧`,`e-mail symbol`,`objects`,`邮件,电子邮件`],[`📨`,`incoming envelope`,`objects`,`邮件,收到`],[`📩`,`envelope with downwards arrow above`,`objects`,`邮件,发送`],[`📪`,`closed mailbox with lowered flag`,`objects`,`邮箱,关闭`],[`📫`,`closed mailbox with raised flag`,`objects`,`邮箱,信箱,邮件`],[`📬`,`open mailbox with raised flag`,`objects`,`邮箱,有信`],[`📭`,`open mailbox with lowered flag`,`objects`,`邮箱,无信`],[`📮`,`postbox`,`objects`,`邮筒,邮政`],[`📯`,`postal horn`,`objects`,``],[`📰`,`newspaper`,`objects`,`报纸,新闻,报`],[`📱`,`mobile phone`,`objects`,`手机,智能手机,电话`],[`📲`,`mobile phone with rightwards arrow at left`,`objects`,`手机,接收,信号`],[`📳`,`vibration mode`,`objects`,``],[`📴`,`mobile phone off`,`objects`,``],[`📵`,`no mobile phones`,`objects`,``],[`📶`,`antenna with bars`,`objects`,``],[`📷`,`camera`,`objects`,`相机,拍照,照片`],[`📸`,`camera with flash`,`objects`,`相机,闪光灯,拍照`],[`📹`,`video camera`,`objects`,`摄像机,录像`],[`📺`,`television`,`objects`,``],[`📻`,`radio`,`objects`,`收音机,广播`],[`📼`,`videocassette`,`objects`,`录像带,磁带`],[`📽`,`film projector`,`objects`,``],[`📿`,`prayer beads`,`objects`,`念珠,佛珠,项链`],[`🔀`,`twisted rightwards arrows`,`objects`,``],[`🔁`,`clockwise rightwards and leftwards open circle arrows`,`objects`,``],[`🔂`,`clockwise rightwards and leftwards open circle arrows with circled one overlay`,`objects`,``],[`🔃`,`clockwise downwards and upwards open circle arrows`,`objects`,``],[`🔄`,`anticlockwise downwards and upwards open circle arrows`,`objects`,``],[`🔅`,`low brightness symbol`,`objects`,``],[`🔆`,`high brightness symbol`,`objects`,``],[`🔇`,`speaker with cancellation stroke`,`objects`,``],[`🔈`,`speaker`,`objects`,``],[`🔉`,`speaker with one sound wave`,`objects`,``],[`🔊`,`speaker with three sound waves`,`objects`,``],[`🔋`,`battery`,`objects`,``],[`🔌`,`electric plug`,`objects`,``],[`🔍`,`left-pointing magnifying glass`,`objects`,`搜索,放大镜,查找,查询`],[`🔎`,`right-pointing magnifying glass`,`objects`,`搜索,放大镜,查找`],[`🔏`,`lock with ink pen`,`objects`,`锁,保密,笔`],[`🔐`,`closed lock with key`,`objects`,`锁,安全,钥匙`],[`🔑`,`key`,`objects`,`钥匙,解锁`],[`🔒`,`lock`,`objects`,`锁,锁定,安全`],[`🔓`,`open lock`,`objects`,`解锁,打开`],[`🔔`,`bell`,`objects`,``],[`🔕`,`bell with cancellation stroke`,`objects`,``],[`🔖`,`bookmark`,`objects`,`书签,标记`],[`🔗`,`link symbol`,`objects`,``],[`🔘`,`radio button`,`objects`,``],[`🔙`,`back with leftwards arrow above`,`objects`,``],[`🔚`,`end with leftwards arrow above`,`objects`,``],[`🔛`,`on with exclamation mark with left right arrow above`,`objects`,``],[`🔜`,`soon with rightwards arrow above`,`objects`,``],[`🔝`,`top with upwards arrow above`,`objects`,``],[`🔞`,`no one under eighteen symbol`,`objects`,``],[`🔟`,`keycap 10`,`objects`,``],[`🔠`,`input symbol for latin capital letters`,`objects`,``],[`🔡`,`input symbol for latin small letters`,`objects`,``],[`🔢`,`input symbol for numbers`,`objects`,``],[`🔣`,`input symbol for symbols`,`objects`,``],[`🔤`,`input symbol for latin letters`,`objects`,``],[`🔥`,`fire`,`objects`,``],[`🔦`,`electric torch`,`objects`,``],[`🔧`,`wrench`,`objects`,`扳手,工具,维修`],[`🔨`,`hammer`,`objects`,`锤子,工具`],[`🔩`,`nut and bolt`,`objects`,`螺丝,螺母`],[`🔪`,`hocho`,`objects`,``],[`🔫`,`pistol`,`objects`,`枪`],[`🔬`,`microscope`,`objects`,`显微镜,科学,研究`],[`🔭`,`telescope`,`objects`,`望远镜,天文,观察`],[`🔮`,`crystal ball`,`objects`,``],[`🔯`,`six pointed star with middle dot`,`objects`,``],[`🔰`,`japanese symbol for beginner`,`objects`,``],[`🔱`,`trident emblem`,`objects`,``],[`🔲`,`black square button`,`objects`,``],[`🔳`,`white square button`,`objects`,``],[`🔴`,`large red circle`,`objects`,``],[`🔵`,`large blue circle`,`objects`,``],[`🔶`,`large orange diamond`,`objects`,``],[`🔷`,`large blue diamond`,`objects`,``],[`🔸`,`small orange diamond`,`objects`,``],[`🔹`,`small blue diamond`,`objects`,``],[`🔺`,`up-pointing red triangle`,`objects`,``],[`🔻`,`down-pointing red triangle`,`objects`,``],[`🔼`,`up-pointing small red triangle`,`objects`,``],[`🔽`,`down-pointing small red triangle`,`objects`,``],[`🕉`,`om symbol`,`objects`,``],[`🕊`,`dove of peace`,`objects`,``],[`🕋`,`kaaba`,`objects`,`天房,麦加,伊斯兰`],[`🕌`,`mosque`,`objects`,`清真寺,伊斯兰`],[`🕍`,`synagogue`,`objects`,`犹太教堂,犹太`],[`🕎`,`menorah with nine branches`,`objects`,``],[`🕐`,`clock face one oclock`,`objects`,`一点,时钟`],[`🕑`,`clock face two oclock`,`objects`,`两点,时钟`],[`🕒`,`clock face three oclock`,`objects`,`三点,时钟`],[`🕓`,`clock face four oclock`,`objects`,`四点,时钟`],[`🕔`,`clock face five oclock`,`objects`,`五点,时钟`],[`🕕`,`clock face six oclock`,`objects`,`六点,时钟`],[`🕖`,`clock face seven oclock`,`objects`,`七点,时钟`],[`🕗`,`clock face eight oclock`,`objects`,`八点,时钟`],[`🕘`,`clock face nine oclock`,`objects`,`九点,时钟`],[`🕙`,`clock face ten oclock`,`objects`,`十点,时钟`],[`🕚`,`clock face eleven oclock`,`objects`,`十一点,时钟`],[`🕛`,`clock face twelve oclock`,`objects`,`十二点,时钟,时间`],[`🕜`,`clock face one-thirty`,`objects`,``],[`🕝`,`clock face two-thirty`,`objects`,``],[`🕞`,`clock face three-thirty`,`objects`,``],[`🕟`,`clock face four-thirty`,`objects`,``],[`🕠`,`clock face five-thirty`,`objects`,``],[`🕡`,`clock face six-thirty`,`objects`,``],[`🕢`,`clock face seven-thirty`,`objects`,``],[`🕣`,`clock face eight-thirty`,`objects`,``],[`🕤`,`clock face nine-thirty`,`objects`,``],[`🕥`,`clock face ten-thirty`,`objects`,``],[`🕦`,`clock face eleven-thirty`,`objects`,``],[`🕧`,`clock face twelve-thirty`,`objects`,``],[`🕯`,`candle`,`objects`,``],[`🕰`,`mantelpiece clock`,`objects`,``],[`🕳`,`hole`,`objects`,``],[`🕴`,`man in business suit levitating`,`objects`,``],[`🕵`,`sleuth or spy`,`objects`,``],[`🕶`,`dark sunglasses`,`objects`,``],[`🕷`,`spider`,`objects`,``],[`🕸`,`spider web`,`objects`,``],[`🕹`,`joystick`,`objects`,``],[`🕺`,`man dancing`,`objects`,`跳舞,舞男`],[`🖇`,`linked paperclips`,`objects`,``],[`🖊`,`lower left ballpoint pen`,`objects`,``],[`🖋`,`lower left fountain pen`,`objects`,``],[`🖌`,`lower left paintbrush`,`objects`,``],[`🖍`,`lower left crayon`,`objects`,``],[`🖐`,`raised hand with fingers splayed`,`objects`,``],[`🖕`,`reversed hand with middle finger extended`,`objects`,`中指,骂人`],[`🖖`,`raised hand with part between middle and ring fingers`,`objects`,`瓦肯,举手,胜利`],[`🖤`,`black heart`,`objects`,``],[`🖥`,`desktop computer`,`objects`,``],[`🖨`,`printer`,`objects`,``],[`🖱`,`three button mouse`,`objects`,``],[`🖲`,`trackball`,`objects`,``],[`🖼`,`frame with picture`,`objects`,``],[`🗂`,`card index dividers`,`objects`,``],[`🗃`,`card file box`,`objects`,``],[`🗄`,`file cabinet`,`objects`,``],[`🗑`,`wastebasket`,`objects`,``],[`🗒`,`spiral note pad`,`objects`,``],[`🗓`,`spiral calendar pad`,`objects`,``],[`🗜`,`compression`,`objects`,``],[`🗝`,`old key`,`objects`,``],[`🗞`,`rolled-up newspaper`,`objects`,``],[`🗡`,`dagger knife`,`objects`,``],[`🗣`,`speaking head in silhouette`,`objects`,``],[`🗨`,`left speech bubble`,`objects`,``],[`🗯`,`right anger bubble`,`objects`,``],[`🗳`,`ballot box with ballot`,`objects`,``],[`🗺`,`world map`,`objects`,``],[`🗻`,`mount fuji`,`objects`,`富士山,山`],[`🗼`,`tokyo tower`,`objects`,`塔,东京塔`],[`🗽`,`statue of liberty`,`objects`,`自由女神像,纽约`],[`🗾`,`silhouette of japan`,`objects`,``],[`🗿`,`moyai`,`objects`,`雕像`],[`😀`,`grinning face`,`smileys`,`笑脸,开心,高兴`],[`😁`,`grinning face with smiling eyes`,`smileys`,`笑脸,开心`],[`😂`,`face with tears of joy`,`smileys`,`笑哭,大笑,笑`],[`😃`,`smiling face with open mouth`,`smileys`,`笑脸,开心`],[`😄`,`smiling face with open mouth and smiling eyes`,`smileys`,`笑脸,开心`],[`😅`,`smiling face with open mouth and cold sweat`,`smileys`,`笑脸,汗,尴尬`],[`😆`,`smiling face with open mouth and tightly-closed eyes`,`smileys`,`笑脸,大笑`],[`😇`,`smiling face with halo`,`smileys`,`天使,微笑,善良`],[`😈`,`smiling face with horns`,`smileys`,`恶魔,坏笑,邪恶`],[`😉`,`winking face`,`smileys`,`眨眼,调皮`],[`😊`,`smiling face with smiling eyes`,`smileys`,`微笑,开心,脸红`],[`😋`,`face savouring delicious food`,`smileys`,`好吃,美味,舔`],[`😌`,`relieved face`,`smileys`,`放松,安心`],[`😍`,`smiling face with heart-shaped eyes`,`smileys`,`爱,喜欢,花痴`],[`😎`,`smiling face with sunglasses`,`smileys`,`酷,墨镜,帅气`],[`😏`,`smirking face`,`smileys`,`得意,微笑,坏笑`],[`😐`,`neutral face`,`smileys`,`无语,面无表情`],[`😑`,`expressionless face`,`smileys`,`无语,面无表情`],[`😒`,`unamused face`,`smileys`,`不满,无语,翻白眼`],[`😓`,`face with cold sweat`,`smileys`,`冷汗,尴尬`],[`😔`,`pensive face`,`smileys`,`难过,低落`],[`😕`,`confused face`,`smileys`,`困惑,不解`],[`😖`,`confounded face`,`smileys`,`纠结,痛苦`],[`😗`,`kissing face`,`smileys`,`亲亲,吻`],[`😘`,`face throwing a kiss`,`smileys`,`飞吻,亲亲,爱`],[`😙`,`kissing face with smiling eyes`,`smileys`,``],[`😚`,`kissing face with closed eyes`,`smileys`,`亲亲,吻`],[`😛`,`face with stuck-out tongue`,`smileys`,`吐舌头,调皮`],[`😜`,`face with stuck-out tongue and winking eye`,`smileys`,`吐舌头,调皮,眨眼`],[`😝`,`face with stuck-out tongue and tightly-closed eyes`,`smileys`,`吐舌头,调皮`],[`😞`,`disappointed face`,`smileys`,`失望,难过`],[`😟`,`worried face`,`smileys`,`担心,忧虑`],[`😠`,`angry face`,`smileys`,`生气,愤怒`],[`😡`,`pouting face`,`smileys`,`生气,愤怒,红脸`],[`😢`,`crying face`,`smileys`,`哭,伤心,流泪`],[`😣`,`persevering face`,`smileys`,`挣扎,痛苦`],[`😤`,`face with look of triumph`,`smileys`,`生气,冒烟,气`],[`😥`,`disappointed but relieved face`,`smileys`,`难过,失望,松气`],[`😦`,`frowning face with open mouth`,`smileys`,`惊讶,张嘴`],[`😧`,`anguished face`,`smileys`,`震惊,痛苦`],[`😨`,`fearful face`,`smileys`,`害怕,恐惧`],[`😩`,`weary face`,`smileys`,`累,疲惫,哭`],[`😪`,`sleepy face`,`smileys`,`困,想睡`],[`😫`,`tired face`,`smileys`,`累,疲惫`],[`😬`,`grimacing face`,`smileys`,`尴尬,咧嘴`],[`😭`,`loudly crying face`,`smileys`,`大哭,伤心,哭`],[`😮`,`face with open mouth`,`smileys`,`惊讶,哇`],[`😯`,`hushed face`,`smileys`,`惊讶,安静`],[`😰`,`face with open mouth and cold sweat`,`smileys`,`担心,冷汗`],[`😱`,`face screaming in fear`,`smileys`,`尖叫,害怕,恐怖`],[`😲`,`astonished face`,`smileys`,`震惊,惊讶`],[`😳`,`flushed face`,`smileys`,`脸红,害羞,震惊`],[`😴`,`sleeping face`,`smileys`,`睡觉,睡觉`],[`😵`,`dizzy face`,`smileys`,`晕,头晕,死`],[`😶`,`face without mouth`,`smileys`,`沉默,无语`],[`😷`,`face with medical mask`,`smileys`,`生病,口罩,感冒`],[`😸`,`grinning cat face with smiling eyes`,`smileys`,`猫,笑脸`],[`😹`,`cat face with tears of joy`,`smileys`,`猫,笑哭`],[`😺`,`smiling cat face with open mouth`,`smileys`,`猫,笑脸,开心`],[`😻`,`smiling cat face with heart-shaped eyes`,`smileys`,`猫,爱,喜欢`],[`😼`,`cat face with wry smile`,`smileys`,`猫,坏笑`],[`😽`,`kissing cat face with closed eyes`,`smileys`,`猫,亲亲`],[`😾`,`pouting cat face`,`smileys`,`猫,生气`],[`😿`,`crying cat face`,`smileys`,`猫,哭,伤心`],[`🙀`,`weary cat face`,`smileys`,`猫,震惊,害怕`],[`🙁`,`slightly frowning face`,`smileys`,`难过,失望`],[`🙂`,`slightly smiling face`,`smileys`,`微笑,笑`],[`🙃`,`upside-down face`,`smileys`,`微笑,倒`],[`🙄`,`face with rolling eyes`,`smileys`,`翻白眼,无语`],[`🙅`,`face with no good gesture`,`smileys`,``],[`🙆`,`face with ok gesture`,`smileys`,``],[`🙇`,`person bowing deeply`,`smileys`,``],[`🙈`,`see-no-evil monkey`,`smileys`,``],[`🙉`,`hear-no-evil monkey`,`smileys`,``],[`🙊`,`speak-no-evil monkey`,`smileys`,``],[`🙋`,`happy person raising one hand`,`smileys`,``],[`🙌`,`person raising both hands in celebration`,`smileys`,`欢呼,举起,庆祝`],[`🙍`,`person frowning`,`smileys`,``],[`🙎`,`person with pouting face`,`smileys`,``],[`🙏`,`person with folded hands`,`smileys`,`祈祷,拜托,感谢,合十`],[`🚀`,`rocket`,`travel`,`火箭,发射,太空`],[`🚁`,`helicopter`,`travel`,`直升机`],[`🚂`,`steam locomotive`,`travel`,`火车,蒸汽火车`],[`🚃`,`railway car`,`travel`,`电车,火车`],[`🚄`,`high-speed train`,`travel`,`高铁,动车,火车`],[`🚅`,`high-speed train with bullet nose`,`travel`,``],[`🚆`,`train`,`travel`,`火车,铁路`],[`🚇`,`metro`,`travel`,`地铁,地铁站`],[`🚈`,`light rail`,`travel`,`轻轨,轨道交通`],[`🚉`,`station`,`travel`,`火车站,车站`],[`🚊`,`tram`,`travel`,`电车`],[`🚋`,`tram car`,`travel`,`电车,有轨电车`],[`🚌`,`bus`,`travel`,`公交车,巴士`],[`🚍`,`oncoming bus`,`travel`,`公交车`],[`🚎`,`trolleybus`,`travel`,`无轨电车,巴士`],[`🚏`,`bus stop`,`travel`,`公交站,车站`],[`🚐`,`minibus`,`travel`,`面包车,小巴`],[`🚑`,`ambulance`,`travel`,`救护车,急救`],[`🚒`,`fire engine`,`travel`,`消防车,救火`],[`🚓`,`police car`,`travel`,`警车,警察`],[`🚔`,`oncoming police car`,`travel`,`警车,巡逻`],[`🚕`,`taxi`,`travel`,`出租车,的士`],[`🚖`,`oncoming taxi`,`travel`,`出租车`],[`🚗`,`automobile`,`travel`,`汽车,轿车,车`],[`🚘`,`oncoming automobile`,`travel`,`汽车`],[`🚙`,`recreational vehicle`,`travel`,`SUV,越野车,汽车`],[`🚚`,`delivery truck`,`travel`,`卡车,货车`],[`🚛`,`articulated lorry`,`travel`,`卡车,货车`],[`🚜`,`tractor`,`travel`,`拖拉机,农用`],[`🚝`,`monorail`,`travel`,`单轨,单轨列车`],[`🚞`,`mountain railway`,`travel`,`火车,山区铁路`],[`🚟`,`suspension railway`,`travel`,`缆车,悬挂列车`],[`🚠`,`mountain cableway`,`travel`,`缆车,高山`],[`🚡`,`aerial tramway`,`travel`,`缆车,索道`],[`🚢`,`ship`,`travel`,`轮船,船,大海`],[`🚣`,`rowboat`,`travel`,``],[`🚤`,`speedboat`,`travel`,`快艇,汽艇`],[`🚥`,`horizontal traffic light`,`travel`,`红绿灯,交通信号灯`],[`🚦`,`vertical traffic light`,`travel`,`红绿灯,信号灯`],[`🚧`,`construction sign`,`travel`,`施工,施工中,路障`],[`🚨`,`police cars revolving light`,`travel`,`警车灯,警报,紧急`],[`🚩`,`triangular flag on post`,`travel`,`红旗,旗帜,标志`],[`🚪`,`door`,`travel`,`门,房门`],[`🚫`,`no entry sign`,`travel`,``],[`🚬`,`smoking symbol`,`travel`,`香烟,烟,吸烟`],[`🚭`,`no smoking symbol`,`travel`,``],[`🚮`,`put litter in its place symbol`,`travel`,`垃圾,清理`],[`🚯`,`do not litter symbol`,`travel`,``],[`🚰`,`potable water symbol`,`travel`,``],[`🚱`,`non-potable water symbol`,`travel`,``],[`🚲`,`bicycle`,`travel`,`自行车,单车,骑行`],[`🚳`,`no bicycles`,`travel`,``],[`🚴`,`bicyclist`,`travel`,``],[`🚵`,`mountain bicyclist`,`travel`,``],[`🚶`,`pedestrian`,`travel`,`走路,步行,散步`],[`🚷`,`no pedestrians`,`travel`,``],[`🚸`,`children crossing`,`travel`,``],[`🚹`,`mens symbol`,`travel`,``],[`🚺`,`womens symbol`,`travel`,``],[`🚻`,`restroom`,`travel`,``],[`🚼`,`baby symbol`,`travel`,``],[`🚽`,`toilet`,`travel`,`马桶,厕所,卫生间`],[`🚾`,`water closet`,`travel`,``],[`🚿`,`shower`,`travel`,`淋浴,洗澡`],[`🛀`,`bath`,`travel`,`泡澡`],[`🛁`,`bathtub`,`travel`,`浴缸,洗澡,泡澡`],[`🛂`,`passport control`,`travel`,``],[`🛃`,`customs`,`travel`,``],[`🛄`,`baggage claim`,`travel`,``],[`🛅`,`left luggage`,`travel`,``],[`🛋`,`couch and lamp`,`travel`,``],[`🛌`,`sleeping accommodation`,`travel`,`睡觉`],[`🛍`,`shopping bags`,`travel`,``],[`🛎`,`bellhop bell`,`travel`,``],[`🛏`,`bed`,`travel`,``],[`🛐`,`place of worship`,`travel`,``],[`🛑`,`octagonal sign`,`travel`,`停止,停车,红圈`],[`🛒`,`shopping trolley`,`travel`,`购物车,购物`],[`🛕`,`hindu temple`,`travel`,`印度教神庙`],[`🛖`,`hut`,`travel`,`草屋,小屋`],[`🛗`,`elevator`,`travel`,``],[`🛜`,`wireless`,`travel`,``],[`🛝`,`playground slide`,`travel`,``],[`🛞`,`wheel`,`travel`,`车轮,轮胎`],[`🛟`,`ring buoy`,`travel`,`救生圈,救生`],[`🛠`,`hammer and wrench`,`travel`,``],[`🛡`,`shield`,`travel`,``],[`🛢`,`oil drum`,`travel`,``],[`🛣`,`motorway`,`travel`,``],[`🛤`,`railway track`,`travel`,``],[`🛥`,`motor boat`,`travel`,``],[`🛩`,`small airplane`,`travel`,``],[`🛫`,`airplane departure`,`travel`,`起飞,飞机,出发`],[`🛬`,`airplane arriving`,`travel`,`降落,飞机,到达`],[`🛰`,`satellite`,`travel`,``],[`🛳`,`passenger ship`,`travel`,``],[`🛴`,`scooter`,`travel`,`滑板车,平衡车`],[`🛵`,`motor scooter`,`travel`,`摩托车,电动车,踏板车`],[`🛶`,`canoe`,`travel`,`独木舟,皮划艇`],[`🛷`,`sled`,`travel`,`雪橇,雪车`],[`🛸`,`flying saucer`,`travel`,`飞碟,UFO,外星人`],[`🛹`,`skateboard`,`travel`,`滑板`],[`🛺`,`auto rickshaw`,`travel`,`三轮车,突突车`],[`🛻`,`pickup truck`,`travel`,`皮卡,卡车`],[`🛼`,`roller skate`,`travel`,`轮滑`],[`🟠`,`large orange circle`,`symbols`,``],[`🟡`,`large yellow circle`,`symbols`,``],[`🟢`,`large green circle`,`symbols`,``],[`🟣`,`large purple circle`,`symbols`,``],[`🟤`,`large brown circle`,`symbols`,``],[`🟥`,`large red square`,`symbols`,``],[`🟦`,`large blue square`,`symbols`,``],[`🟧`,`large orange square`,`symbols`,``],[`🟨`,`large yellow square`,`symbols`,``],[`🟩`,`large green square`,`symbols`,``],[`🟪`,`large purple square`,`symbols`,``],[`🟫`,`large brown square`,`symbols`,``],[`🟰`,`heavy equals sign`,`symbols`,``],[`🤌`,`pinched fingers`,`symbols`,`手指,捏,意大利`],[`🤍`,`white heart`,`symbols`,`白心,白色,爱心`],[`🤎`,`brown heart`,`symbols`,`棕心,棕色,爱心`],[`🤏`,`pinching hand`,`symbols`,`捏,一点点,微小`],[`🤐`,`zipper-mouth face`,`smileys`,`闭嘴,不说`],[`🤑`,`money-mouth face`,`smileys`,`发财,金钱,贪婪`],[`🤒`,`face with thermometer`,`smileys`,`发烧,生病,温度计`],[`🤓`,`nerd face`,`smileys`,`书呆子,眼镜`],[`🤔`,`thinking face`,`smileys`,`思考,疑问,想`],[`🤕`,`face with head-bandage`,`smileys`,`受伤,包扎,头`],[`🤖`,`robot face`,`smileys`,`机器人,AI,机械`],[`🤗`,`hugging face`,`smileys`,`拥抱,欢迎`],[`🤘`,`sign of the horns`,`smileys`,`摇滚,手势,牛`],[`🤙`,`call me hand`,`smileys`,`打电话,挂,酷`],[`🤚`,`raised back of hand`,`smileys`,`手,举手,停`],[`🤛`,`left-facing fist`,`smileys`,`拳头,左边`],[`🤜`,`right-facing fist`,`smileys`,`拳头,右边`],[`🤝`,`handshake`,`smileys`,`握手,合作,协议`],[`🤞`,`hand with index and middle fingers crossed`,`smileys`,`祈祷,好运,手指交叉`],[`🤟`,`i love you hand sign`,`smileys`,`爱你,摇滚`],[`🤠`,`face with cowboy hat`,`smileys`,`牛仔,帽子`],[`🤡`,`clown face`,`smileys`,`小丑,马戏团`],[`🤢`,`nauseated face`,`smileys`,`恶心,呕吐`],[`🤣`,`rolling on the floor laughing`,`smileys`,`笑哭,大笑,笑`],[`🤤`,`drooling face`,`smileys`,`流口水,馋`],[`🤥`,`lying face`,`smileys`,`说谎,撒谎`],[`🤦`,`face palm`,`smileys`,`捂脸,无奈,扶额`],[`🤧`,`sneezing face`,`smileys`,`打喷嚏,感冒`],[`🤨`,`face with one eyebrow raised`,`symbols`,`怀疑,挑眉`],[`🤩`,`grinning face with star eyes`,`symbols`,`星星眼,兴奋,惊讶`],[`🤪`,`grinning face with one large and one small eye`,`symbols`,`疯狂,搞怪`],[`🤫`,`face with finger covering closed lips`,`symbols`,`嘘,安静`],[`🤬`,`serious face with symbols covering mouth`,`symbols`,`骂人,脏话,生气`],[`🤭`,`smiling face with smiling eyes and hand covering mouth`,`symbols`,`捂嘴,偷笑,惊讶`],[`🤮`,`face with open mouth vomiting`,`symbols`,`呕吐,恶心`],[`🤯`,`shocked face with exploding head`,`smileys`,`爆炸,震惊,头炸`],[`🤰`,`pregnant woman`,`people`,`孕妇,怀孕`],[`🤱`,`breast-feeding`,`people`,``],[`🤲`,`palms up together`,`people`,``],[`🤳`,`selfie`,`people`,`自拍,拍照`],[`🤴`,`prince`,`people`,`王子,国王`],[`🤵`,`man in tuxedo`,`people`,`新郎,西装,燕尾服`],[`🤶`,`mother christmas`,`people`,`圣诞奶奶,圣诞老人`],[`🤷`,`shrug`,`people`,`耸肩,无奈,不知道`],[`🤸`,`person doing cartwheel`,`people`,`翻跟头,体操,空翻`],[`🤹`,`juggling`,`people`,`杂耍`],[`🤺`,`fencer`,`people`,`击剑,剑术`],[`🤼`,`wrestlers`,`activity`,`摔跤,格斗`],[`🤽`,`water polo`,`activity`,``],[`🤾`,`handball`,`activity`,``],[`🤿`,`diving mask`,`activity`,`潜水面罩,潜水`],[`🥀`,`wilted flower`,`symbols`,``],[`🥁`,`drum with drumsticks`,`symbols`,`鼓,打鼓,乐器`],[`🥂`,`clinking glasses`,`symbols`,`干杯,香槟杯`],[`🥃`,`tumbler glass`,`symbols`,`威士忌,酒杯`],[`🥄`,`spoon`,`symbols`,`勺子,汤匙`],[`🥅`,`goal net`,`symbols`,`球门,网,进球`],[`🥇`,`first place medal`,`symbols`,`金牌,冠军,第一名,奖牌`],[`🥈`,`second place medal`,`symbols`,`银牌,第二名,奖牌`],[`🥉`,`third place medal`,`symbols`,`铜牌,第三名,奖牌`],[`🥊`,`boxing glove`,`symbols`,`拳击,拳击手套,打拳`],[`🥋`,`martial arts uniform`,`symbols`,`道服,武术,空手道`],[`🥌`,`curling stone`,`symbols`,`冰壶,冰壶`],[`🥍`,`lacrosse stick and ball`,`symbols`,``],[`🥎`,`softball`,`symbols`,`垒球,球`],[`🥏`,`flying disc`,`symbols`,`飞盘,飞碟`],[`🥐`,`croissant`,`food`,`牛角包,可颂`],[`🥑`,`avocado`,`food`,`牛油果,鳄梨`],[`🥒`,`cucumber`,`food`,`黄瓜`],[`🥓`,`bacon`,`food`,`培根,腊肉`],[`🥔`,`potato`,`food`,`土豆,马铃薯`],[`🥕`,`carrot`,`food`,`胡萝卜`],[`🥖`,`baguette bread`,`food`,`法棍,面包`],[`🥗`,`green salad`,`food`,`沙拉,蔬菜`],[`🥘`,`shallow pan of food`,`food`,`炖锅,海鲜饭`],[`🥙`,`stuffed flatbread`,`food`,`卷饼,肉夹馍`],[`🥚`,`egg`,`food`,`鸡蛋,蛋`],[`🥛`,`glass of milk`,`food`,`牛奶,奶`],[`🥜`,`peanuts`,`food`,``],[`🥝`,`kiwifruit`,`food`,`猕猴桃,奇异果`],[`🥞`,`pancakes`,`food`,`松饼,煎饼`],[`🥟`,`dumpling`,`food`,`饺子,锅贴`],[`🥠`,`fortune cookie`,`food`,`幸运饼干`],[`🥡`,`takeout box`,`food`,``],[`🥢`,`chopsticks`,`food`,`筷子`],[`🥣`,`bowl with spoon`,`food`,``],[`🥤`,`cup with straw`,`food`,`饮料,杯`],[`🥥`,`coconut`,`food`,`椰子`],[`🥦`,`broccoli`,`food`,`西兰花`],[`🥧`,`pie`,`food`,`派,馅饼`],[`🥨`,`pretzel`,`food`,`椒盐卷饼`],[`🥩`,`cut of meat`,`food`,`牛排,肉`],[`🥪`,`sandwich`,`food`,`三明治`],[`🥫`,`canned food`,`food`,`罐头,罐装`],[`🥬`,`leafy green`,`symbols`,`青菜,白菜,生菜`],[`🥭`,`mango`,`symbols`,`芒果`],[`🥮`,`moon cake`,`symbols`,``],[`🥯`,`bagel`,`symbols`,`贝果,面包圈`],[`🥰`,`smiling face with smiling eyes and three hearts`,`smileys`,`爱,微笑,爱心`],[`🥱`,`yawning face`,`smileys`,`打哈欠,困,无聊`],[`🥲`,`smiling face with tear`,`smileys`,``],[`🥳`,`face with party horn and party hat`,`smileys`,`庆祝,派对,欢呼`],[`🥴`,`face with uneven eyes and wavy mouth`,`smileys`,`晕,醉,头昏`],[`🥵`,`overheated face`,`smileys`,`热`],[`🥶`,`freezing face`,`smileys`,`冷`],[`🥷`,`ninja`,`people`,`忍者,忍者`],[`🥸`,`disguised face`,`symbols`,`伪装`],[`🥹`,`face holding back tears`,`symbols`,`感动,忍住,哭,泪目`],[`🥺`,`face with pleading eyes`,`smileys`,`可怜,委屈,求`],[`🥻`,`sari`,`symbols`,`纱丽,印度`],[`🥼`,`lab coat`,`symbols`,``],[`🥽`,`goggles`,`symbols`,``],[`🥾`,`hiking boot`,`symbols`,`靴子,登山鞋`],[`🥿`,`flat shoe`,`symbols`,`平底鞋,鞋`],[`🦀`,`crab`,`animals`,`螃蟹,海鲜`],[`🦁`,`lion face`,`animals`,``],[`🦂`,`scorpion`,`animals`,``],[`🦃`,`turkey`,`animals`,`火鸡,感恩节`],[`🦄`,`unicorn face`,`animals`,`独角兽,梦幻`],[`🦅`,`eagle`,`animals`,`老鹰,鹰`],[`🦆`,`duck`,`animals`,`鸭子,鸭`],[`🦇`,`bat`,`animals`,`蝙蝠`],[`🦈`,`shark`,`animals`,`鲨鱼,鱼`],[`🦉`,`owl`,`animals`,`猫头鹰,智慧`],[`🦊`,`fox face`,`animals`,``],[`🦋`,`butterfly`,`animals`,``],[`🦌`,`deer`,`animals`,`鹿,麋鹿`],[`🦍`,`gorilla`,`animals`,``],[`🦎`,`lizard`,`animals`,`蜥蜴,爬行动物`],[`🦏`,`rhinoceros`,`animals`,`犀牛`],[`🦐`,`shrimp`,`animals`,`虾,海鲜`],[`🦑`,`squid`,`animals`,`鱿鱼,海鲜`],[`🦒`,`giraffe face`,`animals`,`长颈鹿`],[`🦓`,`zebra face`,`animals`,`斑马`],[`🦔`,`hedgehog`,`animals`,`刺猬`],[`🦕`,`sauropod`,`animals`,`恐龙,雷龙`],[`🦖`,`t-rex`,`animals`,`恐龙,霸王龙`],[`🦗`,`cricket`,`animals`,``],[`🦘`,`kangaroo`,`animals`,`袋鼠`],[`🦙`,`llama`,`animals`,`羊驼,草泥马`],[`🦚`,`peacock`,`animals`,`孔雀,开屏`],[`🦛`,`hippopotamus`,`animals`,`河马`],[`🦜`,`parrot`,`animals`,`鹦鹉`],[`🦝`,`raccoon`,`animals`,`浣熊`],[`🦞`,`lobster`,`animals`,`龙虾,海鲜`],[`🦟`,`mosquito`,`animals`,``],[`🦠`,`microbe`,`animals`,``],[`🦡`,`badger`,`animals`,`獾`],[`🦢`,`swan`,`animals`,`天鹅,鹅`],[`🦣`,`mammoth`,`animals`,`猛犸象`],[`🦤`,`dodo`,`animals`,`渡渡鸟`],[`🦥`,`sloth`,`animals`,`树懒`],[`🦦`,`otter`,`animals`,`水獭`],[`🦧`,`orangutan`,`animals`,``],[`🦨`,`skunk`,`animals`,`臭鼬`],[`🦩`,`flamingo`,`animals`,`火烈鸟,红鹤`],[`🦪`,`oyster`,`animals`,`生蚝,牡蛎`],[`🦫`,`beaver`,`animals`,`河狸,海狸`],[`🦬`,`bison`,`animals`,`野牛,水牛`],[`🦭`,`seal`,`animals`,`海豹,海狮`],[`🦮`,`guide dog`,`animals`,`导盲犬,狗`],[`🦯`,`probing cane`,`symbols`,``],[`🦰`,`emoji component red hair`,`people`,`红发,头发,发色`],[`🦱`,`emoji component curly hair`,`people`,`卷发,头发`],[`🦲`,`emoji component bald`,`people`,`光头,秃头`],[`🦳`,`emoji component white hair`,`people`,`白发,头发`],[`🦴`,`bone`,`people`,``],[`🦵`,`leg`,`people`,`腿,大腿`],[`🦶`,`foot`,`people`,`脚,足`],[`🦷`,`tooth`,`people`,`牙齿,牙`],[`🦸`,`superhero`,`people`,`英雄`],[`🦹`,`supervillain`,`people`,`超级反派,坏人,反派`],[`🦺`,`safety vest`,`symbols`,``],[`🦻`,`ear with hearing aid`,`symbols`,`助听器,耳朵`],[`🦼`,`motorized wheelchair`,`people`,``],[`🦽`,`manual wheelchair`,`people`,``],[`🦾`,`mechanical arm`,`people`,`机械臂,机器人,义肢`],[`🦿`,`mechanical leg`,`people`,`机械腿,义肢`],[`🧀`,`cheese wedge`,`food`,`奶酪,芝士`],[`🧁`,`cupcake`,`food`,`纸杯蛋糕,杯子蛋糕`],[`🧂`,`salt shaker`,`food`,``],[`🧃`,`beverage box`,`food`,`果汁盒,饮料`],[`🧄`,`garlic`,`food`,`大蒜,蒜`],[`🧅`,`onion`,`food`,`洋葱`],[`🧆`,`falafel`,`food`,`鹰嘴豆丸子`],[`🧇`,`waffle`,`food`,`华夫饼`],[`🧈`,`butter`,`food`,`黄油,奶油`],[`🧉`,`mate drink`,`food`,`马黛茶`],[`🧊`,`ice cube`,`food`,`冰块,冰`],[`🧋`,`bubble tea`,`food`,`奶茶,珍珠奶茶`],[`🧌`,`troll`,`symbols`,`巨魔,妖怪`],[`🧍`,`standing person`,`symbols`,`站立,站着,人`],[`🧎`,`kneeling person`,`symbols`,`跪,跪下,祈祷`],[`🧏`,`deaf person`,`symbols`,``],[`🧐`,`face with monocle`,`people`,`检查,研究,眼镜`],[`🧑`,`adult`,`people`,`人`],[`🧒`,`child`,`people`,``],[`🧓`,`older adult`,`people`,`老人,奶奶,爷爷`],[`🧔`,`bearded person`,`people`,`胡子,胡须,大叔`],[`🧕`,`person with headscarf`,`people`,`头巾`],[`🧖`,`person in steamy room`,`people`,`桑拿,蒸汽,洗澡`],[`🧗`,`person climbing`,`people`,`攀岩`],[`🧘`,`person in lotus position`,`people`,`打坐`],[`🧙`,`mage`,`people`,`巫师,魔法师,法师`],[`🧚`,`fairy`,`people`,`仙女,精灵,小仙女`],[`🧛`,`vampire`,`people`,`吸血鬼,德古拉`],[`🧜`,`merperson`,`people`,`美人鱼,人鱼`],[`🧝`,`elf`,`people`,`精灵,耳朵`],[`🧞`,`genie`,`people`,`灯神,精灵,神灯`],[`🧟`,`zombie`,`people`,`僵尸,丧尸`],[`🧠`,`brain`,`people`,`大脑,思考,记忆,AI`],[`🧡`,`orange heart`,`people`,``],[`🧢`,`billed cap`,`people`,`棒球帽,帽子`],[`🧣`,`scarf`,`people`,`围巾,冬天`],[`🧤`,`gloves`,`people`,`手套,冬天`],[`🧥`,`coat`,`people`,`大衣,外套`],[`🧦`,`socks`,`people`,`袜子`],[`🧧`,`red gift envelope`,`objects`,`红包,利是,新年`],[`🧨`,`firecracker`,`objects`,``],[`🧩`,`jigsaw puzzle piece`,`objects`,`拼图,拼图游戏`],[`🧪`,`test tube`,`objects`,`试管,实验,化学,科学`],[`🧫`,`petri dish`,`objects`,`培养皿,实验,细菌`],[`🧬`,`dna double helix`,`objects`,`DNA,基因,生物`],[`🧭`,`compass`,`objects`,`指南针`],[`🧮`,`abacus`,`objects`,`算盘,计算`],[`🧯`,`fire extinguisher`,`objects`,`灭火器,消防`],[`🧰`,`toolbox`,`objects`,`工具箱,工具`],[`🧱`,`brick`,`objects`,`砖`],[`🧲`,`magnet`,`objects`,`磁铁,磁性`],[`🧳`,`luggage`,`objects`,`行李箱`],[`🧴`,`lotion bottle`,`objects`,`乳液,护肤,防晒`],[`🧵`,`spool of thread`,`objects`,`线,针线,缝纫`],[`🧶`,`ball of yarn`,`objects`,`毛线,织毛衣`],[`🧷`,`safety pin`,`objects`,`别针,安全别针`],[`🧸`,`teddy bear`,`objects`,`泰迪熊,玩具熊`],[`🧹`,`broom`,`objects`,`扫帚`],[`🧺`,`basket`,`objects`,`篮子`],[`🧻`,`roll of paper`,`objects`,`纸巾`],[`🧼`,`bar of soap`,`objects`,`肥皂,洗手,清洁`],[`🧽`,`sponge`,`objects`,`海绵,清洁`],[`🧾`,`receipt`,`objects`,`收据`],[`🧿`,`nazar amulet`,`objects`,`护身符`],[`🩰`,`ballet shoes`,`activity`,`芭蕾`],[`🩱`,`one-piece swimsuit`,`activity`,`泳衣`],[`🩲`,`briefs`,`activity`,`泳裤`],[`🩳`,`shorts`,`activity`,`短裤`],[`🩴`,`thong sandal`,`activity`,`凉拖`],[`🩵`,`light blue heart`,`activity`,`浅蓝`],[`🩶`,`grey heart`,`activity`,`灰心`],[`🩷`,`pink heart`,`activity`,`粉色`],[`🩸`,`drop of blood`,`activity`,`血`],[`🩹`,`adhesive bandage`,`activity`,`创可贴`],[`🩺`,`stethoscope`,`activity`,`听诊器`],[`🩻`,`x-ray`,`activity`,`X光`],[`🩼`,`crutch`,`activity`,`拐杖`],[`🪀`,`yo-yo`,`objects`,`玩具`],[`🪁`,`kite`,`objects`,`风筝`],[`🪂`,`parachute`,`objects`,`跳伞`],[`🪃`,`boomerang`,`objects`,``],[`🪄`,`magic wand`,`objects`,`魔杖,魔法,魔术`],[`🪅`,`pinata`,`objects`,`皮纳塔`],[`🪆`,`nesting dolls`,`objects`,``],[`🪇`,`maracas`,`objects`,`沙锤`],[`🪈`,`flute`,`objects`,`笛子`],[`🪐`,`ringed planet`,`objects`,``],[`🪑`,`chair`,`objects`,`椅子`],[`🪒`,`razor`,`objects`,`剃须刀,剃刀`],[`🪓`,`axe`,`objects`,`斧头,斧子`],[`🪔`,`diya lamp`,`objects`,`油灯`],[`🪕`,`banjo`,`objects`,`班卓琴`],[`🪖`,`military helmet`,`objects`,`军盔`],[`🪗`,`accordion`,`objects`,`手风琴`],[`🪘`,`long drum`,`objects`,`鼓`],[`🪙`,`coin`,`objects`,`金币`],[`🪚`,`carpentry saw`,`objects`,`锯子,锯`],[`🪛`,`screwdriver`,`objects`,`螺丝刀`],[`🪜`,`ladder`,`objects`,`梯子`],[`🪝`,`hook`,`objects`,`钩子,挂钩`],[`🪞`,`mirror`,`objects`,`镜子`],[`🪟`,`window`,`objects`,`窗户`],[`🪠`,`plunger`,`objects`,`皮搋子,通马桶`],[`🪡`,`sewing needle`,`objects`,`针,缝纫,刺绣`],[`🪢`,`knot`,`objects`,``],[`🪣`,`bucket`,`objects`,`水桶,桶`],[`🪤`,`mouse trap`,`objects`,`捕鼠器`],[`🪥`,`toothbrush`,`objects`,`牙刷,刷牙`],[`🪦`,`headstone`,`objects`,`墓碑`],[`🪧`,`placard`,`objects`,`告示牌`],[`🪨`,`rock`,`objects`,`石头,岩石`],[`🪩`,`mirror ball`,`objects`,`迪斯科球`],[`🪪`,`identification card`,`objects`,`身份证`],[`🪫`,`low battery`,`objects`,`电池,没电,低电量`],[`🪬`,`hamsa`,`objects`,`手掌印,护身符`],[`🪭`,`folding hand fan`,`objects`,``],[`🪮`,`hair pick`,`objects`,`梳子`],[`🪯`,`khanda`,`objects`,``],[`🪰`,`fly`,`objects`,`苍蝇,飞虫`],[`🪱`,`worm`,`objects`,``],[`🪲`,`beetle`,`objects`,`甲虫,昆虫`],[`🪳`,`cockroach`,`objects`,`蟑螂,虫子`],[`🪴`,`potted plant`,`objects`,`盆栽,植物,绿植`],[`🪵`,`wood`,`objects`,`木头,柴火,木`],[`🪶`,`feather`,`objects`,`羽毛,羽毛笔`],[`🪷`,`lotus`,`objects`,`莲花`],[`🪸`,`coral`,`objects`,`珊瑚`],[`🪹`,`empty nest`,`objects`,`鸟巢`],[`🪺`,`nest with eggs`,`objects`,`鸟巢`],[`🪻`,`hyacinth`,`objects`,`风信子`],[`🪼`,`jellyfish`,`objects`,`水母`],[`🪽`,`wing`,`objects`,`翅膀`],[`🪿`,`goose`,`objects`,`鹅`],[`🫀`,`anatomical heart`,`objects`,`心脏,心跳`],[`🫁`,`lungs`,`objects`,`肺,呼吸`],[`🫂`,`people hugging`,`objects`,`拥抱,人,朋友`],[`🫃`,`pregnant man`,`objects`,`孕妇,怀孕`],[`🫄`,`pregnant person`,`objects`,`孕妇,怀孕`],[`🫅`,`person with crown`,`objects`,`国王,王子,皇冠`],[`🫎`,`moose`,`objects`,`驼鹿,麋鹿`],[`🫏`,`donkey`,`objects`,`驴,动物`],[`🫐`,`blueberries`,`food`,`蓝莓`],[`🫑`,`bell pepper`,`food`,`甜椒,彩椒`],[`🫒`,`olive`,`food`,`橄榄`],[`🫓`,`flatbread`,`food`,`薄饼,饼`],[`🫔`,`tamale`,`food`,`玉米粉蒸肉`],[`🫕`,`fondue`,`food`,`奶酪火锅`],[`🫖`,`teapot`,`food`,`茶壶,茶`],[`🫗`,`pouring liquid`,`food`,`倒,倒水,水杯`],[`🫘`,`beans`,`food`,`豆子,红豆`],[`🫙`,`jar`,`food`,`罐子,玻璃罐`],[`🫚`,`ginger root`,`food`,`姜,生姜`],[`🫛`,`pea pod`,`food`,`豌豆荚,豆`],[`🫠`,`melting face`,`smileys`,`融化`],[`🫡`,`saluting face`,`smileys`,`敬礼`],[`🫢`,`face with open eyes and hand over mouth`,`smileys`,`捂眼`],[`🫣`,`face with peeking eye`,`smileys`,`偷看`],[`🫤`,`face with diagonal mouth`,`smileys`,`撇嘴`],[`🫥`,`dotted line face`,`smileys`,`隐形`],[`🫦`,`biting lip`,`smileys`,`咬唇,嘴唇`],[`🫧`,`bubbles`,`smileys`,`泡泡`],[`🫨`,`shaking face`,`smileys`,`摇晃,震动,抖`],[`🫰`,`hand with index finger and thumb crossed`,`people`,`比心,手指,捏`],[`🫱`,`rightwards hand`,`people`,`手,右边,推`],[`🫲`,`leftwards hand`,`people`,`手,左边,推`],[`🫳`,`palm down hand`,`people`,`手,向下,放`],[`🫴`,`palm up hand`,`people`,`手,向上,举`],[`🫵`,`index pointing at the viewer`,`people`,`指,你`],[`🫶`,`heart hands`,`people`,`比心,爱心,手势`],[`🫷`,`leftwards pushing hand`,`people`,`手,推,右边`],[`🫸`,`rightwards pushing hand`,`people`,`手,推,左边`],[`‼`,`double exclamation mark`,`symbols`,``],[`‼️`,`double exclamation mark`,`symbols`,``],[`⁉`,`exclamation question mark`,`symbols`,``],[`⁉️`,`exclamation question mark`,`symbols`,``],[`™`,`trade mark sign`,`symbols`,``],[`™️`,`trade mark sign`,`symbols`,``],[`ℹ`,`information source`,`symbols`,``],[`ℹ️`,`information source`,`symbols`,``],[`↔`,`left right arrow`,`symbols`,``],[`↔️`,`left right arrow`,`symbols`,``],[`↕`,`up down arrow`,`symbols`,``],[`↕️`,`up down arrow`,`symbols`,``],[`↖`,`north west arrow`,`symbols`,``],[`↖️`,`north west arrow`,`symbols`,``],[`↗`,`north east arrow`,`symbols`,``],[`↗️`,`north east arrow`,`symbols`,``],[`↘`,`south east arrow`,`symbols`,``],[`↘️`,`south east arrow`,`symbols`,``],[`↙`,`south west arrow`,`symbols`,``],[`↙️`,`south west arrow`,`symbols`,``],[`↩`,`leftwards arrow with hook`,`symbols`,``],[`↩️`,`leftwards arrow with hook`,`symbols`,``],[`↪`,`rightwards arrow with hook`,`symbols`,``],[`↪️`,`rightwards arrow with hook`,`symbols`,``],[`⌚`,`watch`,`objects`,`手表`],[`⌚️`,`watch`,`objects`,``],[`⌛`,`hourglass`,`objects`,`沙漏,时间,等待`],[`⌛️`,`hourglass`,`objects`,``],[`⌨`,`keyboard`,`symbols`,``],[`⌨️`,`keyboard`,`symbols`,`键盘,打字`],[`⏏`,`eject symbol`,`symbols`,``],[`⏏️`,`eject symbol`,`symbols`,``],[`⏩`,`black right-pointing double triangle`,`objects`,``],[`⏪`,`black left-pointing double triangle`,`objects`,``],[`⏫`,`black up-pointing double triangle`,`objects`,``],[`⏬`,`black down-pointing double triangle`,`objects`,``],[`⏭`,`black right-pointing double triangle with vertical bar`,`objects`,``],[`⏭️`,`black right-pointing double triangle with vertical bar`,`objects`,``],[`⏮`,`black left-pointing double triangle with vertical bar`,`objects`,``],[`⏮️`,`black left-pointing double triangle with vertical bar`,`objects`,``],[`⏯`,`black right-pointing triangle with double vertical bar`,`objects`,``],[`⏯️`,`black right-pointing triangle with double vertical bar`,`objects`,``],[`⏰`,`alarm clock`,`objects`,`闹钟,时间,起床`],[`⏱`,`stopwatch`,`objects`,``],[`⏱️`,`stopwatch`,`objects`,`秒表`],[`⏲`,`timer clock`,`objects`,``],[`⏲️`,`timer clock`,`objects`,`计时器`],[`⏳`,`hourglass with flowing sand`,`objects`,`沙漏`],[`⏸`,`double vertical bar`,`symbols`,``],[`⏸️`,`double vertical bar`,`symbols`,``],[`⏹`,`black square for stop`,`symbols`,``],[`⏹️`,`black square for stop`,`symbols`,``],[`⏺`,`black circle for record`,`symbols`,``],[`⏺️`,`black circle for record`,`symbols`,``],[`Ⓜ`,`circled latin capital letter m`,`symbols`,``],[`Ⓜ️`,`circled latin capital letter m`,`symbols`,``],[`▪`,`black small square`,`symbols`,``],[`▪️`,`black small square`,`symbols`,``],[`▫`,`white small square`,`symbols`,``],[`▫️`,`white small square`,`symbols`,``],[`▶`,`black right-pointing triangle`,`symbols`,``],[`▶️`,`black right-pointing triangle`,`symbols`,``],[`◀`,`black left-pointing triangle`,`symbols`,``],[`◀️`,`black left-pointing triangle`,`symbols`,``],[`◻`,`white medium square`,`symbols`,``],[`◻️`,`white medium square`,`symbols`,``],[`◼`,`black medium square`,`symbols`,``],[`◼️`,`black medium square`,`symbols`,``],[`◽`,`white medium small square`,`symbols`,``],[`◾`,`black medium small square`,`symbols`,``],[`◾️`,`black medium small square`,`symbols`,``],[`☀`,`black sun with rays`,`symbols`,``],[`☀️`,`black sun with rays`,`symbols`,`太阳,晴天,阳光`],[`☁`,`cloud`,`symbols`,``],[`☁️`,`cloud`,`symbols`,`云,多云,天气`],[`☂`,`umbrella`,`symbols`,``],[`☂️`,`umbrella`,`symbols`,``],[`☃`,`snowman`,`symbols`,``],[`☃️`,`snowman`,`symbols`,`雪人,冬天,雪`],[`☄`,`comet`,`symbols`,``],[`☄️`,`comet`,`symbols`,``],[`☎`,`black telephone`,`symbols`,``],[`☎️`,`black telephone`,`symbols`,`电话`],[`☑`,`ballot box with check`,`symbols`,``],[`☑️`,`ballot box with check`,`symbols`,``],[`☔`,`umbrella with rain drops`,`symbols`,``],[`☔️`,`umbrella with rain drops`,`symbols`,``],[`☕`,`hot beverage`,`food`,`咖啡,热饮`],[`☕️`,`hot beverage`,`food`,``],[`☘`,`shamrock`,`symbols`,``],[`☘️`,`shamrock`,`symbols`,``],[`☝`,`white up pointing index`,`symbols`,``],[`☝️`,`white up pointing index`,`symbols`,`指,上面,向上`],[`☠`,`skull and crossbones`,`symbols`,``],[`☠️`,`skull and crossbones`,`symbols`,`骷髅,死亡,危险`],[`☢`,`radioactive sign`,`symbols`,``],[`☢️`,`radioactive sign`,`symbols`,``],[`☣`,`biohazard sign`,`symbols`,``],[`☣️`,`biohazard sign`,`symbols`,``],[`☦`,`orthodox cross`,`symbols`,``],[`☦️`,`orthodox cross`,`symbols`,``],[`☪`,`star and crescent`,`symbols`,``],[`☪️`,`star and crescent`,`symbols`,``],[`☮`,`peace symbol`,`symbols`,``],[`☮️`,`peace symbol`,`symbols`,``],[`☯`,`yin yang`,`symbols`,``],[`☯️`,`yin yang`,`symbols`,``],[`☸`,`wheel of dharma`,`symbols`,``],[`☸️`,`wheel of dharma`,`symbols`,``],[`☹`,`white frowning face`,`smileys`,``],[`☹️`,`white frowning face`,`smileys`,``],[`☺`,`white smiling face`,`smileys`,``],[`☺️`,`white smiling face`,`smileys`,``],[`♀`,`female sign`,`symbols`,``],[`♀️`,`female sign`,`symbols`,``],[`♂`,`male sign`,`symbols`,``],[`♂️`,`male sign`,`symbols`,``],[`♈`,`aries`,`symbols`,``],[`♈️`,`aries`,`symbols`,``],[`♉`,`taurus`,`symbols`,``],[`♉️`,`taurus`,`symbols`,``],[`♊`,`gemini`,`symbols`,``],[`♊️`,`gemini`,`symbols`,``],[`♋`,`cancer`,`symbols`,``],[`♋️`,`cancer`,`symbols`,``],[`♌`,`leo`,`symbols`,``],[`♌️`,`leo`,`symbols`,``],[`♍`,`virgo`,`symbols`,``],[`♍️`,`virgo`,`symbols`,``],[`♎`,`libra`,`symbols`,``],[`♎️`,`libra`,`symbols`,``],[`♏`,`scorpius`,`symbols`,``],[`♏️`,`scorpius`,`symbols`,``],[`♐`,`sagittarius`,`symbols`,``],[`♐️`,`sagittarius`,`symbols`,``],[`♑`,`capricorn`,`symbols`,``],[`♑️`,`capricorn`,`symbols`,``],[`♒`,`aquarius`,`symbols`,``],[`♒️`,`aquarius`,`symbols`,``],[`♓`,`pisces`,`symbols`,``],[`♓️`,`pisces`,`symbols`,``],[`♟`,`black chess pawn`,`symbols`,``],[`♟️`,`black chess pawn`,`symbols`,`棋子,国际象棋,象棋`],[`♠`,`black spade suit`,`symbols`,``],[`♠️`,`black spade suit`,`symbols`,``],[`♣`,`black club suit`,`symbols`,``],[`♣️`,`black club suit`,`symbols`,``],[`♥`,`black heart suit`,`symbols`,``],[`♥️`,`black heart suit`,`symbols`,``],[`♦`,`black diamond suit`,`symbols`,``],[`♦️`,`black diamond suit`,`symbols`,``],[`♨`,`hot springs`,`symbols`,``],[`♨️`,`hot springs`,`symbols`,`温泉,热泉`],[`♻`,`black universal recycling symbol`,`symbols`,``],[`♻️`,`black universal recycling symbol`,`symbols`,``],[`♾`,`permanent paper sign`,`symbols`,``],[`♾️`,`permanent paper sign`,`symbols`,``],[`♿`,`wheelchair symbol`,`symbols`,``],[`♿️`,`wheelchair symbol`,`symbols`,``],[`⚒`,`hammer and pick`,`symbols`,``],[`⚒️`,`hammer and pick`,`symbols`,`锤子,工具`],[`⚓`,`anchor`,`symbols`,`锚,航海,停泊`],[`⚔`,`crossed swords`,`symbols`,``],[`⚔️`,`crossed swords`,`symbols`,`剑,交叉,战斗`],[`⚕`,`staff of aesculapius`,`symbols`,``],[`⚕️`,`staff of aesculapius`,`symbols`,``],[`⚖`,`scales`,`symbols`,``],[`⚖️`,`scales`,`symbols`,``],[`⚗`,`alembic`,`symbols`,``],[`⚗️`,`alembic`,`symbols`,``],[`⚙`,`gear`,`symbols`,``],[`⚙️`,`gear`,`symbols`,``],[`⚛`,`atom symbol`,`symbols`,``],[`⚛️`,`atom symbol`,`symbols`,``],[`⚜`,`fleur-de-lis`,`symbols`,``],[`⚜️`,`fleur-de-lis`,`symbols`,``],[`⚠`,`warning sign`,`symbols`,``],[`⚠️`,`warning sign`,`symbols`,``],[`⚡`,`high voltage sign`,`symbols`,``],[`⚧`,`male with stroke and male and female sign`,`symbols`,``],[`⚧️`,`male with stroke and male and female sign`,`symbols`,``],[`⚪`,`medium white circle`,`symbols`,``],[`⚪️`,`medium white circle`,`symbols`,``],[`⚫`,`medium black circle`,`symbols`,``],[`⚰`,`coffin`,`symbols`,``],[`⚰️`,`coffin`,`symbols`,`棺材,死亡`],[`⚱`,`funeral urn`,`symbols`,``],[`⚱️`,`funeral urn`,`symbols`,`骨灰盒,死亡`],[`⚽`,`soccer ball`,`activity`,`足球,球`],[`⚽️`,`soccer ball`,`activity`,``],[`⚾`,`baseball`,`activity`,`棒球,球`],[`⚾️`,`baseball`,`activity`,``],[`⛄`,`snowman without snow`,`symbols`,`雪人,冬天`],[`⛄️`,`snowman without snow`,`symbols`,``],[`⛅`,`sun behind cloud`,`symbols`,`太阳,云,多云`],[`⛈`,`thunder cloud and rain`,`symbols`,``],[`⛈️`,`thunder cloud and rain`,`symbols`,`雷雨,雷暴,天气`],[`⛎`,`ophiuchus`,`symbols`,``],[`⛏`,`pick`,`symbols`,``],[`⛏️`,`pick`,`symbols`,`镐,工具`],[`⛑`,`helmet with white cross`,`symbols`,``],[`⛑️`,`helmet with white cross`,`symbols`,`头盔,救援,安全`],[`⛓`,`chains`,`symbols`,``],[`⛓️`,`chains`,`symbols`,``],[`⛔`,`no entry`,`symbols`,``],[`⛩`,`shinto shrine`,`travel`,``],[`⛩️`,`shinto shrine`,`travel`,`鸟居,神社,日本`],[`⛪`,`church`,`travel`,`教堂`],[`⛰`,`mountain`,`travel`,``],[`⛰️`,`mountain`,`travel`,`山,山峰`],[`⛱`,`umbrella on ground`,`travel`,``],[`⛱️`,`umbrella on ground`,`travel`,``],[`⛲`,`fountain`,`travel`,`喷泉`],[`⛲️`,`fountain`,`travel`,``],[`⛳`,`flag in hole`,`activity`,`高尔夫,高尔夫球,球洞`],[`⛳️`,`flag in hole`,`activity`,``],[`⛴`,`ferry`,`travel`,``],[`⛴️`,`ferry`,`travel`,`渡轮,船`],[`⛵`,`sailboat`,`travel`,`帆船,船`],[`⛵️`,`sailboat`,`travel`,``],[`⛷`,`skier`,`activity`,``],[`⛷️`,`skier`,`activity`,``],[`⛸`,`ice skate`,`activity`,``],[`⛸️`,`ice skate`,`activity`,`溜冰,冰刀,滑冰`],[`⛹`,`person with ball`,`activity`,``],[`⛹️`,`person with ball`,`activity`,``],[`⛺`,`tent`,`travel`,`帐篷,露营`],[`⛺️`,`tent`,`travel`,``],[`⛽`,`fuel pump`,`travel`,`加油站,加油,汽油`],[`✂`,`black scissors`,`symbols`,``],[`✂️`,`black scissors`,`symbols`,``],[`✅`,`white heavy check mark`,`symbols`,``],[`✈`,`airplane`,`travel`,``],[`✈️`,`airplane`,`travel`,`飞机,航班,起飞`],[`✉`,`envelope`,`symbols`,``],[`✉️`,`envelope`,`symbols`,`信封,邮件,信`],[`✊`,`raised fist`,`people`,`拳头,加油,力量`],[`✋`,`raised hand`,`people`,`手,举手,停`],[`✌`,`victory hand`,`symbols`,``],[`✌️`,`victory hand`,`symbols`,`胜利,耶,剪刀手`],[`✍`,`writing hand`,`symbols`,``],[`✍️`,`writing hand`,`symbols`,`写字,写作,手`],[`✏`,`pencil`,`symbols`,``],[`✏️`,`pencil`,`symbols`,``],[`✒`,`black nib`,`symbols`,``],[`✒️`,`black nib`,`symbols`,``],[`✔`,`heavy check mark`,`symbols`,``],[`✔️`,`heavy check mark`,`symbols`,``],[`✖`,`heavy multiplication x`,`symbols`,``],[`✖️`,`heavy multiplication x`,`symbols`,``],[`✝`,`latin cross`,`symbols`,``],[`✝️`,`latin cross`,`symbols`,``],[`✡`,`star of david`,`symbols`,``],[`✡️`,`star of david`,`symbols`,``],[`✨`,`sparkles`,`symbols`,`星星,闪光,发光`],[`✳`,`eight spoked asterisk`,`symbols`,``],[`✳️`,`eight spoked asterisk`,`symbols`,``],[`✴`,`eight pointed black star`,`symbols`,``],[`✴️`,`eight pointed black star`,`symbols`,``],[`❄`,`snowflake`,`symbols`,``],[`❄️`,`snowflake`,`symbols`,`雪花,雪,冬天,冷`],[`❇`,`sparkle`,`symbols`,``],[`❇️`,`sparkle`,`symbols`,``],[`❌`,`cross mark`,`symbols`,``],[`❎`,`negative squared cross mark`,`symbols`,``],[`❓`,`black question mark ornament`,`symbols`,``],[`❔`,`white question mark ornament`,`symbols`,``],[`❕`,`white exclamation mark ornament`,`symbols`,``],[`❗`,`heavy exclamation mark symbol`,`symbols`,``],[`❗️`,`heavy exclamation mark symbol`,`symbols`,``],[`❣`,`heavy heart exclamation mark ornament`,`symbols`,``],[`❣️`,`heavy heart exclamation mark ornament`,`symbols`,`爱心,感叹号`],[`❤`,`heavy black heart`,`smileys`,``],[`❤️`,`heavy black heart`,`smileys`,`爱心,红心,爱`],[`➕`,`heavy plus sign`,`symbols`,``],[`➖`,`heavy minus sign`,`symbols`,``],[`➗`,`heavy division sign`,`symbols`,``],[`➡`,`black rightwards arrow`,`symbols`,``],[`➡️`,`black rightwards arrow`,`symbols`,``],[`➰`,`curly loop`,`symbols`,``],[`➿`,`double curly loop`,`symbols`,``],[`⬅`,`leftwards black arrow`,`symbols`,``],[`⬅️`,`leftwards black arrow`,`symbols`,``],[`⬆`,`upwards black arrow`,`symbols`,``],[`⬆️`,`upwards black arrow`,`symbols`,``],[`⬇`,`downwards black arrow`,`symbols`,``],[`⬇️`,`downwards black arrow`,`symbols`,``],[`⬛`,`black large square`,`symbols`,``],[`⬛️`,`black large square`,`symbols`,``],[`⬜`,`white large square`,`symbols`,``],[`⬜️`,`white large square`,`symbols`,``],[`⭐`,`white medium star`,`symbols`,`星星,五星,评分`],[`⭕`,`heavy large circle`,`symbols`,``],[`⭕️`,`heavy large circle`,`symbols`,``],[`⤴`,`arrow pointing rightwards then curving upwards`,`symbols`,``],[`⤴️`,`arrow pointing rightwards then curving upwards`,`symbols`,``],[`⤵`,`arrow pointing rightwards then curving downwards`,`symbols`,``],[`⤵️`,`arrow pointing rightwards then curving downwards`,`symbols`,``],[`〰`,`wavy dash`,`symbols`,``],[`〰️`,`wavy dash`,`symbols`,``],[`〽`,`part alternation mark`,`symbols`,``],[`〽️`,`part alternation mark`,`symbols`,``],[`㊗`,`circled ideograph congratulation`,`symbols`,``],[`㊗️`,`circled ideograph congratulation`,`symbols`,``],[`㊙`,`circled ideograph secret`,`symbols`,``],[`㊙️`,`circled ideograph secret`,`symbols`,``],[`©`,`copyright sign`,`symbols`,``],[`©️`,`copyright sign`,`symbols`,``],[`®`,`registered sign`,`symbols`,``],[`®️`,`registered sign`,`symbols`,``],[`👨💻`,`man technologist`,`people`,`程序员,开发者,工程师,码农`],[`👩💻`,`woman technologist`,`people`,`程序员,开发者,工程师`],[`🧑💻`,`technologist`,`people`,`程序员,开发者,工程师`],[`👨🔧`,`man mechanic`,`people`,``],[`👩🔧`,`woman mechanic`,`people`,``],[`👨🎨`,`man artist`,`people`,``],[`👩🎨`,`woman artist`,`people`,``],[`👨🚀`,`man astronaut`,`people`,``],[`👩🚀`,`woman astronaut`,`people`,``],[`👨⚕️`,`man health worker`,`people`,``],[`👩⚕️`,`woman health worker`,`people`,``],[`👨🏫`,`man teacher`,`people`,``],[`👩🏫`,`woman teacher`,`people`,``],[`👨🍳`,`man cook`,`people`,``],[`👩🍳`,`woman cook`,`people`,``],[`👨🌾`,`man farmer`,`people`,``],[`👩🌾`,`woman farmer`,`people`,``],[`👩🏭`,`woman factory worker`,`people`,``],[`👨🎓`,`man student`,`people`,``],[`👩🎓`,`woman student`,`people`,``],[`👨🚒`,`man firefighter`,`people`,``],[`👩🚒`,`woman firefighter`,`people`,``],[`👨⚖️`,`man judge`,`people`,``],[`👩⚖️`,`woman judge`,`people`,``],[`👨💼`,`man office worker`,`people`,``],[`👩💼`,`woman office worker`,`people`,``],[`👨🎤`,`man singer`,`people`,``],[`👩🎤`,`woman singer`,`people`,``],[`👨🦰`,`man red hair`,`people`,``],[`👩🦰`,`woman red hair`,`people`,``],[`👨🦱`,`man curly hair`,`people`,``],[`👩🦱`,`woman curly hair`,`people`,``],[`👩🦲`,`woman bald`,`people`,``],[`👨🦳`,`man white hair`,`people`,``],[`👩🦳`,`woman white hair`,`people`,``],[`👩❤️👨`,`couple with heart`,`people`,``],[`👨❤️👨`,`couple with heart`,`people`,``],[`👩❤️👩`,`couple with heart`,`people`,``],[`👨👩👧`,`family man woman girl`,`people`,``],[`👨👩👦`,`family man woman boy`,`people`,``],[`👨👩👧👦`,`family man woman girl boy`,`people`,``],[`👨👩👦👦`,`man`,`people`,``],[`👨👩👧👧`,`family man woman girl girl`,`people`,``],[`👩👩👧`,`family woman woman girl`,`people`,``],[`👨👨👧`,`family man man girl`,`people`,``],[`👨👦`,`family man boy`,`people`,``],[`👩👧`,`family woman girl`,`people`,``],[`👨👧👦`,`family man girl boy`,`people`,``],[`👩❤️💋👨`,`kiss woman man`,`people`,``],[`🧑🤝🧑`,`people holding hands`,`people`,``],[`❤️🔥`,`heart on fire`,`smileys`,``],[`🧑🚒`,`firefighter`,`people`,`消防员`],[`🧑🏭`,`factory worker`,`people`,``],[`🧑🎓`,`student`,`people`,`学生,毕业生,大学生`],[`🧑🏫`,`teacher`,`people`,`老师,教师,教授`],[`🧑🎤`,`singer`,`people`,`歌手,歌星`],[`🧑⚕️`,`health worker`,`people`,`医生,医疗`],[`🧑⚖️`,`judge`,`people`,`法官,审判`],[`🧑🍳`,`cook`,`people`,`厨师,大厨`],[`🧑🌾`,`farmer`,`people`,`农民,农夫`],[`🧑🎨`,`artist`,`people`,`画家,艺术家`],[`🧑🔬`,`scientist`,`people`,``],[`🧑🔧`,`mechanic`,`people`,`技工,维修工`],[`🧑💼`,`office worker`,`people`,`白领,上班族,职员`],[`🧑🚀`,`astronaut`,`people`,`宇航员,太空人`],[`🏃♂️`,`man running`,`activity`,``],[`🏃♀️`,`woman running`,`activity`,``],[`🚶♂️`,`man walking`,`travel`,``],[`🚶♀️`,`woman walking`,`travel`,``],[`🧎♂️`,`man kneeling`,`symbols`,``],[`🧎♀️`,`woman kneeling`,`symbols`,``],[`🏋️♂️`,`man lifting weights`,`activity`,``],[`🏋️♀️`,`woman lifting weights`,`activity`,``],[`🤸♂️`,`man cartwheeling`,`people`,``],[`🤸♀️`,`woman cartwheeling`,`people`,``],[`⛹️♂️`,`man bouncing ball`,`activity`,``],[`⛹️♀️`,`woman bouncing ball`,`activity`,``],[`🤾♂️`,`man playing handball`,`activity`,``],[`🤾♀️`,`woman playing handball`,`activity`,``],[`🧘♀️`,`woman in lotus position`,`people`,``],[`🏄♂️`,`man surfing`,`activity`,``],[`🏄♀️`,`woman surfing`,`activity`,``],[`🏊♂️`,`man swimming`,`activity`,``],[`🏊♀️`,`woman swimming`,`activity`,``],[`🚴♂️`,`man biking`,`travel`,``],[`🚴♀️`,`woman biking`,`travel`,``],[`🚵♂️`,`man mountain biking`,`travel`,``],[`🚵♀️`,`woman mountain biking`,`travel`,``],[`👯♂️`,`men with bunny ears`,`people`,``],[`👯♀️`,`women with bunny ears`,`people`,``],[`🧖♂️`,`man in steamy room`,`people`,``],[`🧖♀️`,`woman in steamy room`,`people`,``],[`🧗♂️`,`man climbing`,`people`,``],[`🧗♀️`,`woman climbing`,`people`,``],[`🤦♂️`,`man facepalming`,`smileys`,``],[`🤦♀️`,`woman facepalming`,`smileys`,``],[`🤷♂️`,`man shrugging`,`people`,``],[`🤷♀️`,`woman shrugging`,`people`,``],[`🙍♂️`,`person frowning`,`smileys`,``],[`🙍♀️`,`woman frowning`,`smileys`,``],[`🙎♂️`,`man pouting`,`smileys`,``],[`🙎♀️`,`woman pouting`,`smileys`,``],[`🙅♂️`,`man gesturing no`,`smileys`,``],[`🙅♀️`,`woman gesturing no`,`smileys`,``],[`🙆♂️`,`man gesturing ok`,`smileys`,``],[`🙆♀️`,`woman gesturing ok`,`smileys`,``],[`💁♂️`,`man tipping hand`,`people`,``],[`💁♀️`,`woman tipping hand`,`people`,``],[`🙋♂️`,`man raising hand`,`smileys`,``],[`🙋♀️`,`woman raising hand`,`smileys`,``],[`🙇♂️`,`man bowing`,`smileys`,``],[`🙇♀️`,`woman bowing`,`smileys`,``],[`💆♂️`,`man getting massage`,`people`,``],[`💆♀️`,`woman getting massage`,`people`,``],[`💇♂️`,`man getting haircut`,`people`,``],[`💇♀️`,`woman getting haircut`,`people`,``],[`🧞♂️`,`man genie`,`people`,``],[`🧞♀️`,`woman genie`,`people`,``],[`🧟♂️`,`man zombie`,`people`,``],[`🧟♀️`,`woman zombie`,`people`,``],[`🧜♂️`,`merman`,`people`,``],[`🧚♂️`,`man fairy`,`people`,``],[`🧚♀️`,`woman fairy`,`people`,``],[`🧛♂️`,`man vampire`,`people`,``],[`🧛♀️`,`woman vampire`,`people`,``],[`🧙♂️`,`man mage`,`people`,``],[`🧙♀️`,`mage`,`people`,``],[`🧝♂️`,`man elf`,`people`,``],[`🧝♀️`,`woman elf`,`people`,``],[`🦸♂️`,`man superhero`,`people`,``],[`🦸♀️`,`woman superhero`,`people`,``],[`🦹♂️`,`man supervillain`,`people`,``],[`🦹♀️`,`woman supervillain`,`people`,``],[`0️⃣`,`keycap 0`,`symbols`,``],[`1️⃣`,`keycap 1`,`symbols`,``],[`2️⃣`,`keycap 2`,`symbols`,``],[`3️⃣`,`keycap 3`,`symbols`,``],[`4️⃣`,`keycap 4`,`symbols`,``],[`5️⃣`,`keycap 5`,`symbols`,``],[`6️⃣`,`keycap 6`,`symbols`,``],[`7️⃣`,`keycap 7`,`symbols`,``],[`8️⃣`,`keycap 8`,`symbols`,``],[`9️⃣`,`keycap 9`,`symbols`,``],[`#️⃣`,`keycap #`,`symbols`,``],[`*️⃣`,`keycap *`,`symbols`,``],[`🇨🇳`,`flag china`,`flags`,`中国,国旗,五星红旗`],[`🇺🇸`,`flag united states`,`flags`,`美国,国旗,USA`],[`🇬🇧`,`flag united kingdom`,`flags`,`英国,国旗,UK`],[`🇯🇵`,`flag japan`,`flags`,`日本,国旗`],[`🇫🇷`,`flag france`,`flags`,`法国,国旗`],[`🇩🇪`,`flag germany`,`flags`,`德国,国旗`],[`🇮🇹`,`flag italy`,`flags`,`意大利,国旗`],[`🇪🇸`,`flag spain`,`flags`,`西班牙,国旗`],[`🇷🇺`,`flag russia`,`flags`,`俄罗斯,国旗`],[`🇮🇳`,`regional indicator symbol letter i`,`flags`,`印度,国旗`],[`🇧🇷`,`flag brazil`,`flags`,`巴西,国旗`],[`🇨🇦`,`flag canada`,`flags`,`加拿大,国旗`],[`🇦🇺`,`flag australia`,`flags`,`澳大利亚,国旗`],[`🇸🇬`,`flag singapore`,`flags`,`新加坡,国旗`],[`🇭🇰`,`flag hong kong`,`flags`,`香港,国旗,区旗`],[`🇹🇼`,`flag taiwan`,`flags`,`台湾,国旗`],[`🇲🇴`,`flag macau`,`flags`,`澳门,国旗`],[`🇻🇳`,`flag vietnam`,`flags`,`越南,国旗`],[`🇲🇾`,`regional indicator symbol letter m`,`flags`,`马来西亚,国旗`],[`🇮🇩`,`flag indonesia`,`flags`,`印尼,国旗`],[`🇵🇭`,`flag philippines`,`flags`,`菲律宾,国旗`],[`🇹🇷`,`flag turkey`,`flags`,`土耳其,国旗`],[`🇸🇦`,`flag saudi arabia`,`flags`,`沙特,国旗`],[`🇦🇪`,`flag united arab emirates`,`flags`,`阿联酋,国旗`],[`🇳🇱`,`flag netherlands`,`flags`,`荷兰,国旗`],[`🇸🇪`,`flag sweden`,`flags`,`瑞典,国旗`],[`🇨🇭`,`flag switzerland`,`flags`,`瑞士,国旗`],[`🇦🇹`,`flag austria`,`flags`,`奥地利,国旗`],[`🇧🇪`,`flag belgium`,`flags`,`比利时,国旗`],[`🇵🇹`,`flag portugal`,`flags`,`葡萄牙,国旗`],[`🇬🇷`,`flag greece`,`flags`,`希腊,国旗`],[`🇳🇴`,`flag norway`,`flags`,`挪威,国旗`],[`🇩🇰`,`flag denmark`,`flags`,`丹麦,国旗`],[`🇫🇮`,`flag finland`,`flags`,`芬兰,国旗`],[`🇵🇱`,`flag poland`,`flags`,`波兰,国旗`],[`🇺🇦`,`flag ukraine`,`flags`,`乌克兰,国旗`],[`🇮🇱`,`flag israel`,`flags`,`以色列,国旗`],[`🇪🇬`,`flag egypt`,`flags`,`埃及,国旗`],[`🇿🇦`,`flag south africa`,`flags`,`南非,国旗`],[`🇳🇬`,`flag nigeria`,`flags`,`尼日利亚,国旗`],[`🇲🇽`,`flag mexico`,`flags`,`墨西哥,国旗`],[`🇦🇷`,`flag argentina`,`flags`,``],[`🇨🇱`,`flag chile`,`flags`,`智利,国旗`],[`🇰🇿`,`flag kazakhstan`,`flags`,`哈萨克斯坦,国旗`],[`🇺🇿`,`flag uzbekistan`,`flags`,`乌兹别克斯坦,国旗`],[`🇳🇿`,`flag new zealand`,`flags`,`新西兰,国旗`],[`🇮🇪`,`flag ireland`,`flags`,`爱尔兰,国旗`],[`🇨🇿`,`flag czechia`,`flags`,`捷克,国旗`],[`👍🏻`,`thumbs up light skin`,`people`,``],[`👍🏽`,`thumbs up sign`,`people`,``],[`👍🏾`,`thumbs up medium dark skin`,`people`,``],[`👍🏿`,`thumbs up dark skin`,`people`,``],[`👏🏻`,`clapping hands light skin`,`people`,``],[`👏🏼`,`clapping hands medium light skin`,`people`,``],[`👏🏽`,`clapping hands medium skin`,`people`,``],[`👏🏾`,`clapping hands medium dark skin`,`people`,``],[`👏🏿`,`clapping hands dark skin`,`people`,``],[`🙏🏻`,`folded hands light skin`,`smileys`,``],[`🙏🏼`,`folded hands medium light skin`,`smileys`,``],[`🙏🏽`,`folded hands medium skin`,`smileys`,``],[`🙏🏾`,`folded hands medium dark skin`,`smileys`,``],[`🙏🏿`,`folded hands dark skin`,`smileys`,``],[`🏳️🌈`,`rainbow flag`,`flags`,``],[`🏴☠️`,`pirate flag`,`flags`,`海盗旗,海盗`]];n(`zh`,{agentMgr:{allTools:`全部`,defaultAgentName:`默认助手`,defaultAgentDesc:`全能 AI 助手,拥有所有工具能力`,switchedTo:`已切换到:{name}`,editAgent:`编辑助手`,templateLoaded:`已加载模板:{name}`,noSkillsHint:`暂无启用技能(请先确认 Agent 已连接且技能开关已开启)`,nameRequired:`请输入助手名称`,agentUpdated:`助手已更新`,agentCreated:`助手 "{name}" 已创建`,saveFailed:`保存失败:{message}`,confirmDeleteAgentMessage:`确定要删除助手 "{name}" 吗?
|
|
2191
|
+
`);continue}if(a===`/`&&e[i+1]===`*`){for(i+=2;i<e.length&&!(e[i]===`*`&&e[i+1]===`/`);)i+=1;i+=1;continue}t+=a}return t}function QE(e){let t=``,n=!1,r=!1;for(let i of e){if(n){if(r){t+=i,r=!1;continue}if(i===`\\`){t+=i,r=!0;continue}if(i===`"`){n=!1,t+=i;continue}if(i===`
|
|
2192
|
+
`){t+=`\\n`;continue}if(i===`\r`){t+=`\\r`;continue}if(i===` `){t+=`\\t`;continue}let e=i.codePointAt(0);if(e!==void 0&&e<32){t+=`\\u${e.toString(16).padStart(4,`0`)}`;continue}t+=i;continue}i===`"`&&(n=!0),t+=i}return t}function $E(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;i+=1){let a=e[i];if(n){t+=a,r?r=!1:a===`\\`?r=!0:a===`"`&&(n=!1);continue}if(a===`"`){n=!0,t+=a;continue}if(a===`,`){let t=i+1;for(;t<e.length&&/\s/.test(e[t]);)t+=1;if(e[t]===`}`||e[t]===`]`)continue}t+=a}return t}function eD(e){let t=e.match(/```(?:json|JSON)?\s*([\s\S]*?)```/);return t?t[1].trim():``}function tD(e){let t=[],n=eD(e);n&&t.push(n),t.push(e);for(let e of t){let t=ZE(e),n=[t.trim()],r=0;for(let e=0;e<3;e+=1){let e=t.indexOf(`{`,r);if(e===-1)break;let i=XE(t,e);if(!i)break;n.push(i),r=e+i.length}for(let e of n){if(!e)continue;let t=[e,$E(QE(e))];for(let e of t)try{let t=JSON.parse(e);if(typeof t==`string`&&(t=JSON.parse(t)),t&&typeof t==`object`&&!Array.isArray(t))return t}catch{}}}throw Error(`invalid_json`)}function nD(e){let t=YE(e);if(!t)throw Error(`empty_reply`);if(!t.includes(`{`))throw Error(`no_json_object`);let n=tD(t),r=n.action,i=GE(WE(n.message),500);if(r===`ask`){let e=n.question||{},t=WE(e.text),a=Array.isArray(e.options)?e.options.map(WE).filter(Boolean).slice(0,4):[];if(!t||a.length===0)throw Error(`invalid_question`);let o=Number.isInteger(e.recommended)?e.recommended:0;return{action:r,message:i,question:{text:t,options:a,recommended:Math.min(Math.max(o,0),a.length-1),allowCustom:e.allowCustom!==!1}}}if(r===`done`){if(!n.agent||typeof n.agent!=`object`)throw Error(`invalid_agent`);return{action:r,message:i,agent:n.agent}}throw Error(`invalid_action`)}function rD(e={},{tools:t=[],skills:n=[],language:r=`zh`,baseAgent:i=null}={}){let a=[],o=i||null,s=GE(WE(e.name),BE)||GE(WE(o?.name),BE);s||=r===`en`?`New Assistant`:`未命名助手`;let c=WE(e.icon)||WE(o?.icon);(!c||Array.from(c).length>6)&&(c=`🤖`,WE(e.icon)&&a.push({code:`iconFallback`}));let l=GE(WE(e.description)||WE(o?.description),VE),u=GE(WE(e.systemPrompt)||WE(o?.systemPrompt),HE);Array.from(u).length<60&&a.push({code:`promptShort`});let d=Array.isArray(o?.toolIds)&&o.toolIds.length>0?[...o.toolIds]:null,f=new Set([...t.map(e=>e.id),...d||[]]),p=d;if(e.toolIds===null)p=null;else if(Array.isArray(e.toolIds))if(e.toolIds.length===0)p=null;else{let t=[...new Set(e.toolIds.filter(e=>typeof e==`string`&&e))],n=t.filter(e=>f.has(e)),r=t.filter(e=>!f.has(e));r.length&&a.push({code:n.length>0?`toolsDropped`:`toolsAllDropped`,count:r.length,names:r.slice(0,5)}),p=n.length>0?n:d}let m=Array.isArray(o?.skillIds)&&o.skillIds.length>0?[...o.skillIds]:null,h=new Set([...n.map(e=>e.name),...m||[]]),g=m;if(e.skillIds===null)g=null;else if(Array.isArray(e.skillIds))if(e.skillIds.length===0)g=null;else{let t=[...new Set(e.skillIds.filter(e=>typeof e==`string`&&e))],n=t.filter(e=>h.has(e)),r=t.filter(e=>!h.has(e));r.length&&a.push({code:n.length>0?`skillsDropped`:`skillsAllDropped`,count:r.length,names:r.slice(0,5)}),g=n.length>0?n:m}return{draft:{name:s,icon:c,description:l,systemPrompt:u,toolIds:p,skillIds:g,allowSubDispatch:e.allowSubDispatch===void 0?o?.allowSubDispatch===!0:e.allowSubDispatch===!0,model:o?.model??null,temperature:o?.temperature??null,topP:o?.topP??null,mcpExcludedServerIds:Array.isArray(o?.mcpExcludedServerIds)?[...o.mcpExcludedServerIds]:null},warnings:a}}n(`zh`,{agentBuilder:{title:`AI 创建助手`,subtitle:`描述你的需求,AI 会通过几个问题帮你生成配置`,entry:`AI 帮我创建`,editorBanner:`不知道怎么填?让 AI 问几个问题 →`,editBanner:`让 AI 调整这个助手 →`,editConfirmTitle:`用 AI 调整助手`,editConfirmMessage:`AI 将基于已保存的配置进行修改,当前未保存的修改不会带入。是否继续?`,greeting:`告诉我你想让这个助手做什么,我会问几个关键问题,然后直接帮你创建。`,editGreeting:`已载入「{name}」,想调整什么?可以直接说,例如:更简洁、只保留网页工具、输出改成英文。`,editExample1:`更简洁一点`,editExample2:`只保留网页相关工具`,editExample3:`输出改成英文`,example1:`帮我汇总周报`,example2:`帮我审查代码`,example3:`帮我抓取网页表格数据`,placeholder:`描述你的需求,例如:帮我每天汇总科技新闻…`,send:`发送`,hint:`最多 3 轮澄清,信息够了会自动创建`,restart:`重新开始`,thinking:`正在理解你的需求…`,recommended:`推荐`,customHint:`也可以直接在下方输入你的答案`,noConfig:`请先在设置中配置 API 地址和模型`,requestFailed:`生成失败:{message}`,protocolError:`AI 返回的配置格式不正确,请重试或换个说法。`,timeout:`请求超时`,repairInstruction:`你上一次的输出不是合法 JSON。请严格按协议只输出一个 JSON 对象;所有键和字符串使用英文双引号,字符串内换行写成 \\n,不要代码块和解释。`,created:`助手「{name}」已创建并切换`,updated:`助手「{name}」已更新`,saveFailed:`保存失败:{message}`,changedTitle:`本次修改`,fieldName:`名称`,fieldIcon:`图标`,fieldDescription:`描述`,fieldPrompt:`系统提示词`,fieldTools:`工具`,fieldSkills:`技能`,fieldSubDispatch:`子任务分发`,noChanges:`配置没有变化,已跳过保存。`,undo:`撤销本次修改`,undone:`已撤销本次修改`,undoFailed:`撤销失败:{message}`,promptLabel:`系统提示词`,toolsLabel:`工具`,skillsLabel:`技能`,inheritTools:`继承全局(全部工具)`,inheritSkills:`继承全部启用技能`,continueAdjust:`继续调整`,editInEditor:`在编辑器中微调`,finish:`完成`,adjustHint:`可以直接说想改什么,例如:把输出改成英文、只保留网页相关工具。`,warnIconFallback:`图标不可用,已使用默认图标`,warnPromptShort:`提示词偏短,建议在编辑器中补充`,warnToolsDropped:`已忽略 {count} 个不可用的工具:{names}`,warnSkillsDropped:`已忽略 {count} 个不可用的技能:{names}`,warnToolsAllDropped:`所有推荐工具都不可用,已继承全部工具,请在编辑器中确认权限范围`,warnSkillsAllDropped:`所有推荐技能都不可用,已继承全部启用技能`,roundCapHint:`澄清轮数已达上限,本轮必须直接输出 done,不要再提问。`}}),n(`en`,{agentBuilder:{title:`Create assistant with AI`,subtitle:`Describe your need; AI asks a few questions and builds the config`,entry:`Create with AI`,editorBanner:`Not sure what to fill in? Let AI ask a few questions →`,editBanner:`Adjust this assistant with AI →`,editConfirmTitle:`Adjust with AI`,editConfirmMessage:`AI will modify the saved configuration. Unsaved edits in this form will not be carried over. Continue?`,greeting:`Tell me what you want this assistant to do. I will ask a few key questions and then create it.`,editGreeting:`Loaded "{name}". What would you like to change? For example: make it more concise, keep only web tools, or output in English.`,editExample1:`Make it more concise`,editExample2:`Keep only web tools`,editExample3:`Output in English`,example1:`Summarize my weekly report`,example2:`Review my code`,example3:`Scrape table data from a page`,placeholder:`Describe your need, e.g. summarize tech news every day…`,send:`Send`,hint:`Up to 3 clarification rounds, then it creates automatically`,restart:`Restart`,thinking:`Understanding your need…`,recommended:`Recommended`,customHint:`You can also type your answer below`,noConfig:`Please configure the API base and model in settings first`,requestFailed:`Generation failed: {message}`,protocolError:`AI returned an invalid configuration. Please retry or rephrase.`,timeout:`Request timed out`,repairInstruction:`Your previous output was not valid JSON. Output exactly one JSON object; use English double quotes and escape line breaks inside strings as \\n. No code fences or explanation.`,created:`Assistant "{name}" created and activated`,updated:`Assistant "{name}" updated`,saveFailed:`Save failed: {message}`,changedTitle:`Changed in this update`,fieldName:`Name`,fieldIcon:`Icon`,fieldDescription:`Description`,fieldPrompt:`System prompt`,fieldTools:`Tools`,fieldSkills:`Skills`,fieldSubDispatch:`Sub-task dispatch`,noChanges:`No configuration changes detected; save skipped.`,undo:`Undo this change`,undone:`Change undone`,undoFailed:`Undo failed: {message}`,promptLabel:`System prompt`,toolsLabel:`Tools`,skillsLabel:`Skills`,inheritTools:`Inherit global (all tools)`,inheritSkills:`Inherit all enabled skills`,continueAdjust:`Keep adjusting`,editInEditor:`Fine-tune in editor`,finish:`Done`,adjustHint:`Just say what to change, e.g. output in English, or keep only web tools.`,warnIconFallback:`Icon was invalid; default icon applied`,warnPromptShort:`Prompt is short; consider enriching it in the editor`,warnToolsDropped:`Ignored {count} unavailable tool(s): {names}`,warnSkillsDropped:`Ignored {count} unavailable skill(s): {names}`,warnToolsAllDropped:`None of the suggested tools were available; all global tools are inherited. Review permissions in the editor.`,warnSkillsAllDropped:`None of the suggested skills were available; all enabled skills are inherited.`,roundCapHint:`Clarification limit reached. Output done now without asking more questions.`}});var iD=8,Z={open:!1,catalog:null,catalogPromise:null,messages:[],askCount:0,pending:!1,controller:null,runId:0,createdAgentId:null,draft:null,callbacks:null,sessionMode:`create`,editingAgent:null,previousAgent:null},aD=!1;function oD(e){return document.getElementById(e)}function Q(e,t,n){let r=document.createElement(e);return t&&(r.className=t),n!=null&&(r.textContent=n),r}function sD(e,t=300){let n=String(e||``).replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t)}…`:n}function cD(){let e=oD(`agentBuilderChat`);e&&(e.scrollTop=e.scrollHeight)}function lD(e,t){let n=oD(`agentBuilderChat`);if(!n)return;let r=Q(`div`,`agent-builder-msg ${e}`,t);n.appendChild(r),cD()}function uD(e){let t=oD(`agentBuilderChat`);if(!t)return;let n=Q(`div`,`agent-builder-examples`);for(let t of e){let e=Q(`button`,`agent-builder-example`,t);e.type=`button`,e.dataset.example=t,n.appendChild(e)}t.appendChild(n),cD()}function dD(e){Z.pending=e;let t=oD(`agentBuilderSendBtn`);t&&(t.disabled=e);let n=oD(`agentBuilderChat`);if(!n)return;let i=n.querySelector(`.agent-builder-typing`);e&&!i?(n.appendChild(Q(`div`,`agent-builder-msg assistant agent-builder-typing`,r(`agentBuilder.thinking`))),cD()):!e&&i&&i.remove()}function fD(e){let t=oD(`agentBuilderComposer`);t&&(t.style.display=e?`flex`:`none`)}function pD(){let e=oD(`agentBuilderPanel`);e&&(e.innerHTML=``)}function mD(){if(Z.runId+=1,Z.controller){try{Z.controller.abort()}catch{}Z.controller=null}}async function hD(){let e={};try{e=await chrome.storage.local.get([`apiBase`,`apiKey`,`modelName`])}catch{}let t=String(e.apiBase||``).trim().replace(/\/+$/,``),n=String(e.modelName||``).trim();if(!t||!n)return F(r(`agentBuilder.noConfig`),`warning`),null;let i=k(e.apiKey),a={"Content-Type":`application/json`};return i&&(a.Authorization=`Bearer ${i}`),{apiBase:t,model:n,headers:a}}function gD(e,t=iD){if(e.length<=t)return e;let n=e[0]?.role===`user`?[e[0]]:[];return[...n,...e.slice(-(t-n.length))]}function _D(){let e=JE({language:a(),tools:Z.catalog?.tools||[],skills:Z.catalog?.skills||[],currentAgent:Z.editingAgent});return Z.askCount>=3&&(e+=`\n\n${r(`agentBuilder.roundCapHint`)}`),[{role:`system`,content:e},...gD(Z.messages)]}async function vD(){if(Z.catalogPromise)try{await Z.catalogPromise}catch{}}async function yD(e,t,n){let r=new AbortController;Z.controller=r;let i=setTimeout(()=>r.abort(),9e4);try{let i={model:e.model,temperature:t,max_tokens:2e3,messages:_D()};return n&&(i.response_format={type:`json_object`}),await se(`${e.apiBase}/chat/completions`,{headers:e.headers,body:i,useStream:await ye(),signal:r.signal})}finally{clearTimeout(i),Z.controller===r&&(Z.controller=null)}}async function bD(e=.3){let t=await hD();if(!t)throw Error(r(`agentBuilder.noConfig`));let n=await yD(t,e,!0);if(!n.ok&&[400,422].includes(n.status)&&(i.debug(`[AgentBuilder] json mode unsupported, retrying without response_format`),n=await yD(t,e,!1)),!n.ok)throw Error(`HTTP ${n.status}${n.errorText?`: ${n.errorText}`:``}`);return n.data?.choices?.[0]?.message?.content||``}function xD(e){let t=oD(`agentBuilderPanel`);if(!t)return;t.innerHTML=``;let n=Q(`div`,`agent-builder-q`);n.appendChild(Q(`div`,`agent-builder-q-text`,e.text));let i=Q(`div`,`agent-builder-options`);e.options.forEach((t,n)=>{let a=n===e.recommended,o=Q(`button`,`agent-builder-option${a?` recommended`:``}`,t);o.type=`button`,o.dataset.optionIndex=String(n),o.dataset.answer=t,a&&o.appendChild(Q(`span`,`agent-builder-badge`,r(`agentBuilder.recommended`))),i.appendChild(o)}),n.appendChild(i),e.allowCustom&&n.appendChild(Q(`div`,`agent-builder-custom-hint`,r(`agentBuilder.customHint`))),t.appendChild(n);let a=oD(`agentBuilderInput`);a&&a.focus()}function SD(e){switch(e.code){case`iconFallback`:return r(`agentBuilder.warnIconFallback`);case`promptShort`:return r(`agentBuilder.warnPromptShort`);case`toolsDropped`:return r(`agentBuilder.warnToolsDropped`,{count:e.count,names:(e.names||[]).join(`, `)});case`skillsDropped`:return r(`agentBuilder.warnSkillsDropped`,{count:e.count,names:(e.names||[]).join(`, `)});case`toolsAllDropped`:return r(`agentBuilder.warnToolsAllDropped`);case`skillsAllDropped`:return r(`agentBuilder.warnSkillsAllDropped`);default:return``}}function CD(e){return Z.catalog?.tools.find(t=>t.id===e)?.name||e}function wD(e,t){let n=Q(`div`,`agent-builder-tags`);if(!e||e.length===0)return n.appendChild(Q(`span`,`agent-builder-tag`,t)),n;for(let t of e)n.appendChild(Q(`span`,`agent-builder-tag`,t));return n}function TD(e){return{name:e.name,icon:e.icon,description:e.description,systemPrompt:e.systemPrompt,toolIds:e.toolIds??null,skillIds:e.skillIds??null,allowSubDispatch:e.allowSubDispatch===!0,model:e.model??null,temperature:e.temperature??null,topP:e.topP??null,mcpExcludedServerIds:Array.isArray(e.mcpExcludedServerIds)?e.mcpExcludedServerIds:null}}function ED(e,t){return JSON.stringify(e??null)===JSON.stringify(t??null)}function DD(e,t){let n=[];return(e.name||``)!==(t.name||``)&&n.push(`name`),(e.icon||``)!==(t.icon||``)&&n.push(`icon`),(e.description||``)!==(t.description||``)&&n.push(`description`),(e.systemPrompt||``)!==(t.systemPrompt||``)&&n.push(`prompt`),ED(e.toolIds,t.toolIds)||n.push(`tools`),ED(e.skillIds,t.skillIds)||n.push(`skills`),e.allowSubDispatch===!0!=(t.allowSubDispatch===!0)&&n.push(`subDispatch`),n}function OD(e){let t={name:`fieldName`,icon:`fieldIcon`,description:`fieldDescription`,prompt:`fieldPrompt`,tools:`fieldTools`,skills:`fieldSkills`,subDispatch:`fieldSubDispatch`}[e];return t?r(`agentBuilder.${t}`):e}async function kD(){let e=Z.createdAgentId,t=Z.previousAgent;if(!(!e||!t))try{let n=await mt(e,TD(t));if(!n)throw Error(`agent_not_found`);if(Z.editingAgent={...t},Z.previousAgent=null,Z.callbacks?.onAgentSaved)try{await Z.callbacks.onAgentSaved(n,{updated:!0})}catch(e){i.warn(`[AgentBuilder] onAgentSaved failed:`,e?.message||e)}F(r(`agentBuilder.undone`),`success`),AD(t,[],{changeSummary:r(`agentBuilder.undone`),changedFields:[],canUndo:!1}),fD(!1)}catch(e){i.warn(`[AgentBuilder] undo failed:`,e?.message||e),lD(`assistant error`,r(`agentBuilder.undoFailed`,{message:e?.message||``}))}}function AD(e,t,n={}){let i=oD(`agentBuilderPanel`);if(!i)return;i.innerHTML=``;let o=Q(`div`,`agent-builder-result`),s=Q(`div`,`agent-builder-result-head`);s.appendChild(Q(`span`,`agent-builder-result-icon`,e.icon));let c=Q(`div`,`agent-builder-result-info`);if(c.appendChild(Q(`div`,`agent-builder-result-name`,e.name)),c.appendChild(Q(`div`,`agent-builder-result-desc`,e.description||``)),s.appendChild(c),o.appendChild(s),n.changedFields&&n.changedFields.length>0||n.changeSummary){let e=Q(`div`,`agent-builder-section`);if(e.appendChild(Q(`div`,`agent-builder-section-title`,r(`agentBuilder.changedTitle`))),n.changedFields&&n.changedFields.length>0){let t=Q(`div`,`agent-builder-tags`);for(let e of n.changedFields)t.appendChild(Q(`span`,`agent-builder-tag`,OD(e)));e.appendChild(t)}n.changeSummary&&e.appendChild(Q(`div`,`agent-builder-change-note`,n.changeSummary)),o.appendChild(e)}let l=Q(`div`,`agent-builder-section`);l.appendChild(Q(`div`,`agent-builder-section-title`,r(`agentBuilder.promptLabel`))),l.appendChild(Q(`div`,`agent-builder-prompt`,e.systemPrompt||``)),o.appendChild(l);let u=Q(`div`,`agent-builder-section`);u.appendChild(Q(`div`,`agent-builder-section-title`,r(`agentBuilder.toolsLabel`)));let d=e.toolIds?e.toolIds.map(CD):null;u.appendChild(wD(d,r(`agentBuilder.inheritTools`))),o.appendChild(u);let f=Q(`div`,`agent-builder-section`);f.appendChild(Q(`div`,`agent-builder-section-title`,r(`agentBuilder.skillsLabel`))),f.appendChild(wD(e.skillIds,r(`agentBuilder.inheritSkills`))),o.appendChild(f);let p=(t||[]).map(SD).filter(Boolean);if(p.length>0){let e=a()===`en`?`; `:`;`;o.appendChild(Q(`div`,`agent-builder-warn`,p.join(e)))}let m=Q(`div`,`agent-builder-actions`);if(n.canUndo){let e=Q(`button`,`modal-btn cancel`,r(`agentBuilder.undo`));e.type=`button`,e.dataset.action=`undo`,m.appendChild(e)}let h=Q(`button`,`modal-btn cancel`,r(`agentBuilder.continueAdjust`));h.type=`button`,h.dataset.action=`continue`;let g=Q(`button`,`modal-btn cancel`,r(`agentBuilder.editInEditor`));g.type=`button`,g.dataset.action=`edit`;let _=Q(`button`,`modal-btn confirm`,r(`agentBuilder.finish`));_.type=`button`,_.dataset.action=`finish`,m.append(h,g,_),o.appendChild(m),i.appendChild(o)}async function jD(e,t=``){let n=Z.editingAgent,{draft:o,warnings:s}=rD(e,{tools:Z.catalog?.tools||[],skills:Z.catalog?.skills||[],language:a(),baseAgent:n});Z.draft=o;let c=!!Z.createdAgentId,l=n?DD(n,o):[];if(c&&n&&l.length===0){lD(`assistant`,r(`agentBuilder.noChanges`)),fD(!0);return}let u=null;try{if(c){if(u=await mt(Z.createdAgentId,o),!u)throw Error(`agent_not_found`);Z.previousAgent=n?{...n}:null,Z.editingAgent={...u},F(r(`agentBuilder.updated`,{name:o.name}),`success`)}else u=await gt(o),Z.createdAgentId=u.id,Z.editingAgent={...u},F(r(`agentBuilder.created`,{name:u.name}),`success`)}catch(e){i.error(`[AgentBuilder] save failed:`,e),lD(`assistant error`,r(`agentBuilder.saveFailed`,{message:e?.message||``}));return}if(Z.callbacks?.onAgentSaved)try{await Z.callbacks.onAgentSaved(u,{updated:c})}catch(e){i.warn(`[AgentBuilder] onAgentSaved failed:`,e?.message||e)}AD(o,s,{changeSummary:c&&n?t:``,changedFields:c&&n?l:[],canUndo:c&&!!Z.previousAgent}),fD(!1)}async function MD(e){let t=String(e||``).trim();if(!t||Z.pending)return;pD(),oD(`agentBuilderChat`)?.querySelector(`.agent-builder-examples`)?.remove(),lD(`user`,t),Z.messages.push({role:`user`,content:t}),dD(!0);let n=++Z.runId;try{if(await vD(),n!==Z.runId||!Z.open)return;let e=await bD();if(n!==Z.runId||!Z.open)return;let t;try{t=nD(e)}catch(a){if(i.warn(`[AgentBuilder] invalid reply, retrying once:`,a?.message,`| raw:`,sD(e)),Z.messages.push({role:`assistant`,content:e||``}),Z.messages.push({role:`user`,content:r(`agentBuilder.repairInstruction`)}),e=await bD(0),n!==Z.runId||!Z.open)return;t=nD(e)}Z.messages.push({role:`assistant`,content:e}),t.message&&lD(`assistant`,t.message),t.action===`ask`?(Z.askCount+=1,xD(t.question)):await jD(t.agent,t.message)}catch(e){if(n!==Z.runId)return;i.warn(`[AgentBuilder] request failed:`,e?.message||e);let t=new Set([`empty_reply`,`no_json_object`,`invalid_json`,`invalid_action`,`invalid_question`,`invalid_agent`]),a=e?.message||``;e?.name===`AbortError`?a=r(`agentBuilder.timeout`):t.has(a)&&(a=r(`agentBuilder.protocolError`)),lD(`assistant error`,r(`agentBuilder.requestFailed`,{message:a}))}finally{n===Z.runId&&dD(!1)}}function ND(){if(Z.editingAgent){lD(`assistant`,r(`agentBuilder.editGreeting`,{name:Z.editingAgent.name})),uD([r(`agentBuilder.editExample1`),r(`agentBuilder.editExample2`),r(`agentBuilder.editExample3`)]);return}lD(`assistant`,r(`agentBuilder.greeting`)),uD([r(`agentBuilder.example1`),r(`agentBuilder.example2`),r(`agentBuilder.example3`)])}function PD(){mD(),Z.messages=[],Z.askCount=0,Z.draft=null,Z.pending=!1,Z.previousAgent=null,Z.sessionMode===`edit`&&Z.editingAgent?Z.createdAgentId=Z.editingAgent.id||null:(Z.editingAgent=null,Z.createdAgentId=null);let e=oD(`agentBuilderChat`);e&&(e.innerHTML=``),pD(),fD(!0),dD(!1);let t=oD(`agentBuilderInput`);t&&(t.value=``),ND()}async function FD({agent:e=null,onAgentSaved:t,onEditAgent:n}={}){let r=oD(`agentBuilderModal`);if(!r)return;Z.sessionMode=e?`edit`:`create`,Z.editingAgent=e?{...e}:null,Z.callbacks={onAgentSaved:t,onEditAgent:n},Z.open=!0,r.style.display=`flex`,PD(),Z.catalogPromise=(async()=>{try{Z.catalog=await zE()}catch(e){i.warn(`[AgentBuilder] load catalog failed:`,e?.message||e),Z.catalog={tools:[],skills:[]}}})();let a=oD(`agentBuilderInput`);a&&a.focus()}function ID(){mD(),Z.open=!1,Z.pending=!1;let e=oD(`agentBuilderModal`);e&&(e.style.display=`none`)}function LD(){aD||oD(`agentBuilderModal`)&&(aD=!0,oD(`agentBuilderCloseBtn`)?.addEventListener(`click`,ID),oD(`agentBuilderRestartBtn`)?.addEventListener(`click`,PD),oD(`agentBuilderSendBtn`)?.addEventListener(`click`,()=>{let e=oD(`agentBuilderInput`),t=e?.value||``;e&&(e.value=``),MD(t)}),oD(`agentBuilderInput`)?.addEventListener(`keydown`,e=>{if(e.key===`Enter`&&!e.shiftKey&&!e.isComposing){e.preventDefault();let t=e.target,n=t.value||``;t.value=``,MD(n)}}),oD(`agentBuilderChat`)?.addEventListener(`click`,e=>{let t=e.target.closest(`[data-example]`);!t||Z.pending||MD(t.dataset.example||``)}),oD(`agentBuilderPanel`)?.addEventListener(`click`,e=>{let t=e.target.closest(`[data-option-index]`);if(t){if(Z.pending)return;MD(t.dataset.answer||``);return}let n=e.target.closest(`[data-action]`);if(!n)return;let i=n.dataset.action;if(i===`undo`)kD();else if(i===`continue`)pD(),Z.askCount=0,lD(`assistant`,r(`agentBuilder.adjustHint`)),fD(!0),oD(`agentBuilderInput`)?.focus();else if(i===`edit`){let e=Z.createdAgentId,t=Z.callbacks?.onEditAgent;ID(),e&&t&&t(e)}else i===`finish`&&ID()}),document.addEventListener(`keydown`,e=>{e.key===`Escape`&&Z.open&&ID()}))}var RD=[[`🀄`,`mahjong tile red dragon`,`symbols`,`麻将,红中`],[`🃏`,`playing card black joker`,`symbols`,``],[`🅰`,`negative squared latin capital letter a`,`symbols`,``],[`🅱`,`negative squared latin capital letter b`,`symbols`,``],[`🅾`,`negative squared latin capital letter o`,`symbols`,``],[`🅿`,`negative squared latin capital letter p`,`symbols`,``],[`🆎`,`negative squared ab`,`symbols`,``],[`🆑`,`squared cl`,`symbols`,``],[`🆒`,`squared cool`,`symbols`,``],[`🆓`,`squared free`,`symbols`,``],[`🆔`,`squared id`,`symbols`,``],[`🆕`,`squared new`,`symbols`,``],[`🆖`,`squared ng`,`symbols`,``],[`🆗`,`squared ok`,`symbols`,``],[`🆘`,`squared sos`,`symbols`,``],[`🆙`,`squared up with exclamation mark`,`symbols`,``],[`🆚`,`squared vs`,`symbols`,``],[`🇨🇩`,`regional indicator symbol letter c`,`flags`,``],[`🇬🇭`,`regional indicator symbol letter g`,`flags`,``],[`🇲🇳`,`regional indicator symbol letter m`,`flags`,``],[`🇷🇸`,`regional indicator symbol letter r`,`flags`,``],[`🈁`,`squared katakana koko`,`symbols`,``],[`🈂`,`squared katakana sa`,`symbols`,``],[`🈚`,`squared cjk unified ideograph-7121`,`symbols`,``],[`🈯`,`squared cjk unified ideograph-6307`,`symbols`,``],[`🈲`,`squared cjk unified ideograph-7981`,`symbols`,``],[`🈳`,`squared cjk unified ideograph-7a7a`,`symbols`,``],[`🈴`,`squared cjk unified ideograph-5408`,`symbols`,``],[`🈵`,`squared cjk unified ideograph-6e80`,`symbols`,``],[`🈶`,`squared cjk unified ideograph-6709`,`symbols`,``],[`🈷`,`squared cjk unified ideograph-6708`,`symbols`,``],[`🈸`,`squared cjk unified ideograph-7533`,`symbols`,``],[`🈹`,`squared cjk unified ideograph-5272`,`symbols`,``],[`🈺`,`squared cjk unified ideograph-55b6`,`symbols`,``],[`🉐`,`circled ideograph advantage`,`symbols`,``],[`🉑`,`circled ideograph accept`,`symbols`,``],[`🌀`,`cyclone`,`symbols`,`台风,龙卷风,旋风`],[`🌁`,`foggy`,`symbols`,`雾,雾霾,朦胧`],[`🌂`,`closed umbrella`,`symbols`,``],[`🌃`,`night with stars`,`symbols`,`夜晚,星空,城市`],[`🌄`,`sunrise over mountains`,`symbols`,`日出,山,早晨`],[`🌅`,`sunrise`,`symbols`,`日出,太阳,早晨`],[`🌆`,`cityscape at dusk`,`symbols`,`黄昏,傍晚,城市`],[`🌇`,`sunset over buildings`,`symbols`,`日落,黄昏`],[`🌈`,`rainbow`,`symbols`,`彩虹,雨后`],[`🌉`,`bridge at night`,`symbols`,`桥,大桥`],[`🌊`,`water wave`,`symbols`,`海浪,波浪,海`],[`🌋`,`volcano`,`symbols`,`火山,爆发`],[`🌌`,`milky way`,`symbols`,``],[`🌍`,`earth globe europe-africa`,`symbols`,``],[`🌎`,`earth globe americas`,`symbols`,`地球,美洲`],[`🌏`,`earth globe asia-australia`,`symbols`,`地球,亚洲`],[`🌐`,`globe with meridians`,`symbols`,``],[`🌑`,`new moon symbol`,`symbols`,``],[`🌒`,`waxing crescent moon symbol`,`symbols`,``],[`🌓`,`first quarter moon symbol`,`symbols`,``],[`🌔`,`waxing gibbous moon symbol`,`symbols`,``],[`🌕`,`full moon symbol`,`symbols`,``],[`🌖`,`waning gibbous moon symbol`,`symbols`,``],[`🌗`,`last quarter moon symbol`,`symbols`,``],[`🌘`,`waning crescent moon symbol`,`symbols`,``],[`🌙`,`crescent moon`,`symbols`,``],[`🌚`,`new moon with face`,`symbols`,``],[`🌛`,`first quarter moon with face`,`symbols`,``],[`🌜`,`last quarter moon with face`,`symbols`,``],[`🌝`,`full moon with face`,`symbols`,``],[`🌞`,`sun with face`,`symbols`,``],[`🌟`,`glowing star`,`symbols`,`星星,闪光,闪耀`],[`🌠`,`shooting star`,`symbols`,``],[`🌡`,`thermometer`,`symbols`,``],[`🌤`,`white sun with small cloud`,`symbols`,``],[`🌥`,`white sun behind cloud`,`symbols`,``],[`🌦`,`white sun behind cloud with rain`,`symbols`,``],[`🌧`,`cloud with rain`,`symbols`,``],[`🌨`,`cloud with snow`,`symbols`,``],[`🌩`,`cloud with lightning`,`symbols`,``],[`🌪`,`cloud with tornado`,`symbols`,``],[`🌫`,`fog`,`symbols`,``],[`🌬`,`wind blowing face`,`symbols`,``],[`🌭`,`hot dog`,`food`,`热狗`],[`🌮`,`taco`,`food`,`墨西哥卷饼`],[`🌯`,`burrito`,`food`,`墨西哥卷,卷饼`],[`🌰`,`chestnut`,`food`,`栗子,坚果`],[`🌱`,`seedling`,`food`,``],[`🌲`,`evergreen tree`,`food`,`松树,树`],[`🌳`,`deciduous tree`,`food`,`树,大树`],[`🌴`,`palm tree`,`food`,`棕榈树,热带,度假`],[`🌵`,`cactus`,`food`,`仙人掌,沙漠`],[`🌶`,`hot pepper`,`food`,``],[`🌷`,`tulip`,`food`,`郁金香,花`],[`🌸`,`cherry blossom`,`food`,`樱花,花,春天`],[`🌹`,`rose`,`food`,`玫瑰,花,爱情`],[`🌺`,`hibiscus`,`food`,`花,芙蓉`],[`🌻`,`sunflower`,`food`,`向日葵,花,太阳`],[`🌼`,`blossom`,`food`,`雏菊,花`],[`🌽`,`ear of maize`,`food`,`玉米`],[`🌾`,`ear of rice`,`food`,``],[`🌿`,`herb`,`food`,`草,植物,草药`],[`🍀`,`four leaf clover`,`food`,`四叶草,幸运,好运`],[`🍁`,`maple leaf`,`food`,`枫叶,秋天,红叶`],[`🍂`,`fallen leaf`,`food`,`落叶,秋天`],[`🍃`,`leaf fluttering in wind`,`food`,`树叶,风`],[`🍄`,`mushroom`,`food`,`蘑菇,菌`],[`🍅`,`tomato`,`food`,`番茄,西红柿`],[`🍆`,`aubergine`,`food`,`茄子`],[`🍇`,`grapes`,`food`,`葡萄`],[`🍈`,`melon`,`food`,`哈密瓜,甜瓜`],[`🍉`,`watermelon`,`food`,`西瓜`],[`🍊`,`tangerine`,`food`,`橙子,橘子`],[`🍋`,`lemon`,`food`,`柠檬`],[`🍌`,`banana`,`food`,`香蕉`],[`🍍`,`pineapple`,`food`,`菠萝`],[`🍎`,`red apple`,`food`,`苹果`],[`🍏`,`green apple`,`food`,``],[`🍐`,`pear`,`food`,`梨`],[`🍑`,`peach`,`food`,`桃子,蜜桃`],[`🍒`,`cherries`,`food`,`樱桃,车厘子`],[`🍓`,`strawberry`,`food`,`草莓`],[`🍔`,`hamburger`,`food`,`汉堡,汉堡包`],[`🍕`,`slice of pizza`,`food`,`披萨,比萨`],[`🍖`,`meat on bone`,`food`,`骨头,肉,排骨`],[`🍗`,`poultry leg`,`food`,`鸡腿,炸鸡`],[`🍘`,`rice cracker`,`food`,`米饼,仙贝`],[`🍙`,`rice ball`,`food`,`饭团`],[`🍚`,`cooked rice`,`food`,`米饭,饭`],[`🍛`,`curry and rice`,`food`,`咖喱,咖喱饭`],[`🍜`,`steaming bowl`,`food`,`面条,拉面,面`],[`🍝`,`spaghetti`,`food`,`意大利面,意面`],[`🍞`,`bread`,`food`,`面包`],[`🍟`,`french fries`,`food`,`薯条,炸薯条`],[`🍠`,`roasted sweet potato`,`food`,`红薯,地瓜`],[`🍡`,`dango`,`food`,`团子,丸子`],[`🍢`,`oden`,`food`,`关东煮,串`],[`🍣`,`sushi`,`food`,`寿司,三文鱼`],[`🍤`,`fried shrimp`,`food`,`炸虾,天妇罗`],[`🍥`,`fish cake with swirl design`,`food`,`鱼板,鸣门卷`],[`🍦`,`soft ice cream`,`food`,`冰淇淋,甜筒`],[`🍧`,`shaved ice`,`food`,`刨冰,冰沙`],[`🍨`,`ice cream`,`food`,`冰淇淋,圣代`],[`🍩`,`doughnut`,`food`,``],[`🍪`,`cookie`,`food`,``],[`🍫`,`chocolate bar`,`food`,`巧克力`],[`🍬`,`candy`,`food`,`糖果,糖`],[`🍭`,`lollipop`,`food`,`棒棒糖`],[`🍮`,`custard`,`food`,`布丁,焦糖`],[`🍯`,`honey pot`,`food`,`蜂蜜,蜜`],[`🍰`,`shortcake`,`food`,`蛋糕,奶油蛋糕`],[`🍱`,`bento box`,`food`,`便当,盒饭`],[`🍲`,`pot of food`,`food`,`火锅,汤锅,炖菜`],[`🍳`,`cooking`,`food`,`煎蛋,鸡蛋`],[`🍴`,`fork and knife`,`food`,`刀叉,餐具`],[`🍵`,`teacup without handle`,`food`,`绿茶,茶,抹茶`],[`🍶`,`sake bottle and cup`,`food`,`清酒,日本酒`],[`🍷`,`wine glass`,`food`,`红酒,葡萄酒,酒`],[`🍸`,`cocktail glass`,`food`,`鸡尾酒,马提尼`],[`🍹`,`tropical drink`,`food`,`果汁,鸡尾酒`],[`🍺`,`beer mug`,`food`,`啤酒,啤酒杯`],[`🍻`,`clinking beer mugs`,`food`,`干杯,碰杯,啤酒`],[`🍼`,`baby bottle`,`food`,`奶瓶,婴儿,奶粉`],[`🍽`,`fork and knife with plate`,`food`,``],[`🍾`,`bottle with popping cork`,`food`,`香槟,起泡酒,庆祝`],[`🍿`,`popcorn`,`food`,``],[`🎀`,`ribbon`,`activity`,`蝴蝶结,礼物,装饰`],[`🎁`,`wrapped present`,`activity`,`礼物,礼盒,生日`],[`🎂`,`birthday cake`,`activity`,`生日蛋糕,生日,蛋糕`],[`🎃`,`jack-o-lantern`,`activity`,``],[`🎄`,`christmas tree`,`activity`,``],[`🎅`,`father christmas`,`activity`,`圣诞老人,圣诞,圣诞节`],[`🎆`,`fireworks`,`activity`,``],[`🎇`,`firework sparkler`,`activity`,``],[`🎈`,`balloon`,`activity`,`气球,庆祝,派对`],[`🎉`,`party popper`,`activity`,`彩带,庆祝,派对,欢呼`],[`🎊`,`confetti ball`,`activity`,`庆祝`],[`🎋`,`tanabata tree`,`activity`,``],[`🎌`,`crossed flags`,`flags`,`旗,日本,交叉旗`],[`🎍`,`pine decoration`,`activity`,``],[`🎎`,`japanese dolls`,`activity`,`人偶,日本人偶`],[`🎏`,`carp streamer`,`activity`,`鲤鱼旗,日本,端午节`],[`🎐`,`wind chime`,`activity`,`风铃,夏天`],[`🎑`,`moon viewing ceremony`,`activity`,``],[`🎒`,`school satchel`,`activity`,`书包,背包`],[`🎓`,`graduation cap`,`activity`,`学士帽,毕业,学位`],[`🎖`,`military medal`,`activity`,``],[`🎗`,`reminder ribbon`,`activity`,``],[`🎙`,`studio microphone`,`activity`,``],[`🎚`,`level slider`,`activity`,``],[`🎛`,`control knobs`,`activity`,``],[`🎞`,`film frames`,`activity`,``],[`🎟`,`admission tickets`,`activity`,``],[`🎠`,`carousel horse`,`activity`,`旋转木马,游乐园`],[`🎡`,`ferris wheel`,`activity`,`摩天轮,游乐园`],[`🎢`,`roller coaster`,`activity`,`过山车,游乐园`],[`🎣`,`fishing pole and fish`,`activity`,`钓鱼`],[`🎤`,`microphone`,`activity`,`麦克风,唱歌,K歌`],[`🎥`,`movie camera`,`activity`,`摄影机,电影,拍摄`],[`🎦`,`cinema`,`activity`,``],[`🎧`,`headphone`,`activity`,`耳机,听歌,音乐,戴`],[`🎨`,`artist palette`,`activity`,`调色板,画画,美术,艺术`],[`🎩`,`top hat`,`activity`,`礼帽,魔术帽,帽子`],[`🎪`,`circus tent`,`activity`,`马戏团`],[`🎫`,`ticket`,`activity`,`门票,票,入场券`],[`🎬`,`clapper board`,`activity`,`场记板,电影,拍戏,导演`],[`🎭`,`performing arts`,`activity`,`面具,戏剧,表演,舞台`],[`🎮`,`video game`,`activity`,`游戏机,游戏,手柄,玩`],[`🎯`,`direct hit`,`activity`,`目标`],[`🎰`,`slot machine`,`activity`,``],[`🎱`,`billiards`,`activity`,`台球`],[`🎲`,`game die`,`activity`,`骰子,赌博,游戏`],[`🎳`,`bowling`,`activity`,`保龄球,球`],[`🎴`,`flower playing cards`,`activity`,`花牌,卡牌,纸牌`],[`🎵`,`musical note`,`activity`,`音符,音乐,歌`],[`🎶`,`multiple musical notes`,`activity`,`音符,音乐,唱歌`],[`🎷`,`saxophone`,`activity`,`萨克斯,爵士,乐器`],[`🎸`,`guitar`,`activity`,`吉他,弹吉他,摇滚`],[`🎹`,`musical keyboard`,`activity`,`钢琴,键盘,弹琴`],[`🎺`,`trumpet`,`activity`,`小号,喇叭,乐器`],[`🎻`,`violin`,`activity`,`小提琴,弦乐`],[`🎼`,`musical score`,`activity`,`乐谱,音乐,谱`],[`🎽`,`running shirt with sash`,`activity`,`背心`],[`🎾`,`tennis racquet and ball`,`activity`,`网球,球`],[`🎿`,`ski and ski boot`,`activity`,`滑雪`],[`🏀`,`basketball and hoop`,`activity`,`篮球,球`],[`🏁`,`chequered flag`,`flags`,`终点,旗帜,赛车,比赛`],[`🏂`,`snowboarder`,`activity`,``],[`🏃`,`runner`,`activity`,`跑步,跑,奔跑`],[`🏄`,`surfer`,`activity`,``],[`🏅`,`sports medal`,`activity`,`奖牌,奖章,荣誉`],[`🏆`,`trophy`,`activity`,``],[`🏇`,`horse racing`,`activity`,``],[`🏈`,`american football`,`activity`,`橄榄球,美式足球`],[`🏉`,`rugby football`,`activity`,`橄榄球,英式`],[`🏊`,`swimmer`,`activity`,``],[`🏋`,`weight lifter`,`activity`,``],[`🏌`,`golfer`,`activity`,``],[`🏍`,`racing motorcycle`,`activity`,``],[`🏎`,`racing car`,`activity`,``],[`🏏`,`cricket bat and ball`,`activity`,``],[`🏐`,`volleyball`,`activity`,`排球,球`],[`🏑`,`field hockey stick and ball`,`activity`,``],[`🏒`,`ice hockey stick and puck`,`activity`,``],[`🏓`,`table tennis paddle and ball`,`activity`,`乒乓球,乒乓,球`],[`🏔`,`snow capped mountain`,`activity`,``],[`🏕`,`camping`,`activity`,``],[`🏖`,`beach with umbrella`,`activity`,``],[`🏗`,`building construction`,`activity`,``],[`🏘`,`house buildings`,`activity`,``],[`🏙`,`cityscape`,`activity`,``],[`🏚`,`derelict house building`,`activity`,``],[`🏛`,`classical building`,`activity`,``],[`🏜`,`desert`,`activity`,``],[`🏝`,`desert island`,`activity`,``],[`🏞`,`national park`,`activity`,``],[`🏟`,`stadium`,`activity`,``],[`🏠`,`house building`,`travel`,`房子,家,住宅`],[`🏡`,`house with garden`,`travel`,`房子,家,花园`],[`🏢`,`office building`,`travel`,`办公楼,大楼,写字楼`],[`🏣`,`japanese post office`,`travel`,`邮局,邮政`],[`🏤`,`european post office`,`travel`,`邮局`],[`🏥`,`hospital`,`travel`,`医院,医疗`],[`🏦`,`bank`,`travel`,`银行,金融`],[`🏧`,`automated teller machine`,`travel`,``],[`🏨`,`hotel`,`travel`,`酒店,旅馆`],[`🏩`,`love hotel`,`travel`,`爱情旅馆,酒店`],[`🏪`,`convenience store`,`travel`,`便利店,商店`],[`🏫`,`school`,`travel`,`学校,校园`],[`🏬`,`department store`,`travel`,`商场,百货,购物`],[`🏭`,`factory`,`travel`,`工厂,工业`],[`🏮`,`izakaya lantern`,`travel`,``],[`🏯`,`japanese castle`,`objects`,`城堡,日本城堡`],[`🏰`,`european castle`,`travel`,`城堡,童话`],[`🏳`,`waving white flag`,`flags`,``],[`🏴`,`waving black flag`,`flags`,`黑旗`],[`🏵`,`rosette`,`objects`,``],[`🏷`,`label`,`objects`,``],[`🏸`,`badminton racquet and shuttlecock`,`activity`,`羽毛球,球`],[`🏹`,`bow and arrow`,`activity`,`射箭,弓箭,弓`],[`🏺`,`amphora`,`activity`,`陶罐,花瓶,双耳瓶`],[`🏻`,`emoji modifier fitzpatrick type-1-2`,`symbols`,``],[`🏼`,`emoji modifier fitzpatrick type-3`,`symbols`,``],[`🏽`,`emoji modifier fitzpatrick type-4`,`symbols`,``],[`🏾`,`emoji modifier fitzpatrick type-5`,`symbols`,``],[`🏿`,`emoji modifier fitzpatrick type-6`,`symbols`,``],[`🐀`,`rat`,`animals`,`老鼠,鼠`],[`🐁`,`mouse`,`animals`,`老鼠,鼠`],[`🐂`,`ox`,`animals`,`公牛,牛`],[`🐃`,`water buffalo`,`animals`,`水牛,牛`],[`🐄`,`cow`,`animals`,`奶牛,牛`],[`🐅`,`tiger`,`animals`,``],[`🐆`,`leopard`,`animals`,``],[`🐇`,`rabbit`,`animals`,`兔子,兔`],[`🐈`,`cat`,`animals`,`猫,猫咪`],[`🐉`,`dragon`,`animals`,`龙,中国龙`],[`🐊`,`crocodile`,`animals`,`鳄鱼,短吻鳄`],[`🐋`,`whale`,`animals`,`鲸鱼`],[`🐌`,`snail`,`animals`,``],[`🐍`,`snake`,`animals`,`蛇,爬行动物`],[`🐎`,`horse`,`animals`,``],[`🐏`,`ram`,`animals`,`羊,公羊`],[`🐐`,`goat`,`animals`,`山羊,羊`],[`🐑`,`sheep`,`animals`,`羊,绵羊`],[`🐒`,`monkey`,`animals`,``],[`🐓`,`rooster`,`animals`,`公鸡,鸡`],[`🐔`,`chicken`,`animals`,`鸡,母鸡`],[`🐕`,`dog`,`animals`,`狗,小狗`],[`🐖`,`pig`,`animals`,`猪`],[`🐗`,`boar`,`animals`,`野猪,猪`],[`🐘`,`elephant`,`animals`,`大象`],[`🐙`,`octopus`,`animals`,`章鱼,八爪鱼`],[`🐚`,`spiral shell`,`animals`,``],[`🐛`,`bug`,`animals`,``],[`🐜`,`ant`,`animals`,``],[`🐝`,`honeybee`,`animals`,``],[`🐞`,`lady beetle`,`animals`,``],[`🐟`,`fish`,`animals`,`鱼,鱼`],[`🐠`,`tropical fish`,`animals`,`热带鱼,鱼`],[`🐡`,`blowfish`,`animals`,`河豚,鱼`],[`🐢`,`turtle`,`animals`,`乌龟,慢`],[`🐣`,`hatching chick`,`animals`,`小鸡,破壳,孵化`],[`🐤`,`baby chick`,`animals`,`小鸡,黄,可爱`],[`🐥`,`front-facing baby chick`,`animals`,`小鸡,正面`],[`🐦`,`bird`,`animals`,`鸟`],[`🐧`,`penguin`,`animals`,`企鹅,南极`],[`🐨`,`koala`,`animals`,`考拉,无尾熊`],[`🐩`,`poodle`,`animals`,`贵宾犬,狗`],[`🐪`,`dromedary camel`,`animals`,`骆驼`],[`🐫`,`bactrian camel`,`animals`,`骆驼,双峰`],[`🐬`,`dolphin`,`animals`,`海豚,海洋`],[`🐭`,`mouse face`,`animals`,`老鼠,鼠`],[`🐮`,`cow face`,`animals`,`牛,奶牛`],[`🐯`,`tiger face`,`animals`,``],[`🐰`,`rabbit face`,`animals`,`兔子,兔,可爱`],[`🐱`,`cat face`,`animals`,``],[`🐲`,`dragon face`,`animals`,`龙,龙头`],[`🐳`,`spouting whale`,`animals`,`鲸鱼,喷水`],[`🐴`,`horse face`,`animals`,`马`],[`🐵`,`monkey face`,`animals`,``],[`🐶`,`dog face`,`animals`,``],[`🐷`,`pig face`,`animals`,`猪,猪头`],[`🐸`,`frog face`,`animals`,`青蛙,蛙`],[`🐹`,`hamster face`,`animals`,`仓鼠`],[`🐺`,`wolf face`,`animals`,``],[`🐻`,`bear face`,`animals`,`熊,泰迪熊`],[`🐼`,`panda face`,`animals`,``],[`🐽`,`pig nose`,`animals`,`猪鼻子,猪`],[`🐾`,`paw prints`,`animals`,`爪印,脚印`],[`🐿`,`chipmunk`,`animals`,``],[`👀`,`eyes`,`people`,``],[`👁`,`eye`,`people`,``],[`👂`,`ear`,`people`,`耳朵,听`],[`👃`,`nose`,`people`,`鼻子,闻`],[`👄`,`mouth`,`people`,`嘴巴,嘴唇,吻`],[`👅`,`tongue`,`people`,`舌头,舔`],[`👆`,`white up pointing backhand index`,`people`,`指,上面,向上`],[`👇`,`white down pointing backhand index`,`people`,`指,下面,向下`],[`👈`,`white left pointing backhand index`,`people`,`指,左边,指向`],[`👉`,`white right pointing backhand index`,`people`,`指,右边,指向`],[`👊`,`fisted hand sign`,`people`,`拳头,打,战斗`],[`👋`,`waving hand sign`,`people`,`挥手,再见,你好`],[`👌`,`ok hand sign`,`people`,`OK,好,可以`],[`👍`,`thumbs up sign`,`people`,`点赞,好,赞,棒`],[`👎`,`thumbs down sign`,`people`,`差评,不好,踩`],[`👏`,`clapping hands sign`,`people`,`鼓掌,拍手,掌声`],[`👐`,`open hands sign`,`people`,`张开,手,开放`],[`👑`,`crown`,`people`,`皇冠,王冠,国王,女王`],[`👒`,`womans hat`,`people`,`帽子,草帽,遮阳帽`],[`👓`,`eyeglasses`,`people`,`眼镜`],[`👔`,`necktie`,`people`,`领带,西装,工作`],[`👕`,`t-shirt`,`people`,`衣服,T恤`],[`👖`,`jeans`,`people`,`裤子,牛仔裤`],[`👗`,`dress`,`people`,`裙子,连衣裙`],[`👘`,`kimono`,`people`,`和服`],[`👙`,`bikini`,`people`,`比基尼,泳装`],[`👚`,`womans clothes`,`people`,`女装,衣服`],[`👛`,`purse`,`people`,`钱包,小包`],[`👜`,`handbag`,`people`,`手提包,包包`],[`👝`,`pouch`,`people`,`手拿包,包包`],[`👞`,`mans shoe`,`people`,`皮鞋,鞋`],[`👟`,`athletic shoe`,`people`,`运动鞋,跑鞋`],[`👠`,`high-heeled shoe`,`people`,`高跟鞋,鞋`],[`👡`,`womans sandal`,`people`,`凉鞋,鞋`],[`👢`,`womans boots`,`people`,`靴子,长靴`],[`👣`,`footprints`,`people`,`脚印,脚步,足迹`],[`👤`,`bust in silhouette`,`people`,`人,剪影,用户`],[`👥`,`busts in silhouette`,`people`,`人群,人,多个人`],[`👦`,`boy`,`people`,`男孩,小男孩`],[`👧`,`girl`,`people`,`女孩,小女孩`],[`👨`,`man`,`people`,`男人,男士`],[`👩`,`woman`,`people`,`女人,女士`],[`👪`,`family`,`people`,`家庭`],[`👫`,`woman and man holding hands`,`people`,``],[`👬`,`men holding hands`,`people`,``],[`👭`,`women holding hands`,`people`,``],[`👮`,`police officer`,`people`,`警察,警官`],[`👯`,`woman with bunny ears`,`people`,`兔子舞,蹦迪,派对`],[`👰`,`bride with veil`,`people`,`新娘,婚纱,结婚`],[`👱`,`person with blond hair`,`people`,``],[`👲`,`man with gua pi mao`,`people`,`中国人`],[`👳`,`man with turban`,`people`,`包头巾,印度,阿拉伯`],[`👴`,`older man`,`people`,`老人,老爷爷`],[`👵`,`older woman`,`people`,`老人,老奶奶`],[`👶`,`baby`,`people`,`婴儿,宝宝,小孩`],[`👷`,`construction worker`,`people`,`工人`],[`👸`,`princess`,`people`,`公主,女王`],[`👹`,`japanese ogre`,`people`,`妖怪,鬼,怪物`],[`👺`,`japanese goblin`,`people`,`天狗,怪物,鬼`],[`👻`,`ghost`,`people`,`幽灵,鬼,万圣节`],[`👼`,`baby angel`,`people`,`天使,婴儿,可爱`],[`👽`,`extraterrestrial alien`,`people`,`外星人,ET,飞碟`],[`👾`,`alien monster`,`people`,`外星人,怪兽,游戏`],[`👿`,`imp`,`people`,`恶魔,愤怒`],[`💀`,`skull`,`people`,`骷髅,死亡,骨头`],[`💁`,`information desk person`,`people`,``],[`💂`,`guardsman`,`people`,`卫兵,士兵`],[`💃`,`dancer`,`people`,`跳舞,舞女,跳舞`],[`💄`,`lipstick`,`people`,`口红,化妆`],[`💅`,`nail polish`,`people`,`美甲,指甲,涂`],[`💆`,`face massage`,`people`,`按摩,放松,头部`],[`💇`,`haircut`,`people`,`理发,剪发,发型`],[`💈`,`barber pole`,`people`,`理发店,理发`],[`💉`,`syringe`,`people`,`注射器,针,疫苗`],[`💊`,`pill`,`people`,`药丸,药,胶囊`],[`💋`,`kiss mark`,`people`,`吻,口红印,亲亲`],[`💌`,`love letter`,`people`,`情书,信,爱情`],[`💍`,`ring`,`people`,`戒指,钻戒,结婚`],[`💎`,`gem stone`,`people`,`钻石,宝石,珠宝`],[`💏`,`kiss`,`people`,``],[`💐`,`bouquet`,`smileys`,`花束,花,礼物`],[`💑`,`couple with heart`,`smileys`,``],[`💒`,`wedding`,`smileys`,`教堂,婚礼,教堂婚礼`],[`💓`,`beating heart`,`smileys`,`爱心,跳动,心跳`],[`💔`,`broken heart`,`smileys`,`心碎,伤心,破碎`],[`💕`,`two hearts`,`smileys`,`爱心,两个,喜欢`],[`💖`,`sparkling heart`,`smileys`,`爱心,闪光,喜欢`],[`💗`,`growing heart`,`smileys`,`爱心,跳动,喜欢`],[`💘`,`heart with arrow`,`smileys`,`爱心,箭,丘比特`],[`💙`,`blue heart`,`smileys`,``],[`💚`,`green heart`,`smileys`,``],[`💛`,`yellow heart`,`smileys`,``],[`💜`,`purple heart`,`smileys`,``],[`💝`,`heart with ribbon`,`smileys`,`爱心,礼物,蝴蝶结`],[`💞`,`revolving hearts`,`smileys`,`爱心,旋转,轮回`],[`💟`,`heart decoration`,`smileys`,`爱心,符号`],[`💠`,`diamond shape with a dot inside`,`objects`,``],[`💡`,`electric light bulb`,`objects`,``],[`💢`,`anger symbol`,`objects`,`生气,怒气`],[`💣`,`bomb`,`objects`,`炸弹,爆炸`],[`💤`,`sleeping symbol`,`objects`,`睡觉,打呼,困`],[`💥`,`collision symbol`,`objects`,``],[`💦`,`splashing sweat symbol`,`objects`,`汗,水,泪`],[`💧`,`droplet`,`objects`,`水滴,水,眼泪`],[`💨`,`dash symbol`,`objects`,`风,跑,快,烟雾`],[`💩`,`pile of poo`,`objects`,`大便,屎,狗屎`],[`💪`,`flexed biceps`,`people`,`肌肉,力量,加油,强壮`],[`💫`,`dizzy symbol`,`objects`,`星星,旋转`],[`💬`,`speech balloon`,`objects`,`对话,聊天`],[`💭`,`thought balloon`,`objects`,`想法,思考,气泡`],[`💮`,`white flower`,`objects`,``],[`💯`,`hundred points symbol`,`objects`,``],[`💰`,`money bag`,`objects`,`钱袋,钱,金钱`],[`💱`,`currency exchange`,`objects`,``],[`💲`,`heavy dollar sign`,`objects`,``],[`💳`,`credit card`,`objects`,`信用卡,银行卡,支付`],[`💴`,`banknote with yen sign`,`objects`,`日元,日圆,钱`],[`💵`,`banknote with dollar sign`,`objects`,`美元,美金,钱`],[`💶`,`banknote with euro sign`,`objects`,`欧元,钱`],[`💷`,`banknote with pound sign`,`objects`,`英镑,钱`],[`💸`,`money with wings`,`objects`,`钱,飞钱,花钱`],[`💹`,`chart with upwards trend and yen sign`,`objects`,`股票,上涨,图表,增长`],[`💺`,`seat`,`objects`,`座位,椅子,飞机座位`],[`💻`,`personal computer`,`objects`,`电脑,笔记本,笔记本电脑`],[`💼`,`briefcase`,`objects`,`公文包,工作,商务`],[`💽`,`minidisc`,`objects`,`光盘,磁盘`],[`💾`,`floppy disk`,`objects`,`软盘,保存`],[`💿`,`optical disc`,`objects`,`光盘,CD`],[`📀`,`dvd`,`objects`,`光盘,DVD`],[`📁`,`file folder`,`objects`,`文件夹`],[`📂`,`open file folder`,`objects`,`文件夹,打开`],[`📃`,`page with curl`,`objects`,`文件,文档`],[`📄`,`page facing up`,`objects`,`文件,文档,纸`],[`📅`,`calendar`,`objects`,`日历`],[`📆`,`tear-off calendar`,`objects`,`日历,日历页`],[`📇`,`card index`,`objects`,`名片,索引卡`],[`📈`,`chart with upwards trend`,`objects`,``],[`📉`,`chart with downwards trend`,`objects`,``],[`📊`,`bar chart`,`objects`,``],[`📋`,`clipboard`,`objects`,`剪贴板,清单,列表`],[`📌`,`pushpin`,`objects`,``],[`📍`,`round pushpin`,`objects`,``],[`📎`,`paperclip`,`objects`,``],[`📏`,`straight ruler`,`objects`,``],[`📐`,`triangular ruler`,`objects`,``],[`📑`,`bookmark tabs`,`objects`,`书签,标签,文件`],[`📒`,`ledger`,`objects`,``],[`📓`,`notebook`,`objects`,``],[`📔`,`notebook with decorative cover`,`objects`,``],[`📕`,`closed book`,`objects`,``],[`📖`,`open book`,`objects`,``],[`📗`,`green book`,`objects`,``],[`📘`,`blue book`,`objects`,``],[`📙`,`orange book`,`objects`,``],[`📚`,`books`,`objects`,``],[`📛`,`name badge`,`objects`,``],[`📜`,`scroll`,`objects`,``],[`📝`,`memo`,`objects`,`笔记,备忘录,写作,文档`],[`📞`,`telephone receiver`,`objects`,`电话`],[`📟`,`pager`,`objects`,`寻呼机,传呼机`],[`📠`,`fax machine`,`objects`,`传真机,传真`],[`📡`,`satellite antenna`,`objects`,`天线,卫星,信号`],[`📢`,`public address loudspeaker`,`objects`,``],[`📣`,`cheering megaphone`,`objects`,``],[`📤`,`outbox tray`,`objects`,`发送,输出,上传`],[`📥`,`inbox tray`,`objects`,`接收,下载,收件箱`],[`📦`,`package`,`objects`,`包裹,快递,箱子`],[`📧`,`e-mail symbol`,`objects`,`邮件,电子邮件`],[`📨`,`incoming envelope`,`objects`,`邮件,收到`],[`📩`,`envelope with downwards arrow above`,`objects`,`邮件,发送`],[`📪`,`closed mailbox with lowered flag`,`objects`,`邮箱,关闭`],[`📫`,`closed mailbox with raised flag`,`objects`,`邮箱,信箱,邮件`],[`📬`,`open mailbox with raised flag`,`objects`,`邮箱,有信`],[`📭`,`open mailbox with lowered flag`,`objects`,`邮箱,无信`],[`📮`,`postbox`,`objects`,`邮筒,邮政`],[`📯`,`postal horn`,`objects`,``],[`📰`,`newspaper`,`objects`,`报纸,新闻,报`],[`📱`,`mobile phone`,`objects`,`手机,智能手机,电话`],[`📲`,`mobile phone with rightwards arrow at left`,`objects`,`手机,接收,信号`],[`📳`,`vibration mode`,`objects`,``],[`📴`,`mobile phone off`,`objects`,``],[`📵`,`no mobile phones`,`objects`,``],[`📶`,`antenna with bars`,`objects`,``],[`📷`,`camera`,`objects`,`相机,拍照,照片`],[`📸`,`camera with flash`,`objects`,`相机,闪光灯,拍照`],[`📹`,`video camera`,`objects`,`摄像机,录像`],[`📺`,`television`,`objects`,``],[`📻`,`radio`,`objects`,`收音机,广播`],[`📼`,`videocassette`,`objects`,`录像带,磁带`],[`📽`,`film projector`,`objects`,``],[`📿`,`prayer beads`,`objects`,`念珠,佛珠,项链`],[`🔀`,`twisted rightwards arrows`,`objects`,``],[`🔁`,`clockwise rightwards and leftwards open circle arrows`,`objects`,``],[`🔂`,`clockwise rightwards and leftwards open circle arrows with circled one overlay`,`objects`,``],[`🔃`,`clockwise downwards and upwards open circle arrows`,`objects`,``],[`🔄`,`anticlockwise downwards and upwards open circle arrows`,`objects`,``],[`🔅`,`low brightness symbol`,`objects`,``],[`🔆`,`high brightness symbol`,`objects`,``],[`🔇`,`speaker with cancellation stroke`,`objects`,``],[`🔈`,`speaker`,`objects`,``],[`🔉`,`speaker with one sound wave`,`objects`,``],[`🔊`,`speaker with three sound waves`,`objects`,``],[`🔋`,`battery`,`objects`,``],[`🔌`,`electric plug`,`objects`,``],[`🔍`,`left-pointing magnifying glass`,`objects`,`搜索,放大镜,查找,查询`],[`🔎`,`right-pointing magnifying glass`,`objects`,`搜索,放大镜,查找`],[`🔏`,`lock with ink pen`,`objects`,`锁,保密,笔`],[`🔐`,`closed lock with key`,`objects`,`锁,安全,钥匙`],[`🔑`,`key`,`objects`,`钥匙,解锁`],[`🔒`,`lock`,`objects`,`锁,锁定,安全`],[`🔓`,`open lock`,`objects`,`解锁,打开`],[`🔔`,`bell`,`objects`,``],[`🔕`,`bell with cancellation stroke`,`objects`,``],[`🔖`,`bookmark`,`objects`,`书签,标记`],[`🔗`,`link symbol`,`objects`,``],[`🔘`,`radio button`,`objects`,``],[`🔙`,`back with leftwards arrow above`,`objects`,``],[`🔚`,`end with leftwards arrow above`,`objects`,``],[`🔛`,`on with exclamation mark with left right arrow above`,`objects`,``],[`🔜`,`soon with rightwards arrow above`,`objects`,``],[`🔝`,`top with upwards arrow above`,`objects`,``],[`🔞`,`no one under eighteen symbol`,`objects`,``],[`🔟`,`keycap 10`,`objects`,``],[`🔠`,`input symbol for latin capital letters`,`objects`,``],[`🔡`,`input symbol for latin small letters`,`objects`,``],[`🔢`,`input symbol for numbers`,`objects`,``],[`🔣`,`input symbol for symbols`,`objects`,``],[`🔤`,`input symbol for latin letters`,`objects`,``],[`🔥`,`fire`,`objects`,``],[`🔦`,`electric torch`,`objects`,``],[`🔧`,`wrench`,`objects`,`扳手,工具,维修`],[`🔨`,`hammer`,`objects`,`锤子,工具`],[`🔩`,`nut and bolt`,`objects`,`螺丝,螺母`],[`🔪`,`hocho`,`objects`,``],[`🔫`,`pistol`,`objects`,`枪`],[`🔬`,`microscope`,`objects`,`显微镜,科学,研究`],[`🔭`,`telescope`,`objects`,`望远镜,天文,观察`],[`🔮`,`crystal ball`,`objects`,``],[`🔯`,`six pointed star with middle dot`,`objects`,``],[`🔰`,`japanese symbol for beginner`,`objects`,``],[`🔱`,`trident emblem`,`objects`,``],[`🔲`,`black square button`,`objects`,``],[`🔳`,`white square button`,`objects`,``],[`🔴`,`large red circle`,`objects`,``],[`🔵`,`large blue circle`,`objects`,``],[`🔶`,`large orange diamond`,`objects`,``],[`🔷`,`large blue diamond`,`objects`,``],[`🔸`,`small orange diamond`,`objects`,``],[`🔹`,`small blue diamond`,`objects`,``],[`🔺`,`up-pointing red triangle`,`objects`,``],[`🔻`,`down-pointing red triangle`,`objects`,``],[`🔼`,`up-pointing small red triangle`,`objects`,``],[`🔽`,`down-pointing small red triangle`,`objects`,``],[`🕉`,`om symbol`,`objects`,``],[`🕊`,`dove of peace`,`objects`,``],[`🕋`,`kaaba`,`objects`,`天房,麦加,伊斯兰`],[`🕌`,`mosque`,`objects`,`清真寺,伊斯兰`],[`🕍`,`synagogue`,`objects`,`犹太教堂,犹太`],[`🕎`,`menorah with nine branches`,`objects`,``],[`🕐`,`clock face one oclock`,`objects`,`一点,时钟`],[`🕑`,`clock face two oclock`,`objects`,`两点,时钟`],[`🕒`,`clock face three oclock`,`objects`,`三点,时钟`],[`🕓`,`clock face four oclock`,`objects`,`四点,时钟`],[`🕔`,`clock face five oclock`,`objects`,`五点,时钟`],[`🕕`,`clock face six oclock`,`objects`,`六点,时钟`],[`🕖`,`clock face seven oclock`,`objects`,`七点,时钟`],[`🕗`,`clock face eight oclock`,`objects`,`八点,时钟`],[`🕘`,`clock face nine oclock`,`objects`,`九点,时钟`],[`🕙`,`clock face ten oclock`,`objects`,`十点,时钟`],[`🕚`,`clock face eleven oclock`,`objects`,`十一点,时钟`],[`🕛`,`clock face twelve oclock`,`objects`,`十二点,时钟,时间`],[`🕜`,`clock face one-thirty`,`objects`,``],[`🕝`,`clock face two-thirty`,`objects`,``],[`🕞`,`clock face three-thirty`,`objects`,``],[`🕟`,`clock face four-thirty`,`objects`,``],[`🕠`,`clock face five-thirty`,`objects`,``],[`🕡`,`clock face six-thirty`,`objects`,``],[`🕢`,`clock face seven-thirty`,`objects`,``],[`🕣`,`clock face eight-thirty`,`objects`,``],[`🕤`,`clock face nine-thirty`,`objects`,``],[`🕥`,`clock face ten-thirty`,`objects`,``],[`🕦`,`clock face eleven-thirty`,`objects`,``],[`🕧`,`clock face twelve-thirty`,`objects`,``],[`🕯`,`candle`,`objects`,``],[`🕰`,`mantelpiece clock`,`objects`,``],[`🕳`,`hole`,`objects`,``],[`🕴`,`man in business suit levitating`,`objects`,``],[`🕵`,`sleuth or spy`,`objects`,``],[`🕶`,`dark sunglasses`,`objects`,``],[`🕷`,`spider`,`objects`,``],[`🕸`,`spider web`,`objects`,``],[`🕹`,`joystick`,`objects`,``],[`🕺`,`man dancing`,`objects`,`跳舞,舞男`],[`🖇`,`linked paperclips`,`objects`,``],[`🖊`,`lower left ballpoint pen`,`objects`,``],[`🖋`,`lower left fountain pen`,`objects`,``],[`🖌`,`lower left paintbrush`,`objects`,``],[`🖍`,`lower left crayon`,`objects`,``],[`🖐`,`raised hand with fingers splayed`,`objects`,``],[`🖕`,`reversed hand with middle finger extended`,`objects`,`中指,骂人`],[`🖖`,`raised hand with part between middle and ring fingers`,`objects`,`瓦肯,举手,胜利`],[`🖤`,`black heart`,`objects`,``],[`🖥`,`desktop computer`,`objects`,``],[`🖨`,`printer`,`objects`,``],[`🖱`,`three button mouse`,`objects`,``],[`🖲`,`trackball`,`objects`,``],[`🖼`,`frame with picture`,`objects`,``],[`🗂`,`card index dividers`,`objects`,``],[`🗃`,`card file box`,`objects`,``],[`🗄`,`file cabinet`,`objects`,``],[`🗑`,`wastebasket`,`objects`,``],[`🗒`,`spiral note pad`,`objects`,``],[`🗓`,`spiral calendar pad`,`objects`,``],[`🗜`,`compression`,`objects`,``],[`🗝`,`old key`,`objects`,``],[`🗞`,`rolled-up newspaper`,`objects`,``],[`🗡`,`dagger knife`,`objects`,``],[`🗣`,`speaking head in silhouette`,`objects`,``],[`🗨`,`left speech bubble`,`objects`,``],[`🗯`,`right anger bubble`,`objects`,``],[`🗳`,`ballot box with ballot`,`objects`,``],[`🗺`,`world map`,`objects`,``],[`🗻`,`mount fuji`,`objects`,`富士山,山`],[`🗼`,`tokyo tower`,`objects`,`塔,东京塔`],[`🗽`,`statue of liberty`,`objects`,`自由女神像,纽约`],[`🗾`,`silhouette of japan`,`objects`,``],[`🗿`,`moyai`,`objects`,`雕像`],[`😀`,`grinning face`,`smileys`,`笑脸,开心,高兴`],[`😁`,`grinning face with smiling eyes`,`smileys`,`笑脸,开心`],[`😂`,`face with tears of joy`,`smileys`,`笑哭,大笑,笑`],[`😃`,`smiling face with open mouth`,`smileys`,`笑脸,开心`],[`😄`,`smiling face with open mouth and smiling eyes`,`smileys`,`笑脸,开心`],[`😅`,`smiling face with open mouth and cold sweat`,`smileys`,`笑脸,汗,尴尬`],[`😆`,`smiling face with open mouth and tightly-closed eyes`,`smileys`,`笑脸,大笑`],[`😇`,`smiling face with halo`,`smileys`,`天使,微笑,善良`],[`😈`,`smiling face with horns`,`smileys`,`恶魔,坏笑,邪恶`],[`😉`,`winking face`,`smileys`,`眨眼,调皮`],[`😊`,`smiling face with smiling eyes`,`smileys`,`微笑,开心,脸红`],[`😋`,`face savouring delicious food`,`smileys`,`好吃,美味,舔`],[`😌`,`relieved face`,`smileys`,`放松,安心`],[`😍`,`smiling face with heart-shaped eyes`,`smileys`,`爱,喜欢,花痴`],[`😎`,`smiling face with sunglasses`,`smileys`,`酷,墨镜,帅气`],[`😏`,`smirking face`,`smileys`,`得意,微笑,坏笑`],[`😐`,`neutral face`,`smileys`,`无语,面无表情`],[`😑`,`expressionless face`,`smileys`,`无语,面无表情`],[`😒`,`unamused face`,`smileys`,`不满,无语,翻白眼`],[`😓`,`face with cold sweat`,`smileys`,`冷汗,尴尬`],[`😔`,`pensive face`,`smileys`,`难过,低落`],[`😕`,`confused face`,`smileys`,`困惑,不解`],[`😖`,`confounded face`,`smileys`,`纠结,痛苦`],[`😗`,`kissing face`,`smileys`,`亲亲,吻`],[`😘`,`face throwing a kiss`,`smileys`,`飞吻,亲亲,爱`],[`😙`,`kissing face with smiling eyes`,`smileys`,``],[`😚`,`kissing face with closed eyes`,`smileys`,`亲亲,吻`],[`😛`,`face with stuck-out tongue`,`smileys`,`吐舌头,调皮`],[`😜`,`face with stuck-out tongue and winking eye`,`smileys`,`吐舌头,调皮,眨眼`],[`😝`,`face with stuck-out tongue and tightly-closed eyes`,`smileys`,`吐舌头,调皮`],[`😞`,`disappointed face`,`smileys`,`失望,难过`],[`😟`,`worried face`,`smileys`,`担心,忧虑`],[`😠`,`angry face`,`smileys`,`生气,愤怒`],[`😡`,`pouting face`,`smileys`,`生气,愤怒,红脸`],[`😢`,`crying face`,`smileys`,`哭,伤心,流泪`],[`😣`,`persevering face`,`smileys`,`挣扎,痛苦`],[`😤`,`face with look of triumph`,`smileys`,`生气,冒烟,气`],[`😥`,`disappointed but relieved face`,`smileys`,`难过,失望,松气`],[`😦`,`frowning face with open mouth`,`smileys`,`惊讶,张嘴`],[`😧`,`anguished face`,`smileys`,`震惊,痛苦`],[`😨`,`fearful face`,`smileys`,`害怕,恐惧`],[`😩`,`weary face`,`smileys`,`累,疲惫,哭`],[`😪`,`sleepy face`,`smileys`,`困,想睡`],[`😫`,`tired face`,`smileys`,`累,疲惫`],[`😬`,`grimacing face`,`smileys`,`尴尬,咧嘴`],[`😭`,`loudly crying face`,`smileys`,`大哭,伤心,哭`],[`😮`,`face with open mouth`,`smileys`,`惊讶,哇`],[`😯`,`hushed face`,`smileys`,`惊讶,安静`],[`😰`,`face with open mouth and cold sweat`,`smileys`,`担心,冷汗`],[`😱`,`face screaming in fear`,`smileys`,`尖叫,害怕,恐怖`],[`😲`,`astonished face`,`smileys`,`震惊,惊讶`],[`😳`,`flushed face`,`smileys`,`脸红,害羞,震惊`],[`😴`,`sleeping face`,`smileys`,`睡觉,睡觉`],[`😵`,`dizzy face`,`smileys`,`晕,头晕,死`],[`😶`,`face without mouth`,`smileys`,`沉默,无语`],[`😷`,`face with medical mask`,`smileys`,`生病,口罩,感冒`],[`😸`,`grinning cat face with smiling eyes`,`smileys`,`猫,笑脸`],[`😹`,`cat face with tears of joy`,`smileys`,`猫,笑哭`],[`😺`,`smiling cat face with open mouth`,`smileys`,`猫,笑脸,开心`],[`😻`,`smiling cat face with heart-shaped eyes`,`smileys`,`猫,爱,喜欢`],[`😼`,`cat face with wry smile`,`smileys`,`猫,坏笑`],[`😽`,`kissing cat face with closed eyes`,`smileys`,`猫,亲亲`],[`😾`,`pouting cat face`,`smileys`,`猫,生气`],[`😿`,`crying cat face`,`smileys`,`猫,哭,伤心`],[`🙀`,`weary cat face`,`smileys`,`猫,震惊,害怕`],[`🙁`,`slightly frowning face`,`smileys`,`难过,失望`],[`🙂`,`slightly smiling face`,`smileys`,`微笑,笑`],[`🙃`,`upside-down face`,`smileys`,`微笑,倒`],[`🙄`,`face with rolling eyes`,`smileys`,`翻白眼,无语`],[`🙅`,`face with no good gesture`,`smileys`,``],[`🙆`,`face with ok gesture`,`smileys`,``],[`🙇`,`person bowing deeply`,`smileys`,``],[`🙈`,`see-no-evil monkey`,`smileys`,``],[`🙉`,`hear-no-evil monkey`,`smileys`,``],[`🙊`,`speak-no-evil monkey`,`smileys`,``],[`🙋`,`happy person raising one hand`,`smileys`,``],[`🙌`,`person raising both hands in celebration`,`smileys`,`欢呼,举起,庆祝`],[`🙍`,`person frowning`,`smileys`,``],[`🙎`,`person with pouting face`,`smileys`,``],[`🙏`,`person with folded hands`,`smileys`,`祈祷,拜托,感谢,合十`],[`🚀`,`rocket`,`travel`,`火箭,发射,太空`],[`🚁`,`helicopter`,`travel`,`直升机`],[`🚂`,`steam locomotive`,`travel`,`火车,蒸汽火车`],[`🚃`,`railway car`,`travel`,`电车,火车`],[`🚄`,`high-speed train`,`travel`,`高铁,动车,火车`],[`🚅`,`high-speed train with bullet nose`,`travel`,``],[`🚆`,`train`,`travel`,`火车,铁路`],[`🚇`,`metro`,`travel`,`地铁,地铁站`],[`🚈`,`light rail`,`travel`,`轻轨,轨道交通`],[`🚉`,`station`,`travel`,`火车站,车站`],[`🚊`,`tram`,`travel`,`电车`],[`🚋`,`tram car`,`travel`,`电车,有轨电车`],[`🚌`,`bus`,`travel`,`公交车,巴士`],[`🚍`,`oncoming bus`,`travel`,`公交车`],[`🚎`,`trolleybus`,`travel`,`无轨电车,巴士`],[`🚏`,`bus stop`,`travel`,`公交站,车站`],[`🚐`,`minibus`,`travel`,`面包车,小巴`],[`🚑`,`ambulance`,`travel`,`救护车,急救`],[`🚒`,`fire engine`,`travel`,`消防车,救火`],[`🚓`,`police car`,`travel`,`警车,警察`],[`🚔`,`oncoming police car`,`travel`,`警车,巡逻`],[`🚕`,`taxi`,`travel`,`出租车,的士`],[`🚖`,`oncoming taxi`,`travel`,`出租车`],[`🚗`,`automobile`,`travel`,`汽车,轿车,车`],[`🚘`,`oncoming automobile`,`travel`,`汽车`],[`🚙`,`recreational vehicle`,`travel`,`SUV,越野车,汽车`],[`🚚`,`delivery truck`,`travel`,`卡车,货车`],[`🚛`,`articulated lorry`,`travel`,`卡车,货车`],[`🚜`,`tractor`,`travel`,`拖拉机,农用`],[`🚝`,`monorail`,`travel`,`单轨,单轨列车`],[`🚞`,`mountain railway`,`travel`,`火车,山区铁路`],[`🚟`,`suspension railway`,`travel`,`缆车,悬挂列车`],[`🚠`,`mountain cableway`,`travel`,`缆车,高山`],[`🚡`,`aerial tramway`,`travel`,`缆车,索道`],[`🚢`,`ship`,`travel`,`轮船,船,大海`],[`🚣`,`rowboat`,`travel`,``],[`🚤`,`speedboat`,`travel`,`快艇,汽艇`],[`🚥`,`horizontal traffic light`,`travel`,`红绿灯,交通信号灯`],[`🚦`,`vertical traffic light`,`travel`,`红绿灯,信号灯`],[`🚧`,`construction sign`,`travel`,`施工,施工中,路障`],[`🚨`,`police cars revolving light`,`travel`,`警车灯,警报,紧急`],[`🚩`,`triangular flag on post`,`travel`,`红旗,旗帜,标志`],[`🚪`,`door`,`travel`,`门,房门`],[`🚫`,`no entry sign`,`travel`,``],[`🚬`,`smoking symbol`,`travel`,`香烟,烟,吸烟`],[`🚭`,`no smoking symbol`,`travel`,``],[`🚮`,`put litter in its place symbol`,`travel`,`垃圾,清理`],[`🚯`,`do not litter symbol`,`travel`,``],[`🚰`,`potable water symbol`,`travel`,``],[`🚱`,`non-potable water symbol`,`travel`,``],[`🚲`,`bicycle`,`travel`,`自行车,单车,骑行`],[`🚳`,`no bicycles`,`travel`,``],[`🚴`,`bicyclist`,`travel`,``],[`🚵`,`mountain bicyclist`,`travel`,``],[`🚶`,`pedestrian`,`travel`,`走路,步行,散步`],[`🚷`,`no pedestrians`,`travel`,``],[`🚸`,`children crossing`,`travel`,``],[`🚹`,`mens symbol`,`travel`,``],[`🚺`,`womens symbol`,`travel`,``],[`🚻`,`restroom`,`travel`,``],[`🚼`,`baby symbol`,`travel`,``],[`🚽`,`toilet`,`travel`,`马桶,厕所,卫生间`],[`🚾`,`water closet`,`travel`,``],[`🚿`,`shower`,`travel`,`淋浴,洗澡`],[`🛀`,`bath`,`travel`,`泡澡`],[`🛁`,`bathtub`,`travel`,`浴缸,洗澡,泡澡`],[`🛂`,`passport control`,`travel`,``],[`🛃`,`customs`,`travel`,``],[`🛄`,`baggage claim`,`travel`,``],[`🛅`,`left luggage`,`travel`,``],[`🛋`,`couch and lamp`,`travel`,``],[`🛌`,`sleeping accommodation`,`travel`,`睡觉`],[`🛍`,`shopping bags`,`travel`,``],[`🛎`,`bellhop bell`,`travel`,``],[`🛏`,`bed`,`travel`,``],[`🛐`,`place of worship`,`travel`,``],[`🛑`,`octagonal sign`,`travel`,`停止,停车,红圈`],[`🛒`,`shopping trolley`,`travel`,`购物车,购物`],[`🛕`,`hindu temple`,`travel`,`印度教神庙`],[`🛖`,`hut`,`travel`,`草屋,小屋`],[`🛗`,`elevator`,`travel`,``],[`🛜`,`wireless`,`travel`,``],[`🛝`,`playground slide`,`travel`,``],[`🛞`,`wheel`,`travel`,`车轮,轮胎`],[`🛟`,`ring buoy`,`travel`,`救生圈,救生`],[`🛠`,`hammer and wrench`,`travel`,``],[`🛡`,`shield`,`travel`,``],[`🛢`,`oil drum`,`travel`,``],[`🛣`,`motorway`,`travel`,``],[`🛤`,`railway track`,`travel`,``],[`🛥`,`motor boat`,`travel`,``],[`🛩`,`small airplane`,`travel`,``],[`🛫`,`airplane departure`,`travel`,`起飞,飞机,出发`],[`🛬`,`airplane arriving`,`travel`,`降落,飞机,到达`],[`🛰`,`satellite`,`travel`,``],[`🛳`,`passenger ship`,`travel`,``],[`🛴`,`scooter`,`travel`,`滑板车,平衡车`],[`🛵`,`motor scooter`,`travel`,`摩托车,电动车,踏板车`],[`🛶`,`canoe`,`travel`,`独木舟,皮划艇`],[`🛷`,`sled`,`travel`,`雪橇,雪车`],[`🛸`,`flying saucer`,`travel`,`飞碟,UFO,外星人`],[`🛹`,`skateboard`,`travel`,`滑板`],[`🛺`,`auto rickshaw`,`travel`,`三轮车,突突车`],[`🛻`,`pickup truck`,`travel`,`皮卡,卡车`],[`🛼`,`roller skate`,`travel`,`轮滑`],[`🟠`,`large orange circle`,`symbols`,``],[`🟡`,`large yellow circle`,`symbols`,``],[`🟢`,`large green circle`,`symbols`,``],[`🟣`,`large purple circle`,`symbols`,``],[`🟤`,`large brown circle`,`symbols`,``],[`🟥`,`large red square`,`symbols`,``],[`🟦`,`large blue square`,`symbols`,``],[`🟧`,`large orange square`,`symbols`,``],[`🟨`,`large yellow square`,`symbols`,``],[`🟩`,`large green square`,`symbols`,``],[`🟪`,`large purple square`,`symbols`,``],[`🟫`,`large brown square`,`symbols`,``],[`🟰`,`heavy equals sign`,`symbols`,``],[`🤌`,`pinched fingers`,`symbols`,`手指,捏,意大利`],[`🤍`,`white heart`,`symbols`,`白心,白色,爱心`],[`🤎`,`brown heart`,`symbols`,`棕心,棕色,爱心`],[`🤏`,`pinching hand`,`symbols`,`捏,一点点,微小`],[`🤐`,`zipper-mouth face`,`smileys`,`闭嘴,不说`],[`🤑`,`money-mouth face`,`smileys`,`发财,金钱,贪婪`],[`🤒`,`face with thermometer`,`smileys`,`发烧,生病,温度计`],[`🤓`,`nerd face`,`smileys`,`书呆子,眼镜`],[`🤔`,`thinking face`,`smileys`,`思考,疑问,想`],[`🤕`,`face with head-bandage`,`smileys`,`受伤,包扎,头`],[`🤖`,`robot face`,`smileys`,`机器人,AI,机械`],[`🤗`,`hugging face`,`smileys`,`拥抱,欢迎`],[`🤘`,`sign of the horns`,`smileys`,`摇滚,手势,牛`],[`🤙`,`call me hand`,`smileys`,`打电话,挂,酷`],[`🤚`,`raised back of hand`,`smileys`,`手,举手,停`],[`🤛`,`left-facing fist`,`smileys`,`拳头,左边`],[`🤜`,`right-facing fist`,`smileys`,`拳头,右边`],[`🤝`,`handshake`,`smileys`,`握手,合作,协议`],[`🤞`,`hand with index and middle fingers crossed`,`smileys`,`祈祷,好运,手指交叉`],[`🤟`,`i love you hand sign`,`smileys`,`爱你,摇滚`],[`🤠`,`face with cowboy hat`,`smileys`,`牛仔,帽子`],[`🤡`,`clown face`,`smileys`,`小丑,马戏团`],[`🤢`,`nauseated face`,`smileys`,`恶心,呕吐`],[`🤣`,`rolling on the floor laughing`,`smileys`,`笑哭,大笑,笑`],[`🤤`,`drooling face`,`smileys`,`流口水,馋`],[`🤥`,`lying face`,`smileys`,`说谎,撒谎`],[`🤦`,`face palm`,`smileys`,`捂脸,无奈,扶额`],[`🤧`,`sneezing face`,`smileys`,`打喷嚏,感冒`],[`🤨`,`face with one eyebrow raised`,`symbols`,`怀疑,挑眉`],[`🤩`,`grinning face with star eyes`,`symbols`,`星星眼,兴奋,惊讶`],[`🤪`,`grinning face with one large and one small eye`,`symbols`,`疯狂,搞怪`],[`🤫`,`face with finger covering closed lips`,`symbols`,`嘘,安静`],[`🤬`,`serious face with symbols covering mouth`,`symbols`,`骂人,脏话,生气`],[`🤭`,`smiling face with smiling eyes and hand covering mouth`,`symbols`,`捂嘴,偷笑,惊讶`],[`🤮`,`face with open mouth vomiting`,`symbols`,`呕吐,恶心`],[`🤯`,`shocked face with exploding head`,`smileys`,`爆炸,震惊,头炸`],[`🤰`,`pregnant woman`,`people`,`孕妇,怀孕`],[`🤱`,`breast-feeding`,`people`,``],[`🤲`,`palms up together`,`people`,``],[`🤳`,`selfie`,`people`,`自拍,拍照`],[`🤴`,`prince`,`people`,`王子,国王`],[`🤵`,`man in tuxedo`,`people`,`新郎,西装,燕尾服`],[`🤶`,`mother christmas`,`people`,`圣诞奶奶,圣诞老人`],[`🤷`,`shrug`,`people`,`耸肩,无奈,不知道`],[`🤸`,`person doing cartwheel`,`people`,`翻跟头,体操,空翻`],[`🤹`,`juggling`,`people`,`杂耍`],[`🤺`,`fencer`,`people`,`击剑,剑术`],[`🤼`,`wrestlers`,`activity`,`摔跤,格斗`],[`🤽`,`water polo`,`activity`,``],[`🤾`,`handball`,`activity`,``],[`🤿`,`diving mask`,`activity`,`潜水面罩,潜水`],[`🥀`,`wilted flower`,`symbols`,``],[`🥁`,`drum with drumsticks`,`symbols`,`鼓,打鼓,乐器`],[`🥂`,`clinking glasses`,`symbols`,`干杯,香槟杯`],[`🥃`,`tumbler glass`,`symbols`,`威士忌,酒杯`],[`🥄`,`spoon`,`symbols`,`勺子,汤匙`],[`🥅`,`goal net`,`symbols`,`球门,网,进球`],[`🥇`,`first place medal`,`symbols`,`金牌,冠军,第一名,奖牌`],[`🥈`,`second place medal`,`symbols`,`银牌,第二名,奖牌`],[`🥉`,`third place medal`,`symbols`,`铜牌,第三名,奖牌`],[`🥊`,`boxing glove`,`symbols`,`拳击,拳击手套,打拳`],[`🥋`,`martial arts uniform`,`symbols`,`道服,武术,空手道`],[`🥌`,`curling stone`,`symbols`,`冰壶,冰壶`],[`🥍`,`lacrosse stick and ball`,`symbols`,``],[`🥎`,`softball`,`symbols`,`垒球,球`],[`🥏`,`flying disc`,`symbols`,`飞盘,飞碟`],[`🥐`,`croissant`,`food`,`牛角包,可颂`],[`🥑`,`avocado`,`food`,`牛油果,鳄梨`],[`🥒`,`cucumber`,`food`,`黄瓜`],[`🥓`,`bacon`,`food`,`培根,腊肉`],[`🥔`,`potato`,`food`,`土豆,马铃薯`],[`🥕`,`carrot`,`food`,`胡萝卜`],[`🥖`,`baguette bread`,`food`,`法棍,面包`],[`🥗`,`green salad`,`food`,`沙拉,蔬菜`],[`🥘`,`shallow pan of food`,`food`,`炖锅,海鲜饭`],[`🥙`,`stuffed flatbread`,`food`,`卷饼,肉夹馍`],[`🥚`,`egg`,`food`,`鸡蛋,蛋`],[`🥛`,`glass of milk`,`food`,`牛奶,奶`],[`🥜`,`peanuts`,`food`,``],[`🥝`,`kiwifruit`,`food`,`猕猴桃,奇异果`],[`🥞`,`pancakes`,`food`,`松饼,煎饼`],[`🥟`,`dumpling`,`food`,`饺子,锅贴`],[`🥠`,`fortune cookie`,`food`,`幸运饼干`],[`🥡`,`takeout box`,`food`,``],[`🥢`,`chopsticks`,`food`,`筷子`],[`🥣`,`bowl with spoon`,`food`,``],[`🥤`,`cup with straw`,`food`,`饮料,杯`],[`🥥`,`coconut`,`food`,`椰子`],[`🥦`,`broccoli`,`food`,`西兰花`],[`🥧`,`pie`,`food`,`派,馅饼`],[`🥨`,`pretzel`,`food`,`椒盐卷饼`],[`🥩`,`cut of meat`,`food`,`牛排,肉`],[`🥪`,`sandwich`,`food`,`三明治`],[`🥫`,`canned food`,`food`,`罐头,罐装`],[`🥬`,`leafy green`,`symbols`,`青菜,白菜,生菜`],[`🥭`,`mango`,`symbols`,`芒果`],[`🥮`,`moon cake`,`symbols`,``],[`🥯`,`bagel`,`symbols`,`贝果,面包圈`],[`🥰`,`smiling face with smiling eyes and three hearts`,`smileys`,`爱,微笑,爱心`],[`🥱`,`yawning face`,`smileys`,`打哈欠,困,无聊`],[`🥲`,`smiling face with tear`,`smileys`,``],[`🥳`,`face with party horn and party hat`,`smileys`,`庆祝,派对,欢呼`],[`🥴`,`face with uneven eyes and wavy mouth`,`smileys`,`晕,醉,头昏`],[`🥵`,`overheated face`,`smileys`,`热`],[`🥶`,`freezing face`,`smileys`,`冷`],[`🥷`,`ninja`,`people`,`忍者,忍者`],[`🥸`,`disguised face`,`symbols`,`伪装`],[`🥹`,`face holding back tears`,`symbols`,`感动,忍住,哭,泪目`],[`🥺`,`face with pleading eyes`,`smileys`,`可怜,委屈,求`],[`🥻`,`sari`,`symbols`,`纱丽,印度`],[`🥼`,`lab coat`,`symbols`,``],[`🥽`,`goggles`,`symbols`,``],[`🥾`,`hiking boot`,`symbols`,`靴子,登山鞋`],[`🥿`,`flat shoe`,`symbols`,`平底鞋,鞋`],[`🦀`,`crab`,`animals`,`螃蟹,海鲜`],[`🦁`,`lion face`,`animals`,``],[`🦂`,`scorpion`,`animals`,``],[`🦃`,`turkey`,`animals`,`火鸡,感恩节`],[`🦄`,`unicorn face`,`animals`,`独角兽,梦幻`],[`🦅`,`eagle`,`animals`,`老鹰,鹰`],[`🦆`,`duck`,`animals`,`鸭子,鸭`],[`🦇`,`bat`,`animals`,`蝙蝠`],[`🦈`,`shark`,`animals`,`鲨鱼,鱼`],[`🦉`,`owl`,`animals`,`猫头鹰,智慧`],[`🦊`,`fox face`,`animals`,``],[`🦋`,`butterfly`,`animals`,``],[`🦌`,`deer`,`animals`,`鹿,麋鹿`],[`🦍`,`gorilla`,`animals`,``],[`🦎`,`lizard`,`animals`,`蜥蜴,爬行动物`],[`🦏`,`rhinoceros`,`animals`,`犀牛`],[`🦐`,`shrimp`,`animals`,`虾,海鲜`],[`🦑`,`squid`,`animals`,`鱿鱼,海鲜`],[`🦒`,`giraffe face`,`animals`,`长颈鹿`],[`🦓`,`zebra face`,`animals`,`斑马`],[`🦔`,`hedgehog`,`animals`,`刺猬`],[`🦕`,`sauropod`,`animals`,`恐龙,雷龙`],[`🦖`,`t-rex`,`animals`,`恐龙,霸王龙`],[`🦗`,`cricket`,`animals`,``],[`🦘`,`kangaroo`,`animals`,`袋鼠`],[`🦙`,`llama`,`animals`,`羊驼,草泥马`],[`🦚`,`peacock`,`animals`,`孔雀,开屏`],[`🦛`,`hippopotamus`,`animals`,`河马`],[`🦜`,`parrot`,`animals`,`鹦鹉`],[`🦝`,`raccoon`,`animals`,`浣熊`],[`🦞`,`lobster`,`animals`,`龙虾,海鲜`],[`🦟`,`mosquito`,`animals`,``],[`🦠`,`microbe`,`animals`,``],[`🦡`,`badger`,`animals`,`獾`],[`🦢`,`swan`,`animals`,`天鹅,鹅`],[`🦣`,`mammoth`,`animals`,`猛犸象`],[`🦤`,`dodo`,`animals`,`渡渡鸟`],[`🦥`,`sloth`,`animals`,`树懒`],[`🦦`,`otter`,`animals`,`水獭`],[`🦧`,`orangutan`,`animals`,``],[`🦨`,`skunk`,`animals`,`臭鼬`],[`🦩`,`flamingo`,`animals`,`火烈鸟,红鹤`],[`🦪`,`oyster`,`animals`,`生蚝,牡蛎`],[`🦫`,`beaver`,`animals`,`河狸,海狸`],[`🦬`,`bison`,`animals`,`野牛,水牛`],[`🦭`,`seal`,`animals`,`海豹,海狮`],[`🦮`,`guide dog`,`animals`,`导盲犬,狗`],[`🦯`,`probing cane`,`symbols`,``],[`🦰`,`emoji component red hair`,`people`,`红发,头发,发色`],[`🦱`,`emoji component curly hair`,`people`,`卷发,头发`],[`🦲`,`emoji component bald`,`people`,`光头,秃头`],[`🦳`,`emoji component white hair`,`people`,`白发,头发`],[`🦴`,`bone`,`people`,``],[`🦵`,`leg`,`people`,`腿,大腿`],[`🦶`,`foot`,`people`,`脚,足`],[`🦷`,`tooth`,`people`,`牙齿,牙`],[`🦸`,`superhero`,`people`,`英雄`],[`🦹`,`supervillain`,`people`,`超级反派,坏人,反派`],[`🦺`,`safety vest`,`symbols`,``],[`🦻`,`ear with hearing aid`,`symbols`,`助听器,耳朵`],[`🦼`,`motorized wheelchair`,`people`,``],[`🦽`,`manual wheelchair`,`people`,``],[`🦾`,`mechanical arm`,`people`,`机械臂,机器人,义肢`],[`🦿`,`mechanical leg`,`people`,`机械腿,义肢`],[`🧀`,`cheese wedge`,`food`,`奶酪,芝士`],[`🧁`,`cupcake`,`food`,`纸杯蛋糕,杯子蛋糕`],[`🧂`,`salt shaker`,`food`,``],[`🧃`,`beverage box`,`food`,`果汁盒,饮料`],[`🧄`,`garlic`,`food`,`大蒜,蒜`],[`🧅`,`onion`,`food`,`洋葱`],[`🧆`,`falafel`,`food`,`鹰嘴豆丸子`],[`🧇`,`waffle`,`food`,`华夫饼`],[`🧈`,`butter`,`food`,`黄油,奶油`],[`🧉`,`mate drink`,`food`,`马黛茶`],[`🧊`,`ice cube`,`food`,`冰块,冰`],[`🧋`,`bubble tea`,`food`,`奶茶,珍珠奶茶`],[`🧌`,`troll`,`symbols`,`巨魔,妖怪`],[`🧍`,`standing person`,`symbols`,`站立,站着,人`],[`🧎`,`kneeling person`,`symbols`,`跪,跪下,祈祷`],[`🧏`,`deaf person`,`symbols`,``],[`🧐`,`face with monocle`,`people`,`检查,研究,眼镜`],[`🧑`,`adult`,`people`,`人`],[`🧒`,`child`,`people`,``],[`🧓`,`older adult`,`people`,`老人,奶奶,爷爷`],[`🧔`,`bearded person`,`people`,`胡子,胡须,大叔`],[`🧕`,`person with headscarf`,`people`,`头巾`],[`🧖`,`person in steamy room`,`people`,`桑拿,蒸汽,洗澡`],[`🧗`,`person climbing`,`people`,`攀岩`],[`🧘`,`person in lotus position`,`people`,`打坐`],[`🧙`,`mage`,`people`,`巫师,魔法师,法师`],[`🧚`,`fairy`,`people`,`仙女,精灵,小仙女`],[`🧛`,`vampire`,`people`,`吸血鬼,德古拉`],[`🧜`,`merperson`,`people`,`美人鱼,人鱼`],[`🧝`,`elf`,`people`,`精灵,耳朵`],[`🧞`,`genie`,`people`,`灯神,精灵,神灯`],[`🧟`,`zombie`,`people`,`僵尸,丧尸`],[`🧠`,`brain`,`people`,`大脑,思考,记忆,AI`],[`🧡`,`orange heart`,`people`,``],[`🧢`,`billed cap`,`people`,`棒球帽,帽子`],[`🧣`,`scarf`,`people`,`围巾,冬天`],[`🧤`,`gloves`,`people`,`手套,冬天`],[`🧥`,`coat`,`people`,`大衣,外套`],[`🧦`,`socks`,`people`,`袜子`],[`🧧`,`red gift envelope`,`objects`,`红包,利是,新年`],[`🧨`,`firecracker`,`objects`,``],[`🧩`,`jigsaw puzzle piece`,`objects`,`拼图,拼图游戏`],[`🧪`,`test tube`,`objects`,`试管,实验,化学,科学`],[`🧫`,`petri dish`,`objects`,`培养皿,实验,细菌`],[`🧬`,`dna double helix`,`objects`,`DNA,基因,生物`],[`🧭`,`compass`,`objects`,`指南针`],[`🧮`,`abacus`,`objects`,`算盘,计算`],[`🧯`,`fire extinguisher`,`objects`,`灭火器,消防`],[`🧰`,`toolbox`,`objects`,`工具箱,工具`],[`🧱`,`brick`,`objects`,`砖`],[`🧲`,`magnet`,`objects`,`磁铁,磁性`],[`🧳`,`luggage`,`objects`,`行李箱`],[`🧴`,`lotion bottle`,`objects`,`乳液,护肤,防晒`],[`🧵`,`spool of thread`,`objects`,`线,针线,缝纫`],[`🧶`,`ball of yarn`,`objects`,`毛线,织毛衣`],[`🧷`,`safety pin`,`objects`,`别针,安全别针`],[`🧸`,`teddy bear`,`objects`,`泰迪熊,玩具熊`],[`🧹`,`broom`,`objects`,`扫帚`],[`🧺`,`basket`,`objects`,`篮子`],[`🧻`,`roll of paper`,`objects`,`纸巾`],[`🧼`,`bar of soap`,`objects`,`肥皂,洗手,清洁`],[`🧽`,`sponge`,`objects`,`海绵,清洁`],[`🧾`,`receipt`,`objects`,`收据`],[`🧿`,`nazar amulet`,`objects`,`护身符`],[`🩰`,`ballet shoes`,`activity`,`芭蕾`],[`🩱`,`one-piece swimsuit`,`activity`,`泳衣`],[`🩲`,`briefs`,`activity`,`泳裤`],[`🩳`,`shorts`,`activity`,`短裤`],[`🩴`,`thong sandal`,`activity`,`凉拖`],[`🩵`,`light blue heart`,`activity`,`浅蓝`],[`🩶`,`grey heart`,`activity`,`灰心`],[`🩷`,`pink heart`,`activity`,`粉色`],[`🩸`,`drop of blood`,`activity`,`血`],[`🩹`,`adhesive bandage`,`activity`,`创可贴`],[`🩺`,`stethoscope`,`activity`,`听诊器`],[`🩻`,`x-ray`,`activity`,`X光`],[`🩼`,`crutch`,`activity`,`拐杖`],[`🪀`,`yo-yo`,`objects`,`玩具`],[`🪁`,`kite`,`objects`,`风筝`],[`🪂`,`parachute`,`objects`,`跳伞`],[`🪃`,`boomerang`,`objects`,``],[`🪄`,`magic wand`,`objects`,`魔杖,魔法,魔术`],[`🪅`,`pinata`,`objects`,`皮纳塔`],[`🪆`,`nesting dolls`,`objects`,``],[`🪇`,`maracas`,`objects`,`沙锤`],[`🪈`,`flute`,`objects`,`笛子`],[`🪐`,`ringed planet`,`objects`,``],[`🪑`,`chair`,`objects`,`椅子`],[`🪒`,`razor`,`objects`,`剃须刀,剃刀`],[`🪓`,`axe`,`objects`,`斧头,斧子`],[`🪔`,`diya lamp`,`objects`,`油灯`],[`🪕`,`banjo`,`objects`,`班卓琴`],[`🪖`,`military helmet`,`objects`,`军盔`],[`🪗`,`accordion`,`objects`,`手风琴`],[`🪘`,`long drum`,`objects`,`鼓`],[`🪙`,`coin`,`objects`,`金币`],[`🪚`,`carpentry saw`,`objects`,`锯子,锯`],[`🪛`,`screwdriver`,`objects`,`螺丝刀`],[`🪜`,`ladder`,`objects`,`梯子`],[`🪝`,`hook`,`objects`,`钩子,挂钩`],[`🪞`,`mirror`,`objects`,`镜子`],[`🪟`,`window`,`objects`,`窗户`],[`🪠`,`plunger`,`objects`,`皮搋子,通马桶`],[`🪡`,`sewing needle`,`objects`,`针,缝纫,刺绣`],[`🪢`,`knot`,`objects`,``],[`🪣`,`bucket`,`objects`,`水桶,桶`],[`🪤`,`mouse trap`,`objects`,`捕鼠器`],[`🪥`,`toothbrush`,`objects`,`牙刷,刷牙`],[`🪦`,`headstone`,`objects`,`墓碑`],[`🪧`,`placard`,`objects`,`告示牌`],[`🪨`,`rock`,`objects`,`石头,岩石`],[`🪩`,`mirror ball`,`objects`,`迪斯科球`],[`🪪`,`identification card`,`objects`,`身份证`],[`🪫`,`low battery`,`objects`,`电池,没电,低电量`],[`🪬`,`hamsa`,`objects`,`手掌印,护身符`],[`🪭`,`folding hand fan`,`objects`,``],[`🪮`,`hair pick`,`objects`,`梳子`],[`🪯`,`khanda`,`objects`,``],[`🪰`,`fly`,`objects`,`苍蝇,飞虫`],[`🪱`,`worm`,`objects`,``],[`🪲`,`beetle`,`objects`,`甲虫,昆虫`],[`🪳`,`cockroach`,`objects`,`蟑螂,虫子`],[`🪴`,`potted plant`,`objects`,`盆栽,植物,绿植`],[`🪵`,`wood`,`objects`,`木头,柴火,木`],[`🪶`,`feather`,`objects`,`羽毛,羽毛笔`],[`🪷`,`lotus`,`objects`,`莲花`],[`🪸`,`coral`,`objects`,`珊瑚`],[`🪹`,`empty nest`,`objects`,`鸟巢`],[`🪺`,`nest with eggs`,`objects`,`鸟巢`],[`🪻`,`hyacinth`,`objects`,`风信子`],[`🪼`,`jellyfish`,`objects`,`水母`],[`🪽`,`wing`,`objects`,`翅膀`],[`🪿`,`goose`,`objects`,`鹅`],[`🫀`,`anatomical heart`,`objects`,`心脏,心跳`],[`🫁`,`lungs`,`objects`,`肺,呼吸`],[`🫂`,`people hugging`,`objects`,`拥抱,人,朋友`],[`🫃`,`pregnant man`,`objects`,`孕妇,怀孕`],[`🫄`,`pregnant person`,`objects`,`孕妇,怀孕`],[`🫅`,`person with crown`,`objects`,`国王,王子,皇冠`],[`🫎`,`moose`,`objects`,`驼鹿,麋鹿`],[`🫏`,`donkey`,`objects`,`驴,动物`],[`🫐`,`blueberries`,`food`,`蓝莓`],[`🫑`,`bell pepper`,`food`,`甜椒,彩椒`],[`🫒`,`olive`,`food`,`橄榄`],[`🫓`,`flatbread`,`food`,`薄饼,饼`],[`🫔`,`tamale`,`food`,`玉米粉蒸肉`],[`🫕`,`fondue`,`food`,`奶酪火锅`],[`🫖`,`teapot`,`food`,`茶壶,茶`],[`🫗`,`pouring liquid`,`food`,`倒,倒水,水杯`],[`🫘`,`beans`,`food`,`豆子,红豆`],[`🫙`,`jar`,`food`,`罐子,玻璃罐`],[`🫚`,`ginger root`,`food`,`姜,生姜`],[`🫛`,`pea pod`,`food`,`豌豆荚,豆`],[`🫠`,`melting face`,`smileys`,`融化`],[`🫡`,`saluting face`,`smileys`,`敬礼`],[`🫢`,`face with open eyes and hand over mouth`,`smileys`,`捂眼`],[`🫣`,`face with peeking eye`,`smileys`,`偷看`],[`🫤`,`face with diagonal mouth`,`smileys`,`撇嘴`],[`🫥`,`dotted line face`,`smileys`,`隐形`],[`🫦`,`biting lip`,`smileys`,`咬唇,嘴唇`],[`🫧`,`bubbles`,`smileys`,`泡泡`],[`🫨`,`shaking face`,`smileys`,`摇晃,震动,抖`],[`🫰`,`hand with index finger and thumb crossed`,`people`,`比心,手指,捏`],[`🫱`,`rightwards hand`,`people`,`手,右边,推`],[`🫲`,`leftwards hand`,`people`,`手,左边,推`],[`🫳`,`palm down hand`,`people`,`手,向下,放`],[`🫴`,`palm up hand`,`people`,`手,向上,举`],[`🫵`,`index pointing at the viewer`,`people`,`指,你`],[`🫶`,`heart hands`,`people`,`比心,爱心,手势`],[`🫷`,`leftwards pushing hand`,`people`,`手,推,右边`],[`🫸`,`rightwards pushing hand`,`people`,`手,推,左边`],[`‼`,`double exclamation mark`,`symbols`,``],[`‼️`,`double exclamation mark`,`symbols`,``],[`⁉`,`exclamation question mark`,`symbols`,``],[`⁉️`,`exclamation question mark`,`symbols`,``],[`™`,`trade mark sign`,`symbols`,``],[`™️`,`trade mark sign`,`symbols`,``],[`ℹ`,`information source`,`symbols`,``],[`ℹ️`,`information source`,`symbols`,``],[`↔`,`left right arrow`,`symbols`,``],[`↔️`,`left right arrow`,`symbols`,``],[`↕`,`up down arrow`,`symbols`,``],[`↕️`,`up down arrow`,`symbols`,``],[`↖`,`north west arrow`,`symbols`,``],[`↖️`,`north west arrow`,`symbols`,``],[`↗`,`north east arrow`,`symbols`,``],[`↗️`,`north east arrow`,`symbols`,``],[`↘`,`south east arrow`,`symbols`,``],[`↘️`,`south east arrow`,`symbols`,``],[`↙`,`south west arrow`,`symbols`,``],[`↙️`,`south west arrow`,`symbols`,``],[`↩`,`leftwards arrow with hook`,`symbols`,``],[`↩️`,`leftwards arrow with hook`,`symbols`,``],[`↪`,`rightwards arrow with hook`,`symbols`,``],[`↪️`,`rightwards arrow with hook`,`symbols`,``],[`⌚`,`watch`,`objects`,`手表`],[`⌚️`,`watch`,`objects`,``],[`⌛`,`hourglass`,`objects`,`沙漏,时间,等待`],[`⌛️`,`hourglass`,`objects`,``],[`⌨`,`keyboard`,`symbols`,``],[`⌨️`,`keyboard`,`symbols`,`键盘,打字`],[`⏏`,`eject symbol`,`symbols`,``],[`⏏️`,`eject symbol`,`symbols`,``],[`⏩`,`black right-pointing double triangle`,`objects`,``],[`⏪`,`black left-pointing double triangle`,`objects`,``],[`⏫`,`black up-pointing double triangle`,`objects`,``],[`⏬`,`black down-pointing double triangle`,`objects`,``],[`⏭`,`black right-pointing double triangle with vertical bar`,`objects`,``],[`⏭️`,`black right-pointing double triangle with vertical bar`,`objects`,``],[`⏮`,`black left-pointing double triangle with vertical bar`,`objects`,``],[`⏮️`,`black left-pointing double triangle with vertical bar`,`objects`,``],[`⏯`,`black right-pointing triangle with double vertical bar`,`objects`,``],[`⏯️`,`black right-pointing triangle with double vertical bar`,`objects`,``],[`⏰`,`alarm clock`,`objects`,`闹钟,时间,起床`],[`⏱`,`stopwatch`,`objects`,``],[`⏱️`,`stopwatch`,`objects`,`秒表`],[`⏲`,`timer clock`,`objects`,``],[`⏲️`,`timer clock`,`objects`,`计时器`],[`⏳`,`hourglass with flowing sand`,`objects`,`沙漏`],[`⏸`,`double vertical bar`,`symbols`,``],[`⏸️`,`double vertical bar`,`symbols`,``],[`⏹`,`black square for stop`,`symbols`,``],[`⏹️`,`black square for stop`,`symbols`,``],[`⏺`,`black circle for record`,`symbols`,``],[`⏺️`,`black circle for record`,`symbols`,``],[`Ⓜ`,`circled latin capital letter m`,`symbols`,``],[`Ⓜ️`,`circled latin capital letter m`,`symbols`,``],[`▪`,`black small square`,`symbols`,``],[`▪️`,`black small square`,`symbols`,``],[`▫`,`white small square`,`symbols`,``],[`▫️`,`white small square`,`symbols`,``],[`▶`,`black right-pointing triangle`,`symbols`,``],[`▶️`,`black right-pointing triangle`,`symbols`,``],[`◀`,`black left-pointing triangle`,`symbols`,``],[`◀️`,`black left-pointing triangle`,`symbols`,``],[`◻`,`white medium square`,`symbols`,``],[`◻️`,`white medium square`,`symbols`,``],[`◼`,`black medium square`,`symbols`,``],[`◼️`,`black medium square`,`symbols`,``],[`◽`,`white medium small square`,`symbols`,``],[`◾`,`black medium small square`,`symbols`,``],[`◾️`,`black medium small square`,`symbols`,``],[`☀`,`black sun with rays`,`symbols`,``],[`☀️`,`black sun with rays`,`symbols`,`太阳,晴天,阳光`],[`☁`,`cloud`,`symbols`,``],[`☁️`,`cloud`,`symbols`,`云,多云,天气`],[`☂`,`umbrella`,`symbols`,``],[`☂️`,`umbrella`,`symbols`,``],[`☃`,`snowman`,`symbols`,``],[`☃️`,`snowman`,`symbols`,`雪人,冬天,雪`],[`☄`,`comet`,`symbols`,``],[`☄️`,`comet`,`symbols`,``],[`☎`,`black telephone`,`symbols`,``],[`☎️`,`black telephone`,`symbols`,`电话`],[`☑`,`ballot box with check`,`symbols`,``],[`☑️`,`ballot box with check`,`symbols`,``],[`☔`,`umbrella with rain drops`,`symbols`,``],[`☔️`,`umbrella with rain drops`,`symbols`,``],[`☕`,`hot beverage`,`food`,`咖啡,热饮`],[`☕️`,`hot beverage`,`food`,``],[`☘`,`shamrock`,`symbols`,``],[`☘️`,`shamrock`,`symbols`,``],[`☝`,`white up pointing index`,`symbols`,``],[`☝️`,`white up pointing index`,`symbols`,`指,上面,向上`],[`☠`,`skull and crossbones`,`symbols`,``],[`☠️`,`skull and crossbones`,`symbols`,`骷髅,死亡,危险`],[`☢`,`radioactive sign`,`symbols`,``],[`☢️`,`radioactive sign`,`symbols`,``],[`☣`,`biohazard sign`,`symbols`,``],[`☣️`,`biohazard sign`,`symbols`,``],[`☦`,`orthodox cross`,`symbols`,``],[`☦️`,`orthodox cross`,`symbols`,``],[`☪`,`star and crescent`,`symbols`,``],[`☪️`,`star and crescent`,`symbols`,``],[`☮`,`peace symbol`,`symbols`,``],[`☮️`,`peace symbol`,`symbols`,``],[`☯`,`yin yang`,`symbols`,``],[`☯️`,`yin yang`,`symbols`,``],[`☸`,`wheel of dharma`,`symbols`,``],[`☸️`,`wheel of dharma`,`symbols`,``],[`☹`,`white frowning face`,`smileys`,``],[`☹️`,`white frowning face`,`smileys`,``],[`☺`,`white smiling face`,`smileys`,``],[`☺️`,`white smiling face`,`smileys`,``],[`♀`,`female sign`,`symbols`,``],[`♀️`,`female sign`,`symbols`,``],[`♂`,`male sign`,`symbols`,``],[`♂️`,`male sign`,`symbols`,``],[`♈`,`aries`,`symbols`,``],[`♈️`,`aries`,`symbols`,``],[`♉`,`taurus`,`symbols`,``],[`♉️`,`taurus`,`symbols`,``],[`♊`,`gemini`,`symbols`,``],[`♊️`,`gemini`,`symbols`,``],[`♋`,`cancer`,`symbols`,``],[`♋️`,`cancer`,`symbols`,``],[`♌`,`leo`,`symbols`,``],[`♌️`,`leo`,`symbols`,``],[`♍`,`virgo`,`symbols`,``],[`♍️`,`virgo`,`symbols`,``],[`♎`,`libra`,`symbols`,``],[`♎️`,`libra`,`symbols`,``],[`♏`,`scorpius`,`symbols`,``],[`♏️`,`scorpius`,`symbols`,``],[`♐`,`sagittarius`,`symbols`,``],[`♐️`,`sagittarius`,`symbols`,``],[`♑`,`capricorn`,`symbols`,``],[`♑️`,`capricorn`,`symbols`,``],[`♒`,`aquarius`,`symbols`,``],[`♒️`,`aquarius`,`symbols`,``],[`♓`,`pisces`,`symbols`,``],[`♓️`,`pisces`,`symbols`,``],[`♟`,`black chess pawn`,`symbols`,``],[`♟️`,`black chess pawn`,`symbols`,`棋子,国际象棋,象棋`],[`♠`,`black spade suit`,`symbols`,``],[`♠️`,`black spade suit`,`symbols`,``],[`♣`,`black club suit`,`symbols`,``],[`♣️`,`black club suit`,`symbols`,``],[`♥`,`black heart suit`,`symbols`,``],[`♥️`,`black heart suit`,`symbols`,``],[`♦`,`black diamond suit`,`symbols`,``],[`♦️`,`black diamond suit`,`symbols`,``],[`♨`,`hot springs`,`symbols`,``],[`♨️`,`hot springs`,`symbols`,`温泉,热泉`],[`♻`,`black universal recycling symbol`,`symbols`,``],[`♻️`,`black universal recycling symbol`,`symbols`,``],[`♾`,`permanent paper sign`,`symbols`,``],[`♾️`,`permanent paper sign`,`symbols`,``],[`♿`,`wheelchair symbol`,`symbols`,``],[`♿️`,`wheelchair symbol`,`symbols`,``],[`⚒`,`hammer and pick`,`symbols`,``],[`⚒️`,`hammer and pick`,`symbols`,`锤子,工具`],[`⚓`,`anchor`,`symbols`,`锚,航海,停泊`],[`⚔`,`crossed swords`,`symbols`,``],[`⚔️`,`crossed swords`,`symbols`,`剑,交叉,战斗`],[`⚕`,`staff of aesculapius`,`symbols`,``],[`⚕️`,`staff of aesculapius`,`symbols`,``],[`⚖`,`scales`,`symbols`,``],[`⚖️`,`scales`,`symbols`,``],[`⚗`,`alembic`,`symbols`,``],[`⚗️`,`alembic`,`symbols`,``],[`⚙`,`gear`,`symbols`,``],[`⚙️`,`gear`,`symbols`,``],[`⚛`,`atom symbol`,`symbols`,``],[`⚛️`,`atom symbol`,`symbols`,``],[`⚜`,`fleur-de-lis`,`symbols`,``],[`⚜️`,`fleur-de-lis`,`symbols`,``],[`⚠`,`warning sign`,`symbols`,``],[`⚠️`,`warning sign`,`symbols`,``],[`⚡`,`high voltage sign`,`symbols`,``],[`⚧`,`male with stroke and male and female sign`,`symbols`,``],[`⚧️`,`male with stroke and male and female sign`,`symbols`,``],[`⚪`,`medium white circle`,`symbols`,``],[`⚪️`,`medium white circle`,`symbols`,``],[`⚫`,`medium black circle`,`symbols`,``],[`⚰`,`coffin`,`symbols`,``],[`⚰️`,`coffin`,`symbols`,`棺材,死亡`],[`⚱`,`funeral urn`,`symbols`,``],[`⚱️`,`funeral urn`,`symbols`,`骨灰盒,死亡`],[`⚽`,`soccer ball`,`activity`,`足球,球`],[`⚽️`,`soccer ball`,`activity`,``],[`⚾`,`baseball`,`activity`,`棒球,球`],[`⚾️`,`baseball`,`activity`,``],[`⛄`,`snowman without snow`,`symbols`,`雪人,冬天`],[`⛄️`,`snowman without snow`,`symbols`,``],[`⛅`,`sun behind cloud`,`symbols`,`太阳,云,多云`],[`⛈`,`thunder cloud and rain`,`symbols`,``],[`⛈️`,`thunder cloud and rain`,`symbols`,`雷雨,雷暴,天气`],[`⛎`,`ophiuchus`,`symbols`,``],[`⛏`,`pick`,`symbols`,``],[`⛏️`,`pick`,`symbols`,`镐,工具`],[`⛑`,`helmet with white cross`,`symbols`,``],[`⛑️`,`helmet with white cross`,`symbols`,`头盔,救援,安全`],[`⛓`,`chains`,`symbols`,``],[`⛓️`,`chains`,`symbols`,``],[`⛔`,`no entry`,`symbols`,``],[`⛩`,`shinto shrine`,`travel`,``],[`⛩️`,`shinto shrine`,`travel`,`鸟居,神社,日本`],[`⛪`,`church`,`travel`,`教堂`],[`⛰`,`mountain`,`travel`,``],[`⛰️`,`mountain`,`travel`,`山,山峰`],[`⛱`,`umbrella on ground`,`travel`,``],[`⛱️`,`umbrella on ground`,`travel`,``],[`⛲`,`fountain`,`travel`,`喷泉`],[`⛲️`,`fountain`,`travel`,``],[`⛳`,`flag in hole`,`activity`,`高尔夫,高尔夫球,球洞`],[`⛳️`,`flag in hole`,`activity`,``],[`⛴`,`ferry`,`travel`,``],[`⛴️`,`ferry`,`travel`,`渡轮,船`],[`⛵`,`sailboat`,`travel`,`帆船,船`],[`⛵️`,`sailboat`,`travel`,``],[`⛷`,`skier`,`activity`,``],[`⛷️`,`skier`,`activity`,``],[`⛸`,`ice skate`,`activity`,``],[`⛸️`,`ice skate`,`activity`,`溜冰,冰刀,滑冰`],[`⛹`,`person with ball`,`activity`,``],[`⛹️`,`person with ball`,`activity`,``],[`⛺`,`tent`,`travel`,`帐篷,露营`],[`⛺️`,`tent`,`travel`,``],[`⛽`,`fuel pump`,`travel`,`加油站,加油,汽油`],[`✂`,`black scissors`,`symbols`,``],[`✂️`,`black scissors`,`symbols`,``],[`✅`,`white heavy check mark`,`symbols`,``],[`✈`,`airplane`,`travel`,``],[`✈️`,`airplane`,`travel`,`飞机,航班,起飞`],[`✉`,`envelope`,`symbols`,``],[`✉️`,`envelope`,`symbols`,`信封,邮件,信`],[`✊`,`raised fist`,`people`,`拳头,加油,力量`],[`✋`,`raised hand`,`people`,`手,举手,停`],[`✌`,`victory hand`,`symbols`,``],[`✌️`,`victory hand`,`symbols`,`胜利,耶,剪刀手`],[`✍`,`writing hand`,`symbols`,``],[`✍️`,`writing hand`,`symbols`,`写字,写作,手`],[`✏`,`pencil`,`symbols`,``],[`✏️`,`pencil`,`symbols`,``],[`✒`,`black nib`,`symbols`,``],[`✒️`,`black nib`,`symbols`,``],[`✔`,`heavy check mark`,`symbols`,``],[`✔️`,`heavy check mark`,`symbols`,``],[`✖`,`heavy multiplication x`,`symbols`,``],[`✖️`,`heavy multiplication x`,`symbols`,``],[`✝`,`latin cross`,`symbols`,``],[`✝️`,`latin cross`,`symbols`,``],[`✡`,`star of david`,`symbols`,``],[`✡️`,`star of david`,`symbols`,``],[`✨`,`sparkles`,`symbols`,`星星,闪光,发光`],[`✳`,`eight spoked asterisk`,`symbols`,``],[`✳️`,`eight spoked asterisk`,`symbols`,``],[`✴`,`eight pointed black star`,`symbols`,``],[`✴️`,`eight pointed black star`,`symbols`,``],[`❄`,`snowflake`,`symbols`,``],[`❄️`,`snowflake`,`symbols`,`雪花,雪,冬天,冷`],[`❇`,`sparkle`,`symbols`,``],[`❇️`,`sparkle`,`symbols`,``],[`❌`,`cross mark`,`symbols`,``],[`❎`,`negative squared cross mark`,`symbols`,``],[`❓`,`black question mark ornament`,`symbols`,``],[`❔`,`white question mark ornament`,`symbols`,``],[`❕`,`white exclamation mark ornament`,`symbols`,``],[`❗`,`heavy exclamation mark symbol`,`symbols`,``],[`❗️`,`heavy exclamation mark symbol`,`symbols`,``],[`❣`,`heavy heart exclamation mark ornament`,`symbols`,``],[`❣️`,`heavy heart exclamation mark ornament`,`symbols`,`爱心,感叹号`],[`❤`,`heavy black heart`,`smileys`,``],[`❤️`,`heavy black heart`,`smileys`,`爱心,红心,爱`],[`➕`,`heavy plus sign`,`symbols`,``],[`➖`,`heavy minus sign`,`symbols`,``],[`➗`,`heavy division sign`,`symbols`,``],[`➡`,`black rightwards arrow`,`symbols`,``],[`➡️`,`black rightwards arrow`,`symbols`,``],[`➰`,`curly loop`,`symbols`,``],[`➿`,`double curly loop`,`symbols`,``],[`⬅`,`leftwards black arrow`,`symbols`,``],[`⬅️`,`leftwards black arrow`,`symbols`,``],[`⬆`,`upwards black arrow`,`symbols`,``],[`⬆️`,`upwards black arrow`,`symbols`,``],[`⬇`,`downwards black arrow`,`symbols`,``],[`⬇️`,`downwards black arrow`,`symbols`,``],[`⬛`,`black large square`,`symbols`,``],[`⬛️`,`black large square`,`symbols`,``],[`⬜`,`white large square`,`symbols`,``],[`⬜️`,`white large square`,`symbols`,``],[`⭐`,`white medium star`,`symbols`,`星星,五星,评分`],[`⭕`,`heavy large circle`,`symbols`,``],[`⭕️`,`heavy large circle`,`symbols`,``],[`⤴`,`arrow pointing rightwards then curving upwards`,`symbols`,``],[`⤴️`,`arrow pointing rightwards then curving upwards`,`symbols`,``],[`⤵`,`arrow pointing rightwards then curving downwards`,`symbols`,``],[`⤵️`,`arrow pointing rightwards then curving downwards`,`symbols`,``],[`〰`,`wavy dash`,`symbols`,``],[`〰️`,`wavy dash`,`symbols`,``],[`〽`,`part alternation mark`,`symbols`,``],[`〽️`,`part alternation mark`,`symbols`,``],[`㊗`,`circled ideograph congratulation`,`symbols`,``],[`㊗️`,`circled ideograph congratulation`,`symbols`,``],[`㊙`,`circled ideograph secret`,`symbols`,``],[`㊙️`,`circled ideograph secret`,`symbols`,``],[`©`,`copyright sign`,`symbols`,``],[`©️`,`copyright sign`,`symbols`,``],[`®`,`registered sign`,`symbols`,``],[`®️`,`registered sign`,`symbols`,``],[`👨💻`,`man technologist`,`people`,`程序员,开发者,工程师,码农`],[`👩💻`,`woman technologist`,`people`,`程序员,开发者,工程师`],[`🧑💻`,`technologist`,`people`,`程序员,开发者,工程师`],[`👨🔧`,`man mechanic`,`people`,``],[`👩🔧`,`woman mechanic`,`people`,``],[`👨🎨`,`man artist`,`people`,``],[`👩🎨`,`woman artist`,`people`,``],[`👨🚀`,`man astronaut`,`people`,``],[`👩🚀`,`woman astronaut`,`people`,``],[`👨⚕️`,`man health worker`,`people`,``],[`👩⚕️`,`woman health worker`,`people`,``],[`👨🏫`,`man teacher`,`people`,``],[`👩🏫`,`woman teacher`,`people`,``],[`👨🍳`,`man cook`,`people`,``],[`👩🍳`,`woman cook`,`people`,``],[`👨🌾`,`man farmer`,`people`,``],[`👩🌾`,`woman farmer`,`people`,``],[`👩🏭`,`woman factory worker`,`people`,``],[`👨🎓`,`man student`,`people`,``],[`👩🎓`,`woman student`,`people`,``],[`👨🚒`,`man firefighter`,`people`,``],[`👩🚒`,`woman firefighter`,`people`,``],[`👨⚖️`,`man judge`,`people`,``],[`👩⚖️`,`woman judge`,`people`,``],[`👨💼`,`man office worker`,`people`,``],[`👩💼`,`woman office worker`,`people`,``],[`👨🎤`,`man singer`,`people`,``],[`👩🎤`,`woman singer`,`people`,``],[`👨🦰`,`man red hair`,`people`,``],[`👩🦰`,`woman red hair`,`people`,``],[`👨🦱`,`man curly hair`,`people`,``],[`👩🦱`,`woman curly hair`,`people`,``],[`👩🦲`,`woman bald`,`people`,``],[`👨🦳`,`man white hair`,`people`,``],[`👩🦳`,`woman white hair`,`people`,``],[`👩❤️👨`,`couple with heart`,`people`,``],[`👨❤️👨`,`couple with heart`,`people`,``],[`👩❤️👩`,`couple with heart`,`people`,``],[`👨👩👧`,`family man woman girl`,`people`,``],[`👨👩👦`,`family man woman boy`,`people`,``],[`👨👩👧👦`,`family man woman girl boy`,`people`,``],[`👨👩👦👦`,`man`,`people`,``],[`👨👩👧👧`,`family man woman girl girl`,`people`,``],[`👩👩👧`,`family woman woman girl`,`people`,``],[`👨👨👧`,`family man man girl`,`people`,``],[`👨👦`,`family man boy`,`people`,``],[`👩👧`,`family woman girl`,`people`,``],[`👨👧👦`,`family man girl boy`,`people`,``],[`👩❤️💋👨`,`kiss woman man`,`people`,``],[`🧑🤝🧑`,`people holding hands`,`people`,``],[`❤️🔥`,`heart on fire`,`smileys`,``],[`🧑🚒`,`firefighter`,`people`,`消防员`],[`🧑🏭`,`factory worker`,`people`,``],[`🧑🎓`,`student`,`people`,`学生,毕业生,大学生`],[`🧑🏫`,`teacher`,`people`,`老师,教师,教授`],[`🧑🎤`,`singer`,`people`,`歌手,歌星`],[`🧑⚕️`,`health worker`,`people`,`医生,医疗`],[`🧑⚖️`,`judge`,`people`,`法官,审判`],[`🧑🍳`,`cook`,`people`,`厨师,大厨`],[`🧑🌾`,`farmer`,`people`,`农民,农夫`],[`🧑🎨`,`artist`,`people`,`画家,艺术家`],[`🧑🔬`,`scientist`,`people`,``],[`🧑🔧`,`mechanic`,`people`,`技工,维修工`],[`🧑💼`,`office worker`,`people`,`白领,上班族,职员`],[`🧑🚀`,`astronaut`,`people`,`宇航员,太空人`],[`🏃♂️`,`man running`,`activity`,``],[`🏃♀️`,`woman running`,`activity`,``],[`🚶♂️`,`man walking`,`travel`,``],[`🚶♀️`,`woman walking`,`travel`,``],[`🧎♂️`,`man kneeling`,`symbols`,``],[`🧎♀️`,`woman kneeling`,`symbols`,``],[`🏋️♂️`,`man lifting weights`,`activity`,``],[`🏋️♀️`,`woman lifting weights`,`activity`,``],[`🤸♂️`,`man cartwheeling`,`people`,``],[`🤸♀️`,`woman cartwheeling`,`people`,``],[`⛹️♂️`,`man bouncing ball`,`activity`,``],[`⛹️♀️`,`woman bouncing ball`,`activity`,``],[`🤾♂️`,`man playing handball`,`activity`,``],[`🤾♀️`,`woman playing handball`,`activity`,``],[`🧘♀️`,`woman in lotus position`,`people`,``],[`🏄♂️`,`man surfing`,`activity`,``],[`🏄♀️`,`woman surfing`,`activity`,``],[`🏊♂️`,`man swimming`,`activity`,``],[`🏊♀️`,`woman swimming`,`activity`,``],[`🚴♂️`,`man biking`,`travel`,``],[`🚴♀️`,`woman biking`,`travel`,``],[`🚵♂️`,`man mountain biking`,`travel`,``],[`🚵♀️`,`woman mountain biking`,`travel`,``],[`👯♂️`,`men with bunny ears`,`people`,``],[`👯♀️`,`women with bunny ears`,`people`,``],[`🧖♂️`,`man in steamy room`,`people`,``],[`🧖♀️`,`woman in steamy room`,`people`,``],[`🧗♂️`,`man climbing`,`people`,``],[`🧗♀️`,`woman climbing`,`people`,``],[`🤦♂️`,`man facepalming`,`smileys`,``],[`🤦♀️`,`woman facepalming`,`smileys`,``],[`🤷♂️`,`man shrugging`,`people`,``],[`🤷♀️`,`woman shrugging`,`people`,``],[`🙍♂️`,`person frowning`,`smileys`,``],[`🙍♀️`,`woman frowning`,`smileys`,``],[`🙎♂️`,`man pouting`,`smileys`,``],[`🙎♀️`,`woman pouting`,`smileys`,``],[`🙅♂️`,`man gesturing no`,`smileys`,``],[`🙅♀️`,`woman gesturing no`,`smileys`,``],[`🙆♂️`,`man gesturing ok`,`smileys`,``],[`🙆♀️`,`woman gesturing ok`,`smileys`,``],[`💁♂️`,`man tipping hand`,`people`,``],[`💁♀️`,`woman tipping hand`,`people`,``],[`🙋♂️`,`man raising hand`,`smileys`,``],[`🙋♀️`,`woman raising hand`,`smileys`,``],[`🙇♂️`,`man bowing`,`smileys`,``],[`🙇♀️`,`woman bowing`,`smileys`,``],[`💆♂️`,`man getting massage`,`people`,``],[`💆♀️`,`woman getting massage`,`people`,``],[`💇♂️`,`man getting haircut`,`people`,``],[`💇♀️`,`woman getting haircut`,`people`,``],[`🧞♂️`,`man genie`,`people`,``],[`🧞♀️`,`woman genie`,`people`,``],[`🧟♂️`,`man zombie`,`people`,``],[`🧟♀️`,`woman zombie`,`people`,``],[`🧜♂️`,`merman`,`people`,``],[`🧚♂️`,`man fairy`,`people`,``],[`🧚♀️`,`woman fairy`,`people`,``],[`🧛♂️`,`man vampire`,`people`,``],[`🧛♀️`,`woman vampire`,`people`,``],[`🧙♂️`,`man mage`,`people`,``],[`🧙♀️`,`mage`,`people`,``],[`🧝♂️`,`man elf`,`people`,``],[`🧝♀️`,`woman elf`,`people`,``],[`🦸♂️`,`man superhero`,`people`,``],[`🦸♀️`,`woman superhero`,`people`,``],[`🦹♂️`,`man supervillain`,`people`,``],[`🦹♀️`,`woman supervillain`,`people`,``],[`0️⃣`,`keycap 0`,`symbols`,``],[`1️⃣`,`keycap 1`,`symbols`,``],[`2️⃣`,`keycap 2`,`symbols`,``],[`3️⃣`,`keycap 3`,`symbols`,``],[`4️⃣`,`keycap 4`,`symbols`,``],[`5️⃣`,`keycap 5`,`symbols`,``],[`6️⃣`,`keycap 6`,`symbols`,``],[`7️⃣`,`keycap 7`,`symbols`,``],[`8️⃣`,`keycap 8`,`symbols`,``],[`9️⃣`,`keycap 9`,`symbols`,``],[`#️⃣`,`keycap #`,`symbols`,``],[`*️⃣`,`keycap *`,`symbols`,``],[`🇨🇳`,`flag china`,`flags`,`中国,国旗,五星红旗`],[`🇺🇸`,`flag united states`,`flags`,`美国,国旗,USA`],[`🇬🇧`,`flag united kingdom`,`flags`,`英国,国旗,UK`],[`🇯🇵`,`flag japan`,`flags`,`日本,国旗`],[`🇫🇷`,`flag france`,`flags`,`法国,国旗`],[`🇩🇪`,`flag germany`,`flags`,`德国,国旗`],[`🇮🇹`,`flag italy`,`flags`,`意大利,国旗`],[`🇪🇸`,`flag spain`,`flags`,`西班牙,国旗`],[`🇷🇺`,`flag russia`,`flags`,`俄罗斯,国旗`],[`🇮🇳`,`regional indicator symbol letter i`,`flags`,`印度,国旗`],[`🇧🇷`,`flag brazil`,`flags`,`巴西,国旗`],[`🇨🇦`,`flag canada`,`flags`,`加拿大,国旗`],[`🇦🇺`,`flag australia`,`flags`,`澳大利亚,国旗`],[`🇸🇬`,`flag singapore`,`flags`,`新加坡,国旗`],[`🇭🇰`,`flag hong kong`,`flags`,`香港,国旗,区旗`],[`🇹🇼`,`flag taiwan`,`flags`,`台湾,国旗`],[`🇲🇴`,`flag macau`,`flags`,`澳门,国旗`],[`🇻🇳`,`flag vietnam`,`flags`,`越南,国旗`],[`🇲🇾`,`regional indicator symbol letter m`,`flags`,`马来西亚,国旗`],[`🇮🇩`,`flag indonesia`,`flags`,`印尼,国旗`],[`🇵🇭`,`flag philippines`,`flags`,`菲律宾,国旗`],[`🇹🇷`,`flag turkey`,`flags`,`土耳其,国旗`],[`🇸🇦`,`flag saudi arabia`,`flags`,`沙特,国旗`],[`🇦🇪`,`flag united arab emirates`,`flags`,`阿联酋,国旗`],[`🇳🇱`,`flag netherlands`,`flags`,`荷兰,国旗`],[`🇸🇪`,`flag sweden`,`flags`,`瑞典,国旗`],[`🇨🇭`,`flag switzerland`,`flags`,`瑞士,国旗`],[`🇦🇹`,`flag austria`,`flags`,`奥地利,国旗`],[`🇧🇪`,`flag belgium`,`flags`,`比利时,国旗`],[`🇵🇹`,`flag portugal`,`flags`,`葡萄牙,国旗`],[`🇬🇷`,`flag greece`,`flags`,`希腊,国旗`],[`🇳🇴`,`flag norway`,`flags`,`挪威,国旗`],[`🇩🇰`,`flag denmark`,`flags`,`丹麦,国旗`],[`🇫🇮`,`flag finland`,`flags`,`芬兰,国旗`],[`🇵🇱`,`flag poland`,`flags`,`波兰,国旗`],[`🇺🇦`,`flag ukraine`,`flags`,`乌克兰,国旗`],[`🇮🇱`,`flag israel`,`flags`,`以色列,国旗`],[`🇪🇬`,`flag egypt`,`flags`,`埃及,国旗`],[`🇿🇦`,`flag south africa`,`flags`,`南非,国旗`],[`🇳🇬`,`flag nigeria`,`flags`,`尼日利亚,国旗`],[`🇲🇽`,`flag mexico`,`flags`,`墨西哥,国旗`],[`🇦🇷`,`flag argentina`,`flags`,``],[`🇨🇱`,`flag chile`,`flags`,`智利,国旗`],[`🇰🇿`,`flag kazakhstan`,`flags`,`哈萨克斯坦,国旗`],[`🇺🇿`,`flag uzbekistan`,`flags`,`乌兹别克斯坦,国旗`],[`🇳🇿`,`flag new zealand`,`flags`,`新西兰,国旗`],[`🇮🇪`,`flag ireland`,`flags`,`爱尔兰,国旗`],[`🇨🇿`,`flag czechia`,`flags`,`捷克,国旗`],[`👍🏻`,`thumbs up light skin`,`people`,``],[`👍🏽`,`thumbs up sign`,`people`,``],[`👍🏾`,`thumbs up medium dark skin`,`people`,``],[`👍🏿`,`thumbs up dark skin`,`people`,``],[`👏🏻`,`clapping hands light skin`,`people`,``],[`👏🏼`,`clapping hands medium light skin`,`people`,``],[`👏🏽`,`clapping hands medium skin`,`people`,``],[`👏🏾`,`clapping hands medium dark skin`,`people`,``],[`👏🏿`,`clapping hands dark skin`,`people`,``],[`🙏🏻`,`folded hands light skin`,`smileys`,``],[`🙏🏼`,`folded hands medium light skin`,`smileys`,``],[`🙏🏽`,`folded hands medium skin`,`smileys`,``],[`🙏🏾`,`folded hands medium dark skin`,`smileys`,``],[`🙏🏿`,`folded hands dark skin`,`smileys`,``],[`🏳️🌈`,`rainbow flag`,`flags`,``],[`🏴☠️`,`pirate flag`,`flags`,`海盗旗,海盗`]];n(`zh`,{agentMgr:{allTools:`全部`,defaultAgentName:`默认助手`,defaultAgentDesc:`全能 AI 助手,拥有所有工具能力`,switchedTo:`已切换到:{name}`,editAgent:`编辑助手`,templateLoaded:`已加载模板:{name}`,noSkillsHint:`暂无启用技能(请先确认 Agent 已连接且技能开关已开启)`,nameRequired:`请输入助手名称`,agentUpdated:`助手已更新`,agentCreated:`助手 "{name}" 已创建`,saveFailed:`保存失败:{message}`,confirmDeleteAgentMessage:`确定要删除助手 "{name}" 吗?
|
|
2192
2193
|
正在使用该助手的会话将恢复为默认助手。`,deleteAgentTitle:`删除助手`,agentDeleted:`助手已删除`,deleteFailed:`删除失败:{message}`,cannotDeleteDefault:`默认助手不支持删除`,emojiCatSmileys:`笑脸与表情`,emojiCatPeople:`人物与身体`,emojiCatAnimals:`动物与自然`,emojiCatFood:`食物与饮品`,emojiCatTravel:`旅行与交通`,emojiCatActivity:`活动与运动`,emojiCatObjects:`物品`,emojiCatSymbols:`符号`,emojiCatFlags:`旗帜`,emojiSearchPlaceholder:`搜索 Emoji(英文名 / 中文关键词)`,emojiSearchClear:`清空搜索`,emojiNoMatch:`未找到匹配的 Emoji`,confirm:`确认`},agentTemplates:{codeReviewName:`代码审查专家`,codeReviewDesc:`专注于代码审查和质量保证`,webAutomationName:`网页自动化助手`,webAutomationDesc:`专注于网页交互和自动化`,dataAnalystName:`数据分析师`,dataAnalystDesc:`专注于数据提取、分析和可视化`,documentationName:`文档助手`,documentationDesc:`专注于技术文档和内容整理`}}),n(`en`,{agentMgr:{allTools:`All`,defaultAgentName:`Default Assistant`,defaultAgentDesc:`All-purpose AI assistant with all tool capabilities`,switchedTo:`Switched to: {name}`,editAgent:`Edit assistant`,templateLoaded:`Template loaded: {name}`,noSkillsHint:`No enabled skills (please confirm Agent is connected and skill switch is on)`,nameRequired:`Please enter assistant name`,agentUpdated:`Assistant updated`,agentCreated:`Assistant "{name}" created`,saveFailed:`Save failed: {message}`,confirmDeleteAgentMessage:`Are you sure you want to delete assistant "{name}"?
|
|
2193
|
-
Sessions using this assistant will revert to the default assistant.`,deleteAgentTitle:`Delete assistant`,agentDeleted:`Assistant deleted`,deleteFailed:`Delete failed: {message}`,cannotDeleteDefault:`Default assistant cannot be deleted`,emojiCatSmileys:`Smileys & Emotion`,emojiCatPeople:`People & Body`,emojiCatAnimals:`Animals & Nature`,emojiCatFood:`Food & Drink`,emojiCatTravel:`Travel & Places`,emojiCatActivity:`Activities`,emojiCatObjects:`Objects`,emojiCatSymbols:`Symbols`,emojiCatFlags:`Flags`,emojiSearchPlaceholder:`Search emoji (name / keyword)`,emojiSearchClear:`Clear search`,emojiNoMatch:`No matching emoji`,confirm:`Confirm`},agentTemplates:{codeReviewName:`Code Review Expert`,codeReviewDesc:`Focused on code review and quality assurance`,webAutomationName:`Web Automation Assistant`,webAutomationDesc:`Focused on web interaction and automation`,dataAnalystName:`Data Analyst`,dataAnalystDesc:`Focused on data extraction, analysis, and visualization`,documentationName:`Documentation Assistant`,documentationDesc:`Focused on technical documentation and content organization`}});async function
|
|
2194
|
+
Sessions using this assistant will revert to the default assistant.`,deleteAgentTitle:`Delete assistant`,agentDeleted:`Assistant deleted`,deleteFailed:`Delete failed: {message}`,cannotDeleteDefault:`Default assistant cannot be deleted`,emojiCatSmileys:`Smileys & Emotion`,emojiCatPeople:`People & Body`,emojiCatAnimals:`Animals & Nature`,emojiCatFood:`Food & Drink`,emojiCatTravel:`Travel & Places`,emojiCatActivity:`Activities`,emojiCatObjects:`Objects`,emojiCatSymbols:`Symbols`,emojiCatFlags:`Flags`,emojiSearchPlaceholder:`Search emoji (name / keyword)`,emojiSearchClear:`Clear search`,emojiNoMatch:`No matching emoji`,confirm:`Confirm`},agentTemplates:{codeReviewName:`Code Review Expert`,codeReviewDesc:`Focused on code review and quality assurance`,webAutomationName:`Web Automation Assistant`,webAutomationDesc:`Focused on web interaction and automation`,dataAnalystName:`Data Analyst`,dataAnalystDesc:`Focused on data extraction, analysis, and visualization`,documentationName:`Documentation Assistant`,documentationDesc:`Focused on technical documentation and content organization`}});async function zD(){await BD(),await VD(),WD(),KD(),LD(),i.debug(`[AgentMgr] Agent managerinitialization complete, activeAgentId:`,C.activeAgentId)}async function BD(){let[e,t]=await Promise.all([ht(),_t()]);C.activeSessionId||(C.activeAgentId=e),C.customAgents=t.filter(e=>!e.isBuiltin);let n=C.activeAgentId||e,r=t.find(e=>e.id===n||!n&&e.id==="default");C.activeAgentToolIds=r?r.toolIds:null,i.debug(`[AgentMgr] Agent state loaded, activeAgentId:`,C.activeAgentId,`total:`,t.length,`toolIds:`,C.activeAgentToolIds)}async function VD(){let e=document.getElementById(`agentListItems`),t=document.getElementById(`agentDropdownFooter`);if(!e)return;let n=await _t(),i=C.activeAgentId,a=``;for(let e of n){let t=e.id===i||!i&&e.id==="default",n=e.toolIds?e.toolIds.length:r(`agentMgr.allTools`),o=e.id==="default"?r(`agentMgr.defaultAgentName`):e.name,s=e.id==="default"?r(`agentMgr.defaultAgentDesc`):e.description||r(`agentConfig.toolCount`,{count:n});a+=`
|
|
2194
2195
|
<div class="agent-item ${t?`active`:``} ${e.isBuiltin?``:`is-editable`}" data-agent-id="${$(e.id)}">
|
|
2195
|
-
<span class="agent-item-icon">${
|
|
2196
|
+
<span class="agent-item-icon">${kO(e.icon)}</span>
|
|
2196
2197
|
<div class="agent-item-info">
|
|
2197
|
-
<span class="agent-item-name">${
|
|
2198
|
-
<span class="agent-item-desc" title="${$(s)}">${
|
|
2198
|
+
<span class="agent-item-name">${kO(o)}</span>
|
|
2199
|
+
<span class="agent-item-desc" title="${$(s)}">${kO(s)}</span>
|
|
2199
2200
|
</div>
|
|
2200
2201
|
<div class="agent-item-actions">
|
|
2201
2202
|
${e.isBuiltin?``:`<button class="agent-item-edit" data-action="edit" data-agent-id="${$(e.id)}" title="${$(r(`common.edit`))}">✎</button>`}
|
|
@@ -2210,25 +2211,25 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2210
2211
|
<div class="agent-item" id="agentAddBtn" style="color:var(--brand-500);">
|
|
2211
2212
|
<span class="agent-item-icon" style="color:var(--brand-500);">+</span>
|
|
2212
2213
|
<span class="agent-item-name">${r(`agentEditor.createNew`)}</span>
|
|
2213
|
-
</div>`),PD(n,i)}function PD(e,t){let n=document.getElementById(`agentSelectorBtn`),i=document.getElementById(`agentSelectorText`),a=document.getElementById(`agentSelectorEmoji`);if(!n||!i)return;let o=e.find(e=>e.id===t)||e.find(e=>e.id==="default");if(o){let e=o.id==="default"?r(`agentMgr.defaultAgentName`):o.name;i.textContent=`${o.icon} ${e}`,a&&(a.textContent=o.icon),n.title=`${r(`header.switchAgent`)}: ${o.icon} ${e}`}else i.textContent=r(`header.defaultAssistant`),a&&(a.textContent=`🤖`),n.title=r(`header.switchAgent`)}function FD(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`),n=document.getElementById(`agentSelectorWrapper`);if(!e||!t||!n)return;let r=n.getBoundingClientRect(),i=document.body.clientWidth;t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,i-16)+`px`;let a=t.getBoundingClientRect().width,o=Math.min(a,i-16),s=e.getBoundingClientRect(),c=s.left+s.width/2,l=i-o-8,u=Math.max(8,Math.min(l,c-o/2));t.style.left=u-r.left+`px`}function ID(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`);!e||!t||(e.addEventListener(`click`,async e=>{if(e.stopPropagation(),t.style.display===`flex`)t.style.display=`none`;else{t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,document.body.clientWidth-16)+`px`,t.style.display=`flex`,FD();try{await ND()}catch{}FD()}}),document.addEventListener(`click`,()=>{t.style.display=`none`}),t.addEventListener(`click`,async e=>{let n=e.target.closest(`.agent-item`);if(!n)return;let r=e.target.closest(`[data-action]`);if(r&&r.dataset.action===`edit`){e.stopPropagation();let t=r.dataset.agentId;QD(t);return}if(r&&r.dataset.action===`delete`){e.stopPropagation(),await vO(r.dataset.agentId);return}if(n.id===`agentAIBuildBtn`){t.style.display=`none`,ZD();return}if(n.id===`agentAddBtn`){QD(null);return}let i=n.dataset.agentId;i&&(await LD(i),t.style.display=`none`)}))}async function LD(e){let t=e?await pt(e):null;if(C.activeAgentId=e,C.activeAgentToolIds=t?t.toolIds:null,C.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null,await yt(e),yi().catch(()=>{}),t&&!t.isBuiltin)t.model&&(C.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(C.temperature=t.temperature,C.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`));else if(!t||t.isBuiltin)try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(C.currentModel=e.modelName),e.temperature!==void 0&&(C.temperature=e.temperature),e.topP!==void 0&&(C.topP=e.topP),document.dispatchEvent(new CustomEvent(`agent-model-changed`))}catch{}await ND();let n=`agentMcpClosedServers_${e||`default`}`,a=await chrome.storage.local.get([n,`ragTools`,`ragToolsIntroduced`]),o=a.ragTools||[];C.mcpClosedServers=a[n]||[];let s=`agentEnabledTools_${e||`default`}`,c=await chrome.storage.local.get([s,`enabledTools`]),l=!!c[s],u=c[s]||c.enabledTools;if(l||u&&u.length>0){let e=va(o),t=u.filter(t=>e.has(t));if(l)C.enabledTools=t;else{let e=f.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);C.enabledTools=[...t,...e]}let n=_a(C.enabledTools,o,a.ragToolsIntroduced);C.enabledTools=n.tools,C.enabledTools.length!==u.length&&chrome.storage.local.set({[s]:C.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{C.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let e=_a(C.enabledTools,o,a.ragToolsIntroduced);C.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[s]:C.enabledTools})}let d=document.getElementById(`toolsPopupOverlay`);d&&d.classList.contains(`show`)&&(ra(),da(),fa()),ha();let p=t&&t.id!=="default"?t.name:r(`agentMgr.defaultAgentName`);F(r(`agentMgr.switchedTo`,{name:p}),`info`,2e3),i.debug(`[AgentMgr] switched Agent:`,e,p)}function RD(){let e=document.getElementById(`agentEditModal`);if(!e)return;e.querySelector(`#agentModalCloseBtn`)?.addEventListener(`click`,$D),e.querySelector(`#agentAiBuildBtn`)?.addEventListener(`click`,async()=>{let t=e.querySelector(`#agentEditId`)?.value||``;if(!t){$D(),ZD();return}if(!await SO(r(`agentBuilder.editConfirmMessage`),r(`agentBuilder.editConfirmTitle`)))return;let n=await pt(t);!n||n.isBuiltin||($D(),ZD(n))}),e.querySelector(`#agentSaveBtn`)?.addEventListener(`click`,gO),e.querySelector(`#agentDeleteBtn`)?.addEventListener(`click`,_O),e.querySelector(`#agentTemplateSelect`)?.addEventListener(`change`,tO),UD();let t=document.getElementById(`agentToolActions`);t&&t.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAll`?WD():n===`deselectAll`?GD():n===`toggleSelectedOnly`&&(nO.selectedOnly=!nO.selectedOnly,iO())});let n=document.getElementById(`agentToolSearchInput`);if(n){let e=null,t=document.getElementById(`agentToolSearchClear`),r=()=>{t&&(t.style.display=n.value?`block`:`none`)};n.addEventListener(`input`,()=>{r(),clearTimeout(e),e=setTimeout(()=>{nO.searchText=n.value,iO()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),n.value=``,r(),nO.searchText=``,iO(),n.focus()}),r()}let i=document.getElementById(`agentSkillActions`);i&&i.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAllSkills`?KD():n===`deselectAllSkills`?qD():n===`toggleSelectedOnlySkills`&&(cO.selectedOnly=!cO.selectedOnly,uO())});let a=document.getElementById(`agentSkillSearchInput`);if(a){let e=null,t=document.getElementById(`agentSkillSearchClear`),n=()=>{t&&(t.style.display=a.value?`block`:`none`)};a.addEventListener(`input`,()=>{n(),clearTimeout(e),e=setTimeout(()=>{cO.searchText=a.value,uO()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),a.value=``,n(),cO.searchText=``,uO(),a.focus()}),n()}let o=document.getElementById(`agentToolList`);o&&(o.addEventListener(`click`,e=>{let t=e.target.closest(`.agent-mcp-expand-btn`);if(t){e.preventDefault(),aO(t.dataset.serverId,t);return}let n=e.target.closest(`.agent-mcp-service-item`);if(n&&!e.target.closest(`input[type="checkbox"]`)){e.preventDefault(),aO(n.dataset.mcpServerId,n.querySelector(`.agent-mcp-expand-btn`));return}let r=e.target.closest(`.agent-tool-category-clickable`);r&&JD(r.dataset.category)}),o.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=nO,n=e.target.dataset.toolId,r=e.target.dataset.mcpServerId;t.inheritMode=!1,n?e.target.checked?t.selectedSet.add(n):t.selectedSet.delete(n):r&&(e.target.checked?t.excludedSet.delete(r):t.excludedSet.add(r)),t.selectedOnly?iO():YD()}));let s=document.getElementById(`agentSkillList`);s&&s.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=cO;t.inheritMode=!1,e.target.checked?t.selectedSet.add(e.target.value):t.selectedSet.delete(e.target.value),t.selectedOnly&&!e.target.checked?uO():XD()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`emojiPicker`),n=document.getElementById(`agentEditIconBtn`);t&&n&&t.style.display===`block`&&!n.contains(e.target)&&!t.contains(e.target)&&(t.style.display=`none`)})}var zD=[[`smileys`,`emojiCatSmileys`],[`people`,`emojiCatPeople`],[`animals`,`emojiCatAnimals`],[`food`,`emojiCatFood`],[`travel`,`emojiCatTravel`],[`activity`,`emojiCatActivity`],[`objects`,`emojiCatObjects`],[`symbols`,`emojiCatSymbols`],[`flags`,`emojiCatFlags`]];function BD(e,t){return!!(e[1].includes(t)||e[3]&&e[3].includes(t))}function VD(e){let t=``;for(let[e,n]of zD){let i=AD.filter(t=>t[2]===e);if(i.length){t+=`<div class="emoji-category-label">${r(`agentMgr.`+n)}</div>`,t+=`<div class="emoji-picker-grid">`;for(let e of i)t+=`<button type="button" class="emoji-picker-item" data-emoji="${$(e[0])}" title="${$(e[1])}">${e[0]}</button>`;t+=`</div>`}}e.innerHTML=t}function HD(e,t){let n=AD.filter(e=>BD(e,t));if(!n.length){e.innerHTML=`<div class="emoji-picker-empty">${r(`agentMgr.emojiNoMatch`)}</div>`;return}let i=`<div class="emoji-picker-grid">`;for(let e of n)i+=`<button type="button" class="emoji-picker-item" data-emoji="${$(e[0])}" title="${$(e[1])}">${e[0]}</button>`;i+=`</div>`,e.innerHTML=i}function UD(){let e=document.getElementById(`emojiPicker`),t=document.getElementById(`agentEditIconBtn`),n=document.getElementById(`agentEditIcon`),r=document.getElementById(`emojiSearchInput`),i=document.getElementById(`emojiSearchClear`),a=document.getElementById(`emojiPickerBody`);if(!e||!t)return;let o=()=>{let e=r?r.value.trim().toLowerCase():``;e?HD(a,e):VD(a),i&&(i.style.display=e?`flex`:`none`)};t.addEventListener(`click`,n=>{if(n.stopPropagation(),e.style.display===`block`){e.style.display=`none`;return}r&&(r.value=``),o();let i=t.getBoundingClientRect();document.body.clientWidth-i.left>=330?(e.style.left=`0`,e.style.right=`auto`):(e.style.left=`auto`,e.style.right=`0`),e.style.display=`block`}),r&&r.addEventListener(`input`,o),i&&i.addEventListener(`click`,e=>{e.stopPropagation(),r&&(r.value=``),o(),r&&r.focus()}),e.addEventListener(`click`,r=>{let i=r.target.closest(`.emoji-picker-item`);if(!i)return;let a=i.dataset.emoji;t.textContent=a,n&&(n.value=a),e.style.display=`none`})}function WD(){let e=nO;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.add(t.id)),e.mcpServices.forEach(t=>e.excludedSet.delete(t.serverId)),iO()}function GD(){let e=nO;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.delete(t.id)),e.mcpServices.forEach(t=>e.excludedSet.add(t.serverId)),iO()}function KD(){let e=cO;e.inheritMode=!1,e.skills.forEach(t=>e.selectedSet.add(t.name)),uO()}function qD(){let e=cO;e.inheritMode=!1,e.selectedSet.clear(),uO()}function JD(e){let t=nO;if(e===`mcp`){if(t.mcpServices.length===0)return;t.inheritMode=!1;let e=t.mcpServices.every(e=>!t.excludedSet.has(e.serverId));t.mcpServices.forEach(n=>{e?t.excludedSet.add(n.serverId):t.excludedSet.delete(n.serverId)}),document.querySelectorAll(`#agentToolList .agent-mcp-service-item input[type="checkbox"]`).forEach(t=>{t.checked=!e})}else{let n=t.allTools.filter(t=>(t.category||`other`)===e);if(n.length===0)return;t.inheritMode=!1;let r=n.every(e=>t.selectedSet.has(e.id));n.forEach(e=>{r?t.selectedSet.delete(e.id):t.selectedSet.add(e.id)}),document.querySelectorAll(`#agentToolList .agent-tool-item[data-category="${e}"] input[type="checkbox"]`).forEach(e=>{e.checked=!r})}t.selectedOnly?iO():YD()}function YD(){let e=nO,t=document.getElementById(`agentToolList`);if(!t)return;let n=e.mcpServices.filter(t=>!e.excludedSet.has(t.serverId)).length;t.querySelectorAll(`.agent-tool-category-clickable`).forEach(t=>{let r=t.dataset.category,i=t.querySelector(`.agent-tool-cat-count`);if(i)if(r===`mcp`)i.textContent=`${n}/${e.mcpServices.length}`;else{let t=e.allTools.filter(e=>(e.category||`other`)===r);i.textContent=`${t.filter(t=>e.selectedSet.has(t.id)).length}/${t.length}`}});let i=document.getElementById(`agentToolCount`);if(i){let t=e.allTools.filter(t=>e.selectedSet.has(t.id)).length,a=e.allTools.length+e.mcpServices.length;i.textContent=r(`agentConfig.selectedTotalCount`,{selected:e.inheritMode?a:t+n,total:a})}}function XD(){let e=document.getElementById(`agentSkillCount`);if(!e)return;let t=cO,n=t.skills.length;e.textContent=r(`agentConfig.selectedTotalCount`,{selected:t.inheritMode?n:t.selectedSet.size,total:n})}function ZD(e=null){DD({agent:e,onAgentSaved:async e=>{await MD(),await LD(e.id),ha()},onEditAgent:e=>QD(e)})}async function QD(e){let t=document.getElementById(`agentEditModal`);if(!t)return;await fO(),pO(-1),t.querySelector(`#agentEditId`).value=``,t.querySelector(`#agentEditName`).value=``,t.querySelector(`#agentEditIcon`).value=`🤖`;let n=t.querySelector(`#agentEditIconBtn`);n&&(n.textContent=`🤖`),t.querySelector(`#agentEditDesc`).value=``,t.querySelector(`#agentEditPrompt`).value=``,t.querySelector(`#agentEditAllowSub`).checked=!1,t.querySelector(`#agentTemplateSelect`).value=``,t.querySelector(`#agentEditModel`).value=``;let i=t.querySelector(`#agentDeleteBtn`),a=t.querySelector(`#agentEditTitle`),o=t.querySelector(`#agentAiBuildBtn`),s=e=>{if(!o)return;let t=e===`edit`?`agentBuilder.editBanner`:`agentBuilder.editorBanner`;o.dataset.i18n=t,o.textContent=r(t),o.style.display=`block`};if(s(`create`),e){let n=await pt(e);if(!n||n.isBuiltin){o&&(o.style.display=`none`);return}s(`edit`),a.textContent=r(`agentMgr.editAgent`),t.querySelector(`#agentEditId`).value=n.id,t.querySelector(`#agentEditName`).value=n.name,t.querySelector(`#agentEditIcon`).value=n.icon||`🤖`;let c=t.querySelector(`#agentEditIconBtn`);c&&(c.textContent=n.icon||`🤖`),t.querySelector(`#agentEditDesc`).value=n.description||``,t.querySelector(`#agentEditPrompt`).value=n.systemPrompt||``,t.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,t.querySelector(`#agentEditModel`).value=n.model||``,pO(hO(n.temperature,n.topP)),i.style.display=`block`,rO(n.toolIds,n.mcpExcludedServerIds??[]),lO(n.skillIds)}else a.textContent=r(`agentEditor.createNew`),i.style.display=`none`,rO(null,[]),lO(null);eO(),t.style.display=`flex`;let c=t.querySelector(`#agentEditModel`);if(c){let e=c.value,t=c.cloneNode(!0);c.parentNode.replaceChild(t,c),t.value=e,t.addEventListener(`mousedown`,()=>{let e=t.value;e&&(t.dataset._saved=e,t.value=``)}),t.addEventListener(`blur`,()=>{setTimeout(()=>{t.value||=t.dataset._saved||``},150)})}}function $D(){let e=document.getElementById(`agentEditModal`);e&&(e.style.display=`none`)}function eO(){let e=document.getElementById(`agentTemplateSelect`);if(!e)return;let t=[r(`agentTemplates.codeReviewName`),r(`agentTemplates.webAutomationName`),r(`agentTemplates.dataAnalystName`),r(`agentTemplates.documentationName`)],n=`<option value="">${r(`agentEditor.selectTemplate`)}</option>`;for(let e=0;e<_.length;e++){let r=_[e];n+=`<option value="${e}">${r.icon} ${t[e]}</option>`}e.innerHTML=n}function tO(e){let t=parseInt(e.target.value);if(isNaN(t)||t<0||t>=_.length)return;let n=_[t],i=document.getElementById(`agentEditModal`);if(!i)return;let o=[`agentTemplates.codeReviewName`,`agentTemplates.webAutomationName`,`agentTemplates.dataAnalystName`,`agentTemplates.documentationName`],s=[`agentTemplates.codeReviewDesc`,`agentTemplates.webAutomationDesc`,`agentTemplates.dataAnalystDesc`,`agentTemplates.documentationDesc`];i.querySelector(`#agentEditName`).value=r(o[t]),i.querySelector(`#agentEditIcon`).value=n.icon;let c=i.querySelector(`#agentEditIconBtn`);c&&(c.textContent=n.icon),i.querySelector(`#agentEditDesc`).value=r(s[t]),i.querySelector(`#agentEditPrompt`).value=a()===`en`?n.systemPrompt:n.systemPromptZh||n.systemPrompt,i.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,i.querySelector(`#agentEditModel`).value=n.model||``,pO(hO(n.temperature,n.topP)),rO(n.toolIds,[]),lO(n.skillIds||null),F(r(`agentMgr.templateLoaded`,{name:n.name}),`info`,2e3)}var nO={allTools:[],mcpServices:[],selectedSet:new Set,excludedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function rO(e,t){if(!document.getElementById(`agentToolList`))return;let n=await jE(),r=n.tools,i=n.mcpServices,a=new Set(Array.isArray(t)?t:[]),o=nO;o.allTools=r,o.mcpServices=i,o.selectedSet=new Set(e||[]),o.excludedSet=a,o.searchText=``,o.selectedOnly=!1,o.inheritMode=!e;let s=document.getElementById(`agentToolSearchInput`);s&&(s.value=``);let c=document.getElementById(`agentToolSearchClear`);c&&(c.style.display=`none`),iO()}function iO(){let e=document.getElementById(`agentToolList`);if(!e)return;let t=nO,n=Sa({tools:t.allTools,services:t.mcpServices,selectedSet:t.selectedSet,excludedSet:t.excludedSet,query:t.searchText,selectedOnly:t.selectedOnly,getDesc:Ri}),i=t.mcpServices.filter(e=>!t.excludedSet.has(e.serverId)).length,a={};for(let e of n.tools){let t=e.category||`other`;a[t]||(a[t]=[]),a[t].push(e)}let o=``;for(let[e,n]of Object.entries(a)){let i=r(`toolCategory.${e}`)===`toolCategory.${e}`?e:r(`toolCategory.${e}`),a=t.allTools.filter(t=>(t.category||`other`)===e),s=a.filter(e=>t.selectedSet.has(e.id)).length;o+=`<div class="agent-tool-category agent-tool-category-clickable" data-category="${$(e)}" title="${$(r(`agentConfig.toggleCategoryAll`))}">${i} <span class="agent-tool-cat-count" style="font-weight:400;color:var(--text-tertiary);">${s}/${a.length}</span></div>`;for(let r of n){let n=t.selectedSet.has(r.id)?`checked`:``,i=Ri(r),a=i.length>40?i.substring(0,40)+`...`:i;o+=`
|
|
2214
|
+
</div>`),HD(n,i)}function HD(e,t){let n=document.getElementById(`agentSelectorBtn`),i=document.getElementById(`agentSelectorText`),a=document.getElementById(`agentSelectorEmoji`);if(!n||!i)return;let o=e.find(e=>e.id===t)||e.find(e=>e.id==="default");if(o){let e=o.id==="default"?r(`agentMgr.defaultAgentName`):o.name;i.textContent=`${o.icon} ${e}`,a&&(a.textContent=o.icon),n.title=`${r(`header.switchAgent`)}: ${o.icon} ${e}`}else i.textContent=r(`header.defaultAssistant`),a&&(a.textContent=`🤖`),n.title=r(`header.switchAgent`)}function UD(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`),n=document.getElementById(`agentSelectorWrapper`);if(!e||!t||!n)return;let r=n.getBoundingClientRect(),i=document.body.clientWidth;t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,i-16)+`px`;let a=t.getBoundingClientRect().width,o=Math.min(a,i-16),s=e.getBoundingClientRect(),c=s.left+s.width/2,l=i-o-8,u=Math.max(8,Math.min(l,c-o/2));t.style.left=u-r.left+`px`}function WD(){let e=document.getElementById(`agentSelectorBtn`),t=document.getElementById(`agentSelectorDropdown`);!e||!t||(e.addEventListener(`click`,async e=>{if(e.stopPropagation(),t.style.display===`flex`)t.style.display=`none`;else{t.style.left=``,t.style.right=`auto`,t.style.maxWidth=Math.min(320,document.body.clientWidth-16)+`px`,t.style.display=`flex`,UD();try{await VD()}catch{}UD()}}),document.addEventListener(`click`,()=>{t.style.display=`none`}),t.addEventListener(`click`,async e=>{let n=e.target.closest(`.agent-item`);if(!n)return;let r=e.target.closest(`[data-action]`);if(r&&r.dataset.action===`edit`){e.stopPropagation();let t=r.dataset.agentId;oO(t);return}if(r&&r.dataset.action===`delete`){e.stopPropagation(),await EO(r.dataset.agentId);return}if(n.id===`agentAIBuildBtn`){t.style.display=`none`,aO();return}if(n.id===`agentAddBtn`){oO(null);return}let i=n.dataset.agentId;i&&(await GD(i),t.style.display=`none`)}))}async function GD(e){let t=e?await pt(e):null;if(C.activeAgentId=e,C.activeAgentToolIds=t?t.toolIds:null,C.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null,await yt(e),yi().catch(()=>{}),t&&!t.isBuiltin)t.model&&(C.currentModel=t.model),t.temperature!==null&&t.temperature!==void 0&&(C.temperature=t.temperature,C.topP=t.topP!==null&&t.topP!==void 0?t.topP:1),document.dispatchEvent(new CustomEvent(`agent-model-changed`));else if(!t||t.isBuiltin)try{let e=await chrome.storage.local.get([`modelName`,`temperature`,`topP`]);e.modelName&&(C.currentModel=e.modelName),e.temperature!==void 0&&(C.temperature=e.temperature),e.topP!==void 0&&(C.topP=e.topP),document.dispatchEvent(new CustomEvent(`agent-model-changed`))}catch{}await VD();let n=`agentMcpClosedServers_${e||`default`}`,a=await chrome.storage.local.get([n,`ragTools`,`ragToolsIntroduced`]),o=a.ragTools||[];C.mcpClosedServers=a[n]||[];let s=`agentEnabledTools_${e||`default`}`,c=await chrome.storage.local.get([s,`enabledTools`]),l=!!c[s],u=c[s]||c.enabledTools;if(l||u&&u.length>0){let e=va(o),t=u.filter(t=>e.has(t));if(l)C.enabledTools=t;else{let e=f.filter(e=>e.enabled&&!t.includes(e.id)).map(e=>e.id);C.enabledTools=[...t,...e]}let n=_a(C.enabledTools,o,a.ragToolsIntroduced);C.enabledTools=n.tools,C.enabledTools.length!==u.length&&chrome.storage.local.set({[s]:C.enabledTools,...n.migrated?{ragToolsIntroduced:!0}:{}})}else{C.enabledTools=f.filter(e=>e.enabled).map(e=>e.id);let e=_a(C.enabledTools,o,a.ragToolsIntroduced);C.enabledTools=e.tools,e.migrated&&chrome.storage.local.set({ragToolsIntroduced:!0,[s]:C.enabledTools})}let d=document.getElementById(`toolsPopupOverlay`);d&&d.classList.contains(`show`)&&(ra(),da(),fa()),ha();let p=t&&t.id!=="default"?t.name:r(`agentMgr.defaultAgentName`);F(r(`agentMgr.switchedTo`,{name:p}),`info`,2e3),i.debug(`[AgentMgr] switched Agent:`,e,p)}function KD(){let e=document.getElementById(`agentEditModal`);if(!e)return;e.querySelector(`#agentModalCloseBtn`)?.addEventListener(`click`,sO),e.querySelector(`#agentAiBuildBtn`)?.addEventListener(`click`,async()=>{let t=e.querySelector(`#agentEditId`)?.value||``;if(!t){sO(),aO();return}if(!await AO(r(`agentBuilder.editConfirmMessage`),r(`agentBuilder.editConfirmTitle`)))return;let n=await pt(t);!n||n.isBuiltin||(sO(),aO(n))}),e.querySelector(`#agentSaveBtn`)?.addEventListener(`click`,wO),e.querySelector(`#agentDeleteBtn`)?.addEventListener(`click`,TO),e.querySelector(`#agentTemplateSelect`)?.addEventListener(`change`,lO),ZD();let t=document.getElementById(`agentToolActions`);t&&t.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAll`?QD():n===`deselectAll`?$D():n===`toggleSelectedOnly`&&(uO.selectedOnly=!uO.selectedOnly,fO())});let n=document.getElementById(`agentToolSearchInput`);if(n){let e=null,t=document.getElementById(`agentToolSearchClear`),r=()=>{t&&(t.style.display=n.value?`block`:`none`)};n.addEventListener(`input`,()=>{r(),clearTimeout(e),e=setTimeout(()=>{uO.searchText=n.value,fO()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),n.value=``,r(),uO.searchText=``,fO(),n.focus()}),r()}let i=document.getElementById(`agentSkillActions`);i&&i.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAllSkills`?eO():n===`deselectAllSkills`?tO():n===`toggleSelectedOnlySkills`&&(gO.selectedOnly=!gO.selectedOnly,vO())});let a=document.getElementById(`agentSkillSearchInput`);if(a){let e=null,t=document.getElementById(`agentSkillSearchClear`),n=()=>{t&&(t.style.display=a.value?`block`:`none`)};a.addEventListener(`input`,()=>{n(),clearTimeout(e),e=setTimeout(()=>{gO.searchText=a.value,vO()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),a.value=``,n(),gO.searchText=``,vO(),a.focus()}),n()}let o=document.getElementById(`agentToolList`);o&&(o.addEventListener(`click`,e=>{let t=e.target.closest(`.agent-mcp-expand-btn`);if(t){e.preventDefault(),pO(t.dataset.serverId,t);return}let n=e.target.closest(`.agent-mcp-service-item`);if(n&&!e.target.closest(`input[type="checkbox"]`)){e.preventDefault(),pO(n.dataset.mcpServerId,n.querySelector(`.agent-mcp-expand-btn`));return}let r=e.target.closest(`.agent-tool-category-clickable`);r&&nO(r.dataset.category)}),o.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=uO,n=e.target.dataset.toolId,r=e.target.dataset.mcpServerId;t.inheritMode=!1,n?e.target.checked?t.selectedSet.add(n):t.selectedSet.delete(n):r&&(e.target.checked?t.excludedSet.delete(r):t.excludedSet.add(r)),t.selectedOnly?fO():rO()}));let s=document.getElementById(`agentSkillList`);s&&s.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=gO;t.inheritMode=!1,e.target.checked?t.selectedSet.add(e.target.value):t.selectedSet.delete(e.target.value),t.selectedOnly&&!e.target.checked?vO():iO()}),document.addEventListener(`click`,e=>{let t=document.getElementById(`emojiPicker`),n=document.getElementById(`agentEditIconBtn`);t&&n&&t.style.display===`block`&&!n.contains(e.target)&&!t.contains(e.target)&&(t.style.display=`none`)})}var qD=[[`smileys`,`emojiCatSmileys`],[`people`,`emojiCatPeople`],[`animals`,`emojiCatAnimals`],[`food`,`emojiCatFood`],[`travel`,`emojiCatTravel`],[`activity`,`emojiCatActivity`],[`objects`,`emojiCatObjects`],[`symbols`,`emojiCatSymbols`],[`flags`,`emojiCatFlags`]];function JD(e,t){return!!(e[1].includes(t)||e[3]&&e[3].includes(t))}function YD(e){let t=``;for(let[e,n]of qD){let i=RD.filter(t=>t[2]===e);if(i.length){t+=`<div class="emoji-category-label">${r(`agentMgr.`+n)}</div>`,t+=`<div class="emoji-picker-grid">`;for(let e of i)t+=`<button type="button" class="emoji-picker-item" data-emoji="${$(e[0])}" title="${$(e[1])}">${e[0]}</button>`;t+=`</div>`}}e.innerHTML=t}function XD(e,t){let n=RD.filter(e=>JD(e,t));if(!n.length){e.innerHTML=`<div class="emoji-picker-empty">${r(`agentMgr.emojiNoMatch`)}</div>`;return}let i=`<div class="emoji-picker-grid">`;for(let e of n)i+=`<button type="button" class="emoji-picker-item" data-emoji="${$(e[0])}" title="${$(e[1])}">${e[0]}</button>`;i+=`</div>`,e.innerHTML=i}function ZD(){let e=document.getElementById(`emojiPicker`),t=document.getElementById(`agentEditIconBtn`),n=document.getElementById(`agentEditIcon`),r=document.getElementById(`emojiSearchInput`),i=document.getElementById(`emojiSearchClear`),a=document.getElementById(`emojiPickerBody`);if(!e||!t)return;let o=()=>{let e=r?r.value.trim().toLowerCase():``;e?XD(a,e):YD(a),i&&(i.style.display=e?`flex`:`none`)};t.addEventListener(`click`,n=>{if(n.stopPropagation(),e.style.display===`block`){e.style.display=`none`;return}r&&(r.value=``),o();let i=t.getBoundingClientRect();document.body.clientWidth-i.left>=330?(e.style.left=`0`,e.style.right=`auto`):(e.style.left=`auto`,e.style.right=`0`),e.style.display=`block`}),r&&r.addEventListener(`input`,o),i&&i.addEventListener(`click`,e=>{e.stopPropagation(),r&&(r.value=``),o(),r&&r.focus()}),e.addEventListener(`click`,r=>{let i=r.target.closest(`.emoji-picker-item`);if(!i)return;let a=i.dataset.emoji;t.textContent=a,n&&(n.value=a),e.style.display=`none`})}function QD(){let e=uO;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.add(t.id)),e.mcpServices.forEach(t=>e.excludedSet.delete(t.serverId)),fO()}function $D(){let e=uO;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.delete(t.id)),e.mcpServices.forEach(t=>e.excludedSet.add(t.serverId)),fO()}function eO(){let e=gO;e.inheritMode=!1,e.skills.forEach(t=>e.selectedSet.add(t.name)),vO()}function tO(){let e=gO;e.inheritMode=!1,e.selectedSet.clear(),vO()}function nO(e){let t=uO;if(e===`mcp`){if(t.mcpServices.length===0)return;t.inheritMode=!1;let e=t.mcpServices.every(e=>!t.excludedSet.has(e.serverId));t.mcpServices.forEach(n=>{e?t.excludedSet.add(n.serverId):t.excludedSet.delete(n.serverId)}),document.querySelectorAll(`#agentToolList .agent-mcp-service-item input[type="checkbox"]`).forEach(t=>{t.checked=!e})}else{let n=t.allTools.filter(t=>(t.category||`other`)===e);if(n.length===0)return;t.inheritMode=!1;let r=n.every(e=>t.selectedSet.has(e.id));n.forEach(e=>{r?t.selectedSet.delete(e.id):t.selectedSet.add(e.id)}),document.querySelectorAll(`#agentToolList .agent-tool-item[data-category="${e}"] input[type="checkbox"]`).forEach(e=>{e.checked=!r})}t.selectedOnly?fO():rO()}function rO(){let e=uO,t=document.getElementById(`agentToolList`);if(!t)return;let n=e.mcpServices.filter(t=>!e.excludedSet.has(t.serverId)).length;t.querySelectorAll(`.agent-tool-category-clickable`).forEach(t=>{let r=t.dataset.category,i=t.querySelector(`.agent-tool-cat-count`);if(i)if(r===`mcp`)i.textContent=`${n}/${e.mcpServices.length}`;else{let t=e.allTools.filter(e=>(e.category||`other`)===r);i.textContent=`${t.filter(t=>e.selectedSet.has(t.id)).length}/${t.length}`}});let i=document.getElementById(`agentToolCount`);if(i){let t=e.allTools.filter(t=>e.selectedSet.has(t.id)).length,a=e.allTools.length+e.mcpServices.length;i.textContent=r(`agentConfig.selectedTotalCount`,{selected:e.inheritMode?a:t+n,total:a})}}function iO(){let e=document.getElementById(`agentSkillCount`);if(!e)return;let t=gO,n=t.skills.length;e.textContent=r(`agentConfig.selectedTotalCount`,{selected:t.inheritMode?n:t.selectedSet.size,total:n})}function aO(e=null){FD({agent:e,onAgentSaved:async e=>{await BD(),await GD(e.id),ha()},onEditAgent:e=>oO(e)})}async function oO(e){let t=document.getElementById(`agentEditModal`);if(!t)return;await bO(),xO(-1),t.querySelector(`#agentEditId`).value=``,t.querySelector(`#agentEditName`).value=``,t.querySelector(`#agentEditIcon`).value=`🤖`;let n=t.querySelector(`#agentEditIconBtn`);n&&(n.textContent=`🤖`),t.querySelector(`#agentEditDesc`).value=``,t.querySelector(`#agentEditPrompt`).value=``,t.querySelector(`#agentEditAllowSub`).checked=!1,t.querySelector(`#agentTemplateSelect`).value=``,t.querySelector(`#agentEditModel`).value=``;let i=t.querySelector(`#agentDeleteBtn`),a=t.querySelector(`#agentEditTitle`),o=t.querySelector(`#agentAiBuildBtn`),s=e=>{if(!o)return;let t=e===`edit`?`agentBuilder.editBanner`:`agentBuilder.editorBanner`;o.dataset.i18n=t,o.textContent=r(t),o.style.display=`block`};if(s(`create`),e){let n=await pt(e);if(!n||n.isBuiltin){o&&(o.style.display=`none`);return}s(`edit`),a.textContent=r(`agentMgr.editAgent`),t.querySelector(`#agentEditId`).value=n.id,t.querySelector(`#agentEditName`).value=n.name,t.querySelector(`#agentEditIcon`).value=n.icon||`🤖`;let c=t.querySelector(`#agentEditIconBtn`);c&&(c.textContent=n.icon||`🤖`),t.querySelector(`#agentEditDesc`).value=n.description||``,t.querySelector(`#agentEditPrompt`).value=n.systemPrompt||``,t.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,t.querySelector(`#agentEditModel`).value=n.model||``,xO(CO(n.temperature,n.topP)),i.style.display=`block`,dO(n.toolIds,n.mcpExcludedServerIds??[]),_O(n.skillIds)}else a.textContent=r(`agentEditor.createNew`),i.style.display=`none`,dO(null,[]),_O(null);cO(),t.style.display=`flex`;let c=t.querySelector(`#agentEditModel`);if(c){let e=c.value,t=c.cloneNode(!0);c.parentNode.replaceChild(t,c),t.value=e,t.addEventListener(`mousedown`,()=>{let e=t.value;e&&(t.dataset._saved=e,t.value=``)}),t.addEventListener(`blur`,()=>{setTimeout(()=>{t.value||=t.dataset._saved||``},150)})}}function sO(){let e=document.getElementById(`agentEditModal`);e&&(e.style.display=`none`)}function cO(){let e=document.getElementById(`agentTemplateSelect`);if(!e)return;let t=[r(`agentTemplates.codeReviewName`),r(`agentTemplates.webAutomationName`),r(`agentTemplates.dataAnalystName`),r(`agentTemplates.documentationName`)],n=`<option value="">${r(`agentEditor.selectTemplate`)}</option>`;for(let e=0;e<_.length;e++){let r=_[e];n+=`<option value="${e}">${r.icon} ${t[e]}</option>`}e.innerHTML=n}function lO(e){let t=parseInt(e.target.value);if(isNaN(t)||t<0||t>=_.length)return;let n=_[t],i=document.getElementById(`agentEditModal`);if(!i)return;let o=[`agentTemplates.codeReviewName`,`agentTemplates.webAutomationName`,`agentTemplates.dataAnalystName`,`agentTemplates.documentationName`],s=[`agentTemplates.codeReviewDesc`,`agentTemplates.webAutomationDesc`,`agentTemplates.dataAnalystDesc`,`agentTemplates.documentationDesc`];i.querySelector(`#agentEditName`).value=r(o[t]),i.querySelector(`#agentEditIcon`).value=n.icon;let c=i.querySelector(`#agentEditIconBtn`);c&&(c.textContent=n.icon),i.querySelector(`#agentEditDesc`).value=r(s[t]),i.querySelector(`#agentEditPrompt`).value=a()===`en`?n.systemPrompt:n.systemPromptZh||n.systemPrompt,i.querySelector(`#agentEditAllowSub`).checked=n.allowSubDispatch||!1,i.querySelector(`#agentEditModel`).value=n.model||``,xO(CO(n.temperature,n.topP)),dO(n.toolIds,[]),_O(n.skillIds||null),F(r(`agentMgr.templateLoaded`,{name:n.name}),`info`,2e3)}var uO={allTools:[],mcpServices:[],selectedSet:new Set,excludedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function dO(e,t){if(!document.getElementById(`agentToolList`))return;let n=await zE(),r=n.tools,i=n.mcpServices,a=new Set(Array.isArray(t)?t:[]),o=uO;o.allTools=r,o.mcpServices=i,o.selectedSet=new Set(e||[]),o.excludedSet=a,o.searchText=``,o.selectedOnly=!1,o.inheritMode=!e;let s=document.getElementById(`agentToolSearchInput`);s&&(s.value=``);let c=document.getElementById(`agentToolSearchClear`);c&&(c.style.display=`none`),fO()}function fO(){let e=document.getElementById(`agentToolList`);if(!e)return;let t=uO,n=Sa({tools:t.allTools,services:t.mcpServices,selectedSet:t.selectedSet,excludedSet:t.excludedSet,query:t.searchText,selectedOnly:t.selectedOnly,getDesc:Ri}),i=t.mcpServices.filter(e=>!t.excludedSet.has(e.serverId)).length,a={};for(let e of n.tools){let t=e.category||`other`;a[t]||(a[t]=[]),a[t].push(e)}let o=``;for(let[e,n]of Object.entries(a)){let i=r(`toolCategory.${e}`)===`toolCategory.${e}`?e:r(`toolCategory.${e}`),a=t.allTools.filter(t=>(t.category||`other`)===e),s=a.filter(e=>t.selectedSet.has(e.id)).length;o+=`<div class="agent-tool-category agent-tool-category-clickable" data-category="${$(e)}" title="${$(r(`agentConfig.toggleCategoryAll`))}">${i} <span class="agent-tool-cat-count" style="font-weight:400;color:var(--text-tertiary);">${s}/${a.length}</span></div>`;for(let r of n){let n=t.selectedSet.has(r.id)?`checked`:``,i=Ri(r),a=i.length>40?i.substring(0,40)+`...`:i;o+=`
|
|
2214
2215
|
<label class="agent-tool-item" data-category="${$(e)}">
|
|
2215
2216
|
<input type="checkbox" value="${$(r.id)}" ${n} data-tool-id="${$(r.id)}">
|
|
2216
|
-
<span class="agent-tool-name" title="${$(r.name)}">${
|
|
2217
|
-
<span class="agent-tool-desc" title="${$(i)}">${
|
|
2218
|
-
</label>`}}if(n.services.length>0){let e=r(`toolCategory.mcp`)===`toolCategory.mcp`?`mcp`:r(`toolCategory.mcp`);o+=`<div class="agent-tool-category agent-tool-category-clickable" data-category="mcp" title="${$(r(`agentConfig.toggleCategoryAll`))}">${e} <span class="agent-tool-cat-count" style="font-weight:400;color:var(--text-tertiary);">${i}/${t.mcpServices.length}</span></div>`;for(let e of n.services){let n=t.excludedSet.has(e.serverId)?``:`checked`,i=r(`toolPanel.mcpServiceToolCount`,{count:e.tools.length}),a=e.tools.map(e=>e.name).join(`, `),s=e.tools.map(e=>{let t=e.name||``,n=zi(e);return`<div class="agent-mcp-tool-row" title="${$(n?`${t}:${n}`:t)}"><div class="agent-mcp-tool-name">${
|
|
2217
|
+
<span class="agent-tool-name" title="${$(r.name)}">${kO(r.name)}</span>
|
|
2218
|
+
<span class="agent-tool-desc" title="${$(i)}">${kO(a)}</span>
|
|
2219
|
+
</label>`}}if(n.services.length>0){let e=r(`toolCategory.mcp`)===`toolCategory.mcp`?`mcp`:r(`toolCategory.mcp`);o+=`<div class="agent-tool-category agent-tool-category-clickable" data-category="mcp" title="${$(r(`agentConfig.toggleCategoryAll`))}">${e} <span class="agent-tool-cat-count" style="font-weight:400;color:var(--text-tertiary);">${i}/${t.mcpServices.length}</span></div>`;for(let e of n.services){let n=t.excludedSet.has(e.serverId)?``:`checked`,i=r(`toolPanel.mcpServiceToolCount`,{count:e.tools.length}),a=e.tools.map(e=>e.name).join(`, `),s=e.tools.map(e=>{let t=e.name||``,n=zi(e);return`<div class="agent-mcp-tool-row" title="${$(n?`${t}:${n}`:t)}"><div class="agent-mcp-tool-name">${kO(t)}</div>`+(n?`<div class="agent-mcp-tool-desc">${kO(n)}</div>`:``)+`</div>`}).join(``);o+=`
|
|
2219
2220
|
<label class="agent-tool-item agent-mcp-service-item" data-category="mcp" data-mcp-server-id="${$(e.serverId)}">
|
|
2220
2221
|
<input type="checkbox" ${n} data-mcp-server-id="${$(e.serverId)}">
|
|
2221
|
-
<span class="agent-tool-name" title="${$(e.serverName)}">${
|
|
2222
|
-
<span class="agent-tool-desc" title="${$(a)}">${
|
|
2223
|
-
<span class="agent-mcp-service-id" title="ID: ${$(e.serverId)}">ID: ${
|
|
2222
|
+
<span class="agent-tool-name" title="${$(e.serverName)}">${kO(e.serverName)}</span>
|
|
2223
|
+
<span class="agent-tool-desc" title="${$(a)}">${kO(i)}</span>
|
|
2224
|
+
<span class="agent-mcp-service-id" title="ID: ${$(e.serverId)}">ID: ${kO(e.serverId)}</span>
|
|
2224
2225
|
<button type="button" class="agent-mcp-expand-btn" data-server-id="${$(e.serverId)}" title="${$(r(`toolPanel.mcpServiceExpand`))}">▶</button>
|
|
2225
2226
|
</label>
|
|
2226
|
-
<div class="agent-mcp-tool-list collapsed" data-server-id="${$(e.serverId)}">${s}</div>`}}o||=`<div class="agent-tool-empty">${
|
|
2227
|
+
<div class="agent-mcp-tool-list collapsed" data-server-id="${$(e.serverId)}">${s}</div>`}}o||=`<div class="agent-tool-empty">${kO(r(`toolPanel.noMatch`))}</div>`,e.innerHTML=o;let s=document.getElementById(`agentToolSelectedOnlyBtn`);if(s){s.classList.toggle(`active`,t.selectedOnly),s.textContent=r(t.selectedOnly?`agentEditor.showAllTools`:`agentEditor.selectedOnlyFilter`);let e=t.allTools.filter(e=>t.selectedSet.has(e.id)).length;s.title=r(`agentToolFilter.selectedCountHint`,{count:e+i})}rO()}function pO(e,t){let n=document.getElementById(`agentToolList`);if(!n||!e)return;let r=Array.from(n.querySelectorAll(`.agent-mcp-tool-list`)).find(t=>t.dataset.serverId===e);if(!r)return;let i=r.classList.toggle(`collapsed`),a=t||r.previousElementSibling?.querySelector(`.agent-mcp-expand-btn`);a&&(a.textContent=i?`▶`:`▼`)}function mO(){let e=uO,t=e.allTools.filter(t=>e.selectedSet.has(t.id)).map(e=>e.id),n=new Set(t),r=[...e.selectedSet].filter(e=>!n.has(e)),i=[...t,...r];return i.length>0?i:null}function hO(){let e=uO;if(e.mcpServices.length!==0)return e.mcpServices.filter(t=>e.excludedSet.has(t.serverId)).map(e=>e.serverId)}var gO={skills:[],selectedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function _O(e){if(!document.getElementById(`agentSkillList`))return;let t=[];try{t=await uE()}catch{}let n=gO;n.skills=t,n.selectedSet=new Set(e||[]),n.searchText=``,n.selectedOnly=!1,n.inheritMode=e==null;let r=document.getElementById(`agentSkillSearchInput`);r&&(r.value=``);let i=document.getElementById(`agentSkillSearchClear`);i&&(i.style.display=`none`),vO()}function vO(){let e=document.getElementById(`agentSkillList`);if(!e)return;let t=gO;if(t.skills.length===0)e.innerHTML=`<div style="color:var(--text-tertiary);font-size:12px;padding:8px;text-align:center;">${r(`agentMgr.noSkillsHint`)}</div>`;else{let n=Sa({tools:t.skills.map(e=>({id:e.name,name:e.name,description:e.description||``})),services:[],selectedSet:t.selectedSet,excludedSet:new Set,query:t.searchText,selectedOnly:t.selectedOnly}).tools;n.length===0?e.innerHTML=`<div class="agent-tool-empty">${kO(r(`toolPanel.noMatch`))}</div>`:e.innerHTML=n.map(e=>{let n=t.selectedSet.has(e.name)?`checked`:``,r=e.description||``;return`
|
|
2227
2228
|
<label class="agent-tool-item">
|
|
2228
2229
|
<input type="checkbox" value="${$(e.name)}" ${n}>
|
|
2229
|
-
<span class="agent-tool-name" title="${$(e.name)}">${
|
|
2230
|
-
<span class="agent-tool-desc" title="${$(r)}">${
|
|
2231
|
-
</label>`}).join(``)}let n=document.getElementById(`agentSkillSelectedOnlyBtn`);n&&(n.classList.toggle(`active`,t.selectedOnly),n.textContent=r(t.selectedOnly?`agentEditor.showAllSkills`:`agentEditor.selectedOnlyFilter`),n.title=r(`agentToolFilter.selectedCountHint`,{count:t.selectedSet.size})),XD()}function dO(){let e=cO,t=e.skills.filter(t=>e.selectedSet.has(t.name)).map(e=>e.name),n=new Set(t),r=[...e.selectedSet].filter(e=>!n.has(e)),i=[...t,...r];return i.length>0?i:null}async function fO(){let e=document.getElementById(`agentModelList`);if(e)return new Promise(t=>{chrome.storage.local.get([`customModels`],n=>{let r=[];(n.customModels||[]).forEach(e=>{let t;typeof e==`string`?t=e:e&&e.name&&(t=e.name),t&&!r.includes(t)&&r.push(t)}),e.innerHTML=r.map(e=>`<option value="${$(e)}">`).join(``),t()})})}function pO(e){let t=document.getElementById(`agentEditTempPreset`);if(t){for(;t.options.length>1;)t.remove(1);$t.forEach((e,n)=>{let i=document.createElement(`option`);i.value=n,i.textContent=`${r(e.labelKey)}(${e.temp.toFixed(2)})`,t.appendChild(i)}),e!==void 0&&e>=0?t.value=e:t.value=``}}function mO(){let e=document.getElementById(`agentEditTempPreset`);if(!e||e.value===``)return{temperature:null,topP:null};let t=parseInt(e.value);if(isNaN(t)||t<0||t>=$t.length)return{temperature:null,topP:null};let n=$t[t];return{temperature:n.temp,topP:n.topP}}function hO(e,t){if(e==null)return-1;for(let n=0;n<$t.length;n++){let r=$t[n];if(Math.abs(r.temp-e)<.001&&Math.abs(r.topP-(t||1))<.001)return n}return-1}async function gO(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`).value,n=e.querySelector(`#agentEditName`).value.trim(),a=e.querySelector(`#agentEditIcon`).value.trim()||`🤖`,o=e.querySelector(`#agentEditDesc`).value.trim(),s=e.querySelector(`#agentEditPrompt`).value.trim(),c=e.querySelector(`#agentEditAllowSub`).checked,l=oO(),u=sO(),d=dO(),f=e.querySelector(`#agentEditModel`).value.trim()||null,{temperature:p,topP:m}=mO();if(!n){F(r(`agentMgr.nameRequired`),`warning`);return}let h={name:n,icon:a,description:o,systemPrompt:s,allowSubDispatch:c,toolIds:l,skillIds:d,model:f,temperature:p,topP:m};u!==void 0&&(h.mcpExcludedServerIds=u);try{t?(await mt(t,h),t===C.activeAgentId&&u!==void 0&&(C.activeAgentMcpExcludedServerIds=u),F(r(`agentMgr.agentUpdated`),`success`)):F(r(`agentMgr.agentCreated`,{name:(await gt(h)).name}),`success`),await MD(),await ND(),$D(),ha()}catch(e){i.error(`[AgentMgr] save Agent failed:`,e),F(r(`agentMgr.saveFailed`,{message:e.message}),`error`)}}async function _O(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`)?.value;if(!t)return;let n=await pt(t);if(await SO(r(`agentMgr.confirmDeleteAgentMessage`,{name:n?n.name:``}),r(`agentMgr.deleteAgentTitle`)))try{await vt(t),F(r(`agentMgr.agentDeleted`),`success`),await MD(),await ND(),$D()}catch(e){i.error(`[AgentMgr] delete Agent failed:`,e),F(r(`agentMgr.deleteFailed`,{message:e.message}),`error`)}}async function vO(e){if(!e)return!1;let t=await pt(e);if(!t||t.isBuiltin)return F(r(`agentMgr.cannotDeleteDefault`),`warning`),!1;if(!await SO(r(`agentMgr.confirmDeleteAgentMessage`,{name:t.name}),r(`agentMgr.deleteAgentTitle`)))return!1;try{return await vt(e),F(r(`agentMgr.agentDeleted`),`success`),await MD(),await ND(),!0}catch(e){return i.error(`[AgentMgr] delete Agent failed:`,e),F(r(`agentMgr.deleteFailed`,{message:e.message}),`error`),!1}}async function yO(e=C.activeAgentId){return e?await pt(e):null}function bO(e){return e?e.toolIds:null}function xO(e){if(!e)return``;let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function $(e){return e?e.replace(/["&<>]/g,e=>({'"':`"`,"&":`&`,"<":`<`,">":`>`})[e]):``}async function SO(e,t){return typeof window.showCustomConfirm==`function`?window.showCustomConfirm(e,t):new Promise(n=>{let i=document.getElementById(`agentConfirmModal`);if(!i){n(confirm(e));return}i.querySelector(`#agentConfirmMessage`).textContent=e,i.querySelector(`#agentConfirmTitle`).textContent=t||r(`agentMgr.confirm`),i.style.display=`flex`;let a=()=>{i.style.display=`none`,i.querySelector(`#agentConfirmOk`).removeEventListener(`click`,o),i.querySelector(`#agentConfirmCancel`).removeEventListener(`click`,s),i.removeEventListener(`click`,c)},o=()=>{a(),n(!0)},s=()=>{a(),n(!1)},c=e=>{e.target===i&&(a(),n(!1))};i.querySelector(`#agentConfirmOk`).addEventListener(`click`,o),i.querySelector(`#agentConfirmCancel`).addEventListener(`click`,s),i.addEventListener(`click`,c)})}n(`zh`,{contextUsage:{indicatorTitle:`上下文占用 {percent}%({used} / {total} tokens)· 点击查看详情`,memoryOffToast:`记忆已关闭,无可压缩内容`,generatingToast:`正在生成回复,请稍后再试`,nothingToCompactToast:`没有新的消息可压缩`,confirmTitle:`压缩上下文`,confirmMessage:`将压缩 {count} 条历史消息(约 {tokens} tokens)为一份摘要{summaryHint}。原始消息仍保留在会话中,发送新消息前可撤销。`,confirmWithOldSummary:`(含已有摘要,将合并为新摘要)`,confirmOk:`开始压缩`,compactingTitle:`正在压缩上下文`,compactingHint:`正在调用模型生成摘要,请稍候…(通常需要几秒到十几秒)`,compactDone:`压缩完成,节约约 {saved} tokens`,compactErrConfig:`无法压缩:API 配置缺失`,compactErrFailed:`压缩失败,请稍后重试`,compactErrEmpty:`模型未返回摘要内容`,compactErrHttp:`接口错误 HTTP {status}`,compactErrTimeout:`请求超时`,autoCompactedToast:`上下文接近上限,已自动压缩(预计省 {saved} tokens)`,undoTitle:`撤销压缩`,undoMessage:`撤销后,发送将恢复携带完整历史。确定撤销吗?`,undoOk:`撤销`,undoDone:`已撤销压缩`,dividerText:`⬆ 上方 {count} 条消息已压缩为摘要`,dividerView:`查看`,dividerUndo:`撤销`,popupTitle:`上下文占用明细`,rowSystem:`系统提示词`,rowTools:`工具定义`,rowHistory:`历史消息`,rowInput:`当前输入`,historyMeta:`选中 {selected} 条 / 共 {total} 条`,historyTrimmed:`为控制预算裁剪了 {count} 条(以规则摘要替代)`,refInfo:`输出预留 {output} · 安全余量 {safety}(不计入上方占用)`,memoryLabel:`记忆设置`,memoryAll:`携带全部历史`,memoryLimited:`携带最近 {n} 条`,memoryOff:`不携带历史(仅当前消息)`,compactionActive:`已压缩 {count} 条历史 · 摘要约 {tokens} tokens`,compactionInvalidHint:`压缩点已失效(对应消息已被删除),本次发送未使用压缩`,removeInvalid:`移除失效的压缩记录`,btnCompact:`压缩上下文`,btnCompactAgain:`再次压缩`,btnUndoCompact:`撤销压缩`,undoExpiredToast:`已发送新消息,无法再撤销压缩(可再次压缩合并更新)`,summaryTitle:`上下文摘要(压缩 {count} 条历史)`,summaryTabPreview:`预览`,summaryTabSource:`源码`}}),n(`en`,{contextUsage:{indicatorTitle:`Context usage {percent}% ({used} / {total} tokens) · Click for details`,memoryOffToast:`Memory is off, nothing to compact`,generatingToast:`Generating a reply, please try again later`,nothingToCompactToast:`No new messages to compact`,confirmTitle:`Compact Context`,confirmMessage:`Compact {count} history messages (~{tokens} tokens) into a summary{summaryHint}. Original messages remain in the session; undo is available before sending new messages.`,confirmWithOldSummary:` (including the existing summary, which will be merged into a new one)`,confirmOk:`Start Compaction`,compactingTitle:`Compacting Context`,compactingHint:`Generating a summary with the model, please wait… (usually takes a few seconds)`,compactDone:`Compaction complete, saved ~{saved} tokens`,compactErrConfig:`Cannot compact: API configuration missing`,compactErrFailed:`Compaction failed, please try again later`,compactErrEmpty:`the model returned no summary`,compactErrHttp:`API error HTTP {status}`,compactErrTimeout:`request timed out`,autoCompactedToast:`Context is near its limit; auto-compacted (est. {saved} tokens saved)`,undoTitle:`Undo Compaction`,undoMessage:`After undo, sending will include the full history again. Undo?`,undoOk:`Undo`,undoDone:`Compaction undone`,dividerText:`⬆ {count} messages above compacted into a summary`,dividerView:`View`,dividerUndo:`Undo`,popupTitle:`Context Usage Details`,rowSystem:`System prompt`,rowTools:`Tool definitions`,rowHistory:`History messages`,rowInput:`Current input`,historyMeta:`Selected {selected} / {total} total`,historyTrimmed:`{count} messages trimmed for budget (replaced by rule summary)`,refInfo:`Output reserve {output} · Safety margin {safety} (not counted above)`,memoryLabel:`Memory setting`,memoryAll:`Carry all history`,memoryLimited:`Carry latest {n} messages`,memoryOff:`No history (current message only)`,compactionActive:`{count} messages compacted · summary ~{tokens} tokens`,compactionInvalidHint:`Compaction point is stale (its message was deleted); this send ignores the compaction`,removeInvalid:`Remove stale compaction record`,btnCompact:`Compact Context`,btnCompactAgain:`Compact Again`,btnUndoCompact:`Undo Compaction`,undoExpiredToast:`New messages have been sent; compaction can no longer be undone (you can compact again)`,summaryTitle:`Context Summary ({count} messages compacted)`,summaryTabPreview:`Preview`,summaryTabSource:`Source`}});var CO=300,wO=``,TO=0,EO=null;async function DO(){try{let{mcpTools:e}=await chrome.storage.local.get([`mcpTools`]),t=e||[],n=new Set(Array.isArray(C.mcpClosedServers)?C.mcpClosedServers:[]),r=new Set(Array.isArray(C.activeAgentMcpExcludedServerIds)?C.activeAgentMcpExcludedServerIds:[]);return t.filter(e=>{let t=e.serverId||`unknown`;return!n.has(t)&&!r.has(t)}).length}catch{return 0}}function OO(){let e=document.getElementById(`userInput`)?.value||``;return{usage:sn({model:C.currentModel,customModelMap:C.customModelMap,systemPromptText:wO,toolCount:(C.useTools?C.enabledTools.length:0)+TO,history:C.messageHistory,inputText:e,maxMemoryMessages:C.chatConfig?.maxMemoryMessages??null,compaction:C.activeCompaction,isolateChat:C.isolateChat}),inputText:e}}function kO(e){let t=document.getElementById(`contextUsageIndicator`);if(!t)return;t._lastUsage=e,t.dataset.level=e.level;let n=Math.round(e.ratio*100),i=t.querySelector(`.context-usage-percent`);i&&(i.textContent=`${n}%`),t.style.setProperty(`--usage-ratio`,String(Math.min(Math.max(e.ratio,0),1))),t.title=r(`contextUsage.indicatorTitle`,{percent:n,used:I(e.usedTokens),total:I(e.contextWindow)})}function AO(){try{let{usage:e}=OO();return kO(e),HO(),e}catch(e){return i.warn(`[ContextIndicator] update failed:`,e?.message),null}}function jO(){clearTimeout(EO),EO=setTimeout(()=>AO(),CO)}async function MO(e=null){let t=e===null?C.activeSessionId:e;try{wO=await Ke(await yO(),{sessionId:t})}catch(e){i.warn(`[ContextIndicator] refresh system prompt failed:`,e?.message)}try{TO=await DO()}catch{TO=0}AO()}function NO(){let e=document.getElementById(`contextUsageIndicator`);e&&(e.addEventListener(`click`,()=>KO()),document.getElementById(`userInput`)?.addEventListener(`input`,jO),document.addEventListener(`generating-state-changed`,()=>{MO()}),document.addEventListener(`agent-model-changed`,()=>{MO()}),document.addEventListener(`session-switched`,()=>{MO()}),document.addEventListener(`session-workdir-changed`,()=>{MO()}),chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&((e.chatMaxMemoryMessages||e.isolateChat)&&jO(),(e.modelName||e.customModels)&&jO(),(e.isolateChat||e.mcpTools||e.mcpEnabled||e.enabledTools||e.enableTools)&&MO())}),MO())}function PO({title:e,message:t,okText:n}){return new Promise(i=>{let a=document.createElement(`div`);a.className=`modal-overlay show`,a.style.zIndex=`10200`,a.innerHTML=`
|
|
2230
|
+
<span class="agent-tool-name" title="${$(e.name)}">${kO(e.name)}</span>
|
|
2231
|
+
<span class="agent-tool-desc" title="${$(r)}">${kO(r.substring(0,40))}${r.length>40?`...`:``}</span>
|
|
2232
|
+
</label>`}).join(``)}let n=document.getElementById(`agentSkillSelectedOnlyBtn`);n&&(n.classList.toggle(`active`,t.selectedOnly),n.textContent=r(t.selectedOnly?`agentEditor.showAllSkills`:`agentEditor.selectedOnlyFilter`),n.title=r(`agentToolFilter.selectedCountHint`,{count:t.selectedSet.size})),iO()}function yO(){let e=gO,t=e.skills.filter(t=>e.selectedSet.has(t.name)).map(e=>e.name),n=new Set(t),r=[...e.selectedSet].filter(e=>!n.has(e)),i=[...t,...r];return i.length>0?i:null}async function bO(){let e=document.getElementById(`agentModelList`);if(e)return new Promise(t=>{chrome.storage.local.get([`customModels`],n=>{let r=[];(n.customModels||[]).forEach(e=>{let t;typeof e==`string`?t=e:e&&e.name&&(t=e.name),t&&!r.includes(t)&&r.push(t)}),e.innerHTML=r.map(e=>`<option value="${$(e)}">`).join(``),t()})})}function xO(e){let t=document.getElementById(`agentEditTempPreset`);if(t){for(;t.options.length>1;)t.remove(1);$t.forEach((e,n)=>{let i=document.createElement(`option`);i.value=n,i.textContent=`${r(e.labelKey)}(${e.temp.toFixed(2)})`,t.appendChild(i)}),e!==void 0&&e>=0?t.value=e:t.value=``}}function SO(){let e=document.getElementById(`agentEditTempPreset`);if(!e||e.value===``)return{temperature:null,topP:null};let t=parseInt(e.value);if(isNaN(t)||t<0||t>=$t.length)return{temperature:null,topP:null};let n=$t[t];return{temperature:n.temp,topP:n.topP}}function CO(e,t){if(e==null)return-1;for(let n=0;n<$t.length;n++){let r=$t[n];if(Math.abs(r.temp-e)<.001&&Math.abs(r.topP-(t||1))<.001)return n}return-1}async function wO(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`).value,n=e.querySelector(`#agentEditName`).value.trim(),a=e.querySelector(`#agentEditIcon`).value.trim()||`🤖`,o=e.querySelector(`#agentEditDesc`).value.trim(),s=e.querySelector(`#agentEditPrompt`).value.trim(),c=e.querySelector(`#agentEditAllowSub`).checked,l=mO(),u=hO(),d=yO(),f=e.querySelector(`#agentEditModel`).value.trim()||null,{temperature:p,topP:m}=SO();if(!n){F(r(`agentMgr.nameRequired`),`warning`);return}let h={name:n,icon:a,description:o,systemPrompt:s,allowSubDispatch:c,toolIds:l,skillIds:d,model:f,temperature:p,topP:m};u!==void 0&&(h.mcpExcludedServerIds=u);try{t?(await mt(t,h),t===C.activeAgentId&&u!==void 0&&(C.activeAgentMcpExcludedServerIds=u),F(r(`agentMgr.agentUpdated`),`success`)):F(r(`agentMgr.agentCreated`,{name:(await gt(h)).name}),`success`),await BD(),await VD(),sO(),ha()}catch(e){i.error(`[AgentMgr] save Agent failed:`,e),F(r(`agentMgr.saveFailed`,{message:e.message}),`error`)}}async function TO(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`)?.value;if(!t)return;let n=await pt(t);if(await AO(r(`agentMgr.confirmDeleteAgentMessage`,{name:n?n.name:``}),r(`agentMgr.deleteAgentTitle`)))try{await vt(t),F(r(`agentMgr.agentDeleted`),`success`),await BD(),await VD(),sO()}catch(e){i.error(`[AgentMgr] delete Agent failed:`,e),F(r(`agentMgr.deleteFailed`,{message:e.message}),`error`)}}async function EO(e){if(!e)return!1;let t=await pt(e);if(!t||t.isBuiltin)return F(r(`agentMgr.cannotDeleteDefault`),`warning`),!1;if(!await AO(r(`agentMgr.confirmDeleteAgentMessage`,{name:t.name}),r(`agentMgr.deleteAgentTitle`)))return!1;try{return await vt(e),F(r(`agentMgr.agentDeleted`),`success`),await BD(),await VD(),!0}catch(e){return i.error(`[AgentMgr] delete Agent failed:`,e),F(r(`agentMgr.deleteFailed`,{message:e.message}),`error`),!1}}async function DO(e=C.activeAgentId){return e?await pt(e):null}function OO(e){return e?e.toolIds:null}function kO(e){if(!e)return``;let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function $(e){return e?e.replace(/["&<>]/g,e=>({'"':`"`,"&":`&`,"<":`<`,">":`>`})[e]):``}async function AO(e,t){return typeof window.showCustomConfirm==`function`?window.showCustomConfirm(e,t):new Promise(n=>{let i=document.getElementById(`agentConfirmModal`);if(!i){n(confirm(e));return}i.querySelector(`#agentConfirmMessage`).textContent=e,i.querySelector(`#agentConfirmTitle`).textContent=t||r(`agentMgr.confirm`),i.style.display=`flex`;let a=()=>{i.style.display=`none`,i.querySelector(`#agentConfirmOk`).removeEventListener(`click`,o),i.querySelector(`#agentConfirmCancel`).removeEventListener(`click`,s),i.removeEventListener(`click`,c)},o=()=>{a(),n(!0)},s=()=>{a(),n(!1)},c=e=>{e.target===i&&(a(),n(!1))};i.querySelector(`#agentConfirmOk`).addEventListener(`click`,o),i.querySelector(`#agentConfirmCancel`).addEventListener(`click`,s),i.addEventListener(`click`,c)})}n(`zh`,{contextUsage:{indicatorTitle:`上下文占用 {percent}%({used} / {total} tokens)· 点击查看详情`,memoryOffToast:`记忆已关闭,无可压缩内容`,generatingToast:`正在生成回复,请稍后再试`,nothingToCompactToast:`没有新的消息可压缩`,confirmTitle:`压缩上下文`,confirmMessage:`将压缩 {count} 条历史消息(约 {tokens} tokens)为一份摘要{summaryHint}。原始消息仍保留在会话中,发送新消息前可撤销。`,confirmWithOldSummary:`(含已有摘要,将合并为新摘要)`,confirmOk:`开始压缩`,compactingTitle:`正在压缩上下文`,compactingHint:`正在调用模型生成摘要,请稍候…(通常需要几秒到十几秒)`,compactDone:`压缩完成,节约约 {saved} tokens`,compactErrConfig:`无法压缩:API 配置缺失`,compactErrFailed:`压缩失败,请稍后重试`,compactErrEmpty:`模型未返回摘要内容`,compactErrHttp:`接口错误 HTTP {status}`,compactErrTimeout:`请求超时`,autoCompactedToast:`上下文接近上限,已自动压缩(预计省 {saved} tokens)`,undoTitle:`撤销压缩`,undoMessage:`撤销后,发送将恢复携带完整历史。确定撤销吗?`,undoOk:`撤销`,undoDone:`已撤销压缩`,dividerText:`⬆ 上方 {count} 条消息已压缩为摘要`,dividerView:`查看`,dividerUndo:`撤销`,popupTitle:`上下文占用明细`,rowSystem:`系统提示词`,rowTools:`工具定义`,rowHistory:`历史消息`,rowInput:`当前输入`,historyMeta:`选中 {selected} 条 / 共 {total} 条`,historyTrimmed:`为控制预算裁剪了 {count} 条(以规则摘要替代)`,refInfo:`输出预留 {output} · 安全余量 {safety}(不计入上方占用)`,memoryLabel:`记忆设置`,memoryAll:`携带全部历史`,memoryLimited:`携带最近 {n} 条`,memoryOff:`不携带历史(仅当前消息)`,compactionActive:`已压缩 {count} 条历史 · 摘要约 {tokens} tokens`,compactionInvalidHint:`压缩点已失效(对应消息已被删除),本次发送未使用压缩`,removeInvalid:`移除失效的压缩记录`,btnCompact:`压缩上下文`,btnCompactAgain:`再次压缩`,btnUndoCompact:`撤销压缩`,undoExpiredToast:`已发送新消息,无法再撤销压缩(可再次压缩合并更新)`,summaryTitle:`上下文摘要(压缩 {count} 条历史)`,summaryTabPreview:`预览`,summaryTabSource:`源码`}}),n(`en`,{contextUsage:{indicatorTitle:`Context usage {percent}% ({used} / {total} tokens) · Click for details`,memoryOffToast:`Memory is off, nothing to compact`,generatingToast:`Generating a reply, please try again later`,nothingToCompactToast:`No new messages to compact`,confirmTitle:`Compact Context`,confirmMessage:`Compact {count} history messages (~{tokens} tokens) into a summary{summaryHint}. Original messages remain in the session; undo is available before sending new messages.`,confirmWithOldSummary:` (including the existing summary, which will be merged into a new one)`,confirmOk:`Start Compaction`,compactingTitle:`Compacting Context`,compactingHint:`Generating a summary with the model, please wait… (usually takes a few seconds)`,compactDone:`Compaction complete, saved ~{saved} tokens`,compactErrConfig:`Cannot compact: API configuration missing`,compactErrFailed:`Compaction failed, please try again later`,compactErrEmpty:`the model returned no summary`,compactErrHttp:`API error HTTP {status}`,compactErrTimeout:`request timed out`,autoCompactedToast:`Context is near its limit; auto-compacted (est. {saved} tokens saved)`,undoTitle:`Undo Compaction`,undoMessage:`After undo, sending will include the full history again. Undo?`,undoOk:`Undo`,undoDone:`Compaction undone`,dividerText:`⬆ {count} messages above compacted into a summary`,dividerView:`View`,dividerUndo:`Undo`,popupTitle:`Context Usage Details`,rowSystem:`System prompt`,rowTools:`Tool definitions`,rowHistory:`History messages`,rowInput:`Current input`,historyMeta:`Selected {selected} / {total} total`,historyTrimmed:`{count} messages trimmed for budget (replaced by rule summary)`,refInfo:`Output reserve {output} · Safety margin {safety} (not counted above)`,memoryLabel:`Memory setting`,memoryAll:`Carry all history`,memoryLimited:`Carry latest {n} messages`,memoryOff:`No history (current message only)`,compactionActive:`{count} messages compacted · summary ~{tokens} tokens`,compactionInvalidHint:`Compaction point is stale (its message was deleted); this send ignores the compaction`,removeInvalid:`Remove stale compaction record`,btnCompact:`Compact Context`,btnCompactAgain:`Compact Again`,btnUndoCompact:`Undo Compaction`,undoExpiredToast:`New messages have been sent; compaction can no longer be undone (you can compact again)`,summaryTitle:`Context Summary ({count} messages compacted)`,summaryTabPreview:`Preview`,summaryTabSource:`Source`}});var jO=300,MO=``,NO=0,PO=null;async function FO(){try{let{mcpTools:e}=await chrome.storage.local.get([`mcpTools`]),t=e||[],n=new Set(Array.isArray(C.mcpClosedServers)?C.mcpClosedServers:[]),r=new Set(Array.isArray(C.activeAgentMcpExcludedServerIds)?C.activeAgentMcpExcludedServerIds:[]);return t.filter(e=>{let t=e.serverId||`unknown`;return!n.has(t)&&!r.has(t)}).length}catch{return 0}}function IO(){let e=document.getElementById(`userInput`)?.value||``;return{usage:sn({model:C.currentModel,customModelMap:C.customModelMap,systemPromptText:MO,toolCount:(C.useTools?C.enabledTools.length:0)+NO,history:C.messageHistory,inputText:e,maxMemoryMessages:C.chatConfig?.maxMemoryMessages??null,compaction:C.activeCompaction,isolateChat:C.isolateChat}),inputText:e}}function LO(e){let t=document.getElementById(`contextUsageIndicator`);if(!t)return;t._lastUsage=e,t.dataset.level=e.level;let n=Math.round(e.ratio*100),i=t.querySelector(`.context-usage-percent`);i&&(i.textContent=`${n}%`),t.style.setProperty(`--usage-ratio`,String(Math.min(Math.max(e.ratio,0),1))),t.title=r(`contextUsage.indicatorTitle`,{percent:n,used:I(e.usedTokens),total:I(e.contextWindow)})}function RO(){try{let{usage:e}=IO();return LO(e),XO(),e}catch(e){return i.warn(`[ContextIndicator] update failed:`,e?.message),null}}function zO(){clearTimeout(PO),PO=setTimeout(()=>RO(),jO)}async function BO(e=null){let t=e===null?C.activeSessionId:e;try{MO=await Ke(await DO(),{sessionId:t})}catch(e){i.warn(`[ContextIndicator] refresh system prompt failed:`,e?.message)}try{NO=await FO()}catch{NO=0}RO()}function VO(){let e=document.getElementById(`contextUsageIndicator`);e&&(e.addEventListener(`click`,()=>ek()),document.getElementById(`userInput`)?.addEventListener(`input`,zO),document.addEventListener(`generating-state-changed`,()=>{BO()}),document.addEventListener(`agent-model-changed`,()=>{BO()}),document.addEventListener(`session-switched`,()=>{BO()}),document.addEventListener(`session-workdir-changed`,()=>{BO()}),chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&((e.chatMaxMemoryMessages||e.isolateChat)&&zO(),(e.modelName||e.customModels)&&zO(),(e.isolateChat||e.mcpTools||e.mcpEnabled||e.enabledTools||e.enableTools)&&BO())}),BO())}function HO({title:e,message:t,okText:n}){return new Promise(i=>{let a=document.createElement(`div`);a.className=`modal-overlay show`,a.style.zIndex=`10200`,a.innerHTML=`
|
|
2232
2233
|
<div class="modal-container">
|
|
2233
2234
|
<div class="modal-title"></div>
|
|
2234
2235
|
<div class="modal-message"></div>
|
|
@@ -2236,20 +2237,20 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2236
2237
|
<button class="modal-btn cancel">${r(`common.cancel`)}</button>
|
|
2237
2238
|
</div>
|
|
2238
2239
|
</div>
|
|
2239
|
-
`,a.querySelector(`.modal-title`).textContent=e,a.querySelector(`.modal-message`).textContent=t;let o=a.querySelector(`.modal-actions`),s=document.createElement(`button`);s.className=`modal-btn confirm`,s.textContent=n,o.appendChild(s),document.body.appendChild(a);let c=e=>{a.remove(),i(e)};a.querySelector(`.modal-btn.cancel`).addEventListener(`click`,()=>c(!1)),s.addEventListener(`click`,()=>c(!0)),a.addEventListener(`click`,e=>{e.target===a&&c(!1)})})}function
|
|
2240
|
+
`,a.querySelector(`.modal-title`).textContent=e,a.querySelector(`.modal-message`).textContent=t;let o=a.querySelector(`.modal-actions`),s=document.createElement(`button`);s.className=`modal-btn confirm`,s.textContent=n,o.appendChild(s),document.body.appendChild(a);let c=e=>{a.remove(),i(e)};a.querySelector(`.modal-btn.cancel`).addEventListener(`click`,()=>c(!1)),s.addEventListener(`click`,()=>c(!0)),a.addEventListener(`click`,e=>{e.target===a&&c(!1)})})}function UO(){let e=document.createElement(`div`);return e.className=`modal-overlay show context-usage-compacting-overlay`,e.style.zIndex=`10200`,e.innerHTML=`
|
|
2240
2241
|
<div class="modal-container context-usage-compacting-modal">
|
|
2241
2242
|
<div class="context-usage-compacting-spinner"></div>
|
|
2242
2243
|
<div class="modal-title"></div>
|
|
2243
2244
|
<div class="modal-message"></div>
|
|
2244
2245
|
</div>
|
|
2245
|
-
`,e.querySelector(`.modal-title`).textContent=r(`contextUsage.compactingTitle`),e.querySelector(`.modal-message`).textContent=r(`contextUsage.compactingHint`),document.body.appendChild(e),{close:()=>e.remove()}}function
|
|
2246
|
+
`,e.querySelector(`.modal-title`).textContent=r(`contextUsage.compactingTitle`),e.querySelector(`.modal-message`).textContent=r(`contextUsage.compactingHint`),document.body.appendChild(e),{close:()=>e.remove()}}function WO(e){let t=String(e||``);if(t===`empty_summary`)return r(`contextUsage.compactErrEmpty`);if(t.includes(`CHAT_STREAM_IDLE_TIMEOUT`))return r(`contextUsage.compactErrTimeout`);if(t.startsWith(`http_`)){let e=t.slice(5),n=e.indexOf(`:`),i=r(`contextUsage.compactErrHttp`,{status:n<0?e:e.slice(0,n)}),a=n<0?``:e.slice(n+1).trim();if(!a)return i;let o=a;try{let e=JSON.parse(a);o=e?.error?.message||e?.message||a}catch{}return`${i}: ${String(o).slice(0,200)}`}return t.includes(`超时`)||/timeout/i.test(t)?r(`contextUsage.compactErrTimeout`):t}async function GO({silent:e=!1}={}){if(!C.isolateChat)return e||F(r(`contextUsage.memoryOffToast`),`warning`),{success:!1,reason:`memory_off`};if(C.isGenerating)return e||F(r(`contextUsage.generatingToast`),`warning`),{success:!1,reason:`generating`};let t=C.messageHistory;if(!t.length)return e||F(r(`contextUsage.nothingToCompactToast`),`warning`),{success:!1,reason:`nothing_to_compact`};let n=C.activeCompaction,{material:a,includedCount:o,hasOldSummary:c}=cn(t,{maxMemoryMessages:C.chatConfig?.maxMemoryMessages??null,compaction:n});if(o===0)return e||F(r(`contextUsage.nothingToCompactToast`),`warning`),{success:!1,reason:`nothing_to_compact`};let l=E(a.map(e=>({role:e.role,content:e.content})));if(!e&&!await HO({title:r(`contextUsage.confirmTitle`),message:r(`contextUsage.confirmMessage`,{count:o,tokens:I(l),summaryHint:c?r(`contextUsage.confirmWithOldSummary`):``}),okText:r(`contextUsage.confirmOk`)}))return{success:!1,reason:`cancelled`};let u=e?null:UO();try{let i=await chrome.runtime.sendMessage({type:`COMPACT_CONTEXT_SUMMARY`,material:a,model:C.currentModel,sessionId:C.activeSessionId,persistSummaryToMemory:C.chatConfig?.persistSummaryToMemory!==!1,compressedCount:(n?.compressedCount||0)+o,revision:(n?.revision||0)+1,memoryId:n?.memoryId||null});if(!i?.success||!i.summary){if(!e)if(i?.error===`config_missing`)F(r(`contextUsage.compactErrConfig`),`error`);else{let e=WO(i?.error);F(`${r(`contextUsage.compactErrFailed`)}${e?`(${e})`:``}`,`error`)}return{success:!1,reason:i?.error||`failed`}}let c=t[t.length-1],u=s(i.summary);return C.activeCompaction={summary:i.summary,upToMessageId:c?.messageId,compressedCount:(n?.compressedCount||0)+o,summaryTokens:u,savedTokens:Math.max(l-u,0),model:C.currentModel,createdAt:Date.now(),revision:(n?.revision||0)+1,memoryId:i.memoryId||n?.memoryId||null},await yi(),ZO(),RO(),gl(),e?F(r(`contextUsage.autoCompactedToast`,{saved:I(C.activeCompaction.savedTokens)}),`info`):F(r(`contextUsage.compactDone`,{saved:I(C.activeCompaction.savedTokens)}),`success`),{success:!0,savedTokens:C.activeCompaction.savedTokens}}catch(t){if(i.warn(`[ContextIndicator] compaction failed:`,t?.message),!e){let e=WO(t?.message);F(`${r(`contextUsage.compactErrFailed`)}${e?`(${e})`:``}`,`error`)}return{success:!1,reason:`exception`}}finally{u?.close()}}async function KO(){await GO({silent:!1})}function qO(){let e=C.activeCompaction;if(!e?.upToMessageId)return!1;let t=C.messageHistory||[],n=t.findIndex(t=>t.messageId===e.upToMessageId);return n>=0&&n<t.length-1}async function JO(e=!1){if(C.activeCompaction){if(qO()){F(r(`contextUsage.undoExpiredToast`),`warning`);return}!e&&!await HO({title:r(`contextUsage.undoTitle`),message:r(`contextUsage.undoMessage`),okText:r(`contextUsage.undoOk`)})||(C.activeCompaction=null,await yi(),YO(),RO(),F(r(`contextUsage.undoDone`),`success`))}}function YO(){document.querySelectorAll(`.compaction-divider`).forEach(e=>e.remove())}function XO(){let e=qO();document.querySelectorAll(`.compaction-divider [data-action="undo"]`).forEach(t=>{t.style.display=e?`none`:``})}function ZO(){YO();let e=C.activeCompaction;if(!e?.upToMessageId)return;let t=document.getElementById(`chatContainer`);if(!t)return;let n=t.querySelector(`[data-message-id="${CSS.escape(e.upToMessageId)}"]`);if(!n)return;let i=document.createElement(`div`);i.className=`compaction-divider`;let a=!qO();i.innerHTML=`
|
|
2246
2247
|
<span class="compaction-divider-text">${r(`contextUsage.dividerText`,{count:e.compressedCount})}</span>
|
|
2247
2248
|
<button class="compaction-divider-btn" data-action="view">${r(`contextUsage.dividerView`)}</button>
|
|
2248
2249
|
${a?`<button class="compaction-divider-btn" data-action="undo">${r(`contextUsage.dividerUndo`)}</button>`:``}
|
|
2249
|
-
`,i.querySelector(`[data-action="view"]`).addEventListener(`click`,()=>
|
|
2250
|
+
`,i.querySelector(`[data-action="view"]`).addEventListener(`click`,()=>tk(e)),i.querySelector(`[data-action="undo"]`)?.addEventListener(`click`,()=>JO()),n.after(i)}var QO=null;function $O(){document.querySelectorAll(`.context-usage-popup`).forEach(e=>e.remove());let e=document.getElementById(`contextUsageIndicator`);e&&(e._ctxPopupOpen=!1),QO&&=(document.removeEventListener(`click`,QO),null)}function ek(){let e=document.getElementById(`contextUsageIndicator`);if(!e)return;if(e._ctxPopupOpen){$O();return}$O(),e._ctxPopupOpen=!0;let{usage:t}=IO(),n=t.breakdown,i=Math.round(t.ratio*100),a;a=C.isolateChat?C.chatConfig?.maxMemoryMessages>0?r(`contextUsage.memoryLimited`,{n:C.chatConfig.maxMemoryMessages}):r(`contextUsage.memoryAll`):r(`contextUsage.memoryOff`);let o=C.activeCompaction,s;s=o&&n.compactionApplied?`
|
|
2250
2251
|
<div class="context-usage-compaction">
|
|
2251
2252
|
<div class="context-usage-dim">${r(`contextUsage.compactionActive`,{count:o.compressedCount,tokens:I(o.summaryTokens)})}</div>
|
|
2252
|
-
${
|
|
2253
|
+
${qO()?`<button class="context-usage-btn primary" data-action="compact">${r(`contextUsage.btnCompactAgain`)}</button>`:`<button class="context-usage-btn danger-ghost" data-action="undo">${r(`contextUsage.btnUndoCompact`)}</button>`}
|
|
2253
2254
|
</div>`:n.compactionInvalid?`
|
|
2254
2255
|
<div class="context-usage-compaction">
|
|
2255
2256
|
<div class="context-usage-warn">${r(`contextUsage.compactionInvalidHint`)}</div>
|
|
@@ -2282,7 +2283,7 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2282
2283
|
</div>
|
|
2283
2284
|
${s}
|
|
2284
2285
|
</div>
|
|
2285
|
-
`,document.body.appendChild(u);let d=e.getBoundingClientRect();u.style.left=`${Math.max(d.left,8)}px`,u.style.bottom=`${window.innerHeight-d.top+6}px`,u.querySelector(`.context-usage-popup-close`).addEventListener(`click`,()
|
|
2286
|
+
`,document.body.appendChild(u);let d=e.getBoundingClientRect();u.style.left=`${Math.max(d.left,8)}px`,u.style.bottom=`${window.innerHeight-d.top+6}px`,u.querySelector(`.context-usage-popup-close`).addEventListener(`click`,()=>$O()),u.querySelector(`[data-action="compact"]`)?.addEventListener(`click`,()=>{$O(),KO()}),u.querySelector(`[data-action="undo"]`)?.addEventListener(`click`,()=>{$O(),JO(!0)}),u.querySelector(`[data-action="remove-invalid"]`)?.addEventListener(`click`,async()=>{$O(),C.activeCompaction=null,await yi(),YO(),RO()}),QO=e=>{e.target.closest(`.context-usage-popup, #contextUsageIndicator`)||$O()},setTimeout(()=>document.addEventListener(`click`,QO),0)}function tk(e=C.activeCompaction){if(!e?.summary)return;let t=document.createElement(`div`);t.className=`modal-overlay show`,t.style.zIndex=`10200`,t.innerHTML=`
|
|
2286
2287
|
<div class="modal-container context-usage-summary-modal">
|
|
2287
2288
|
<button type="button" class="context-usage-summary-close" title="${r(`common.close`)}">×</button>
|
|
2288
2289
|
<div class="modal-title">${r(`contextUsage.summaryTitle`,{count:e.compressedCount})}
|
|
@@ -2293,4 +2294,4 @@ Sessions using this assistant will revert to the default assistant.`,deleteAgent
|
|
|
2293
2294
|
</div>
|
|
2294
2295
|
<div class="context-usage-summary-body"></div>
|
|
2295
2296
|
</div>
|
|
2296
|
-
`,document.body.appendChild(t);let n=t.querySelector(`.context-usage-summary-body`),i=t.querySelectorAll(`.context-usage-summary-tab`),a=t=>{i.forEach(e=>e.classList.toggle(`active`,e.dataset.mode===t)),t===`preview`?(n.classList.add(`markdown-body`),n.innerHTML=tt(e.summary),it()):(n.classList.remove(`markdown-body`),n.textContent=e.summary)};i.forEach(e=>e.addEventListener(`click`,()=>a(e.dataset.mode))),a(`preview`),t.querySelector(`.context-usage-summary-close`).addEventListener(`click`,()=>t.remove()),t.addEventListener(`click`,e=>{e.target===t&&t.remove()})}export{
|
|
2297
|
+
`,document.body.appendChild(t);let n=t.querySelector(`.context-usage-summary-body`),i=t.querySelectorAll(`.context-usage-summary-tab`),a=t=>{i.forEach(e=>e.classList.toggle(`active`,e.dataset.mode===t)),t===`preview`?(n.classList.add(`markdown-body`),n.innerHTML=tt(e.summary),it()):(n.classList.remove(`markdown-body`),n.textContent=e.summary)};i.forEach(e=>e.addEventListener(`click`,()=>a(e.dataset.mode))),a(`preview`),t.querySelector(`.context-usage-summary-close`).addEventListener(`click`,()=>t.remove()),t.addEventListener(`click`,e=>{e.target===t&&t.remove()})}export{wT as $,Jl as $n,on as $r,dx as $t,iE as A,kp as An,Ci as Ar,aw as At,bT as B,_f as Bn,jr as Br,jx as Bt,lE as C,dh as Cn,da as Cr,uw as Ct,FT as D,th as Dn,gi as Dr,zC as Dt,pE as E,eh as En,ha as Er,LC as Et,HT as F,Sd as Fn,kr as Fr,mS as Ft,Mw as G,Pd as Gn,Tr as Gr,Sx as Gt,NT as H,ef as Hn,Ir as Hr,Rb as Ht,GT as I,Ed as In,Dr as Ir,Yx as It,dT as J,ld as Jn,Dn as Jr,tx as Jt,fT as K,vf as Kn,Bn as Kr,Xb as Kt,pT as L,Id as Ln,Cr as Lr,Mx as Lt,qT as M,Cp as Mn,Mr,NS as Mt,JT as N,Op as Nn,Or as Nr,tS as Nt,RT as O,dm as On,mi as Or,jC as Ot,zT as P,Jf as Pn,Er as Pr,Xx as Pt,jw as Q,Ql as Qn,ln as Qr,px as Qt,CT as R,Td as Rn,Nr as Rr,Ox as Rt,TE as S,uh as Sn,ua as Sr,YC as St,OE as T,Qm as Tn,fa as Tr,mC as Tt,Tw as U,Vd as Un,Lr as Ur,_x as Ut,ST as V,nf as Vn,Ur as Vr,Ax as Vt,Bw as W,Fd as Wn,Hr as Wr,hx as Wt,Iw as X,Eu as Xn,gn as Xr,nx as Xt,Hw as Y,md as Yn,Tn as Yr,zb as Yt,DT as Z,sd as Zn,hn as Zr,Wb as Zt,yE as _,jh as _n,ta as _r,OC as _t,zD as a,wx as an,Ec as ar,Aw as at,kE as b,wh as bn,pa as br,GC as bt,_E as c,ox as cn,Fo as cr,HC as ct,EE as d,Sg as dn,wa as dr,bw as dt,rn as ei,rx as en,Yl as er,ET as et,dE as f,ny as fn,Ea as fr,WC as ft,PE as g,kh as gn,la as gr,xw as gt,CE as h,Oh as hn,va as hr,XS as ht,RO as i,mx as in,Kc as ir,vT as it,KT as j,Dp as jn,tr as jr,JS as jt,BT as k,lm as kn,fi as kr,FC as kt,AE as l,Vy as ln,Po as lr,KC as lt,bE as m,Mh as mn,na as mr,Cw as mt,VO as n,vx as nn,_l as nr,Rw as nt,oO as o,Vb as on,gc as or,Vw as ot,FE as p,ry as pn,_a as pr,vw as pt,PT as q,Ud as qn,On as qr,Yb as qt,GO as r,lx as rn,ll as rr,lT as rt,jE as s,Kb as sn,Ho as sr,uT as st,IO as t,$t as ti,fx as tn,xl as tr,Ow as tt,gE as u,tg as un,ho as ur,ow as ut,NE as v,Dh as vn,ya as vr,kC as vt,xE as w,rh as wn,ga as wr,iw as wt,hE as x,Ch as xn,ma as xr,JC as xt,vE as y,Eh as yn,ra as yr,Sw as yt,_T as z,Hd as zn,Ar as zr,Fx as zt};
|