ai-helper-agent 2.8.7 → 2.8.8
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-QTeMyM9O.js +1 -0
- package/dist/assets/background.js +81 -81
- package/dist/assets/{chat-export-C2PVQS_L.js → chat-export-Aojf945l.js} +5 -5
- package/dist/assets/content.js +37 -37
- package/dist/assets/context-indicator-DSJveMWs.js +2171 -0
- package/dist/assets/{i18n-B1Q34rTV.js → i18n-DvmxOw8q.js} +2 -2
- package/dist/assets/model-profiles-C3kJEHM6.js +98 -0
- package/dist/assets/{options-DamSLmKe.css → options-DB2yC3mX.css} +1 -1
- package/dist/assets/options.js +120 -107
- package/dist/assets/{page-snapshot-renderer-I5Z-2PsZ.js → page-snapshot-renderer-CKAnJPnT.js} +1 -1
- package/dist/assets/session-store-owqj23pJ.js +10 -0
- package/dist/assets/side_panel.js +307 -2476
- package/dist/assets/todo-model-DK2Wxmvk.js +3 -0
- package/dist/assets/version-LLHkaYuT.js +174 -0
- package/dist/assets/workspace-manager-DVPkwn2d.js +1 -0
- package/dist/manifest.json +1 -1
- package/dist/offscreen/offscreen.js +2 -2
- package/dist/options.html +6 -4
- package/dist/side_panel.html +8 -8
- package/package.json +1 -1
- package/dist/assets/agent-store-Dnh5oIad.js +0 -1
- package/dist/assets/markdown-render-3zCG1QbW.js +0 -61
- package/dist/assets/model-profiles-Cq93mdbc.js +0 -24
- package/dist/assets/session-store-BVoqeTLy.js +0 -86
- package/dist/assets/utils-BPCoc5PX.js +0 -112
- package/dist/assets/version-FUgXAu0z.js +0 -3
- package/dist/assets/workspace-manager-DWIiYfRJ.js +0 -1
|
@@ -0,0 +1,2171 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/agent-store-QTeMyM9O.js","assets/chunk-CMxvf4Kt.js","assets/model-profiles-C3kJEHM6.js","assets/i18n-DvmxOw8q.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-Aojf945l.js","assets/dist-BUuoW_84.js","assets/version-LLHkaYuT.js","assets/session-store-owqj23pJ.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-DvmxOw8q.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-C3kJEHM6.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,b as se,c as ce,d as le,f as ue,h as de,j as fe,k as pe,l as me,m as he,n as ge,o as _e,p as ve,r as ye,s as be,t as xe,u as Se,v as Ce,w as we,x as Te,y as Ee}from"./session-store-owqj23pJ.js";import{a as De,n as Oe,r as ke,t as Ae}from"./voice-shortcut-Dtt3nhkz.js";import{A as je,B as Me,C as Ne,E as Pe,F as Fe,H as Ie,I as Le,K as Re,L as ze,M as P,O as Be,R as Ve,S as He,T as Ue,U as We,V as Ge,W as Ke,X as qe,Y as F,Z as Je,_ as Ye,b as Xe,d as Ze,f as Qe,g as $e,h as et,i as tt,j as nt,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 I}from"./version-LLHkaYuT.js";import{a as ft,c as pt,i as mt,n as ht,o as gt,r as _t,s as vt}from"./agent-store-QTeMyM9O.js";import{A as yt,C as bt,D as xt,E as St,M as Ct,O as wt,S as Tt,T as Et,_ as Dt,a as Ot,b as kt,c as At,d as jt,f as Mt,g as Nt,h as Pt,i as Ft,k as It,l as Lt,m as Rt,n as zt,o as Bt,p as Vt,r as Ht,s as Ut,t as Wt,u as Gt,v as Kt,w as qt,x as Jt,y as Yt}from"./workspace-manager-DVPkwn2d.js";var Xt=ne.map(e=>e.id),Zt=[...new Set([...S,`mcp`,`knowledge`])],Qt=[{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 $t=2e3,en=.7,tn=1e3;function nn(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)>tn?e.substring(0,tn*4)+`
|
|
3
|
+
...[历史摘要已截断]`:e)}return{messages:[...g,o],keptHistory:g,compactionApplied:l,trimmedCount:y,historySummaryText:v}}function rn(e,t){return!t||!t.summary?e:`${e}\n\n${r(`contextUsage.compactionInjection`,{count:t.compressedCount||0})}\n${t.summary}`}function an(e,t,n,r){return t?.compactionApplied&&n?.summary?e[0]={...e[0],content:rn(e[0].content,n)}:n?.summary&&r?.warn(`[SidePanel] contextCompaction invalid (upToMessageId not found), ignored this send`),e}function on({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-$t,g=Math.floor(Math.max(h,0)*en),_={role:`user`,content:a},v=d?u:null,y=nn(i,{isolateChat:d,maxMemoryMessages:o,compaction:v,historyBudget:g,currentMessage:_}),b=s(y.compactionApplied?rn(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:$t,selectedCount:y.keptHistory.length,totalCount:i.length,trimmedCount:y.trimmedCount,compactionApplied:y.compactionApplied,compactionInvalid:!!(v&&v.summary&&!y.compactionApplied),historyBudget:g}}}function sn(e,{maxMemoryMessages:t=null,compaction:n=null}={}){let r=nn(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 cn(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(),ln()}function ln(){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 un=[`workspace`,`bookmark`,`toc`,`search`,`todo`,`schedule`],dn=`.workspace-panel.expanded, .bookmark-panel.expanded, .message-toc-panel.expanded, .search-panel.expanded, .schedule-panel.open`,fn=null,pn=null;function mn(){if(fn)return fn;fn=document.createElement(`div`),fn.className=`side-rail`,fn.id=`sideRail`,fn.innerHTML=un.map(e=>`<div class="side-rail-slot" data-slot="${e}"></div>`).join(``),document.body.appendChild(fn),gn();let e=document.getElementById(`chatContainer`);return e&&typeof ResizeObserver<`u`&&new ResizeObserver(gn).observe(e),window.addEventListener(`resize`,gn),fn}function hn(e){return(fn||mn()).querySelector(`.side-rail-slot[data-slot="${e}"]`)}function gn(){if(!fn)return;let e=document.getElementById(`chatContainer`);if(!e)return;let t=e.getBoundingClientRect(),n=window.innerHeight;fn.style.top=`${Math.max(0,Math.round(t.top))}px`,fn.style.bottom=`${Math.max(0,Math.round(n-t.bottom))}px`,_n()}function _n(){pn&&clearTimeout(pn),pn=setTimeout(()=>{pn=null,document.querySelectorAll(dn).forEach(Be)},120)}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 vn=`messageTocLocked`,yn=!1,bn=`<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>`,xn=`<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 Sn(e){e&&(e.innerHTML=yn?xn:bn,e.title=r(yn?`messageToc.unlock`:`messageToc.lock`),e.classList.toggle(`locked`,yn))}function Cn(){try{let e=chrome.storage?.local?.set?.({[vn]:yn});e&&typeof e.catch==`function`&&e.catch(()=>{})}catch{}}function wn(){document.addEventListener(`mouseover`,Tn,!0),document.addEventListener(`mouseout`,En,!0);try{let e=chrome.storage?.local?.get?.(vn);e&&typeof e.then==`function`?e.then(e=>{yn=!!(e&&e[vn])}).catch(()=>{}):e&&typeof e==`object`&&(yn=!!e[vn])}catch{}i.debug(`[SidePanel] messagedirectory featureinitializing`)}function Tn(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){yn||Nn();return}Mn(r,i)}function En(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||yn)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||Nn(),C.tocHideTimer=null},800))}var Dn=null,On=null;function kn(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 An(e,t,n,r){if(jn(),n.length===0)return;let i=kn(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=>e.getBoundingClientRect().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(),On=()=>{if(h(),!l)return;let e=s.get(l);e&&d(e)},Dn=()=>{c&&cancelAnimationFrame(c),c=0,document.removeEventListener(`scroll`,g,{capture:!0}),window.removeEventListener(`resize`,g),_&&_.disconnect()}}function jn(){Dn&&=(Dn(),null),On=null}function Mn(e,t){let n=Array.from(t);C.messageTocContainer&&Nn(),n.forEach((e,t)=>{e.id||=`toc-heading-${Date.now()}-${t}`});let i=document.createElement(`div`);i.className=`message-toc-container`,i.dataset.headingsCount=n.length;let a=0,o=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 a++,`
|
|
4
|
+
<li class="message-toc-item level-${t}"
|
|
5
|
+
data-target="${e.id}"
|
|
6
|
+
data-anchor="${i}"
|
|
7
|
+
title="${n}">
|
|
8
|
+
<span class="toc-anchor">${i}</span>
|
|
9
|
+
<span class="toc-text">${r}</span>
|
|
10
|
+
</li>
|
|
11
|
+
`}).join(``);i.innerHTML=`
|
|
12
|
+
<button class="message-toc-toggle" title="${r(`messageToc.toggleTitle`,{count:t.length})}">
|
|
13
|
+
☰
|
|
14
|
+
</button>
|
|
15
|
+
<div class="message-toc-panel${yn?` locked`:``}">
|
|
16
|
+
<div class="message-toc-header">
|
|
17
|
+
<span>☰</span>
|
|
18
|
+
<span>${r(`messageToc.title`)}</span>
|
|
19
|
+
<span class="message-toc-count">${r(`messageToc.headingCount`,{count:t.length})}</span>
|
|
20
|
+
<button class="message-toc-lock" type="button" title="${r(yn?`messageToc.unlock`:`messageToc.lock`)}">${yn?xn:bn}</button>
|
|
21
|
+
<button class="message-toc-close" type="button" title="${r(`messageToc.close`)}">×</button>
|
|
22
|
+
</div>
|
|
23
|
+
<div class="message-toc-content">
|
|
24
|
+
<ul class="message-toc-list">
|
|
25
|
+
${o}
|
|
26
|
+
</ul>
|
|
27
|
+
</div>
|
|
28
|
+
</div>
|
|
29
|
+
`;let s=e.closest(`.message-fullscreen-overlay`),c=e.closest(`.workspace-preview-overlay.fullscreen`);(s?s.querySelector(`.message-fullscreen-rail`)||hn(`toc`):c&&c.querySelector(`.workspace-preview-rail`)||hn(`toc`)).appendChild(i),C.messageTocContainer=i;let l=i.querySelector(`.message-toc-toggle`),u=i.querySelector(`.message-toc-panel`);yn&&(u.classList.add(`expanded`,`locked`),Be(u));let d=i.querySelector(`.message-toc-lock`);d.addEventListener(`click`,e=>{e.stopPropagation(),yn=!yn,Cn(),Sn(d),yn?(u.classList.add(`expanded`,`locked`),Be(u),requestAnimationFrame(()=>On&&On())):u.classList.remove(`locked`)}),i.querySelector(`.message-toc-close`).addEventListener(`click`,e=>{e.stopPropagation(),yn&&(yn=!1,Cn()),Nn()}),l.addEventListener(`mouseenter`,()=>{u.classList.add(`expanded`),Be(u),requestAnimationFrame(()=>On&&On())}),l.addEventListener(`click`,()=>{u.classList.toggle(`expanded`)?(Be(u),requestAnimationFrame(()=>On&&On())):Re(u)}),u.addEventListener(`mouseenter`,()=>{u.classList.add(`expanded`),requestAnimationFrame(()=>On&&On())}),i.querySelectorAll(`.message-toc-item`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.target,n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),n.classList.add(`toc-highlight`),setTimeout(()=>{n.classList.remove(`toc-highlight`)},1500))})}),An(i,e,n,u)}function Nn(){C.tocHideTimer&&=(clearTimeout(C.tocHideTimer),null),jn(),C.messageTocContainer&&=(C.messageTocContainer.remove(),null)}var Pn=`promptQueues`,Fn=1,In=30*1e3,Ln=15*1e3,Rn=20,L={QUEUED:`queued`,DISPATCHING:`dispatching`,INJECTING:`injecting`,INJECTED:`injected`,DONE:`done`,FAILED:`failed`};new Set([L.INJECTED,L.DONE,L.FAILED]);var zn={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 Bn(){return{version:Fn,sessions:{}}}var R=Bn(),Vn=!1,Hn=null,Un=!1,Wn=``,Gn=new Set,Kn=new Set;function qn(){return{items:[],recent:[],paused:!1,pausedReason:null}}function Jn(e){return e?(R.sessions[e]||(R.sessions[e]=qn()),R.sessions[e]):qn()}function Yn(){return JSON.stringify(R)}function Xn(e,t){for(let n of Kn)try{n(e,t)}catch(e){i.error(`[QueueStore] listener failed:`,e?.message)}}function Zn(){return typeof crypto<`u`&&typeof crypto.randomUUID==`function`?`q_`+crypto.randomUUID():`q_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8)}function Qn(e){return e.reduce((e,t)=>Math.max(e,Number(t.order)||0),0)+1}function $n(e,t){let n=e.indexOf(t);n<0||(e.splice(n,1),e.unshift(t),er(e))}function er(e){e.forEach((e,t)=>{e.order=t+1})}function tr(e){return e.slice().sort((e,t)=>(Number(e.order)||0)-(Number(t.order)||0))}async function nr(e){if(Un)return i.error(`[QueueStore] persist skipped in degraded mode:`,e),!1;let t=Yn();Wn=t,rr(t);try{await zn.set({[Pn]:R})}catch(e){i.error(`[QueueStore] persist failed:`,e?.message)}Xn(e)}function rr(e){if(Gn.add(e),Gn.size<=Rn)return;let t=Gn.values().next().value;Gn.delete(t)}function ir(e,{recoverInterrupted:t=!0}={}){let n=Bn();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===L.DISPATCHING||e.status===L.INJECTING)&&(e.status=L.QUEUED,e.interrupted=!0,e.previousStatus=e.previousStatus||L.DISPATCHING,e.leaseOwner=null,e.leaseUntil=0,o=!0);let s=tr(r);if(o){let e=s.filter(e=>e.interrupted),t=s.filter(e=>!e.interrupted);s.splice(0,s.length,...e,...t)}er(s);let c=s.slice(0,20),l=s.slice(20);for(let e of l.reverse())a.unshift(Dr({...e,status:L.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 ar(){return Un}async function or(){return Vn?R:Hn||(Hn=(async()=>{let e;try{e=await zn.get(Pn)}catch(e){return Un=!0,Hn=null,i.error(`[QueueStore] load failed, enter degraded mode:`,e?.message),R}return R=ir(e),Vn=!0,Un=!1,Wn=Yn(),R})(),Hn)}function sr(){typeof chrome>`u`||!chrome.storage?.onChanged?.addListener||chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`||!e?.[Pn])return;let n=e[Pn].newValue;if(!n)return;let r=JSON.stringify(n);Gn.has(r)||r===Wn||(R=ir(n,{recoverInterrupted:!1}),Vn=!0,Wn=r,Xn(`external`,null))})}function cr(e){return typeof e==`function`?(Kn.add(e),()=>Kn.delete(e)):()=>{}}function lr(e){let t=R.sessions[e];return t?tr(t.items):[]}function ur(e,t=30){let n=R.sessions[e];return n?n.recent.slice(0,t):[]}function dr(e){let t=R.sessions[e];return t?{items:tr(t.items),recent:t.recent.slice(),paused:t.paused===!0,pausedReason:t.pausedReason||null}:qn()}function fr(e){return lr(e).filter(e=>e.status===L.QUEUED).length}function pr(e){return lr(e).find(e=>e.status===L.QUEUED)||null}function mr(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===L.QUEUED)return t.items[e];return null}function hr(e,t){let n=R.sessions[e];return n&&n.items.find(e=>e.id===t)||null}function gr(){return Object.keys(R.sessions).filter(e=>(R.sessions[e]?.items?.length||0)>0)}function _r(e){return R.sessions[e]?.paused===!0}async function vr({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 or(),Un)return{ok:!1,error:`storage_unavailable`};let s=Jn(e);if(s.items.length>=20)return{ok:!1,error:`queue_full`,limit:20};let c={id:Zn(),sessionId:e,text:o,contextSnapshot:n||null,attachmentSummary:i||null,hasContext:r===!0,status:L.QUEUED,order:Qn(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 nr(`enqueue`),{ok:!0,item:c,position:s.items.length}}async function yr(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),er(n.items),await nr(`remove`),!0)}async function br(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 tr(n.items))i.includes(e)||i.push(e);return n.items=i,er(n.items),await nr(`reorder`),!0}async function xr(e,t,n,r={}){let i=hr(e,t);return i?(i.status=n,Object.assign(i,r,{updatedAt:Date.now()}),await nr(`status`),!0):!1}async function Sr(e,t,n=Ln){let r=hr(e,t);return r?(r.previousStatus=r.status,r.status=L.INJECTING,r.injectRequestedAt=Date.now(),r.injectDeadlineAt=Date.now()+n,r.updatedAt=Date.now(),await nr(`inject:request`),!0):!1}async function Cr(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=L.QUEUED,a.injectDeadlineAt=0,a.updatedAt=Date.now(),a.lastError=r||n,a.rollbackReason=n,$n(i.items,a),await nr(`inject:rollback`),!0):!1}async function wr(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 er(o.items),c.status=n||L.DONE,c.settledAt=Date.now(),c.settleNote=r,i&&(c.injectedIntoCallId=i),a!=null&&(c.absorbedIteration=a),o.recent.unshift(Dr(c)),o.recent=o.recent.slice(0,30),await nr(`settle`),!0}async function Tr(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:L.QUEUED,order:Qn(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 nr(`requeue`),{ok:!0,item:a}}async function Er(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 nr(`recent-remove`),!0)}function Dr(e){let{leaseOwner:t,leaseUntil:n,injectDeadlineAt:r,contextSnapshot:i,...a}=e;return{...a,hasContext:e.hasContext===!0,contextDropped:!!i}}async function Or(e,t=`user_stopped`){let n=Jn(e);return n.paused?!1:(n.paused=!0,n.pausedReason=t,await nr(`pause`),!0)}async function kr(e){let t=R.sessions[e];return!t||!t.paused?!1:(t.paused=!1,t.pausedReason=null,await nr(`resume`),!0)}async function Ar(e,t,n){let r=hr(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+In,await nr(`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 nr(`drop-session`),n}var Mr=`ai-helper-queue-attachments`,Nr=1,Pr=`attachments`,Fr=null,Ir=null;function Lr(){return new Promise((e,t)=>{let n=indexedDB.open(Mr,Nr);n.onupgradeneeded=e=>{let t=e.target.result;t.objectStoreNames.contains(Pr)||t.createObjectStore(Pr,{keyPath:`id`}).createIndex(`sessionId`,`sessionId`,{unique:!1})},n.onsuccess=t=>{let n=t.target.result;n.onversionchange=()=>{try{n.close()}catch{}Fr=null},e(n)},n.onerror=()=>t(n.error||Error(`idb_open_failed`)),n.onblocked=()=>{}})}function Rr(){return Fr||=Lr(),Fr}function zr(e,t){return Rr().then(n=>new Promise((r,i)=>{let a;try{a=n.transaction(Pr,e)}catch(e){Fr=null,i(e);return}let o=a.objectStore(Pr),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 Br(){return{async put(e){await zr(`readwrite`,t=>{t.put(e)})},async get(e){return zr(`readonly`,(t,n)=>{let r=t.get(e);r.onsuccess=()=>n(r.result||null)})},async remove(e){await zr(`readwrite`,t=>{t.delete(e)})},async removeBySession(e){await zr(`readwrite`,t=>{let n=t.index(`sessionId`).getAllKeys(e);n.onsuccess=()=>{for(let e of n.result||[])t.delete(e)}})},async allKeys(){return zr(`readonly`,(e,t)=>{let n=e.getAllKeys();n.onsuccess=()=>t(n.result||[])})}}}function Vr(){return Ir||Br()}function Hr(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+Hr(t),0):typeof e==`object`?Object.values(e).reduce((e,t)=>e+Hr(t),0):0}function Ur(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 Wr(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=Hr(n)+Hr(r);if(i>26214400)return{ok:!1,reason:`too_large`,size:i};try{return await Vr().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 Gr(e){if(!e)return null;try{let t=await Vr().get(e);return t?{images:t.images||[],files:t.files||[]}:null}catch{return null}}async function Kr(e){if(!e)return!1;try{return await Vr().remove(e),!0}catch{return!1}}async function qr(e){if(!e)return!1;try{return await Vr().removeBySession(e),!0}catch{return!1}}async function Jr(e){let t=e instanceof Set?e:new Set(e||[]);try{let e=await Vr().allKeys(),n=0;for(let r of e||[])t.has(r)||(await Vr().remove(r),n+=1);return n}catch{return 0}}var Yr=t({appendMessageToSession:()=>_i,archiveCurrentSession:()=>ui,archiveSession:()=>pi,clearSessionCompleted:()=>ei,createSession:()=>ai,deleteArchivedSession:()=>hi,deleteSession:()=>si,duplicateSession:()=>vi,hydrateSessionWorkdir:()=>ri,importSessions:()=>gi,isSessionArchivable:()=>fi,loadArchivedSessions:()=>di,loadSessions:()=>ti,markSessionCompleted:()=>$r,persistSessionState:()=>ii,renameSession:()=>ci,reorderSessions:()=>li,restoreCompletedSessions:()=>Zr,restoreSession:()=>mi,saveCurrentSession:()=>ni,switchToSession:()=>oi}),Xr=`completedSessionIds`;async function Zr(){try{let e=(await chrome.storage.local.get([Xr]))[Xr]||[];C.completedSessionIds=new Set(e)}catch(e){i.warn(`[SessionManager] restore completedSessionIds failed:`,e)}}async function Qr(){try{await chrome.storage.local.set({[Xr]:Array.from(C.completedSessionIds)})}catch(e){i.warn(`[SessionManager] persist completedSessionIds failed:`,e)}}async function $r(e){e&&e!==C.activeSessionId&&(C.completedSessionIds.has(e)||(C.completedSessionIds.add(e),await Qr(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))))}async function ei(e){e&&C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await Qr(),document.dispatchEvent(new CustomEvent(`generating-state-changed`)))}async function ti(){return le()}async function ni(){return de()}function ri(e){return ce(e)}async function ii(e,t){return ue(e,t)}async function ai(){return oe()}async function oi(e){return Ce(e)}async function si(e){await jr(e)>0&&qr(e);let t=await _e(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 Qr()),t}async function ci(e,t){return ve(e,t)}async function li(e){return he(e)}async function ui(){return ge()}async function di(){return Se()}function fi(e){return e?C.generatingSessionIds.has(e)||C.pendingCallApiSessionIds.has(e)?{ok:!1,reason:`running`}:fr(e)>0?{ok:!1,reason:`queued`}:{ok:!0}:{ok:!1,reason:`missing`}}async function pi(e){let t=fi(e);return t.ok?await ye(e)?(C.completedSessionIds.has(e)&&(C.completedSessionIds.delete(e),await Qr(),document.dispatchEvent(new CustomEvent(`generating-state-changed`))),{ok:!0}):{ok:!1,reason:`missing`}:t}async function mi(e){return Ee(e)}async function hi(e){return si(e)}async function gi(e){return me(e)}async function _i(e,t){return xe(e,t)}async function vi(e,t=null){return be(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 yi=[],bi=[];function xi(e){if(!e)return``;let t=`tool.${e.id}`,n=r(t);return n===t?e.description||``:n}function Si(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 Ci(){try{let e=await chrome.runtime.sendMessage({type:`GET_MCP_TOOLS`});if(e?.success&&e.tools)return yi=e.tools,yi}catch{}try{return yi=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[],yi}catch{return yi=[],[]}}async function wi(){try{bi=(await chrome.storage.local.get([`ragTools`])).ragTools||[]}catch{bi=[]}return bi}async function Ti(){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-QTeMyM9O.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 Ei=!1,Di=!0;chrome.storage.local.get([`enableToolPreselect`,`toolConfirmationEnabled`],e=>{Ei=e.enableToolPreselect===!0,Di=e.toolConfirmationEnabled!==!1,$i()}),chrome.storage.onChanged.addListener((e,t)=>{if(t!==`local`)return;let n=!1;e.mcpTools&&(yi=e.mcpTools.newValue||[],i.debug(`[SidePanel] MCP toolcache updated:`,yi.length,``),n=!0),e.ragTools&&(bi=e.ragTools.newValue||[],i.debug(`[SidePanel] RAG toolcache updated:`,bi.length),n=!0),e.mcpEnabled&&(Oi=e.mcpEnabled.newValue===!0,i.debug(`[SidePanel] MCP globaltoggle changed:`,Oi),n=!0),e.skillsEnabled&&(ki=e.skillsEnabled.newValue!==!1,i.debug(`[SidePanel] Skill global toggle changed:`,ki),n=!0),e.enableImageInput&&(Ai=e.enableImageInput.newValue===!0,i.debug(`[SidePanel] 图片识别全局开关变更:`,Ai),n=!0);let r=!1;e.enableToolPreselect&&(Ei=e.enableToolPreselect.newValue===!0,r=!0),e.toolConfirmationEnabled&&(Di=e.toolConfirmationEnabled.newValue!==!1,r=!0),r&&$i(),n&&(document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(Ji(),Yi(),Bi()),Qi())}),Ci().then(()=>Qi()),wi().then(()=>Qi());var Oi=!1,ki=!0,Ai=!1;chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`enableImageInput`],e=>{Oi=e.mcpEnabled===!0,ki=e.skillsEnabled!==!1,Ai=e.enableImageInput===!0,Qi()});function ji(){let e=[...f,...bi],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_`))),Ai||(n=n.filter(e=>e.id!==`read_image`)),n}function Mi(){if(!Oi||C.agentPlatform?.connected!==!0)return[];let e=new Map;return yi.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 Ni(e){return Array.isArray(C.mcpClosedServers)&&C.mcpClosedServers.includes(e)}function Pi(e){return Array.isArray(C.activeAgentMcpExcludedServerIds)&&C.activeAgentMcpExcludedServerIds.includes(e)}function Fi(e){return!Ni(e)&&!Pi(e)}function Ii(){if(C.currentCategory!==`all`&&C.currentCategory!==`mcp`)return[];let e=Mi();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)||xi(e).toLowerCase().includes(t)))}return e}function Li(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 Ri(){let e=document.getElementById(`toolsPopupOverlay`);if(!e)return;C.currentCategory=`all`,C.currentSearch=``;let t=document.getElementById(`toolsSearchInput`);t&&(t.value=``),await Ci(),await wi(),await Ti(),Ji(),Yi(),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)`)}),Bi(),e.classList.add(`show`),i.debug(`[SidePanel] opentool popup`)}function zi(){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 Bi(){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=xi(e).toLowerCase().includes(C.currentSearch);if(!t&&!n)return}let t=e.category||`other`;n[t]||(n[t]=[]),n[t].push(e)});let i=Ii();if(Zt.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=>Fi(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
|
+
<span class="category-expand-icon">${f?`▶`:`▼`}</span>
|
|
31
|
+
<span class="category-name">${r(`toolCategory.`+a)}</span>
|
|
32
|
+
<span class="category-count">${l}</span>
|
|
33
|
+
<button type="button" class="category-select-all" title="${nt(r(`toolPanel.categorySelectAllHint`))}"></button>
|
|
34
|
+
`,d.addEventListener(`click`,e=>{if(e.target.closest(`.category-select-all`)){e.stopPropagation(),Ui(a);return}Hi(a)}),u.appendChild(d);let p=document.createElement(`div`);p.className=`popup-tool-items ${f?`collapsed`:``}`,(o?c:s).forEach(e=>{if(o){p.appendChild(Vi(e,a));return}let t=C.enabledTools.includes(e.id),n=document.createElement(`div`);n.className=`popup-tool-item`,n.dataset.category=a;let r=xi(e);n.innerHTML=`
|
|
35
|
+
<input type="checkbox" id="tool_${e.id}" ${t?`checked`:``}>
|
|
36
|
+
<div class="popup-tool-content">
|
|
37
|
+
<div class="popup-tool-name" title="${nt(e.name)}">${P(e.name)}</div>
|
|
38
|
+
<div class="popup-tool-desc" title="${nt(r)}">${P(r)}</div>
|
|
39
|
+
</div>
|
|
40
|
+
`;let i=n.querySelector(`input[type="checkbox"]`);i&&i.addEventListener(`change`,t=>{if(t.stopPropagation(),t.target.checked)C.enabledTools.includes(e.id)||C.enabledTools.push(e.id);else{let t=C.enabledTools.indexOf(e.id);t>-1&&C.enabledTools.splice(t,1)}Gi(a),Ji(),Yi(),Wi(a)}),p.appendChild(n)}),u.appendChild(p),e.appendChild(u),Wi(a)}),e.children.length===0){let t=document.createElement(`div`);t.className=`popup-tool-empty`,t.textContent=r(`toolPanel.noMatch`),e.appendChild(t)}}function Vi(e,t){let n=Pi(e.serverId),i=!Ni(e.serverId),a=document.createElement(`div`);a.className=`popup-mcp-service-block`,a.dataset.category=t,a.dataset.serverId=e.serverId;let o=document.createElement(`div`);o.className=`popup-tool-item popup-mcp-service-item`,o.innerHTML=`
|
|
41
|
+
<input type="checkbox" id="mcpsvc_${nt(e.serverId)}" ${i?`checked`:``} ${n?`disabled`:``}>
|
|
42
|
+
<div class="popup-tool-content">
|
|
43
|
+
<div class="popup-tool-name" title="${nt(e.serverName)}">
|
|
44
|
+
<span class="popup-mcp-service-name">${P(e.serverName)}</span>
|
|
45
|
+
<span class="popup-mcp-service-count">${r(`toolPanel.mcpServiceToolCount`,{count:e.toolCount})}</span>
|
|
46
|
+
</div>
|
|
47
|
+
<div class="popup-tool-desc popup-mcp-service-meta">
|
|
48
|
+
<span class="popup-mcp-service-id" title="ID: ${nt(e.serverId)}">ID: ${P(e.serverId)}</span>
|
|
49
|
+
</div>
|
|
50
|
+
${n?`<div class="popup-tool-desc popup-mcp-service-hint">${r(`toolPanel.mcpExcludedByAgent`)}</div>`:``}
|
|
51
|
+
</div>
|
|
52
|
+
<button type="button" class="popup-mcp-expand-btn" title="${r(`toolPanel.mcpServiceExpand`)}">▶</button>
|
|
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=Si(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">${P(t)}</span>`+(n?`<span class="popup-mcp-tool-desc">${P(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(),Li(e.serverId,t.target.checked),Gi(`mcp`),Ji(),Yi(),Wi(`mcp`)}),a}function Hi(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 Ui(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`)))}),Wi(e)}function Wi(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 Gi(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=Ii();i=e.length,e.forEach(e=>{if(Pi(e.serverId))return;let t=document.getElementById(`mcpsvc_`+e.serverId);(t?t.checked:!Ni(e.serverId))&&r++})}else{let t=e===`knowledge`?bi: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 Ki(){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=xi(e).toLowerCase().includes(C.currentSearch.toLowerCase());if(!t&&!n)return!1}return!0})}function qi(){Zt.forEach(e=>{Gi(e),Wi(e)})}function Ji(){let e=[`all`,...Zt],t=ji(),n=Mi(),r=n.filter(e=>Fi(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 Yi(){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=Mi(),o=a.filter(e=>Fi(e.serverId)).length;e.textContent=r(`toolPanel.enabledCount`,{enabled:i+o,total:t.length+a.length})}function Xi(){let e=[];[...ta(bi)].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=Mi(),n=new Set(t.map(e=>e.serverId)),a=(C.mcpClosedServers||[]).filter(e=>!n.has(e)),o=0;t.forEach(e=>{if(Pi(e.serverId)){Ni(e.serverId)&&a.push(e.serverId);return}let t=document.getElementById(`mcpsvc_`+e.serverId);(t?t.checked:!Ni(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)}),ni().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)}),Qi();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 Zi(e){Ii().forEach(t=>{if(Pi(t.serverId))return;let n=document.getElementById(`mcpsvc_`+t.serverId);n&&(n.checked=e),Li(t.serverId,e)})}function Qi(){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+Mi().filter(e=>Fi(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 $i(){let e=document.getElementById(`toolsConfigBtn`);if(!e)return;let t=document.getElementById(`toolsConfigFlagPreselect`),n=document.getElementById(`toolsConfigFlagConfirm`);t&&t.classList.toggle(`on`,Ei),n&&n.classList.toggle(`on`,Di);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`),Ei),i(r(`react.toolConfirmation`),Di)].join(`
|
|
54
|
+
`)}function ea(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 ta(e=[]){let t=Array.isArray(e)?e:[];return new Set([...f.map(e=>e.id),...Xt,...t.map(e=>e.id)])}function na(){document.getElementById(`toolsPopupOverlay`)?.classList.contains(`show`)&&(Ji(),Yi(),Bi()),Qi()}n(`zh`,{agentToolFilter:{selectedCountHint:`已勾选 {count} 项`}}),n(`en`,{agentToolFilter:{selectedCountHint:`{count} selected`}});function ra(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 ia(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 aa({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=>ra(e,s)),services:(t||[]).filter(e=>ia(e,s))}}var oa={CONFIRM:`confirm`,CLARIFY:`clarify`},sa=new Map,ca=null,la=[];function ua(e,t){sa.set(e,t)}function da(e){if(ca===e){ma(e)||(ca=null,pa());return}if(ca===null){ca=e,ma(e)||(ca=null,pa());return}la.includes(e)||la.push(e),i.debug(`[SidePanel] interaction ${e} queued behind ${ca}`)}function fa(e){ca===e&&(ca=null,pa())}function pa(){for(;la.length>0;){let e=la.shift();if(ca=e,ma(e))return;ca=null}}function ma(e){let t=sa.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 ha(e){if(!ca||ca===e)return;let t=sa.get(ca);if(!(!t||typeof t.refresh!=`function`))try{t.refresh()}catch(t){i.error(`[SidePanel] refresh ${ca} hint for ${e} change failed:`,t?.message)}}function ga(e){let t=0;for(let[n,r]of sa){if(n===e)continue;let i=typeof r.pendingCount==`function`?r.pendingCount():0;t+=Number.isFinite(i)&&i>0?i:0}return t}function _a(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 va=oa.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 ya=[],z=null,ba=null,xa=!1;function Sa(e){return`${Math.floor(e/60)}:${(e%60).toString().padStart(2,`0`)}`}function Ca(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 wa(e,t){let n=document.getElementById(`clarifyTimer`),i=document.getElementById(`clarifyTimerText`);if(!n||!i)return;i.textContent=r(`clarify.remainingTimeDynamic`,{time:Sa(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:Sa(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&&Ca(`warning`)}function Ta(e){Ea(),C.clarifyTimeoutValue=e;let t=Math.ceil(e/1e3),n=t;wa(n,t),C.clarifyTimerInterval=setInterval(()=>{n--,n<=0?(Ea(),z&&_a(va,z)):wa(n,t)},1e3)}function Ea(){C.clarifyTimerInterval&&=(clearInterval(C.clarifyTimerInterval),null)}function Da(){let e=document.getElementById(`clarifyExtendBtn`);if(!e)return;let t=ba===0;e.disabled=t||xa,e.textContent=r(t?`clarify.extendLimit`:`clarify.extend`)}function Oa(){!z||xa||ba!==0&&(xa=!0,Da(),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(()=>{xa&&(xa=!1,Da())},3e3))}function ka(e){let t=e?.toolCallId;if(!(!z||z.toolCallId!==t)){if(xa=!1,e.denied||typeof e.remainingMs!=`number`){ba=0,Da(),F(r(`clarify.extendLimit`),`warning`);return}ba=typeof e.extendsLeft==`number`?e.extendsLeft:ba,Ta(e.remainingMs),Da(),F(r(`clarify.extended`),`success`),i.debug(`[SidePanel] clarify extended, remainingMs:`,e.remainingMs,`left:`,ba)}}function Aa(e){let t=ya.length,n=ga(va),i=e.question||``;return t>0&&(i+=` ${r(`dialog.pendingQueueClarify`,{count:t})}`),n>0&&(i+=` ${r(`dialog.otherPending`,{count:n})}`),i}function ja(){if(!z)return;let e=document.getElementById(`clarifyQuestion`);e&&(e.textContent=Aa(z))}function Ma(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=Aa(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
|
+
<div class="clarify-option-radio"></div>
|
|
56
|
+
<div class="clarify-option-content">${e}${n?`<span class="clarify-option-badge">${r(`clarify.recommended`)}</span>`:``}</div>
|
|
57
|
+
`,i.addEventListener(`click`,()=>Va(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
|
+
<div class="clarify-option-radio"></div>
|
|
59
|
+
<div class="clarify-option-content clarify-option-other">${r(`clarify.otherOption`)}</div>
|
|
60
|
+
`,e.addEventListener(`click`,()=>Va(-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`),ba=null,xa=!1,Da(),Ta(s),i.debug(`[SidePanel] clarification dialogshown:`,e.toolCallId,t),!0}function Na(){if(z)return!0;if(ya.length===0)return!1;let e=ya.shift();return Ma(e)?(z=e,_a(va,e),!0):(i.error(`[SidePanel] clarify overlay missing, settle as unanswered:`,e.toolCallId),Pa(e),F(r(`clarify.dropped`),`warning`),!1)}function Pa(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 Fa(){if(ya.length>0){da(va);return}Ia(),fa(va)}function Ia(){let e=document.getElementById(`clarifyOverlay`);e&&e.classList.remove(`show`),C.currentClarifyToolCallId=null,C.currentClarifySessionId=null,Ea()}function La(){z=null,Fa()}function Ra(e,t){return!!e.toolCallId&&e.toolCallId===t.toolCallId&&(e.sessionId||null)===(t.sessionId||null)&&e.question===t.question}function za(e){let t={...e,sessionId:e.sessionId||null};if(i.debug(`[SidePanel] showclarification dialog:`,t.toolCallId,e),z&&Ra(z,t)){i.debug(`[SidePanel] duplicate clarify request, ignored:`,t.toolCallId);return}if(ya.some(e=>Ra(e,t))){i.debug(`[SidePanel] queued duplicate clarify, ignored:`,t.toolCallId);return}ya.push(t),da(va),ja(),ha(va)}function Ba(){if(z){La();return}Ia()}function Va(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 Ha(){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),La()}function Ua(){if(z){let e={type:`CLARIFY_RESPONSE`,toolCallId:z.toolCallId,sessionId:z.sessionId,selectedOption:-1,customInput:``,additionalInfo:``};chrome.runtime.sendMessage(e)}Ba()}function Wa(e){return e?.reason===`timeout`&&e?.defaultOption||null}function Ga(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;Ka(Wa(e));return}if(z&&z.toolCallId===t){Ka(Wa(e));return}let n=ya.findIndex(e=>e.toolCallId===t);n>=0&&(i.debug(`[SidePanel] drop queued clarify (already settled by background):`,t),ya.splice(n,1),ja(),ha(va))}function Ka(e=null){let t=z?.question;La(),F(e?r(`clarify.timedOutDefaulted`,{option:e}):`${r(`clarify.timedOut`)}${t?`:${t}`:``}`,`warning`),Ca(`error`)}ua(va,{present:Na,pendingCount:()=>ya.length,refresh:ja});function qa(){let e=document.getElementById(`clarifyConfirmBtn`);e&&e.addEventListener(`click`,Ha);let t=document.getElementById(`clarifyCancelBtn`);t&&t.addEventListener(`click`,Ua);let n=document.getElementById(`clarifyExtendBtn`);n&&n.addEventListener(`click`,Oa);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),za(e.data),n({success:!0})):e.type===`PLAY_NOTIFICATION_SOUND`?(i.debug(`[SidePanel] recei to play soundrequested :`,e),Ca(e.soundType),n({success:!0})):e.type===`CLARIFY_TIMEOUT`?Ga(e):e.type===`CLARIFY_EXTENDED`&&ka(e)}),i.debug(`[SidePanel] clarification dialogeventinitializing`)}var Ja=oa.CONFIRM,Ya=[],Xa=null,Za=null,Qa=null;function $a(e){let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`}function eo(){Za&&=(clearInterval(Za),null),Qa&&=(clearTimeout(Qa),null)}function to(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 no(e){let t=e.message||r(`dialog.confirmAction`,{name:e.toolLabel||e.toolName}),n=Ya.length,i=ga(Ja),a=t;return n>0&&(a+=` ${r(`dialog.pendingQueue`,{count:n})}`),i>0&&(a+=` ${r(`dialog.otherPending`,{count:i})}`),a}function ro(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=no(e)),eo();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:$a(p)}),Za=setInterval(()=>{if(p--,p<=0){clearInterval(Za),Za=null,m.textContent=r(`dialog.remainingTime`,{time:`0:00`});return}m.textContent=r(`dialog.remainingTime`,{time:$a(p)}),p<=30&&h.classList.add(`warning`)},1e3)),s.style.display=`flex`,Qa=setTimeout(()=>{i.debug(`[SidePanel] confirm dialogtimeout,autodeny`),lo(!1,`single`)},o),!0}function io(){if(Xa)return!0;if(Ya.length===0)return!1;let e=Ya.shift();return ro(e)?(Xa=e,_a(Ja,e),!0):(e.resolve&&e.resolve(!1),!1)}function ao(){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(Ya.length>0){da(Ja);return}ao(),fa(Ja)}function so(e){let t=Xa?.resolve;Xa=null,eo(),t&&t(e),oo()}function co(e){let t={...e,sessionId:e.sessionId||null};return i.debug(`[SidePanel] showconfirm dialog:`,t.toolName,e),Xa&&to(Xa,t)?(i.debug(`[SidePanel] duplicate confirm request, ignored:`,t.toolCallId),Promise.resolve(!1)):Ya.some(e=>to(e,t))?(i.debug(`[SidePanel] queued duplicate confirm, ignored:`,t.toolCallId),Promise.resolve(!1)):new Promise(e=>{Ya.push({...t,resolve:e}),da(Ja),Xa&&uo(),ha(Ja)})}function lo(e,t=`single`){if(!Xa)return;let n=Xa.toolCallId,r=Xa.sessionId;eo(),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)}),so(e)}function uo(){if(!Xa)return;let e=document.getElementById(`confirmMessage`);e&&(e.textContent=no(Xa))}function fo(e){let t=e?.toolCallId;if(!t)return;if(Xa&&Xa.toolCallId===t){i.debug(`[SidePanel] dismiss active confirm dialog (already settled by background):`,t),so(!1);return}let n=Ya.findIndex(e=>e.toolCallId===t);if(n>=0){i.debug(`[SidePanel] drop queued confirm dialog (already settled by background):`,t);let[e]=Ya.splice(n,1);e.resolve&&e.resolve(!1),uo(),ha(Ja)}}ua(Ja,{present:io,pendingCount:()=>Ya.length,refresh:()=>{Xa&&uo()}});function po(){let e=document.getElementById(`confirmApproveOnceBtn`),t=document.getElementById(`confirmApproveLoopBtn`),n=document.getElementById(`confirmDenyBtn`);e&&e.addEventListener(`click`,()=>lo(!0,`single`)),t&&t.addEventListener(`click`,()=>{lo(!0,Xa?.variant===`network`?`whitelist`:`loop`)}),n&&n.addEventListener(`click`,()=>lo(!1,`single`)),chrome.runtime.onMessage.addListener((e,t,n)=>e.type===`SHOW_CONFIRM_DIALOG`?(co(e.data),n({received:!0}),!1):e.type===`DISMISS_CONFIRM_DIALOG`?(fo(e.data),n({received:!0}),!1):!1)}var mo=t({closeCurrentSession:()=>ac,handleDuplicateSession:()=>Xs,handleSessionSwitch:()=>Ys,newSession:()=>xo,renderSessionTabs:()=>yo});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:[]},ho={draggedId:null,sourceType:null};function go(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 _o(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 vo(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 yo(e=null){let t=e||await ti({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){Jo(await qo(e.id)),await ic();return}tc(e,async()=>{await ic()})}),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=fr(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&&!Gs){Gs=!0,i.querySelectorAll(`.session-tab.active`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`);try{await Ys(e.id)}finally{Gs=!1,C.activeSessionId!==e.id&&yo({list:C.sessions,activeSessionId:C.activeSessionId})}}}),t.addEventListener(`contextmenu`,t=>{t.preventDefault(),nc(t,e)}),t.addEventListener(`mousedown`,async t=>{t.button===1&&(t.preventDefault(),t.stopPropagation(),Jo(await qo(e.id)),await ic())}),t.draggable=!0,t.addEventListener(`dragstart`,t=>Ao(t,e.id)),t.addEventListener(`dragover`,e=>jo(e)),t.addEventListener(`dragleave`,e=>Mo(e)),t.addEventListener(`drop`,t=>No(t,e.id)),t.addEventListener(`dragend`,e=>Po(e)),i.appendChild(t)}),bo(),So(),Qo(),Ws(),$s(i),To(i),Eo(i),ko(i),Cs(),As())}function bo(){let e=document.getElementById(`sessionTabsMore`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,e=>{e.stopPropagation(),vs()})}async function xo(){let e=C.activeSessionId;await ni();let t=await ai();C.activeSessionId=t.id,C.messageHistory=[],C.activeCompaction=null,ri(t),document.dispatchEvent(new CustomEvent(`session-switched`,{detail:{sessionId:t.id,previousSessionId:e}})),yo()}function So(){let e=document.getElementById(`sessionTabsAdd`);if(!e)return;let t=e.cloneNode(!0);e.parentNode.replaceChild(t,e),t.addEventListener(`click`,()=>xo())}var Co=0,wo=0;function To(e){let t=document.getElementById(`sessionTabsMore`);if(!t)return;if(!fs()){t.style.display=`none`;return}let n=e.scrollWidth>e.clientWidth;t.style.display=n||Co>0?`flex`:`none`}async function Eo(e){let t=++wo,n;try{n=await di()}catch{return}t===wo&&(Co=n.length,To(e))}var Do=null;function Oo(){if(Do)return;let e=document.getElementById(`sessionTabsScroll`);e&&(Do=new ResizeObserver(()=>{requestAnimationFrame(()=>{To(e)})}),Do.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 Ao(e,t){ho.draggedId=t,ho.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 Mo(e){e.currentTarget.classList.remove(`drag-over`)}async function No(e,t){e.preventDefault(),e.currentTarget.classList.remove(`drag-over`);let n=ho.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 li(o.map(e=>e.id)),yo()}function Po(e){e.currentTarget.classList.remove(`dragging`),document.querySelectorAll(`.session-tab.drag-over`).forEach(e=>e.classList.remove(`drag-over`)),ho.draggedId=null,ho.sourceType=null}function Fo(){B.visible?Lo():Io()}async function Io(){let e=document.getElementById(`sessionTabsMore`),t=document.getElementById(`sessionDropdown`);if(!e||!t)return;let n=await ti();C.sessions=n.list,C.activeSessionId=n.activeSessionId,B.filteredSessions=_o([...n.list]),B.highlightIndex=-1,B.visible=!0,Is(),zo(),t.classList.add(`show`);let r=document.getElementById(`sessionDropdownCloseBtn`);r&&(r.onclick=()=>Lo());let i=document.getElementById(`sessionDropdownSearch`),a=document.getElementById(`sessionDropdownSearchClear`);i&&(i.value=B.lastSearchText||``,Ro(),B.lastSearchText&&Go(B.lastSearchText),setTimeout(()=>i.focus(),50),i.oninput=()=>{B.lastSearchText=i.value,Ro(),Go(i.value)},i.onkeydown=e=>{$o(e)}),a&&(a.onclick=()=>{i&&(i.value=``,B.lastSearchText=``,Ro(),Go(``),i.focus())}),e.classList.add(`active`)}function Lo(){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 Ro(){let e=document.getElementById(`sessionDropdownSearch`),t=document.getElementById(`sessionDropdownSearchClear`);t&&e&&(t.style.display=e.value?`flex`:`none`)}function zo(){Bo({listEl:document.getElementById(`sessionDropdownList`),filteredSessions:B.filteredSessions,highlightIndex:B.highlightIndex,onSelect:e=>Ko(e)})}function Bo({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=vo(e.updatedAt);c[t]=(c[t]||0)+1});let l=null;t.forEach((t,u)=>{if(a){let n=vo(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(),Zo(n,s[n]||n)},t.appendChild(e)}e.appendChild(t)}}let d=Wo(t,{index:u,highlightIndex:n,onSelect:i});o&&Ho(d,t.id),e.appendChild(d)})}var Vo=null;function Ho(e,t){e.draggable=!0,e.classList.add(`draggable`),e.addEventListener(`dragstart`,n=>{Vo=t,n.dataTransfer.effectAllowed=`move`,n.dataTransfer.setData(`text/plain`,t),e.classList.add(`dragging`)}),e.addEventListener(`dragover`,n=>{!Vo||Vo===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`),Uo(Vo,t)}),e.addEventListener(`dragend`,()=>{e.classList.remove(`dragging`),document.querySelectorAll(`.session-dropdown-item.drag-over`).forEach(e=>e.classList.remove(`drag-over`)),Vo=null})}async function Uo(e,t){let n=e;if(Vo=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 li(o.map(e=>e.id)),await yo()}function Wo(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=fr(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=go(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(),ec(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 Xs(e.id);let n=await ti({withActiveHistory:!1});C.sessions=n.list,C.activeSessionId=n.activeSessionId,Go(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 Ps(e.id),Go(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 Yo(e.id)}),d.appendChild(h),a.appendChild(d),a.addEventListener(`click`,async t=>{t.preventDefault(),await i(e.id)}),a}function Go(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=_o(n),B.highlightIndex=-1,zo()}async function Ko(e){Lo(),e!==C.activeSessionId&&await Ys(e)}async function qo(e){let t=fr(e)+ur(e).length;return await si(e),t}function Jo(e){e<=0||F(r(`queue.sessionDropped`,{count:e}),`info`,3e3)}async function Yo(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`))||(Jo(await qo(e)),await ic(),Go(document.getElementById(`sessionDropdownSearch`)?.value||``)))}async function Xo(){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 qo(n.id);Jo(t),await ic(),Go(document.getElementById(`sessionDropdownSearch`)?.value||``)}async function Zo(e,t){let n=(C.sessions||[]).filter(t=>vo(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 qo(e.id);Jo(i),await ic(),Go(document.getElementById(`sessionDropdownSearch`)?.value||``)}function Qo(){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 Xo()})}t.addEventListener(`click`,e=>{e.stopPropagation()})}}function $o(e){if(!B.visible)return;let t=B.filteredSessions.length;if(t===0){e.key===`Escape`&&Lo();return}switch(e.key){case`ArrowDown`:e.preventDefault(),B.highlightIndex=Math.min(B.highlightIndex+1,t-1),zo(),es(document.getElementById(`sessionDropdownList`));break;case`ArrowUp`:e.preventDefault(),B.highlightIndex=Math.max(B.highlightIndex-1,0),zo(),es(document.getElementById(`sessionDropdownList`));break;case`Enter`:if(e.preventDefault(),B.highlightIndex>=0&&B.highlightIndex<t){let e=B.filteredSessions[B.highlightIndex];Ko(e.id)}break;case`Escape`:e.preventDefault(),Lo();break}}function es(e){let t=(e||document).querySelector(`.session-dropdown-item.highlighted`);t&&t.scrollIntoView({block:`nearest`})}var ts=560,ns=200,rs=480,is=360,as=240,os=`sessionSidebarExpanded`,ss=`sessionSidebarWidth`,cs=`sessionSidebarSortMode`,ls=`manual`,us=`recent`,V={expanded:!1,width:as,sortMode:ls,narrow:!1,pendingRestore:!1,highlightIndex:-1,filteredSessions:[],inited:!1,lastActiveId:null};function ds(e){let t=document.getElementById(`mainRow`),n=t?Math.max(ns,t.clientWidth-is):rs;return Math.max(ns,Math.min(e,rs,n))}function fs(){let e=document.getElementById(`mainRow`);return e?e.clientWidth<ts:!0}function ps(){let e=document.getElementById(`sessionSidebar`);if(!e)return;V.narrow=fs(),e.classList.toggle(`sidebar-hidden`,V.narrow),e.classList.toggle(`expanded`,!V.narrow&&V.expanded),e.style.setProperty(`--session-sidebar-width`,`${V.width}px`),ms();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 ms(){let e=!V.narrow&&V.expanded?V.width:0;document.body.style.setProperty(`--session-sidebar-offset`,`${e}px`)}async function hs(){try{await chrome.storage.local.set({[os]:V.expanded,[ss]:V.width,[cs]:V.sortMode})}catch{}}function gs(){fs()||(V.expanded=!0,ps(),hs(),Cs())}function _s(){V.expanded=!1,ps(),hs()}function vs(){if(fs()){Fo();return}V.expanded?_s():gs()}function ys(){let e=document.getElementById(`sessionSidebarList`),t=V.sortMode===us,n=!!(document.getElementById(`sessionSidebarSearch`)?.value||``).trim();Bo({listEl:e,filteredSessions:V.filteredSessions,highlightIndex:V.highlightIndex,onSelect:e=>ws(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 bs(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===us?_o(n):n.reverse(),V.highlightIndex=-1,ys()}function xs(){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 Ss(e){e!==ls&&e!==us||V.sortMode!==e&&(V.sortMode=e,xs(),V.lastActiveId=null,bs(document.getElementById(`sessionSidebarSearch`)?.value||``),hs())}function Cs(){let e=document.getElementById(`sessionSidebar`);!e||!e.classList.contains(`expanded`)||bs(document.getElementById(`sessionSidebarSearch`)?.value||``)}async function ws(e){e!==C.activeSessionId&&await Ys(e)}function Ts(e){let t=V.filteredSessions,n=t.length;if(n===0){e.key===`Escape`&&_s();return}switch(e.key){case`ArrowDown`:e.preventDefault(),V.highlightIndex=Math.min(V.highlightIndex+1,n-1),ys(),es(document.getElementById(`sessionSidebarList`));break;case`ArrowUp`:e.preventDefault(),V.highlightIndex=Math.max(V.highlightIndex-1,0),ys(),es(document.getElementById(`sessionSidebarList`));break;case`Enter`:e.preventDefault(),V.highlightIndex>=0&&V.highlightIndex<n&&ws(t[V.highlightIndex].id);break;case`Escape`:e.preventDefault(),_s();break}}function Es(){let e=document.getElementById(`sessionSidebarSearch`),t=document.getElementById(`sessionSidebarSearchClear`);t&&e&&(t.style.display=e.value?`flex`:`none`)}function Ds(){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=ds(r+(t.clientX-n));V.width=i,e.style.setProperty(`--session-sidebar-width`,`${i}px`),ms()}function a(){document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),e.classList.remove(`resizing`),hs()}document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)})}function Os(){let e=document.getElementById(`mainRow`);!e||typeof ResizeObserver>`u`||new ResizeObserver(()=>{requestAnimationFrame(()=>{let e=fs();e!==V.narrow&&(e&&V.expanded?V.pendingRestore=!0:!e&&V.pendingRestore&&(V.pendingRestore=!1),ps(),!e&&V.expanded&&Cs())})}).observe(e)}function ks(){fs()?Io():gs()}async function As(){if(V.inited||!document.getElementById(`sessionSidebar`))return;V.inited=!0;try{let e=await chrome.storage.local.get([os,ss,cs]);V.expanded=e[os]===!0,typeof e[ss]==`number`&&(V.width=ds(e[ss])),(e[cs]===us||e[cs]===ls)&&(V.sortMode=e[cs])}catch{}xs(),fs()&&V.expanded&&(V.pendingRestore=!0),ps(),Cs(),document.getElementById(`sessionSidebarToggle`)?.addEventListener(`click`,()=>vs()),document.getElementById(`sessionSidebarAdd`)?.addEventListener(`click`,()=>{xo()}),document.getElementById(`sessionSidebarCollapse`)?.addEventListener(`click`,()=>_s()),document.querySelectorAll(`.session-sidebar-sort-btn`).forEach(e=>{e.addEventListener(`click`,()=>Ss(e.dataset.mode))}),document.getElementById(`sessionSidebarArchiveEntry`)?.addEventListener(`click`,()=>{Ls()}),document.getElementById(`sessionSidebarCloseAll`)?.addEventListener(`click`,async e=>{e.stopPropagation(),await Xo()});let e=document.getElementById(`sessionSidebarSearch`),t=document.getElementById(`sessionSidebarSearchClear`);e&&(e.addEventListener(`input`,()=>{Es(),bs(e.value)}),e.addEventListener(`keydown`,e=>{Ts(e)})),t&&t.addEventListener(`click`,()=>{e&&(e.value=``,Es(),bs(``),e.focus())}),Ds(),Os(),Is()}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 Ms=``,Ns=!1;async function Ps(e){if(!e)return;let t=fi(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 pi(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 Fs(e);else{let e=await ti();C.sessions=e.list,yo(e)}await Is(),F(r(`session.archived`),`info`)}async function Fs(e){let t=_o([...(await ti()).list]).filter(t=>t.id!==e);if(t.length>0){await Ys(t[0].id);return}await ai(),await ic()}async function Is(){let e=[`sessionArchiveEntryLabel`,`sessionSidebarArchiveLabel`].map(e=>document.getElementById(e));if(!e.some(Boolean))return;Co=(await di()).length;let t=document.getElementById(`sessionTabsScroll`);t&&To(t);let n=r(`session.archiveEntry`);e.forEach(e=>{e&&(e.textContent=n)})}async function Ls(){let e=document.getElementById(`sessionArchivePanel`);if(!e)return;Ws(),Ms=``;let t=document.getElementById(`sessionArchiveSearch`);t&&(t.value=``),zs(),await Bs(),e.classList.add(`show`),Lo()}function Rs(){let e=document.getElementById(`sessionArchivePanel`);e&&e.classList.remove(`show`)}function zs(){let e=document.getElementById(`sessionArchiveSearchClear`);e&&(e.style.display=Ms?`flex`:`none`)}async function Bs(){let e=document.getElementById(`sessionArchiveList`);if(!e)return;let t=await di(),n=Ms.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=vo(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(Vs(t))})}function Vs(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:go(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 Hs(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 Us(e)}),o.appendChild(c),t.appendChild(o),t.addEventListener(`click`,async()=>{await Hs(e.id,{enter:!0})}),t}async function Hs(e,{enter:t=!1}={}){if(!await mi(e)){F(r(`session.operationFailed`,{message:`not found`}),`error`),await Bs();return}let n=await ti();C.sessions=n.list;let i=n.list.find(t=>t.id===e)?.title||r(`session.newSession`);Rs(),await Bs(),await Is(),t?await Ys(e):yo(n),F(r(`session.archivedRestored`,{title:i}),`success`)}async function Us(e){let t=e.title||r(`session.newSession`);await js(r(`session.confirmDeleteForeverMessage`,{title:t}),r(`session.confirmDeleteForeverTitle`))&&(await hi(e.id),await Bs(),await Is(),document.dispatchEvent(new CustomEvent(`session-deleted`,{detail:{sessionId:e.id}})),F(r(`session.archiveDeleted`,{title:t}),`success`))}function Ws(){if(Ns)return;let e=document.getElementById(`sessionArchivePanel`),t=document.getElementById(`sessionArchiveEntry`);if(!e||!t)return;Ns=!0,t.addEventListener(`click`,()=>{Ls()});let n=document.getElementById(`sessionArchiveBackBtn`);n&&n.addEventListener(`click`,()=>{Rs(),ks()});let r=document.getElementById(`sessionArchiveCloseBtn`);r&&r.addEventListener(`click`,()=>Rs());let i=document.getElementById(`sessionArchiveSearch`),a=document.getElementById(`sessionArchiveSearchClear`);i&&(i.addEventListener(`input`,()=>{Ms=i.value,zs(),Bs()}),i.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.stopPropagation(),Rs(),ks())})),a&&a.addEventListener(`click`,()=>{i&&(i.value=``,Ms=``,zs(),Bs(),i.focus())}),document.addEventListener(`session-archived`,()=>{e.classList.contains(`show`)&&Bs()}),document.addEventListener(`session-deleted`,()=>{e.classList.contains(`show`)&&Bs()})}var Gs=!1,Ks=500;function qs(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(()=>yS);return{updateScrollButtonState:e}},void 0).then(({updateScrollButtonState:e})=>e()).catch(()=>{})})}function Js(e,t){setTimeout(()=>{C.activeSessionId===e&&(Fe(t)||qs(e))},Ks)}async function Ys(e,{focusMessageId:t=null}={}){let n=C.activeSessionId;if(!await oi(e))return;let r=`agentEnabledTools_${C.activeAgentId||`default`}`,i=`agentMcpClosedServers_${C.activeAgentId||`default`}`,[a,o,s,c]=await Promise.all([ti(),chrome.storage.local.get([i,`ragTools`,`ragToolsIntroduced`]),chrome.storage.local.get([r,`enabledTools`]),C.activeAgentId?ft(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=ta(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=ea(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=ea(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}:{}}})),ei(e),yo(a),Zs(),OT();try{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await A(async()=>{let{refreshBookmarkPanel:e,updateBookmarkButtons:t}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e,updateBookmarkButtons:t}},void 0);e(),setTimeout(()=>t(),100)}catch{}let p=document.getElementById(`toolsPopupOverlay`);p&&p.classList.contains(`show`)&&(Bi(),Ji(),Yi()),Qi(),t&&Js(e,t)}async function Xs(e,t=null){if(e)try{let n=await vi(e,t);await Ys(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 Zs(){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 Qs=new WeakSet;function $s(e){Qs.has(e)||(Qs.add(e),e.addEventListener(`wheel`,t=>{e.scrollWidth<=e.clientWidth||(t.preventDefault(),e.scrollLeft+=t.deltaY)},{passive:!1}))}function ec(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 ci(e.id,t),yo();let n=await ti();C.sessions=n.list,C.activeSessionId=n.activeSessionId,Go(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 tc(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()=>{Jo(await qo(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 nc(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=rc(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(),ec(t)});i.appendChild(a);let o=rc(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(),Xs(t.id)});i.appendChild(o);let s=rc(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 Ps(t.id)});i.appendChild(s);let c=rc(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){Jo(await qo(t.id)),await ic();return}tc(t,async()=>{await ic()})},`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 rc(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 ic(){let e=C.activeSessionId,t=await ti();t.activeSessionId||(await ai(),t=await ti()),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,ri(n),C.activeAgentId=n&&n.agentId||null,C.activeAgentId){let e=await ft(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}})),yo(),await OT()}async function ac(){let e=C.activeSessionId;if(!e)return;let t=C.sessions?.find(t=>t.id===e);if(t){if((C.messageHistory?.length||0)===0){Jo(await qo(e)),await ic();return}tc(t,async()=>{await ic()})}}document.addEventListener(`generating-state-changed`,()=>{yo()}),document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{Oo(),As()}):(Oo(),As()),[`<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 oc=`<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>`,sc=`<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>`,cc=`<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>`,lc=`<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>`,uc=`<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>`,dc=`<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 fc=null,pc=1,mc=.25,hc=2,gc=.1;function _c(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
|
+
<html>
|
|
62
|
+
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
|
|
63
|
+
<body style="margin:0;padding:0;overflow:auto;">${t}</body>
|
|
64
|
+
</html>`}function vc(e){i.debug(`[SidePanel] show UI prototype preview:`,e),fc=e,Rc();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=_c(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 yc(){let e=document.getElementById(`prototypeOverlay`);e&&e.classList.remove(`show`);let t=document.getElementById(`prototypeIframe`);t&&(t.srcdoc=``),fc=null,i.debug(`[SidePanel] UI prototype previewpopuphidden`)}function bc(){if(!fc)return;let e=fc.id,t=fc.title||r(`uiProto.defaultTitle`);yc();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 xc(){if(!fc||!fc.html){i.error(`[SidePanel] no downloadable prototype`);return}let e=_c(fc.html),t=new Blob([e],{type:`text/html`}),n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=(fc.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 Sc(){if(!fc||!fc.html){i.error(`[SidePanel] no has can open prototype`);return}let e=_c(fc.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 Cc(e){try{let t=await D(e);if(!t){i.error(`[SidePanel] not foundprototype:`,e);return}vc(t)}catch(e){i.error(`[SidePanel] load prototype failed:`,e)}}async function wc(e){try{let t=await D(e);if(!t){i.error(`[SidePanel] not foundprototype (autoopen):`,e);return}fc=t,Sc(),i.debug(`[SidePanel] prototype inbrowserlabelpageautoopen:`,t.title)}catch(e){i.error(`[SidePanel] autoopenprototype failed:`,e)}}async function Tc(){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();Ec(e),Dc(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 Ec(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
|
+
<div class="prototype-library-item" data-id="${e.id}">
|
|
66
|
+
<div class="prototype-library-item-info">
|
|
67
|
+
<div class="prototype-library-item-title" title="${Nc(e.title)}">${Nc(e.title)}</div>
|
|
68
|
+
${e.description?`<div class="prototype-library-item-desc" title="${Nc(e.description)}">${Nc(e.description)}</div>`:`<div class="prototype-library-item-desc prototype-library-item-desc-empty">${r(`uiProto.noDescription`)}</div>`}
|
|
69
|
+
<div class="prototype-library-item-meta">
|
|
70
|
+
<span class="prototype-library-item-id">ID: ${t}</span>
|
|
71
|
+
<span class="prototype-library-item-time">${Pc(e.createdAt)}</span>
|
|
72
|
+
</div>
|
|
73
|
+
</div>
|
|
74
|
+
<div class="prototype-library-item-actions">
|
|
75
|
+
<button class="prototype-library-item-open" title="${r(`uiProto.previewInPanel`)}">
|
|
76
|
+
${sc}
|
|
77
|
+
</button>
|
|
78
|
+
${e.localPath?`
|
|
79
|
+
<button class="prototype-library-item-local-open" data-path="${Nc(e.localPath)}" title="${r(`prototype.openLocal`)}">
|
|
80
|
+
${cc}
|
|
81
|
+
</button>
|
|
82
|
+
`:``}
|
|
83
|
+
<button class="prototype-library-item-optimize" data-id="${e.id}" title="${r(`uiProto.continueOptimizeTitle`)}">
|
|
84
|
+
${lc}
|
|
85
|
+
</button>
|
|
86
|
+
<button class="prototype-library-item-delete" data-id="${e.id}" title="${r(`common.delete`)}">
|
|
87
|
+
${uc}
|
|
88
|
+
</button>
|
|
89
|
+
<button class="prototype-library-item-download" data-id="${e.id}" title="${r(`uiProto.downloadPrototype`)}">
|
|
90
|
+
${dc}
|
|
91
|
+
</button>
|
|
92
|
+
</div>
|
|
93
|
+
</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;Cc(t)}),n&&n.addEventListener(`click`,t=>{t.stopPropagation();let n=e.dataset.id;Cc(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`)),Oc()}),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;Ac(t)})})))}function Dc(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}),Ec(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 Oc(){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 Ac(e){try{let t=await D(e);if(!t||!t.html){i.error(`[SidePanel] download prototype failed:not foundprototype`,e);return}let n=_c(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 Mc(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)}),Tc()}catch(e){i.error(`[SidePanel] delete prototype failed:`,e),alert(r(`uiProto.deleteFailed`,{message:e.message}))}}function Mc(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 Nc(e){let t=document.createElement(`div`);return t.textContent=e,t.innerHTML}function Pc(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 Fc(e){pc=Math.max(mc,Math.min(hc,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 Ic(){Fc(pc+gc),zc()}function Lc(){Fc(pc-gc),zc()}function Rc(){Fc(1)}function zc(){let e=document.getElementById(`prototypeZoomLevel`);e&&(e.classList.add(`flash`),setTimeout(()=>e.classList.remove(`flash`),150))}function Bc(e){!e.ctrlKey&&!e.metaKey||(e.preventDefault(),e.deltaY<0?Ic():Lc())}function Vc(e){(e.ctrlKey||e.metaKey)&&e.key===`0`&&(e.preventDefault(),Rc())}function Hc(){let e=document.getElementById(`prototypeCloseBtn`);e&&e.addEventListener(`click`,yc);let t=document.getElementById(`prototypeDownloadBtn`);t&&t.addEventListener(`click`,xc);let n=document.getElementById(`prototypeOpenTabBtn`);n&&n.addEventListener(`click`,Sc);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`,bc);let o=document.getElementById(`prototypeZoomInBtn`);o&&o.addEventListener(`click`,Ic);let s=document.getElementById(`prototypeZoomOutBtn`);s&&s.addEventListener(`click`,Lc);let c=document.getElementById(`prototypeZoomLevel`);c&&c.addEventListener(`click`,Rc);let l=document.getElementById(`prototypeContent`);l&&l.addEventListener(`wheel`,Bc,{passive:!1}),document.addEventListener(`keydown`,Vc);let u=document.getElementById(`prototypeLibraryCloseBtn`);u&&u.addEventListener(`click`,Oc),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`),wc(e.data.prototypeId)):Cc(e.data.prototypeId),n({success:!0}))}),i.debug(`[SidePanel] UI prototype moduleeventinitializing`)}var Uc={enabled:!1,thresholdRatio:.85,minPending:4,maxFailures:2};function Wc(e,t){let n=Number(e);return Number.isFinite(n)&&n>0&&n<=1?n:t}function Gc(e,t){let n=Number(e);return Number.isFinite(n)&&n>=0?Math.floor(n):t}function Kc({enabled:e,ratio:t,thresholdRatio:n,pendingCount:r,minPending:i,isGenerating:a,isolateChat:o}={}){if(!e||a||!o)return!1;let s=Wc(n,Uc.thresholdRatio),c=Gc(i,Uc.minPending);return!Number.isFinite(t)||t<s?!1:Gc(r,0)>=c}function qc(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 Jc=0;function Yc(){Jc=0}async function Xc({state:e,getRatio:t,compact:n}={}){let r=e?.chatConfig||{},a=r.autoCompaction===!0;if(!a)return{attempted:!1,success:!1,reason:`disabled`};if(Jc>=Uc.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=qc(e);if(!Kc({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),Jc++,{attempted:!0,success:!1,reason:`exception`}}return c?.success?(Yc(),{attempted:!0,success:!0}):(Jc++,i.debug(`[AutoCompaction] skipped send:`,c?.reason),{attempted:!0,success:!1,reason:c?.reason||`failed`})}var Zc=null,Qc=`global`,$c=new Map;function el(){try{chrome.windows?.getCurrent?.().then?.(e=>{e?.id!=null&&(Zc=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=>{Qc=e?.sidePanelScope===`tab-specific`?`tab-specific`:`global`}),chrome.storage?.onChanged?.addListener?.((e,t)=>{t!==`local`||!e?.sidePanelScope||(Qc=e.sidePanelScope.newValue===`tab-specific`?`tab-specific`:`global`)})}catch(e){i.debug(`[PanelContext] init scope mirror failed:`,e?.message)}}function tl(){return Zc}function nl(e){e&&typeof C.currentTabId==`number`&&$c.set(e,C.currentTabId)}function rl(e,t){e&&(typeof t==`number`?$c.set(e,t):$c.delete(e))}function il(e){if(!e)return null;let t=$c.get(e);return typeof t==`number`?t:null}function al(e){let t=null;try{t=typeof document<`u`?!!document.hidden:null}catch{}return{windowId:Zc,hostTabId:il(e),scope:Qc,panelHidden:t}}var ol=0,sl=500,cl=[{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}],ll=[{frequency:440,startTime:0,duration:.16,type:`square`,gain:.22},{frequency:349.23,startTime:.14,duration:.3,type:`square`,gain:.22}],ul=[`#FF3B30`,`#FF9500`,`#FFCC00`,`#34C759`,`#00C7BE`,`#007AFF`,`#AF52DE`,`#FF2D55`],dl=120,fl=4e3,pl=600,ml=1e3,hl=.25,gl=.99,_l=.3,vl=.6,yl=9999;function bl(){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 xl(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 Sl(){xl(cl),i.debug(`[CompletionFeedback] success sound played`)}function Cl(){xl(ll),i.debug(`[CompletionFeedback] failure sound played`)}function wl(){try{return typeof window.matchMedia==`function`&&window.matchMedia(`(prefers-reduced-motion: reduce)`).matches}catch{return!1}}function Tl(){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:${yl};`;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+_l},{x:e*.85,y:t+10,baseAngle:-Math.PI/2-_l}],s=[],c=0,l=0,u=performance.now(),d=e=>{let t=Math.min(dl,Math.floor(Math.min(e,pl)/pl*dl));for(;c<t;){let e=o[c%o.length],t=e.baseAngle+(Math.random()-.5)*vl,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:ul[Math.floor(Math.random()*ul.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>=fl){cancelAnimationFrame(l),n.remove();return}d(i),a.clearRect(0,0,e,t);let o=fl-ml,c=i>o?Math.max(0,1-(i-o)/ml):1;for(let n=s.length-1;n>=0;n--){let r=s[n];if(r.vy+=hl,r.vx*=gl,r.vy*=gl,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 El(e,t,n,r){try{chrome.runtime.sendMessage({type:`TASK_FEEDBACK_NOTIFY`,success:e,sessionId:t||null,error:n||``,question:r||``,panel:al(t)})?.catch?.(()=>{})}catch(e){i.debug(`[CompletionFeedback] desktop notify failed:`,e?.message)}}async function Dl(e=null,t=``){try{let n=Date.now();if(n-ol<sl){i.debug(`[CompletionFeedback] throttled, skip`);return}ol=n;let{soundEnabled:r,confettiEnabled:a}=await bl();r&&Sl(),a&&!wl()&&Tl(),El(!0,e,``,t)}catch(e){i.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}async function Ol(e=null,t=``,n=``){try{let r=Date.now();if(r-ol<sl){i.debug(`[CompletionFeedback] throttled, skip`);return}ol=r;let{soundEnabled:a}=await bl();a&&Cl(),El(!1,e,t,n)}catch(e){i.debug(`[CompletionFeedback] unexpected error:`,e?.message||e)}}var kl=new Set;function Al(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{$r(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 Ml(e){let t=Number(e);return!Number.isFinite(t)||t<=0?3:Math.min(20,Math.max(1,Math.round(t)))}function Nl(){return{callId:null,carried:0,lastIteration:null}}function Pl(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 Fl(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}:Nl(),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=Nl()),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=Ml(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 Il(e,{callId:t=null}={}){let n=e&&typeof e==`object`?e:Nl();return t&&n.callId&&t!==n.callId?n:{...n,carried:(Number(n.carried)||0)+1}}var Ll=/[\p{P}\p{S}]/gu;function Rl(e){return Array.isArray(e)?e.map(e=>e&&e.text||``).join(``):``}function zl(e){return String(e||``).replace(/[\s\u3000]/g,``).replace(Ll,``)}function Bl(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 Vl(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 Hl(e,t){if(!Array.isArray(e)||e.length===0)return{items:Array.isArray(e)?e:[],changed:0,takeAll:!1};let n=Rl(e),r=String(t||``);if(!r)return{items:e,changed:0,takeAll:!1};let i=zl(n),a=zl(r);if(i===a)return{items:e,changed:0,takeAll:!1};if(Math.abs(i.length-a.length)+Ul(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++)zl(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 Ul(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 Wl=15e3,Gl=16e3,Kl=2500,ql=.008,Jl=350,Yl=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:{...Ae},shortcutTrigger:null,shortcutBound:!1,deviceFellBack:!1};function Xl(e){return typeof e==`string`?e:``}function Zl(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 Ql(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 $l(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 eu(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 tu(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 nu(e){return!e||e.success===!1?!1:typeof e.available==`boolean`?e.available:e.deps?.ready===!0&&e.modelsReady===!0&&e.enabled===!0}function ru({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 iu({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 au(e){return!e||e.isComposing||e.repeat?!1:e.altKey===!0&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&e.code===`KeyV`}async function ou(){return H.armed=nu(await tu()),H.btn&&(H.btn.style.display=H.armed?``:`none`),!H.armed&&H.phase!==`idle`&&Lu({rollback:!0}),H.armed}function su(){if(!H.draft||!H.input)return;let e=Rl(H.draft.items),t=H.input.value,n=Xl(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=Vl(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 cu(){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 lu(e,t){let n=Xl(e),r=Xl(t);return r?n?r.startsWith(n)?r.slice(n.length):null:r:``}function uu(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 du(e=!1){let t=H.input;if(!t||!H.draft)return;let n=Rl(H.draft.items);if(!e&&n===Xl(H.appliedText))return;let r=typeof t.selectionStart==`number`?t.selectionStart:void 0,i=H.draft.start,a=i+H.draft.len,o=ru({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,uu(o.value,o.caret)}function fu(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=Xl(e);if(n>=0&&t[n].state===`locked`){let e=lu(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`}]);du()}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}:iu({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 mu(){if(H.wave){H.wave.textContent=``,H.barEls=[];for(let e=0;e<Yl;e++){let e=document.createElement(`i`);H.wave.appendChild(e),H.barEls.push(e)}}}function hu(e,t=``){H.statusEl&&(H.statusEl.textContent=e,H.statusEl.className=`voice-recorder-status`+(t?` is-${t}`:``))}function gu(){H.bar&&(H.bar.classList.add(`show`),H.bar.removeAttribute(`aria-hidden`))}function _u(e){H.permBtn&&(H.permBtn.style.display=e?``:`none`)}function vu(){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 yu(){H.bar&&(typeof document>`u`||!document.body||(vu(),_u(!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 bu(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 xu(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 Su(e){document.body?.classList.toggle(`voice-recording-active`,!!e)}function Cu(){if(H.port)return H.port;try{let e=chrome.runtime.connect({name:`asr`});return e.onMessage.addListener(zu),e.onDisconnect.addListener(()=>{H.port=null,(H.phase===`recording`||H.phase===`finalizing`)&&(Mu(),Nu(),H.draft=null,H.lastText=``,xu(!1),Su(!1),hu(r(`voice.connectionLost`),`warn`),setTimeout(()=>{H.phase===`idle`&&yu()},3500))}),H.port=e,e}catch(e){return i.warn(`[Voice] connect port failed:`,e?.message||e),null}}function wu(e,t){if(bu(t),Tu(t),H.port)try{H.port.postMessage({type:`audio`,data:Ql(e)})}catch(e){i.debug(`[Voice] post audio failed:`,e?.message||e)}}function Tu(e){if(H.phase!==`recording`&&H.phase!==`starting`)return;if(e>=ql){H.silentSince=0,H.silenceWarned&&(H.silenceWarned=!1,hu(r(`voice.listening`)));return}let t=Date.now();if(!H.silentSince){H.silentSince=t;return}H.silenceWarned||t-H.silentSince>=Kl&&(H.silenceWarned=!0,hu(r(`voice.noSpeech`),`warn`))}var Eu=[`voice-capture-worklet.js`,`dist/voice-capture-worklet.js`],Du;async function Ou(){if(Du!==void 0)return Du;for(let e of Eu){let t=``;try{t=chrome.runtime.getURL(e)}catch{continue}try{let e=await fetch(t);if(e&&e.ok)return Du=t,t}catch{}}return Du=null,null}async function ku(e,t){let n=await Ou();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-Gl)>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=eu($l(t,e.sampleRate,Gl))}wu(r,n.rms||0)},t.connect(r),H.node=r}function Au(e,t){let n=e.createScriptProcessor(4096,1,1),r=Math.abs(e.sampleRate-Gl)>1;n.onaudioprocess=t=>{let n=t.inputBuffer.getChannelData(0),i=new Float32Array(n);r&&(i=$l(i,e.sampleRate,Gl));let a=0;for(let e=0;e<i.length;e++)a+=i[e]*i[e];wu(eu(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 hu(r(`voice.unsupported`),`warn`),Error(`unsupported`);let e=await ot(await tt());H.stream=e.stream,H.deviceFellBack=e.fellBack===!0;let t=window.AudioContext||window.webkitAudioContext,n;try{n=new t({sampleRate:Gl})}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),Au(n,a)}}function Mu(){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 Nu(){H.finishWaitTimer&&=(clearTimeout(H.finishWaitTimer),null),H.phase=`idle`}function Pu(){let e=()=>{let e=Date.now()-H.startedAt;H.timerEl&&(H.timerEl.textContent=Zl(e));let t=H.status;e>=(t&&t.maxRecordingMs||300*1e3)&&Iu(`stop`)};H.timer&&clearInterval(H.timer),H.timer=setInterval(e,200),e()}async function Fu(e={}){if(H.phase!==`idle`||!H.armed&&!e.force&&(await ou(),!H.armed||H.phase!==`idle`))return!1;H.phase=`starting`,H.lastText=``,H.appliedText=``,H.openText=``,H.draft=cu(),H.appliedValue=H.input?H.input.value:``,H.draftSupported=!0,H.silentSince=0,H.silenceWarned=!1,gu(),hu(r(`voice.listening`)),xu(!0),Su(!0);let t=Cu();if(!t)return hu(r(`voice.failed`),`warn`),Nu(),xu(!1),Su(!1),!1;try{await ju()}catch(e){if(H.phase!==`starting`)return Mu(),!1;let n=e?.name||``,i=n===`NotAllowedError`||n===`SecurityError`;i?(hu(r(`voice.micDenied`),`warn`),_u(!0)):hu(r(`voice.failed`),`warn`),Mu(),Nu(),xu(!1),Su(!1);try{t.postMessage({type:`cancel`})}catch{}return setTimeout(()=>{H.phase===`idle`&&yu()},i?12e3:4e3),!1}if(H.phase!==`starting`)return Mu(),!1;H.startedAt=Date.now(),H.phase=`recording`,hu(r(`voice.listening`)),H.deviceFellBack&&(H.deviceFellBack=!1,hu(r(`voice.deviceFallback`),`warn`),setTimeout(()=>{H.phase===`recording`&&hu(r(`voice.listening`))},4e3)),Pu();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 Iu(e){if(H.phase!==`recording`)return;H.phase=`finalizing`;let t=Date.now()-H.startedAt;if(Mu(),xu(!1),Su(!1),e===`cancel`){try{H.port?.postMessage({type:`cancel`})}catch{}pu(),Nu(),yu();return}if(t<Jl&&!H.lastText){try{H.port?.postMessage({type:`cancel`})}catch{}pu(),hu(r(`voice.tooShort`),`warn`),Nu(),setTimeout(()=>{H.phase===`idle`&&yu()},2200);return}hu(r(`voice.transcribing`));try{H.port?.postMessage({type:`stop`})}catch{}H.finishWaitTimer&&clearTimeout(H.finishWaitTimer),H.finishWaitTimer=setTimeout(()=>{H.phase===`finalizing`&&Ru(H.lastText,{fallback:!0})},6e4)}function Lu({rollback:e=!0}={}){if(H.phase===`idle`)return!1;let t=H.phase===`recording`||H.phase===`finalizing`;if(H.phase=`finalizing`,Mu(),t)try{H.port?.postMessage({type:`cancel`})}catch{}return e&&pu(),Nu(),xu(!1),Su(!1),yu(),!0}function Ru(e,t={}){let n=Xl(e).trim();if(!n){pu(),hu(r(`voice.noResult`),`warn`),Nu(),setTimeout(()=>{H.phase===`idle`&&yu()},2200);return}if(!H.draft){let e=H.input;if(e){let t=typeof e.selectionStart==`number`?e.selectionStart:e.value.length;uu(e.value.slice(0,t)+n+e.value.slice(t),t+n.length)}hu(r(`voice.done`)),Nu(),setTimeout(()=>{H.phase===`idle`&&yu()},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}=Hl(H.draft.items,n);H.draft.items=o,du(!0),c&&i.debug(`[Voice] final text took over the whole draft`),H.draft=null,H.lastText=``,H.appliedText=``,H.openText=``,Nu(),hu(s>0?r(`voice.refineCorrected`,{n:s}):r(`voice.done`)),setTimeout(()=>{H.phase===`idle`&&yu()},s>0?1800:1200)}function zu(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=Xl(e.text),fu(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:Xl(e.draft)||n.text,state:`draft`}:n),H.openText=``}if(t&&(a.some(t=>t.id===e.id)?a=Bl(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,du()),t&&H.phase===`recording`){let e=H.draft.items.filter(e=>e.id!==null&&e.state===`refined`).length;hu(r(`voice.refineListening`,{n:e}))}return}if(e.type===`refine`){e.enabled===!1&&(H.phase===`recording`||H.phase===`finalizing`)&&hu(r(`voice.refineDegraded`),`warn`);return}if(e.type===`final`){if(H.phase!==`recording`&&H.phase!==`finalizing`)return;Ru(e.text||H.lastText,{fallback:e.fallback===!0,texts:e.texts});return}if(e.type===`closed`){H.phase===`finalizing`&&Ru(H.lastText,{fallback:!0});return}if(e.type===`error`){let t=e.code||`internal`;if(t===`max_duration`){H.phase===`recording`&&Iu(`stop`),hu(r(`voice.maxDuration`),`warn`);return}hu(t===`busy`?r(`voice.busy`):t===`model_missing`?`${r(`voice.modelMissing`)} — ${r(`voice.modelMissingHelp`)}`:r(`voice.failed`),`warn`),Mu(),(H.phase===`recording`||H.phase===`finalizing`)&&pu(),Nu(),xu(!1),Su(!1),t===`model_missing`&&ou(),setTimeout(()=>{H.phase===`idle`&&yu()},3500)}}}async function Bu(){return H.phase===`recording`?(Iu(`stop`),!0):H.phase===`starting`||H.phase===`finalizing`?!1:Fu()}function Vu(){return H.phase===`recording`||H.phase===`starting`||H.phase===`finalizing`}function Hu(){return Vu()?Lu({rollback:!0}):!1}function Uu(){return H.phase===`idle`?!1:Lu({rollback:!1})}async function Wu(){try{let e=(await chrome.storage.session?.get?.(`pendingVoiceStart`))?.pendingVoiceStart;return!(!e||(await chrome.storage.session.remove(`pendingVoiceStart`),typeof e!=`number`||Date.now()-e>Wl))}catch{return!1}}function Gu(){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 Ku(){if(H.shortcutCfg=await ke(),H.shortcutTrigger||=Oe(()=>H.shortcutCfg),Gu(),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(),Bu()))},!0),window.addEventListener(`blur`,()=>{H.shortcutTrigger?.reset()}),De(e=>{H.shortcutCfg=e,Gu()});let e=async()=>{try{let e=await ke();if(e.rightAlt===H.shortcutCfg.rightAlt&&e.rightCtrl===H.shortcutCfg.rightCtrl)return;H.shortcutCfg=e,Gu()}catch{}};window.addEventListener(`focus`,()=>{e()}),document.addEventListener(`visibilitychange`,()=>{document.hidden||e()})}async function qu(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}mu(),xu(!1),hu(r(`voice.listening`)),await Ku(),H.btn.addEventListener(`click`,e=>{e.preventDefault(),Bu()}),document.getElementById(`voiceCancelBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),Lu({rollback:!0})}),document.getElementById(`voiceDoneBtn`)?.addEventListener(`click`,e=>{e.preventDefault(),Iu(`stop`)}),H.permBtn?.addEventListener(`click`,e=>{e.preventDefault();try{chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`asr`}).catch?.(()=>{})}catch{}hu(r(`voice.micDeniedHelp`),`warn`),_u(!1)}),H.input.addEventListener(`input`,()=>{H.programmatic||(H.phase===`recording`||H.phase===`finalizing`)&&su()}),chrome.runtime.onMessage.addListener((e,t,n)=>e?.type===`VOICE_TOGGLE`?(Bu(),n?.({success:!0}),!1):(e?.type===`ASR_STATUS_CHANGED`&&ou(),!1)),window.addEventListener(`pagehide`,()=>{Uu()}),document.addEventListener(`visibilitychange`,()=>{document.hidden&&H.phase===`recording`&&Uu()}),await ou()&&await Wu()&&setTimeout(()=>{Bu()},220)}var Ju=`panel_`+Date.now().toString(36)+`_`+Math.random().toString(36).slice(2,8),Yu=new Set,Xu=new Set,Zu=null,Qu=new Map,$u=`queue-context-cleared`,ed=`queue-context-restored`;function td(e){Zu=e}function nd(e){return C.generatingSessionIds.has(e||C.activeSessionId)}function rd(){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 id(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 ad(){return id(rd())}function od(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 sd(){let e=rd();return id(e)&&ld(),e}function cd(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 ld(){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($u))}var ud=new Set([`pending`,`extracting`]);function dd(){return(C.attachedFiles||[]).some(e=>ud.has(e&&e.status))}function fd(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=Ur({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 Gr(e.id)||Qu.get(e.id)||null,n=!!(e.attachmentSummary||e.contextSnapshot&&e.contextSnapshot.attachmentSummary);return cd({...e.contextSnapshot||{},attachedImages:t&&t.images||[],attachedFiles:t&&t.files||[]}),document.dispatchEvent(new CustomEvent(ed,{detail:{snapshot:e.contextSnapshot||{}}})),{ok:!0,attachments:!!t,wantsAttachments:n}}async function md(e){return e?(Qu.delete(e),Kr(e)):!1}async function hd({autoDrain:e=!0}={}){let t=document.getElementById(`userInput`),n=(t?.value||``).trim()||od(rd());if(!n)return{ok:!1,error:`empty`};Uu();let i=C.activeSessionId;if(!i)return F(r(`queue.noSession`),`error`),{ok:!1,error:`missing_session`};if(dd())return F(r(`queue.filesStillExtracting`),`warning`,4e3),{ok:!1,error:`files_extracting`};let a=sd(),{light:o,heavy:s}=fd(a),c=await vr({sessionId:i,text:n,contextSnapshot:o,hasContext:id(o),attachmentSummary:o.attachmentSummary,source:`manual`});return c.ok?(s&&((await Wr(c.item.id,i,s)).ok||(Qu.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&&!nd(i)&&!_r(i)&&_d(i),c):(cd(a),document.dispatchEvent(new CustomEvent(ed,{detail:{snapshot:a}})),c.error===`queue_full`?F(r(`queue.queueFull`,{limit:c.limit}),`warning`):F(r(`queue.enqueueFailed`),`error`),c)}async function gd(e){try{let{list:t}=await ti(),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 _d(e){let t=e||C.activeSessionId;if(!(!t||!Zu)){if(Yu.has(t)){Xu.add(t);return}Yu.add(t);try{do Xu.delete(t),await vd(t);while(Xu.has(t)&&!_r(t))}finally{Yu.delete(t)}}}async function vd(e){if(nd(e)||_r(e))return;let t=pr(e);if(!t)return;if((t.attempts||0)>=5){await wr(e,t.id,{status:L.FAILED,note:`too_many_attempts`}),F(r(`queue.tooManyAttempts`,{count:5}),`error`,5e3);return}if(!await Ar(e,t.id,Ju)){i.debug(`[QueueRunner] lease held by another panel, skip:`,t.id);return}await xr(e,t.id,L.DISPATCHING,{attempts:(t.attempts||0)+1,lastError:null});let n=await Gr(t.id)||Qu.get(t.id)||null;Qu.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 gd(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 Zu(n)||{ok:!0}}catch(e){l={ok:!1,reason:e?.message||`dispatch_error`},i.error(`[QueueRunner] dispatch failed:`,e?.message||e)}hr(e,t.id)?l.ok===!1?l.delivered?(await wr(e,t.id,{status:L.FAILED,note:l.reason||`failed`}),await Kr(t.id)):(await Cr(e,t.id,`dispatch_failed`,l.reason||`dispatch_failed`),Xu.delete(e)):(await wr(e,t.id,{status:L.DONE,note:a?`relayed_no_attachments`:`relayed`}),await Kr(t.id)):i.debug(`[QueueRunner] item removed during dispatch, drop result:`,t.id)}var yd=new Set;function bd(e){let t=e||C.activeSessionId;return t?(yd.add(t),t):null}function xd(e){let t=e||C.activeSessionId;return!!(t&&pr(t))}async function Sd(e){let t=e||C.activeSessionId;t&&(yd.delete(t),await kr(t),await _d(t))}function Cd(e){_r(e)||_d(e)}var wd=new Map,Td=new Set,Ed=new Map,Dd=new Map;function Od(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 Ad(e,t){let n=kd(e,t),r=wd.get(n);r&&(clearTimeout(r),wd.delete(n))}async function jd(e,t,n,r){Ad(e,t);let i=hr(e,t);!i||i.status!==L.INJECTING||(await Cr(e,t,n,n),r&&F(r,`warning`,4e3))}function Md(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 Nd(e,t,n={}){let i=t||C.activeSessionId,a=n.auto===!0;if(!i||!e)return{ok:!1,error:`missing_session`};let o=hr(i,e);if(!o)return{ok:!1,error:`not_found`};if(o.status!==L.QUEUED)return{ok:!1,error:`not_queued`};if(Od(o))return a||F(r(`queue.injectNoAttachments`),`warning`,4e3),{ok:!1,error:`has_attachments`};let s=kd(i,e);if(Td.has(s))return{ok:!1,error:`in_flight`};Td.add(s);try{await Sr(i,e),wd.set(s,setTimeout(()=>{jd(i,e,`timeout`,r(`queue.injectTimeout`))},Ln));let t=await Md(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{Td.delete(s)}}function Pd(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 Fd(e){let t=C.activeSessionId,n=String(e||``).trim();if(!t||!n)return{ok:!1,error:`empty`};if(Uu(),!nd(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(()=>{Ed.has(i)&&(Ed.delete(i),F(r(`queue.injectTimeoutAdhoc`),`warning`,4e3))},Ln);Ed.set(i,{text:n,timer:a});let o=await Md(t,i,n);return o&&!o.accepted?(clearTimeout(a),Ed.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 Id(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=Ed.get(r);if(n){clearTimeout(n.timer),Ed.delete(r),Pd(n.text);continue}Ad(t,r),hr(t,r)&&(i++,wr(t,r,{status:L.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 Ld(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=Ed.get(e);if(r){clearTimeout(r.timer),Ed.delete(e);continue}jd(t,e,i,e===n[0]?a:null)}}function Rd(e){let t=e?.sessionId;if(!t||e.isSubtask===!0||_r(t))return;let n=Pl(e.executionLog);if(!n)return;let r=pr(t),a=r&&!Od(r)?r:null,o=C.chatConfig||{},s=Fl({tracker:Dd.get(t),callId:e.callId||null,iteration:n,everyN:o.queueAutoCarryEveryNIterations,enabled:o.queueAutoCarry!==!1,hasCandidate:!!a});if(Dd.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;Nd(a.id,t,{auto:!0,iteration:n}).then(e=>{!e||e.ok!==!0||Dd.set(t,Il(Dd.get(t),{callId:c}))})}function zd(e){!e||typeof e!=`object`||(e.type===`INJECT_ABSORBED`?Id(e):e.type===`INJECT_REJECTED`?Ld(e):e.type===`EXECUTION_STATUS_UPDATE`&&Rd(e))}async function Bd(){try{if(ar()){i.warn(`[QueueRunner] skip attachment prune in degraded mode`);return}let e=new Set;for(let t of gr())for(let n of lr(t))e.add(n.id);let t=await Jr(e);t&&i.debug(`[QueueRunner] pruned orphan attachments:`,t)}catch(e){i.warn(`[QueueRunner] prune orphan attachments failed:`,e?.message||e)}}var Vd=!1,Hd=null,Ud=[];function Wd(e,t){document.addEventListener(e,t),Ud.push([e,t])}var Gd=1500;function Kd(e){return new Promise(t=>{let n=!1,r=e=>{n||(n=!0,t(e))},i=setTimeout(()=>r(null),Gd);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 qd(){if(!C.activeSessionId)return!1;let e=gr();if(e.length===0)return!0;let t=!1;for(let n of e){if(_r(n)||nd(n)||!pr(n))continue;let e=await Kd(n);if(e===null){t=!0;continue}if(!e&&!(_r(n)||nd(n)))return await _d(n),!0}return!t}function Jd(){if(Hd)return;let e=0,t=async()=>{if(Hd=null,++e>25)return;let n=!1;try{n=await qd()}catch(e){i.warn(`[QueueRunner] auto-resume attempt failed:`,e?.message||e)}n||(Hd=setTimeout(t,800))};Hd=setTimeout(t,300)}async function Yd({autoResume:e=!0}={}){Vd||(Vd=!0,await or(),sr(),Bd(),Al(Cd),typeof chrome<`u`&&chrome.runtime?.onMessage?.addListener&&chrome.runtime.onMessage.addListener(zd),Wd(`task-stop-requested`,e=>{let t=e?.detail?.sessionId||C.activeSessionId;if(t){if(yd.delete(t)){kr(t).then(()=>_d(t));return}Or(t,`user_stopped`)}}),Wd(`generating-state-changed`,()=>{let e=C.activeSessionId;if(e){if(C.isGenerating&&_r(e)){kr(e);return}for(let e of gr())if(!(_r(e)||nd(e))&&pr(e)){_d(e);break}}}),Wd(`session-switched`,()=>Jd()),Wd(`visibilitychange`,()=>{document.visibilityState===`visible`&&Jd()}),e&&Jd())}async function Xd(e){let t=e||C.activeSessionId;t&&(await kr(t),await _d(t))}var Zd=[/(?:按|按照|以|用|走|使用|开启|启用|切换?到)\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],Qd=[/直到\s*[^。;;\n]{1,40}?(?:全部|都)?(?:通过|完成|跑通|变绿)/,/(?:确保|保证)\s*[^。;;\n]{1,40}?(?:通过|跑通|可用)/,/\buntil\s+[^.;\n]{1,40}?(?:pass|passes|green|works)\b/i],$d=/(?:不要|不用|不必|无需|取消|关闭|停用|停止|退出|不按|不以|别|不)\s*$/,ef=/\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,tf=2e3,nf=40;function rf(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-nf),o.index);if(!(n&&($d.test(t)||ef.test(t)))&&(r.push(o[0].trim()),o[0].length===0))break}}return r}function af(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,tf),i=rf(r,Zd,!0);if(i.length>0)return{detected:!0,strength:`strong`,matches:of(i).slice(0,3)};let a=rf(r,Qd,!0);return a.length>0?{detected:!1,strength:`weak`,matches:of(a).slice(0,3)}:t}function of(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 sf(e){if(typeof e!=`string`)return``;let t=e,n=rf(e.slice(0,tf),Zd,!0);for(let e of n)e&&(t=t.replace(e,` `));return t=t.replace(/^[\s,,。.、::;;-]+/,``).trim(),t||e.trim()}var cf={active:`goal.statusActive`,paused:`goal.statusPaused`,achieved:`goal.statusAchieved`,unmet:`goal.statusUnmet`,budget_limited:`goal.statusBudgetLimited`,cleared:`goal.statusCleared`},lf=new Set([`achieved`,`unmet`,`cleared`]),U=null;function uf(e){return document.getElementById(e)}function df(e){let t=cf[e];return t?r(t):String(e||``)}function ff(e){return!!e&&lf.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 mf(e){return pf({type:`SET_GOAL`,...e})}function hf(){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&&!ff(e);if(U.bar.style.display=i?``:`none`,!i)return;if(U.bar.dataset.status=e?e.status:`none`,U.status.textContent=e?df(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 gf(){return C.activeSessionId||null}async function _f(e=gf()){if(!e)return C.goalSnapshot=null,hf(),null;let t=await pf({type:`GET_GOAL`,sessionId:e});return e===gf()?(C.goalSnapshot=t?.goal||null,hf(),C.goalSnapshot):null}var vf=null;async function yf(){return vf||(vf=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({})}}),vf)}async function bf(){let e=uf(`goalGroup`);if(!e)return;let t=await yf();e.style.display=t.enabled===!1?`none`:``}async function xf({sessionId:e=gf(),text:t=``,attachments:n=[]}={}){if(!e||!String(t||``).trim())return null;let i=await yf(),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=af(t);if(!e.detected)return e.strength===`weak`&&F(r(`goal.intentHint`),`info`,6e3),null;o=String(sf(t)||``).trim()||t}let s=await mf({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===gf()?(C.goalSnapshot=s.goal||null,hf(),s.goal||null):s.goal||null)}function Sf(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 Cf(){C.goalSnapshot=null,hf()}function wf(){return hf(),_f()}function Tf(e=``){return new Promise(t=>{let n=document.createElement(`div`);n.className=`modal-overlay show`,n.innerHTML=`
|
|
95
|
+
<div class="modal-container" style="min-width:320px;">
|
|
96
|
+
<div class="modal-title">${P(r(`goal.editTitle`))}</div>
|
|
97
|
+
<input type="text" class="goal-edit-input" value="${P(e)}"
|
|
98
|
+
placeholder="${P(r(`goal.editPrompt`))}"
|
|
99
|
+
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;">
|
|
100
|
+
<div style="display:flex;justify-content:flex-end;gap:8px;margin-top:12px;">
|
|
101
|
+
<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;">${P(r(`common.cancel`))}</button>
|
|
102
|
+
<button class="goal-edit-confirm" style="padding:6px 16px;border:none;border-radius:6px;background:var(--brand-500);color:var(--text-inverse);cursor:pointer;">${P(r(`common.confirm`))}</button>
|
|
103
|
+
</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 Ef(e){!e||e.status===`active`||F(r(`goal.resumeBlocked`,{turns:e.turnBudget}),`warning`,6e3)}function Df(){if(U)return;let e=uf(`goalModeBtn`),t=uf(`goalBar`);if(!e||!t){i.warn(`[GoalPanel] init skipped: DOM not ready`);return}U={toggle:e,group:uf(`goalGroup`),bar:t,status:uf(`goalBarStatus`),objective:uf(`goalBarObjective`),meta:uf(`goalBarMeta`),approve:uf(`goalBarApprove`),edit:uf(`goalBarEditBtn`),pause:uf(`goalBarPauseBtn`),resume:uf(`goalBarResumeBtn`),clear:uf(`goalBarClearBtn`)},U.toggle.checked=!!C.goalMode,U.toggle.addEventListener(`change`,async()=>{if(C.goalMode=U.toggle.checked,hf(),i.debug(`[GoalPanel] goal mode:`,C.goalMode?`enabled`:`disabled`),C.goalMode){let e=gf(),t=C.goalSnapshot;if(e&&t&&(t.status===`paused`||t.status===`budget_limited`)){let t=await mf({sessionId:e,action:`resume`,autoApprove:!0});t?.goal&&e===gf()&&(C.goalSnapshot=t.goal,hf(),Ef(t.goal))}}else{let e=gf();if(e&&!ff(C.goalSnapshot)){let t=await mf({sessionId:e,action:`pause`});t?.goal&&e===gf()&&(C.goalSnapshot=t.goal,hf())}}}),U.edit.addEventListener(`click`,async()=>{let e=gf();if(!e)return;let t=await Tf(C.goalSnapshot?.objective||``);if(!t)return;let n=await mf({sessionId:e,action:`replace`,objective:t,autoApprove:!!C.goalMode});n?.goal&&e===gf()&&(C.goalSnapshot=n.goal,hf(),F(r(`goal.updated`),`success`))}),U.pause.addEventListener(`click`,async()=>{let e=gf();if(!e)return;let t=await mf({sessionId:e,action:`pause`});t?.goal&&e===gf()&&(C.goalSnapshot=t.goal,hf(),t.goal.status===`paused`&&F(r(C.goalMode?`goal.pausedToast`:`goal.pausedToastChipOff`),`info`,6e3))}),U.resume.addEventListener(`click`,async()=>{let e=gf();if(!e)return;let t=await mf({sessionId:e,action:`resume`,autoApprove:!!C.goalMode});t?.goal&&e===gf()&&(C.goalSnapshot=t.goal,hf(),Ef(t.goal))}),U.clear.addEventListener(`click`,async()=>{let e=gf();e&&(!window.showCustomConfirm||await window.showCustomConfirm(r(`goal.clearConfirm`),r(`goal.label`)))&&(await mf({sessionId:e,action:`clear`}),e===gf()&&(C.goalSnapshot=null,hf()))}),U.approve.addEventListener(`click`,async()=>{let e=gf();if(!e)return;let t=await mf({sessionId:e,action:`pause`});C.goalMode=!1,t?.goal&&e===gf()&&(C.goalSnapshot=t.goal),hf(),F(r(`goal.approvalRevoked`),`info`,6e3)}),chrome.runtime.onMessage.addListener(e=>{e?.type===`GOAL_UPDATE`&&(e.sessionId&&e.sessionId!==gf()||(C.goalSnapshot=e.goal||null,hf()))});try{chrome.storage.onChanged.addListener((e,t)=>{t!==`local`||!(`goalConfig`in e)||(vf=null,bf())})}catch(e){i.debug(`[GoalPanel] storage.onChanged unavailable:`,e?.message)}bf(),document.addEventListener(`session-switched`,()=>{wf()}),document.addEventListener(`session-hydrated`,()=>{wf()}),document.addEventListener(`session-deleted`,()=>{Cf()}),document.addEventListener(`session-archived`,()=>{Cf()}),hf()}var Of=`combo-collapsed`,kf=`summary-collapsed`,Af=`summary-wrapped`,jf=[Of,kf,Af];function Mf(e){if(!e)return;let t=e.querySelector(`.log-summary`);t&&(t.classList.remove(...jf),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(Of),!(t.scrollWidth<=t.clientWidth)&&(t.classList.add(kf),!(t.scrollWidth<=t.clientWidth)&&t.classList.add(Af))))}var Nf=null,Pf=0,Ff=!1;function If(e){e&&(Nf=e,Lf(),!Pf&&(Pf=requestAnimationFrame(()=>{Pf=0;let e=Nf;Nf=null,e&&Mf(e)})))}function Lf(){Ff||typeof window>`u`||(Ff=!0,window.addEventListener(`resize`,()=>{let e=document.querySelector(`.execution-log-panel`);e&&If(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 Rf(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 zf(e){return Rf(e)}function Bf(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 Vf(e,t){let n=e=>e.status===`pending`?2**53-1:new Date(e.timestamp).getTime();return n(e)-n(t)}function Hf(e){let t=Bf(e).sort(Vf),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 _=P(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=zf(e);t&&(_+=` <span class="node-cmd-preview" title="${nt(t)}">${P(t)}</span>`)}i+=`
|
|
105
|
+
<div class="timeline-item ${p}" data-status="${e.status||`processing`}" data-node-type="${e.nodeType||``}">
|
|
106
|
+
<div class="timeline-line"></div>
|
|
107
|
+
<div class="timeline-dot ${g}">
|
|
108
|
+
${h}
|
|
109
|
+
</div>
|
|
110
|
+
<div class="timeline-content">
|
|
111
|
+
<div class="timeline-header">
|
|
112
|
+
<span class="expand-icon">▼</span>
|
|
113
|
+
<span class="node-icon">${m}</span>
|
|
114
|
+
<span class="iteration-badge">[${t+1}/${n}]</span>
|
|
115
|
+
<span class="node-name" title="${P(e.nodeName||r(`execLog.unknownNode`))}">${_}</span>
|
|
116
|
+
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${Ve(e.duration||0)}</span>
|
|
117
|
+
</div>
|
|
118
|
+
|
|
119
|
+
<div class="timeline-details">
|
|
120
|
+
${d&&e.content?`
|
|
121
|
+
<div class="timeline-section">
|
|
122
|
+
<div class="section-title">${r(`execLog.sectionUserInjection`)}</div>
|
|
123
|
+
<div class="section-content">${P(e.content)}</div>
|
|
124
|
+
</div>
|
|
125
|
+
`:``}
|
|
126
|
+
|
|
127
|
+
${e.thought&&e.thought.trim()?`
|
|
128
|
+
<div class="timeline-section">
|
|
129
|
+
<div class="section-title">${r(`execLog.sectionThought`)}</div>
|
|
130
|
+
<div class="section-content">${P(e.thought)}</div>
|
|
131
|
+
</div>
|
|
132
|
+
`:``}
|
|
133
|
+
|
|
134
|
+
${!l&&e.action?`
|
|
135
|
+
<div class="timeline-section">
|
|
136
|
+
<div class="section-title">${r(`execLog.sectionToolCall`)}</div>
|
|
137
|
+
<div class="section-content">
|
|
138
|
+
<strong>${r(`execLog.labelTool`)}</strong> ${P(e.action.name)}<br>
|
|
139
|
+
<strong>${r(`execLog.labelParams`)}</strong> <code>${P(JSON.stringify(e.action.params,null,2))}</code>
|
|
140
|
+
</div>
|
|
141
|
+
</div>
|
|
142
|
+
`:``}
|
|
143
|
+
|
|
144
|
+
${l&&e.action?.params?.selected?`
|
|
145
|
+
<div class="timeline-section">
|
|
146
|
+
<div class="section-title">${r(`execLog.sectionFilterResult`)}</div>
|
|
147
|
+
<div class="section-content">
|
|
148
|
+
<strong>${r(`execLog.labelSelectedTools`)}</strong> ${e.action.params.selected.map(e=>P(e)).join(`, `)}<br>
|
|
149
|
+
<strong>${r(`execLog.labelCount`)}</strong> ${e.action.params.selected.length} ${r(`execLog.unitItems`)}
|
|
150
|
+
</div>
|
|
151
|
+
</div>
|
|
152
|
+
`:``}
|
|
153
|
+
|
|
154
|
+
${e.observation?`
|
|
155
|
+
<div class="timeline-section">
|
|
156
|
+
<div class="section-title">${r(`execLog.sectionObservation`)}</div>
|
|
157
|
+
<div class="section-content">${P(e.observation)}</div>
|
|
158
|
+
</div>
|
|
159
|
+
`:``}
|
|
160
|
+
|
|
161
|
+
${e.apiRequest?`
|
|
162
|
+
<div class="timeline-section">
|
|
163
|
+
<div class="section-title">${r(`execLog.sectionApiRequest`)}</div>
|
|
164
|
+
<div class="section-content">
|
|
165
|
+
${e.apiRequest.model?`<strong>${r(`execLog.labelModel`)}</strong> ${P(e.apiRequest.model)}<br>`:``}
|
|
166
|
+
${e.apiRequest.temperature===void 0?``:`<strong>${r(`execLog.labelTemperature`)}</strong> ${e.apiRequest.temperature}<br>`}
|
|
167
|
+
${e.apiRequest.top_p===void 0?``:`<strong>top_p:</strong> ${e.apiRequest.top_p}<br>`}
|
|
168
|
+
${e.apiRequest.messageCount===void 0?``:`<strong>${r(`execLog.labelMessageCount`)}</strong> ${e.apiRequest.messageCount}<br>`}
|
|
169
|
+
${!l&&e.apiRequest.toolCount!==void 0?`<strong>${r(`execLog.labelToolCount`)}</strong> ${e.apiRequest.toolCount}<br>`:``}
|
|
170
|
+
</div>
|
|
171
|
+
</div>
|
|
172
|
+
`:``}
|
|
173
|
+
|
|
174
|
+
${e.apiResponse?`
|
|
175
|
+
<div class="timeline-section">
|
|
176
|
+
<div class="section-title">${r(`execLog.sectionApiResponse`)}</div>
|
|
177
|
+
<div class="section-content">
|
|
178
|
+
${e.apiResponse.finishReason?`<strong>${r(`execLog.labelFinishReason`)}</strong> ${P(e.apiResponse.finishReason)}<br>`:``}
|
|
179
|
+
${e.apiResponse.toolCountAfter===void 0?``:`<strong>${r(`execLog.labelFilteredToolCount`)}</strong> ${e.apiResponse.toolCountAfter} ${r(`execLog.unitItems`)}<br>`}
|
|
180
|
+
${e.apiResponse.tokenUsage?`
|
|
181
|
+
<strong>${r(`execLog.labelTokenUsage`)}</strong><br>
|
|
182
|
+
- Prompt: ${e.apiResponse.tokenUsage.prompt_tokens||0}<br>
|
|
183
|
+
- Completion: ${e.apiResponse.tokenUsage.completion_tokens||0}<br>
|
|
184
|
+
- Total: ${e.apiResponse.tokenUsage.total_tokens||(e.apiResponse.tokenUsage.prompt_tokens||0)+(e.apiResponse.tokenUsage.completion_tokens||0)}
|
|
185
|
+
`:``}
|
|
186
|
+
</div>
|
|
187
|
+
</div>
|
|
188
|
+
`:``}
|
|
189
|
+
|
|
190
|
+
${e.error?`
|
|
191
|
+
<div class="timeline-section error">
|
|
192
|
+
<div class="section-title">${r(`execLog.sectionError`)}</div>
|
|
193
|
+
<div class="section-content">${P(e.error)}</div>
|
|
194
|
+
</div>
|
|
195
|
+
`:``}
|
|
196
|
+
|
|
197
|
+
${e.description?`
|
|
198
|
+
<div class="timeline-section">
|
|
199
|
+
<div class="section-title">${r(`execLog.sectionSubtaskDesc`)}</div>
|
|
200
|
+
<div class="section-content">${P(e.description)}</div>
|
|
201
|
+
</div>
|
|
202
|
+
`:``}
|
|
203
|
+
|
|
204
|
+
${e.result?`
|
|
205
|
+
<div class="timeline-section">
|
|
206
|
+
<div class="section-title">${r(`execLog.sectionSubtaskResult`)}</div>
|
|
207
|
+
<div class="section-content">${P(e.result)}</div>
|
|
208
|
+
</div>
|
|
209
|
+
`:``}
|
|
210
|
+
|
|
211
|
+
${u?`
|
|
212
|
+
<div class="timeline-section reflection-details">
|
|
213
|
+
${e.prompt?`
|
|
214
|
+
<div class="timeline-section">
|
|
215
|
+
<div class="section-title">${r(`execLog.sectionReflectionPrompt`)}</div>
|
|
216
|
+
<div class="section-content"><pre style="white-space:pre-wrap;word-break:break-word;max-height:300px;overflow-y:auto;">${P(e.prompt)}</pre></div>
|
|
217
|
+
</div>
|
|
218
|
+
`:``}
|
|
219
|
+
${e.rawContent?`
|
|
220
|
+
<div class="timeline-section">
|
|
221
|
+
<div class="section-title">${r(`execLog.sectionReflectionRaw`)}</div>
|
|
222
|
+
<div class="section-content"><pre style="white-space:pre-wrap;word-break:break-word;max-height:200px;overflow-y:auto;">${P(e.rawContent)}</pre></div>
|
|
223
|
+
</div>
|
|
224
|
+
`:``}
|
|
225
|
+
${e.apiResponse?.tokenUsage?`
|
|
226
|
+
<div class="timeline-section">
|
|
227
|
+
<div class="section-title">${r(`execLog.sectionTokenUsage`)}</div>
|
|
228
|
+
<div class="section-content">
|
|
229
|
+
- Prompt: ${e.apiResponse.tokenUsage.prompt_tokens||0}<br>
|
|
230
|
+
- Completion: ${e.apiResponse.tokenUsage.completion_tokens||0}<br>
|
|
231
|
+
- Total: ${e.apiResponse.tokenUsage.total_tokens||(e.apiResponse.tokenUsage.prompt_tokens||0)+(e.apiResponse.tokenUsage.completion_tokens||0)}
|
|
232
|
+
</div>
|
|
233
|
+
</div>
|
|
234
|
+
`:``}
|
|
235
|
+
${e.overallScore!==void 0&&e.overallScore!==null?`
|
|
236
|
+
<div class="section-title">${r(`execLog.overallScore`,{score:e.overallScore})}</div>
|
|
237
|
+
`:``}
|
|
238
|
+
${e.dimensions&&Object.keys(e.dimensions).length>0?`
|
|
239
|
+
<div class="reflection-dimensions">
|
|
240
|
+
${Object.entries(e.dimensions).map(([e,t])=>`
|
|
241
|
+
<div class="dimension-item">
|
|
242
|
+
<span class="dim-label">${e}</span>
|
|
243
|
+
<span class="dim-bar"><span class="dim-fill" style="width:${t*10}%"></span></span>
|
|
244
|
+
<span class="dim-score">${t}/10</span>
|
|
245
|
+
</div>
|
|
246
|
+
`).join(``)}
|
|
247
|
+
</div>
|
|
248
|
+
`:``}
|
|
249
|
+
${e.issues&&e.issues.length>0?`
|
|
250
|
+
<div class="section-title">${r(`execLog.sectionIssues`)}</div>
|
|
251
|
+
<div class="section-content"><ul>${e.issues.map(e=>`<li>${P(e)}</li>`).join(``)}</ul></div>
|
|
252
|
+
`:``}
|
|
253
|
+
${e.suggestions&&e.suggestions.length>0?`
|
|
254
|
+
<div class="section-title">${r(`execLog.sectionSuggestions`)}</div>
|
|
255
|
+
<div class="section-content"><ul>${e.suggestions.map(e=>`<li>${P(e)}</li>`).join(``)}</ul></div>
|
|
256
|
+
`:``}
|
|
257
|
+
${e.action?.decision?`
|
|
258
|
+
<div class="section-title">${r(`execLog.labelDecision`,{decision:P(e.action.decision===`passed`?r(`execLog.decisionPassed`):e.action.decision===`revised`?r(`execLog.decisionRevised`):e.action.decision===`needs_improvement`?r(`execLog.decisionNeedsImprovement`):e.action.decision)})}</div>
|
|
259
|
+
`:``}
|
|
260
|
+
${e.useful===void 0?``:`
|
|
261
|
+
<div class="section-title">${e.useful?r(`execLog.resultUseful`):r(`execLog.resultInvalid`)}</div>
|
|
262
|
+
${e.reasoning?`<div class="section-content">${P(e.reasoning)}</div>`:``}
|
|
263
|
+
${e.suggestion?`<div class="section-content">${r(`execLog.labelSuggestion`,{suggestion:P(e.suggestion)})}</div>`:``}
|
|
264
|
+
`}
|
|
265
|
+
</div>
|
|
266
|
+
`:``}
|
|
267
|
+
</div>
|
|
268
|
+
</div>
|
|
269
|
+
</div>
|
|
270
|
+
`}),i}function Uf(e){let t=Bf(e).sort(Vf);if(!t.some(e=>e.taskGroup))return qf(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=Wf(i,t.length);return n.forEach((e,n)=>{let i=e.status||`processing`;a+=`
|
|
271
|
+
<div class="task-group-container" data-group-id="${n}">
|
|
272
|
+
<div class="task-group-header">
|
|
273
|
+
<div class="task-group-line"></div>
|
|
274
|
+
<div class="task-group-dot ${i}">
|
|
275
|
+
${i===`success`?`✓`:i===`failed`?`✗`:`○`}
|
|
276
|
+
</div>
|
|
277
|
+
<div class="task-group-content">
|
|
278
|
+
<div class="task-group-title">
|
|
279
|
+
<span class="task-group-expand-icon">▼</span>
|
|
280
|
+
<span class="task-group-icon">📁</span>
|
|
281
|
+
<span class="task-group-index">${e.groupIndex}</span>
|
|
282
|
+
<span class="task-group-name">${P(e.groupName)}</span>
|
|
283
|
+
<span class="task-group-count">${r(`execLog.stepCount`,{count:e.entries.length})}</span>
|
|
284
|
+
</div>
|
|
285
|
+
</div>
|
|
286
|
+
</div>
|
|
287
|
+
<div class="task-group-timeline">
|
|
288
|
+
${Gf(e.entries,t.length)}
|
|
289
|
+
</div>
|
|
290
|
+
</div>
|
|
291
|
+
`}),a}function Wf(e,t){if(e.length===0)return``;let n=``;return n+=`
|
|
292
|
+
<div class="main-tasks-container">
|
|
293
|
+
<div class="main-tasks-header">
|
|
294
|
+
<div class="main-tasks-line"></div>
|
|
295
|
+
<div class="main-tasks-dot processing">
|
|
296
|
+
◉
|
|
297
|
+
</div>
|
|
298
|
+
<div class="main-tasks-content">
|
|
299
|
+
<div class="main-tasks-title">
|
|
300
|
+
<span class="main-tasks-icon">🏠</span>
|
|
301
|
+
<span class="main-tasks-name">${r(`execLog.mainTask`)}</span>
|
|
302
|
+
<span class="main-tasks-count">${r(`execLog.stepCount`,{count:e.length})}</span>
|
|
303
|
+
</div>
|
|
304
|
+
</div>
|
|
305
|
+
</div>
|
|
306
|
+
<div class="main-tasks-timeline">
|
|
307
|
+
`,e.forEach((e,r)=>{n+=Kf(e,r,t)}),n+=`
|
|
308
|
+
</div>
|
|
309
|
+
</div>
|
|
310
|
+
`,n}function Gf(e,t){let n=``;return e.forEach((e,r)=>{n+=Kf(e,r,t)}),n}function Kf(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=P(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=zf(e);t&&(h+=` <span class="node-cmd-preview" title="${nt(t)}">${P(t)}</span>`)}return`
|
|
311
|
+
<div class="timeline-item ${d}">
|
|
312
|
+
<div class="timeline-line"></div>
|
|
313
|
+
<div class="timeline-dot ${m}">
|
|
314
|
+
${p}
|
|
315
|
+
</div>
|
|
316
|
+
<div class="timeline-content">
|
|
317
|
+
<div class="timeline-header">
|
|
318
|
+
<span class="expand-icon">▼</span>
|
|
319
|
+
<span class="node-icon">${f}</span>
|
|
320
|
+
<span class="iteration-badge">[${t+1}/${n}]</span>
|
|
321
|
+
<span class="node-name" title="${P(e.nodeName||r(`execLog.unknownNode`))}">${h}</span>
|
|
322
|
+
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${Ve(e.duration)}</span>
|
|
323
|
+
</div>
|
|
324
|
+
|
|
325
|
+
<div class="timeline-details">
|
|
326
|
+
${l&&e.content?`
|
|
327
|
+
<div class="timeline-section">
|
|
328
|
+
<div class="section-title">${r(`execLog.sectionUserInjection`)}</div>
|
|
329
|
+
<div class="section-content">${P(e.content)}</div>
|
|
330
|
+
</div>
|
|
331
|
+
`:``}
|
|
332
|
+
|
|
333
|
+
${e.thought&&e.thought.trim()?`
|
|
334
|
+
<div class="timeline-section">
|
|
335
|
+
<div class="section-title">${r(`execLog.sectionThought`)}</div>
|
|
336
|
+
<div class="section-content">${P(e.thought)}</div>
|
|
337
|
+
</div>
|
|
338
|
+
`:``}
|
|
339
|
+
|
|
340
|
+
${!s&&e.action?`
|
|
341
|
+
<div class="timeline-section">
|
|
342
|
+
<div class="section-title">${r(`execLog.sectionToolCall`)}</div>
|
|
343
|
+
<div class="section-content">
|
|
344
|
+
<strong>${r(`execLog.labelTool`)}</strong> ${P(e.action.name)}<br>
|
|
345
|
+
<strong>${r(`execLog.labelParams`)}</strong> <code>${P(JSON.stringify(e.action.params,null,2))}</code>
|
|
346
|
+
</div>
|
|
347
|
+
</div>
|
|
348
|
+
`:``}
|
|
349
|
+
|
|
350
|
+
${s&&e.action?.params?.selected?`
|
|
351
|
+
<div class="timeline-section">
|
|
352
|
+
<div class="section-title">${r(`execLog.sectionFilterResult`)}</div>
|
|
353
|
+
<div class="section-content">
|
|
354
|
+
<strong>${r(`execLog.labelSelectedTools`)}</strong> ${e.action.params.selected.map(e=>P(e)).join(`, `)}<br>
|
|
355
|
+
<strong>${r(`execLog.labelCount`)}</strong> ${e.action.params.selected.length} ${r(`execLog.unitItems`)}
|
|
356
|
+
</div>
|
|
357
|
+
</div>
|
|
358
|
+
`:``}
|
|
359
|
+
|
|
360
|
+
${e.observation&&e.observation!==e.error?`
|
|
361
|
+
<div class="timeline-section">
|
|
362
|
+
<div class="section-title">${r(`execLog.sectionObservation`)}</div>
|
|
363
|
+
<div class="section-content">${P(e.observation)}</div>
|
|
364
|
+
</div>
|
|
365
|
+
`:``}
|
|
366
|
+
|
|
367
|
+
${e.apiRequest?`
|
|
368
|
+
<div class="timeline-section">
|
|
369
|
+
<div class="section-title">${r(`execLog.sectionApiRequest`)}</div>
|
|
370
|
+
<div class="section-content">
|
|
371
|
+
${e.apiRequest.model?`<strong>${r(`execLog.labelModel`)}</strong> ${P(e.apiRequest.model)}<br>`:``}
|
|
372
|
+
${e.apiRequest.temperature===void 0?``:`<strong>${r(`execLog.labelTemperature`)}</strong> ${e.apiRequest.temperature}<br>`}
|
|
373
|
+
${e.apiRequest.top_p===void 0?``:`<strong>top_p:</strong> ${e.apiRequest.top_p}<br>`}
|
|
374
|
+
${e.apiRequest.messageCount===void 0?``:`<strong>${r(`execLog.labelMessageCount`)}</strong> ${e.apiRequest.messageCount}<br>`}
|
|
375
|
+
${!s&&e.apiRequest.toolCount!==void 0?`<strong>${r(`execLog.labelToolCount`)}</strong> ${e.apiRequest.toolCount}<br>`:``}
|
|
376
|
+
</div>
|
|
377
|
+
</div>
|
|
378
|
+
`:``}
|
|
379
|
+
|
|
380
|
+
${e.apiResponse?`
|
|
381
|
+
<div class="timeline-section">
|
|
382
|
+
<div class="section-title">${r(`execLog.sectionApiResponse`)}</div>
|
|
383
|
+
<div class="section-content">
|
|
384
|
+
${e.apiResponse.finishReason?`<strong>${r(`execLog.labelFinishReason`)}</strong> ${P(e.apiResponse.finishReason)}<br>`:``}
|
|
385
|
+
${e.apiResponse.toolCountAfter===void 0?``:`<strong>${r(`execLog.labelFilteredToolCount`)}</strong> ${e.apiResponse.toolCountAfter} ${r(`execLog.unitItems`)}<br>`}
|
|
386
|
+
${e.apiResponse.tokenUsage?`
|
|
387
|
+
<strong>${r(`execLog.labelTokenUsage`)}</strong><br>
|
|
388
|
+
- Prompt: ${e.apiResponse.tokenUsage.prompt_tokens||0}<br>
|
|
389
|
+
- Completion: ${e.apiResponse.tokenUsage.completion_tokens||0}<br>
|
|
390
|
+
- Total: ${e.apiResponse.tokenUsage.total_tokens||(e.apiResponse.tokenUsage.prompt_tokens||0)+(e.apiResponse.tokenUsage.completion_tokens||0)}
|
|
391
|
+
`:``}
|
|
392
|
+
</div>
|
|
393
|
+
</div>
|
|
394
|
+
`:``}
|
|
395
|
+
|
|
396
|
+
${e.error?`
|
|
397
|
+
<div class="timeline-section error">
|
|
398
|
+
<div class="section-title">${r(`execLog.sectionError`)}</div>
|
|
399
|
+
<div class="section-content">${P(e.error)}</div>
|
|
400
|
+
</div>
|
|
401
|
+
`:``}
|
|
402
|
+
|
|
403
|
+
${e.description?`
|
|
404
|
+
<div class="timeline-section">
|
|
405
|
+
<div class="section-title">${r(`execLog.sectionSubtaskDesc`)}</div>
|
|
406
|
+
<div class="section-content">${P(e.description)}</div>
|
|
407
|
+
</div>
|
|
408
|
+
`:``}
|
|
409
|
+
|
|
410
|
+
${e.result?`
|
|
411
|
+
<div class="timeline-section">
|
|
412
|
+
<div class="section-title">${r(`execLog.sectionSubtaskResult`)}</div>
|
|
413
|
+
<div class="section-content">${P(e.result)}</div>
|
|
414
|
+
</div>
|
|
415
|
+
`:``}
|
|
416
|
+
|
|
417
|
+
${c?`
|
|
418
|
+
<div class="timeline-section reflection-details">
|
|
419
|
+
${e.overallScore!==void 0&&e.overallScore!==null?`
|
|
420
|
+
<div class="section-title">${r(`execLog.overallScore`,{score:e.overallScore})}</div>
|
|
421
|
+
`:``}
|
|
422
|
+
${e.dimensions&&Object.keys(e.dimensions).length>0?`
|
|
423
|
+
<div class="reflection-dimensions">
|
|
424
|
+
${Object.entries(e.dimensions).map(([e,t])=>`
|
|
425
|
+
<div class="dimension-item">
|
|
426
|
+
<span class="dim-label">${e}</span>
|
|
427
|
+
<span class="dim-bar"><span class="dim-fill" style="width:${t*10}%"></span></span>
|
|
428
|
+
<span class="dim-score">${t}/10</span>
|
|
429
|
+
</div>
|
|
430
|
+
`).join(``)}
|
|
431
|
+
</div>
|
|
432
|
+
`:``}
|
|
433
|
+
${e.issues&&e.issues.length>0?`
|
|
434
|
+
<div class="section-title">${r(`execLog.sectionIssues`)}</div>
|
|
435
|
+
<div class="section-content"><ul>${e.issues.map(e=>`<li>${P(e)}</li>`).join(``)}</ul></div>
|
|
436
|
+
`:``}
|
|
437
|
+
${e.suggestions&&e.suggestions.length>0?`
|
|
438
|
+
<div class="section-title">${r(`execLog.sectionSuggestions`)}</div>
|
|
439
|
+
<div class="section-content"><ul>${e.suggestions.map(e=>`<li>${P(e)}</li>`).join(``)}</ul></div>
|
|
440
|
+
`:``}
|
|
441
|
+
${e.action?.decision?`
|
|
442
|
+
<div class="section-title">${r(`execLog.labelDecision`,{decision:P(e.action.decision===`passed`?r(`execLog.decisionPassed`):e.action.decision===`revised`?r(`execLog.decisionRevised`):e.action.decision===`needs_improvement`?r(`execLog.decisionNeedsImprovement`):e.action.decision)})}</div>
|
|
443
|
+
`:``}
|
|
444
|
+
${e.useful===void 0?``:`
|
|
445
|
+
<div class="section-title">${e.useful?r(`execLog.resultUseful`):r(`execLog.resultInvalid`)}</div>
|
|
446
|
+
${e.reasoning?`<div class="section-content">${P(e.reasoning)}</div>`:``}
|
|
447
|
+
${e.suggestion?`<div class="section-content">${r(`execLog.labelSuggestion`,{suggestion:P(e.suggestion)})}</div>`:``}
|
|
448
|
+
`}
|
|
449
|
+
</div>
|
|
450
|
+
`:``}
|
|
451
|
+
</div>
|
|
452
|
+
</div>
|
|
453
|
+
</div>
|
|
454
|
+
`}function qf(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 _=P(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=zf(i);e&&(_+=` <span class="node-cmd-preview" title="${nt(e)}">${P(e)}</span>`)}t+=`
|
|
455
|
+
<div class="timeline-item ${p}">
|
|
456
|
+
<div class="timeline-line"></div>
|
|
457
|
+
<div class="timeline-dot ${g}">
|
|
458
|
+
${h}
|
|
459
|
+
</div>
|
|
460
|
+
<div class="timeline-content">
|
|
461
|
+
<div class="timeline-header">
|
|
462
|
+
<span class="expand-icon">▼</span>
|
|
463
|
+
<span class="node-icon">${m}</span>
|
|
464
|
+
<span class="iteration-badge">[${a+1}/${e.length}]</span>
|
|
465
|
+
<span class="node-name" title="${P(i.nodeName||r(`execLog.unknownNode`))}">${_}</span>
|
|
466
|
+
<span class="duration-badge" title="${r(`execLog.durationTitle`)}">${Ve(i.duration)}</span>
|
|
467
|
+
</div>
|
|
468
|
+
|
|
469
|
+
<div class="timeline-details">
|
|
470
|
+
${d&&i.content?`
|
|
471
|
+
<div class="timeline-section">
|
|
472
|
+
<div class="section-title">${r(`execLog.sectionUserInjection`)}</div>
|
|
473
|
+
<div class="section-content">${P(i.content)}</div>
|
|
474
|
+
</div>
|
|
475
|
+
`:``}
|
|
476
|
+
|
|
477
|
+
${i.thought&&i.thought.trim()?`
|
|
478
|
+
<div class="timeline-section">
|
|
479
|
+
<div class="section-title">${r(`execLog.sectionThought`)}</div>
|
|
480
|
+
<div class="section-content">${P(i.thought)}</div>
|
|
481
|
+
</div>
|
|
482
|
+
`:``}
|
|
483
|
+
|
|
484
|
+
${!l&&i.action?`
|
|
485
|
+
<div class="timeline-section">
|
|
486
|
+
<div class="section-title">${r(`execLog.sectionToolCall`)}</div>
|
|
487
|
+
<div class="section-content">
|
|
488
|
+
<strong>${r(`execLog.labelTool`)}</strong> ${P(i.action.name)}<br>
|
|
489
|
+
<strong>${r(`execLog.labelParams`)}</strong> <code>${P(JSON.stringify(i.action.params,null,2))}</code>
|
|
490
|
+
</div>
|
|
491
|
+
</div>
|
|
492
|
+
`:``}
|
|
493
|
+
|
|
494
|
+
${l&&i.action?.params?.selected?`
|
|
495
|
+
<div class="timeline-section">
|
|
496
|
+
<div class="section-title">${r(`execLog.sectionFilterResult`)}</div>
|
|
497
|
+
<div class="section-content">
|
|
498
|
+
<strong>${r(`execLog.labelSelectedTools`)}</strong> ${i.action.params.selected.map(e=>P(e)).join(`, `)}<br>
|
|
499
|
+
<strong>${r(`execLog.labelCount`)}</strong> ${i.action.params.selected.length} ${r(`execLog.unitItems`)}
|
|
500
|
+
</div>
|
|
501
|
+
</div>
|
|
502
|
+
`:``}
|
|
503
|
+
|
|
504
|
+
${i.observation?`
|
|
505
|
+
<div class="timeline-section">
|
|
506
|
+
<div class="section-title">${r(`execLog.sectionObservation`)}</div>
|
|
507
|
+
<div class="section-content">${P(i.observation)}</div>
|
|
508
|
+
</div>
|
|
509
|
+
`:``}
|
|
510
|
+
|
|
511
|
+
${i.apiRequest?`
|
|
512
|
+
<div class="timeline-section">
|
|
513
|
+
<div class="section-title">${r(`execLog.sectionApiRequest`)}</div>
|
|
514
|
+
<div class="section-content">
|
|
515
|
+
${i.apiRequest.model?`<strong>${r(`execLog.labelModel`)}</strong> ${P(i.apiRequest.model)}<br>`:``}
|
|
516
|
+
${i.apiRequest.temperature===void 0?``:`<strong>${r(`execLog.labelTemperature`)}</strong> ${i.apiRequest.temperature}<br>`}
|
|
517
|
+
${i.apiRequest.top_p===void 0?``:`<strong>top_p:</strong> ${i.apiRequest.top_p}<br>`}
|
|
518
|
+
${i.apiRequest.messageCount===void 0?``:`<strong>${r(`execLog.labelMessageCount`)}</strong> ${i.apiRequest.messageCount}<br>`}
|
|
519
|
+
${!l&&i.apiRequest.toolCount!==void 0?`<strong>${r(`execLog.labelToolCount`)}</strong> ${i.apiRequest.toolCount}<br>`:``}
|
|
520
|
+
</div>
|
|
521
|
+
</div>
|
|
522
|
+
`:``}
|
|
523
|
+
|
|
524
|
+
${i.apiResponse?`
|
|
525
|
+
<div class="timeline-section">
|
|
526
|
+
<div class="section-title">${r(`execLog.sectionApiResponse`)}</div>
|
|
527
|
+
<div class="section-content">
|
|
528
|
+
${i.apiResponse.finishReason?`<strong>${r(`execLog.labelFinishReason`)}</strong> ${P(i.apiResponse.finishReason)}<br>`:``}
|
|
529
|
+
${i.apiResponse.toolCountAfter===void 0?``:`<strong>${r(`execLog.labelFilteredToolCount`)}</strong> ${i.apiResponse.toolCountAfter} ${r(`execLog.unitItems`)}<br>`}
|
|
530
|
+
${i.apiResponse.tokenUsage?`
|
|
531
|
+
<strong>${r(`execLog.labelTokenUsage`)}</strong><br>
|
|
532
|
+
- Prompt: ${i.apiResponse.tokenUsage.prompt_tokens||0}<br>
|
|
533
|
+
- Completion: ${i.apiResponse.tokenUsage.completion_tokens||0}<br>
|
|
534
|
+
- Total: ${i.apiResponse.tokenUsage.total_tokens||(i.apiResponse.tokenUsage.prompt_tokens||0)+(i.apiResponse.tokenUsage.completion_tokens||0)}
|
|
535
|
+
`:``}
|
|
536
|
+
</div>
|
|
537
|
+
</div>
|
|
538
|
+
`:``}
|
|
539
|
+
|
|
540
|
+
${i.error?`
|
|
541
|
+
<div class="timeline-section error">
|
|
542
|
+
<div class="section-title">${r(`execLog.sectionError`)}</div>
|
|
543
|
+
<div class="section-content">${P(i.error)}</div>
|
|
544
|
+
</div>
|
|
545
|
+
`:``}
|
|
546
|
+
|
|
547
|
+
${i.description?`
|
|
548
|
+
<div class="timeline-section">
|
|
549
|
+
<div class="section-title">${r(`execLog.sectionSubtaskDesc`)}</div>
|
|
550
|
+
<div class="section-content">${P(i.description)}</div>
|
|
551
|
+
</div>
|
|
552
|
+
`:``}
|
|
553
|
+
|
|
554
|
+
${i.result?`
|
|
555
|
+
<div class="timeline-section">
|
|
556
|
+
<div class="section-title">${r(`execLog.sectionSubtaskResult`)}</div>
|
|
557
|
+
<div class="section-content">${P(i.result)}</div>
|
|
558
|
+
</div>
|
|
559
|
+
`:``}
|
|
560
|
+
|
|
561
|
+
${u?`
|
|
562
|
+
<div class="timeline-section reflection-details">
|
|
563
|
+
${i.prompt?`
|
|
564
|
+
<div class="timeline-section">
|
|
565
|
+
<div class="section-title">${r(`execLog.sectionReflectionPrompt`)}</div>
|
|
566
|
+
<div class="section-content"><pre style="white-space:pre-wrap;word-break:break-word;max-height:300px;overflow-y:auto;">${P(i.prompt)}</pre></div>
|
|
567
|
+
</div>
|
|
568
|
+
`:``}
|
|
569
|
+
${i.rawContent?`
|
|
570
|
+
<div class="timeline-section">
|
|
571
|
+
<div class="section-title">${r(`execLog.sectionReflectionRaw`)}</div>
|
|
572
|
+
<div class="section-content"><pre style="white-space:pre-wrap;word-break:break-word;max-height:200px;overflow-y:auto;">${P(i.rawContent)}</pre></div>
|
|
573
|
+
</div>
|
|
574
|
+
`:``}
|
|
575
|
+
${i.apiResponse?.tokenUsage?`
|
|
576
|
+
<div class="timeline-section">
|
|
577
|
+
<div class="section-title">${r(`execLog.sectionTokenUsage`)}</div>
|
|
578
|
+
<div class="section-content">
|
|
579
|
+
- Prompt: ${i.apiResponse.tokenUsage.prompt_tokens||0}<br>
|
|
580
|
+
- Completion: ${i.apiResponse.tokenUsage.completion_tokens||0}<br>
|
|
581
|
+
- Total: ${i.apiResponse.tokenUsage.total_tokens||(i.apiResponse.tokenUsage.prompt_tokens||0)+(i.apiResponse.tokenUsage.completion_tokens||0)}
|
|
582
|
+
</div>
|
|
583
|
+
</div>
|
|
584
|
+
`:``}
|
|
585
|
+
${i.overallScore!==void 0&&i.overallScore!==null?`
|
|
586
|
+
<div class="section-title">${r(`execLog.overallScore`,{score:i.overallScore})}</div>
|
|
587
|
+
`:``}
|
|
588
|
+
${i.dimensions&&Object.keys(i.dimensions).length>0?`
|
|
589
|
+
<div class="reflection-dimensions">
|
|
590
|
+
${Object.entries(i.dimensions).map(([e,t])=>`
|
|
591
|
+
<div class="dimension-item">
|
|
592
|
+
<span class="dim-label">${e}</span>
|
|
593
|
+
<span class="dim-bar"><span class="dim-fill" style="width:${t*10}%"></span></span>
|
|
594
|
+
<span class="dim-score">${t}/10</span>
|
|
595
|
+
</div>
|
|
596
|
+
`).join(``)}
|
|
597
|
+
</div>
|
|
598
|
+
`:``}
|
|
599
|
+
${i.issues&&i.issues.length>0?`
|
|
600
|
+
<div class="section-title">${r(`execLog.sectionIssues`)}</div>
|
|
601
|
+
<div class="section-content"><ul>${i.issues.map(e=>`<li>${P(e)}</li>`).join(``)}</ul></div>
|
|
602
|
+
`:``}
|
|
603
|
+
${i.suggestions&&i.suggestions.length>0?`
|
|
604
|
+
<div class="section-title">${r(`execLog.sectionSuggestions`)}</div>
|
|
605
|
+
<div class="section-content"><ul>${i.suggestions.map(e=>`<li>${P(e)}</li>`).join(``)}</ul></div>
|
|
606
|
+
`:``}
|
|
607
|
+
${i.action?.decision?`
|
|
608
|
+
<div class="section-title">${r(`execLog.labelDecision`,{decision:P(i.action.decision===`passed`?r(`execLog.decisionPassed`):i.action.decision===`revised`?r(`execLog.decisionRevised`):i.action.decision===`needs_improvement`?r(`execLog.decisionNeedsImprovement`):i.action.decision)})}</div>
|
|
609
|
+
`:``}
|
|
610
|
+
${i.useful===void 0?``:`
|
|
611
|
+
<div class="section-title">${i.useful?r(`execLog.resultUseful`):r(`execLog.resultInvalid`)}</div>
|
|
612
|
+
${i.reasoning?`<div class="section-content">${P(i.reasoning)}</div>`:``}
|
|
613
|
+
${i.suggestion?`<div class="section-content">${r(`execLog.labelSuggestion`,{suggestion:P(i.suggestion)})}</div>`:``}
|
|
614
|
+
`}
|
|
615
|
+
</div>
|
|
616
|
+
`:``}
|
|
617
|
+
</div>
|
|
618
|
+
</div>
|
|
619
|
+
</div>
|
|
620
|
+
`}),t}function Jf(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=i.filter(e=>e.status===`success`).length,s=i.filter(e=>e.status===`failed`).length,c=i.filter(e=>e.nodeType===`subtask`).length,l=i.filter(e=>e.nodeType===`subtask`&&e.status===`success`).length,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?Hf(i):`<div class="realtime-waiting-message">${r(`execLog.waitingExecution`)}</div>`,If(t),m.scrollTop=m.scrollHeight}function Yf(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
|
+
<div class="log-container">
|
|
622
|
+
<div class="log-header">
|
|
623
|
+
<div class="log-title">
|
|
624
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
625
|
+
<circle cx="12" cy="12" r="10"></circle>
|
|
626
|
+
<polyline points="12 6 12 12 16 14"></polyline>
|
|
627
|
+
</svg>
|
|
628
|
+
<h3>${r(`execLog.realtimeLogTitle`)}</h3>
|
|
629
|
+
</div>
|
|
630
|
+
<div class="log-close">
|
|
631
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
632
|
+
<line x1="18" y1="6" x2="6" y2="18"></line>
|
|
633
|
+
<line x1="6" y1="6" x2="18" y2="18"></line>
|
|
634
|
+
</svg>
|
|
635
|
+
</div>
|
|
636
|
+
</div>
|
|
637
|
+
|
|
638
|
+
<div class="log-summary">
|
|
639
|
+
<div class="realtime-executing-indicator">
|
|
640
|
+
<span class="realtime-pulse-dot"></span>
|
|
641
|
+
<span class="realtime-executing-label">${r(`execLog.executingLabel`)}</span>
|
|
642
|
+
<span class="realtime-executing-node">${r(`execLog.preparing`)}</span>
|
|
643
|
+
</div>
|
|
644
|
+
<div class="summary-combo">
|
|
645
|
+
<div class="combo-main">
|
|
646
|
+
<span class="combo-icon">◉</span>
|
|
647
|
+
<span class="combo-label">${r(`execLog.totalNodes`)}</span>
|
|
648
|
+
<span class="combo-value">0</span>
|
|
649
|
+
</div>
|
|
650
|
+
<div class="combo-stats">
|
|
651
|
+
<div class="combo-stat success" data-status="success">
|
|
652
|
+
<span class="stat-icon">✓</span>
|
|
653
|
+
<span class="stat-label">${r(`execLog.labelSuccess`)}</span>
|
|
654
|
+
<span class="stat-value">0</span>
|
|
655
|
+
</div>
|
|
656
|
+
<div class="combo-stat failed" data-status="failed">
|
|
657
|
+
<span class="stat-icon">✗</span>
|
|
658
|
+
<span class="stat-label">${r(`execLog.labelFailed`)}</span>
|
|
659
|
+
<span class="stat-value">0</span>
|
|
660
|
+
</div>
|
|
661
|
+
<div class="combo-stat subtask" data-status="subtask" style="display:none">
|
|
662
|
+
<span class="stat-icon">🔀</span>
|
|
663
|
+
<span class="stat-label">${r(`execLog.labelSubtask`)}</span>
|
|
664
|
+
<span class="stat-value">0/0</span>
|
|
665
|
+
</div>
|
|
666
|
+
</div>
|
|
667
|
+
</div>
|
|
668
|
+
<div class="summary-actions">
|
|
669
|
+
<button class="toggle-expand-btn" title="${r(`execLog.expandAll`)}">
|
|
670
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
671
|
+
<polyline points="7 13 12 18 17 13"></polyline>
|
|
672
|
+
<polyline points="7 6 12 11 17 6"></polyline>
|
|
673
|
+
</svg>
|
|
674
|
+
</button>
|
|
675
|
+
</div>
|
|
676
|
+
</div>
|
|
677
|
+
|
|
678
|
+
<div class="timeline">
|
|
679
|
+
<div class="realtime-waiting-message">${r(`execLog.waitingExecution`)}</div>
|
|
680
|
+
</div>
|
|
681
|
+
</div>
|
|
682
|
+
`,document.body.appendChild(n),If(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&&Jf(C.currentExecutionStatus)}function Xf(e){let t=document.querySelector(`.execution-log-panel.realtime-mode`);if(t){t.remove();return}Yf(e)}function Zf(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);if(t!==-1){let n=C.currentExecutionStatus.executionLog[t];C.currentExecutionStatus.executionLog[t]={...e,subtaskIndex:e.subtaskIndex??n.subtaskIndex,subtaskId:e.subtaskId??n.subtaskId,subtaskName:e.subtaskName??n.subtaskName}}else C.currentExecutionStatus.executionLog.push(e)}),C.currentExecutionStatus.nodeName=t,C.currentExecutionStatus.status=n):C.currentExecutionStatus={nodeName:t,status:n,executionLog:[]},document.querySelector(`.execution-log-panel.realtime-mode`)&&Jf(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 Qf(){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 ti({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
|
+
<div class="export-session-item" data-id="${e.id}">
|
|
684
|
+
<input type="checkbox" class="export-session-checkbox" data-session-id="${e.id}" ${n?`checked`:``}>
|
|
685
|
+
<div class="export-session-info">
|
|
686
|
+
<div class="export-session-title">${P(e.title||r(`exportImport.unnamedSession`))}${n?`<span class="current-badge">${r(`exportImport.currentBadge`)}</span>`:``}</div>
|
|
687
|
+
<div class="export-session-meta">${r(`exportImport.messageCount`,{count:a})}${o?` · `+o:``}</div>
|
|
688
|
+
</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),$f()})});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}),$f()}),o&&(o.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=!1}),$f()}),s&&(s.onclick=()=>{t.querySelectorAll(`.export-session-checkbox`).forEach(e=>{e.checked=e.dataset.sessionId===i}),$f()}),$f()}}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 $f(){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 ep(){let e=document.getElementById(`exportSessionsModal`);e&&e.classList.remove(`show`)}async function tp(){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 ti({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),ep(),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 np(){let e=document.getElementById(`exportSessionsCloseBtn`),t=document.getElementById(`exportSessionsCancelBtn`),n=document.getElementById(`exportSessionsOkBtn`),r=document.getElementById(`exportSessionsModal`);e&&e.addEventListener(`click`,ep),t&&t.addEventListener(`click`,ep),n&&n.addEventListener(`click`,tp),r&&r.addEventListener(`click`,e=>{e.target===r&&ep()})}function rp(){let e=document.getElementById(`importSessionsFile`);e&&(e.value=``,e.click())}async function ip(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 gi(a);await yo(),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,op=0,sp=0,cp=!1,lp=0,up=0,dp=0,fp=0,pp=[],mp=0,hp=!1,gp=`brush`,_p=`#ff4757`,vp=4,yp=1,bp=!1,xp=0,Sp=0,Cp=0,wp=0,Tp=0,Ep=0,Dp=[],W=null,G=null,K=null,q=null;function Op(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 kp(){let e=document.getElementById(`imagePreviewLarge`);e&&(e.style.transform=`translate(${op}px, ${sp}px) scale(${ap})`,ap>1?(e.classList.add(`zoomable`),cp?e.classList.add(`dragging`):e.classList.remove(`dragging`)):e.classList.remove(`zoomable`,`dragging`))}function Ap(){ap=1,op=0,sp=0,cp=!1,kp()}function jp(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`:``),Mp(e,t),Np(),Fp(e),n.classList.add(`show`)}function Mp(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)}),mp=pp.indexOf(e),mp===-1&&(pp.push(e),mp=pp.length-1)}function Np(){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=``),Pp())}function Pp(){let e=document.getElementById(`imagePreviewPrev`),t=document.getElementById(`imagePreviewNext`),n=document.getElementById(`imagePreviewCounter`);e&&(e.disabled=!1),t&&(t.disabled=!1),n&&(n.textContent=`${mp+1} / ${pp.length}`)}function Fp(e){let t=document.getElementById(`imagePreviewLarge`);t&&(Ap(),t.src=e)}function Ip(e){let t=pp.length;t!==0&&(mp=(mp+e+t)%t,Fp(pp[mp]),Pp())}function Lp(){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`),Ap()},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&&Op(t.src)});let a=document.getElementById(`imagePreviewEdit`);a&&a.addEventListener(`click`,e=>{e.stopPropagation(),Gp()});let o=document.getElementById(`imagePreviewPrev`),s=document.getElementById(`imagePreviewNext`);o&&o.addEventListener(`click`,e=>{e.stopPropagation(),Ip(-1)}),s&&s.addEventListener(`click`,e=>{e.stopPropagation(),Ip(1)}),document.addEventListener(`keydown`,t=>{e.classList.contains(`show`)&&(t.key===`Escape`?n():t.key===`ArrowLeft`?Ip(-1):t.key===`ArrowRight`&&Ip(1))}),e.addEventListener(`wheel`,n=>{if(!e.classList.contains(`show`)||hp)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,op=i-l*(i-op),sp=a-l*(a-sp),kp()},{passive:!1}),t.addEventListener(`mousedown`,t=>{hp||!e.classList.contains(`show`)||ap<=1||(t.preventDefault(),cp=!0,lp=t.clientX,up=t.clientY,dp=op,fp=sp,kp())}),document.addEventListener(`mousemove`,e=>{cp&&(op=dp+(e.clientX-lp),sp=fp+(e.clientY-up),kp())}),document.addEventListener(`mouseup`,()=>{cp&&(cp=!1,kp())}),t.addEventListener(`dblclick`,()=>{hp||e.classList.contains(`show`)&&(ap>1?Ap():(ap=2,op=0,sp=0,kp()))}),Up()}function Rp(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 zp(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}=Rp(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=``),Bp(),f&&f.focus()},r.readAsDataURL(e)},t.onerror=()=>{URL.revokeObjectURL(n),i.error(`[ChatManager] imageload failed`)},t.src=n}function Bp(){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`,()=>{jp(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),Bp()}),i.appendChild(a),i.appendChild(o),e.appendChild(i)})}}function Vp(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 Hp(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 Up(){W=document.getElementById(`imagePreviewEditCanvas`),K=document.getElementById(`imagePreviewPreviewCanvas`),W&&(G=W.getContext(`2d`,{willReadFrequently:!0}),G.lineCap=`round`,G.lineJoin=`round`),K&&(q=K.getContext(`2d`,{willReadFrequently:!0}),q.lineCap=`round`,q.lineJoin=`round`),Wp();let e=document.getElementById(`imagePreviewLarge`);e&&e.addEventListener(`load`,Yp)}function Wp(){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`),gp=t.dataset.tool,W&&(W.style.cursor=gp===`eraser`?`cell`:`crosshair`)})});let t=document.getElementById(`editorColorPicker`);t&&t.addEventListener(`input`,e=>{_p=e.target.value});let n=document.getElementById(`editorBrushSize`);n&&n.addEventListener(`input`,e=>{vp=parseInt(e.target.value)});let r=document.getElementById(`editorUndoBtn`);r&&r.addEventListener(`click`,im);let i=document.getElementById(`editorConfirmBtn`);i&&i.addEventListener(`click`,am);let a=document.getElementById(`editorCancelBtn`);a&&a.addEventListener(`click`,sm),document.addEventListener(`keydown`,t=>{if(!hp)return;let n={b:`brush`,r:`rectangle`,e:`ellipse`,a:`arrow`,l:`line`};n[t.key.toLowerCase()]&&!t.ctrlKey&&!t.metaKey&&(t.preventDefault(),gp=n[t.key.toLowerCase()],e.querySelectorAll(`[data-tool]`).forEach(e=>{e.classList.toggle(`active`,e.dataset.tool===gp)})),(t.ctrlKey||t.metaKey)&&t.key===`z`&&(t.preventDefault(),im()),t.key===`Enter`&&(t.preventDefault(),am()),t.key===`Escape`&&(t.preventDefault(),sm())})}function Gp(){hp?Jp():Kp()}function Kp(){hp=!0,Dp=[];let e=document.getElementById(`imagePreviewLarge`);if(!e||!e.src)return;Ap(),e.style.transform=`none`,ap=1,op=0,sp=0,e.style.pointerEvents=`none`,e.style.zIndex=`1`,W&&(W.style.display=`block`,W.style.pointerEvents=`auto`,W.style.zIndex=`5`),K&&(K.style.display=`block`,K.style.pointerEvents=`none`,K.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`,qp),setTimeout(()=>{Yp()},50),Dp=[],W&&W.addEventListener(`mousedown`,Zp),document.addEventListener(`mousemove`,Qp),document.addEventListener(`mouseup`,$p)}function qp(e){e.preventDefault()}function Jp(){hp=!1,bp=!1;let e=document.getElementById(`imagePreviewLarge`);e&&(e.style.pointerEvents=``,e.style.zIndex=``),W&&(W.style.display=`none`,W.removeEventListener(`mousedown`,Zp)),K&&(K.style.display=`none`,q.clearRect(0,0,K.width,K.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`,qp),document.removeEventListener(`mousemove`,Qp),document.removeEventListener(`mouseup`,$p)}function Yp(){let e=document.getElementById(`imagePreviewLarge`),t=document.getElementById(`imagePreviewViewport`);if(!e||!t||!W||!K)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`,K.width=i,K.height=a,K.style.width=i+`px`,K.style.height=a+`px`,K.style.left=(r.width-i)/2+`px`,K.style.top=(r.height-a)/2+`px`}function Xp(e){if(!W)return{x:0,y:0};let t=W.getBoundingClientRect();return{x:e.clientX-t.left,y:e.clientY-t.top}}function Zp(e){if(!hp)return;e.preventDefault(),bp=!0;let t=Xp(e);xp=t.x,Sp=t.y,Cp=t.x,wp=t.y,Tp=t.x,Ep=t.y,Dp.push(W.toDataURL()),Dp.length>20&&Dp.shift()}function Qp(e){if(!bp||!hp)return;e.preventDefault();let t=Xp(e);if(Tp=t.x,Ep=t.y,gp===`brush`){G.save(),G.beginPath(),G.strokeStyle=_p,G.lineWidth=vp,G.globalAlpha=yp,G.lineCap=`round`,G.lineJoin=`round`;let e=Tp-Cp,t=Ep-wp,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=Cp+e*i,o=wp+t*i;n===1&&G.moveTo(Cp,wp),G.lineTo(a,o)}}else G.moveTo(Cp,wp),G.lineTo(Tp,Ep);G.stroke(),G.restore(),Cp=Tp,wp=Ep}else if(gp===`eraser`){G.save(),G.beginPath(),G.lineWidth=vp*2,G.lineCap=`round`,G.lineJoin=`round`,G.globalCompositeOperation=`destination-out`;let e=Tp-Cp,t=Ep-wp,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=Cp+e*i,o=wp+t*i;n===1&&G.moveTo(Cp,wp),G.lineTo(a,o)}}else G.moveTo(Cp,wp),G.lineTo(Tp,Ep);G.stroke(),G.restore(),Cp=Tp,wp=Ep}else{if(!q)return;switch(q.clearRect(0,0,K.width,K.height),q.strokeStyle=_p,q.lineWidth=vp,q.globalAlpha=yp,q.lineCap=`round`,q.lineJoin=`round`,gp){case`rectangle`:em();break;case`ellipse`:tm();break;case`arrow`:nm();break;case`line`:rm();break}}}function $p(){bp&&(bp=!1,gp!==`brush`&&gp!==`eraser`&&q&&(G.drawImage(K,0,0),q.clearRect(0,0,K.width,K.height)))}function em(){let e=Math.min(xp,Tp),t=Math.min(Sp,Ep),n=Math.abs(Tp-xp),r=Math.abs(Ep-Sp);if(event.shiftKey){let e=Math.max(n,r),t=Tp>xp?xp:xp-e,i=Ep>Sp?Sp:Sp-e;q.strokeRect(t,i,e,e)}else q.strokeRect(e,t,n,r)}function tm(){let e=Math.min(xp,Tp),t=Math.min(Sp,Ep),n=Math.abs(Tp-xp),r=Math.abs(Ep-Sp);if(event.shiftKey){let e=Math.max(n,r),t=Tp>xp?xp:xp-e,i=Ep>Sp?Sp:Sp-e;q.beginPath(),q.ellipse(t+e/2,i+e/2,e/2,e/2,0,0,Math.PI*2),q.stroke()}else q.beginPath(),q.ellipse(e+n/2,t+r/2,n/2,r/2,0,0,Math.PI*2),q.stroke()}function nm(){let e=Math.atan2(Ep-Sp,Tp-xp);q.beginPath(),q.moveTo(xp,Sp),q.lineTo(Tp,Ep),q.stroke(),q.beginPath(),q.moveTo(Tp,Ep),q.lineTo(Tp-12*Math.cos(e-Math.PI/6),Ep-12*Math.sin(e-Math.PI/6)),q.moveTo(Tp,Ep),q.lineTo(Tp-12*Math.cos(e+Math.PI/6),Ep-12*Math.sin(e+Math.PI/6)),q.stroke()}function rm(){q.beginPath(),q.moveTo(xp,Sp),q.lineTo(Tp,Ep),q.stroke()}function im(){if(Dp.length===0)return;let e=Dp.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`),Dp.length>0&&im()},t.src=e}function am(){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)),Jp(),t.classList.remove(`show`),Ap()}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},Bp()}let i=document.getElementById(`imagePreviewLarge`);i&&(i.src=e)}function sm(){G&&G.clearRect(0,0,W.width,W.height),Dp=[],Jp()}var cm=t({attachFiles:()=>Em,buildFileContentText:()=>Am,clearFiles:()=>Om,extractFileContent:()=>_m,formatFileSize:()=>fm,getAgentConnectionInfo:()=>vm,getFileCategory:()=>um,getFileIcon:()=>dm,processFile:()=>Tm,removeFile:()=>Dm,renderFilePreviews:()=>km,runImagePipeline:()=>wm,uploadFileToAgent:()=>bm});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 lm=`.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 um(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`:lm.some(e=>t.endsWith(e))?`text`:`unknown`}function dm(e){switch(um(e)){case`pdf`:return`📄`;case`docx`:case`doc`:return`📝`;case`xlsx`:return`📊`;case`text`:return`📃`;default:return`📎`}}function fm(e){return e<1024?e+` B`:e<1024*1024?(e/1024).toFixed(1)+` KB`:(e/(1024*1024)).toFixed(1)+` MB`}async function pm(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 mm(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
|
+
|
|
691
|
+
`)}async function hm(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 gm(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
|
+
|
|
693
|
+
`)}async function _m(e){switch(um(e.name)){case`pdf`:return await mm(e);case`docx`:return await hm(e);case`doc`:throw Error(r(`fileExtract.oldDocNotSupported`));case`xlsx`:return await gm(e);case`text`:return await pm(e);default:return await pm(e)}}async function vm(){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 ym(e){let t={Authorization:`Bearer ${e}`},n=C.activeSessionId;return n&&(t[`X-AIH-Session-Id`]=n),t}async function bm(e){let t=await vm();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:ym(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 xm(e,t){let n=await vm();if(!n)throw Error(r(`fileExtract.agentNotPaired`));let i=await fetch(`${n.url}${e}`,{method:`POST`,headers:{"Content-Type":`application/json`,...ym(n.token)},body:JSON.stringify(t)});if(!i.ok)throw Error(`HTTP ${i.status}`);return await i.json()}async function Sm(e){let t=await xm(`/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 vm();if(n)for(let t of(e.images||[]).slice(0,se.DESCRIBE_LIMIT))try{let e=await fetch(`${n.url}/api/fs/download`,{method:`POST`,headers:{"Content-Type":`application/json`,...ym(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 Cm(e,t,n){let{images:r,truncated:i,skipped:a}=n===`docx`?await ee(t):n===`xlsx`?await pe(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 wm(e,t,n,r){if(C.enableImageInput&&!(n!==`docx`&&n!==`pdf`&&n!==`xlsx`))try{if(r&&n===`docx`)try{await Sm(e)}catch(r){i.warn(`[FileExtract] agent image extract failed, downgrade to local:`,r.message),await Cm(e,t,n)}else await Cm(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),se.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 Tm(e,t){let n=C.attachedFiles[t];if(!n)return;n.status=`extracting`,km();let a=um(e.name);try{if(C.agentPlatform?.connected)try{let t=await bm(e);n.agentPath=t.path,n.text=t.text||``,n.status=`done`,km(),await wm(n,e,a,!0),km();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 _m(e),n.status=`done`,km(),await wm(n,e,a,!1)}catch(t){i.error(`[FileExtract] file extract failed:`,e.name,t),n.status=`error`,n.error=t.message}km()}function Em(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),Tm(t,C.attachedFiles.length-1)}km()}function Dm(e){let t=C.attachedFiles[e];t?.dataUrl&&URL.revokeObjectURL(t.dataUrl),C.attachedFiles.splice(e,1),km()}function Om(){for(let e of C.attachedFiles)e.dataUrl&&URL.revokeObjectURL(e.dataUrl);C.attachedFiles=[],km()}function km(){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} (${fm(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=dm(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=fm(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=we(t),i.appendChild(e)}else !C.enableImageInput&&[`docx`,`pdf`,`xlsx`].includes(um(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(),Dm(n)}),i.appendChild(a),e.appendChild(i)})}}function Am(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
|
+
`+r(`fileExtract.truncated`):e.text;n.push(r(`fileExtract.fileContentMarker`,{name:e.name})+`
|
|
695
|
+
`+t+ie(e,e.name))}return`
|
|
696
|
+
|
|
697
|
+
`+n.join(`
|
|
698
|
+
|
|
699
|
+
---
|
|
700
|
+
|
|
701
|
+
`)}async function jm(){try{C.bookmarks=await o()||[],i.debug(`[Bookmark] loadedbookmark:`,C.bookmarks.length,``)}catch(e){i.error(`[Bookmark] load bookmarks failed:`,e),C.bookmarks=[]}}function Mm(e,t){return C.bookmarks.find(n=>n.sessionId===e&&n.messageId===t)||null}async function Nm(e,t,n,r){if(!e||!t)return null;let a=Mm(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 Pm(e,t){let n=Mm(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 Fm(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 Im(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 Lm(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 Rm=t({initBookmarkPanel:()=>zm,refreshBookmarkPanel:()=>Bm,updateBookmarkBadge:()=>Wm,updateBookmarkBtnState:()=>Km,updateBookmarkButtons:()=>Gm});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 zm(){let e=document.createElement(`div`);e.className=`bookmark-panel-container`,e.id=`bookmarkPanelContainer`,e.innerHTML=`
|
|
702
|
+
<button class="bookmark-panel-toggle" id="bookmarkPanelToggle" title="${r(`bookmark.toggleTitle`)}">
|
|
703
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
704
|
+
<path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>
|
|
705
|
+
</svg>
|
|
706
|
+
|
|
707
|
+
</button>
|
|
708
|
+
<div class="bookmark-panel" id="bookmarkPanel">
|
|
709
|
+
<div class="bookmark-panel-header">
|
|
710
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:16px;height:16px;color:var(--warning-500);">
|
|
711
|
+
<path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>
|
|
712
|
+
</svg>
|
|
713
|
+
<span>${r(`bookmark.title`)}</span>
|
|
714
|
+
<span class="bookmark-panel-count" id="bookmarkPanelCount"></span>
|
|
715
|
+
<button class="bookmark-panel-close-btn" id="bookmarkPanelClose" title="${r(`common.close`)}">
|
|
716
|
+
<svg viewBox="0 0 16 16" fill="currentColor"><path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/></svg>
|
|
717
|
+
</button>
|
|
718
|
+
</div>
|
|
719
|
+
<div class="bookmark-search">
|
|
720
|
+
<div class="bookmark-search-input-wrapper">
|
|
721
|
+
<input type="text" class="bookmark-search-input" id="bookmarkSearchInput" placeholder="${r(`bookmark.searchPlaceholder`)}" />
|
|
722
|
+
<button class="bookmark-search-clear" id="bookmarkSearchClear" title="${r(`bookmark.clearSearchTitle`)}" style="display:none;">
|
|
723
|
+
<svg viewBox="0 0 16 16" fill="currentColor"><path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/></svg>
|
|
724
|
+
</button>
|
|
725
|
+
</div>
|
|
726
|
+
</div>
|
|
727
|
+
<div class="bookmark-panel-content" id="bookmarkPanelContent">
|
|
728
|
+
<div class="bookmark-panel-empty">${r(`bookmark.empty`)}</div>
|
|
729
|
+
</div>
|
|
730
|
+
</div>
|
|
731
|
+
`,hn(`bookmark`).appendChild(e);let t=document.getElementById(`bookmarkPanelToggle`),n=document.getElementById(`bookmarkPanel`),a=document.getElementById(`bookmarkSearchInput`),o=document.getElementById(`bookmarkPanelClose`);C.bookmarkSearchHistory=[],C.bookmarkSearchHistoryIndex=-1;try{chrome.storage.local.get([`bookmarkSearchHistory`],e=>{e.bookmarkSearchHistory&&(C.bookmarkSearchHistory=e.bookmarkSearchHistory)})}catch{}function s(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`)?(n.classList.remove(`expanded`),Re(n)):(Bm(a.value),n.classList.add(`expanded`),Be(n))}),o.addEventListener(`click`,()=>{n.classList.remove(`expanded`),Re(n)});let c=document.getElementById(`bookmarkSearchClear`);a.addEventListener(`input`,()=>{let e=a.value.trim();Bm(e),c.style.display=e?``:`none`}),c.addEventListener(`click`,()=>{a.value=``,c.style.display=`none`,C.bookmarkSearchHistoryIndex=-1,Bm()}),a.addEventListener(`keydown`,e=>{if(e.key===`Enter`){e.preventDefault();let t=a.value.trim();t&&(s(t),Bm(t))}else if(e.key===`Escape`)C.bookmarkSearchHistoryIndex>=0&&(C.bookmarkSearchHistoryIndex=-1,a.value=``,Bm(),c.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]||``,c.style.display=a.value?``:`none`,Bm(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=``),c.style.display=a.value?``:`none`,Bm(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 Fm(n),Bm(),Gm();return}if(e.target.closest(`.bookmark-item-pin`)){e.stopPropagation();let t=C.bookmarks.find(e=>e.id===n);t&&(await Im(n,!t.pinned),Bm());return}await Um(r,i)}),i.debug(`[BookmarkPanel] bookmark panelinitializing`)}function Bm(e){let t=document.getElementById(`bookmarkPanelContent`),n=document.getElementById(`bookmarkPanelCount`);if(!t||!n)return;let i=C.activeSessionId,a=Lm(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>`,Wm();return}if(c&&d===0){t.innerHTML=`<div class="bookmark-panel-empty">${r(`bookmark.noMatch`)}</div>`,Wm();return}let f=``;a.length>0&&(f+=`<div class="bookmark-section">
|
|
732
|
+
<div class="bookmark-section-title">${r(`searchPanel.currentSession`)}</div>
|
|
733
|
+
${Vm(a,c)}
|
|
734
|
+
</div>`),o.length>0&&(f+=`<div class="bookmark-section">
|
|
735
|
+
<div class="bookmark-section-title">${r(`bookmark.otherSessions`)}</div>
|
|
736
|
+
${Vm(o,c)}
|
|
737
|
+
</div>`),t.innerHTML=f,Wm()}function Vm(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=Hm(a,n),o=Hm(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
|
+
<div class="bookmark-item ${s}" data-bookmark-id="${e.id}" data-session-id="${e.sessionId}" data-message-id="${e.messageId}">
|
|
739
|
+
<div class="bookmark-item-header">
|
|
740
|
+
<span class="bookmark-item-session" title="${P(i)}">${o}</span>
|
|
741
|
+
<span class="bookmark-item-time">${c}</span>
|
|
742
|
+
</div>
|
|
743
|
+
<div class="bookmark-item-content" title="${P(t)}">${a}</div>
|
|
744
|
+
<div class="bookmark-item-actions">
|
|
745
|
+
<button class="bookmark-item-pin" title="${e.pinned?r(`bookmark.unpinTitle`):r(`bookmark.pinTitle`)}">
|
|
746
|
+
<svg viewBox="0 0 24 24" fill="${e.pinned?`currentColor`:`none`}" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
747
|
+
<line x1="12" y1="17" x2="12" y2="22"/>
|
|
748
|
+
<path d="M5 17h14v-1.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V6h1a2 2 0 0 0 0-4H8a2 2 0 0 0 0 4h1v4.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24Z"/>
|
|
749
|
+
</svg>
|
|
750
|
+
</button>
|
|
751
|
+
<button class="bookmark-item-remove" title="${r(`bookmark.removeBookmarkTitle`)}">
|
|
752
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
753
|
+
<path d="M3 6h18M19 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"/>
|
|
754
|
+
</svg>
|
|
755
|
+
</button>
|
|
756
|
+
</div>
|
|
757
|
+
</div>
|
|
758
|
+
`}).join(``)}function Hm(e,t){if(!t)return e;let n=P(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 Um(e,t){if(!(!e||!t)){if(C.activeSessionId!==e)try{let n=C.activeSessionId;if(await oi(e)===!1||C.activeSessionId!==e){await Pm(e,t),Bm(),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(()=>mo);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)):Pm(e,t).then(()=>{Bm(),F(r(`bookmark.messageNotExistToast`),`warning`)})},500)}}function Wm(){let e=document.getElementById(`bookmarkPanelContainer`),t=C.bookmarks.length;e&&(e.style.display=t>0?``:`none`)}function Gm(){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;Km(t,r,n)})}function Km(e,t,n){Mm(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 qm(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 Jm(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 Ym(e){return e===`drive`?`💽`:e===`home`?`🏠`:e===`root`?`🗂`:`📁`}function Xm(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
|
+
<div class="wdb-header">
|
|
760
|
+
<div class="wdb-agent">${P(n(`workspace.browseAgentHost`,{platform:i||r,host:a||`-`}))}</div>
|
|
761
|
+
<div class="wdb-purge" hidden></div>
|
|
762
|
+
<div class="wdb-roots"></div>
|
|
763
|
+
</div>
|
|
764
|
+
<div class="wdb-error" hidden></div>
|
|
765
|
+
<div class="wdb-crumbs"></div>
|
|
766
|
+
<div class="wdb-list" role="listbox" tabindex="0" aria-label="${P(n(`workspace.browseRoots`))}"></div>
|
|
767
|
+
<div class="wdb-footer">
|
|
768
|
+
<button type="button" class="wdb-btn wdb-back">${P(n(`workspace.browseBackToList`))}</button>
|
|
769
|
+
<span class="wdb-spacer"></span>
|
|
770
|
+
<button type="button" class="wdb-btn wdb-native" ${l?``:`hidden`}>${P(n(`workspace.browseUseNative`))}</button>
|
|
771
|
+
<button type="button" class="wdb-btn wdb-choose" disabled>${P(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">${P(n(`workspace.browseRoots`))}</span>`+p.roots.map(e=>`<button type="button" class="wdb-root" data-path="${P(e.path)}" title="${P(e.path)}">${Ym(e.kind)} ${P(e.name)}</button>`).join(``)}function _(){if(!p.currentPath){f.crumbs.innerHTML=``;return}let e=qm(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="${P(t.path)}" title="${P(t.path)}"${r?` disabled`:``}>${P(t.name)}</button>`}).join(`<span class="wdb-crumb-sep">›</span>`)}function v(){if(p.outdated){f.list.innerHTML=`<div class="wdb-state">${P(n(`workspace.browseUnsupported`))}</div>`;return}if(p.loading){f.list.innerHTML=`<div class="wdb-state">${P(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">${P(n(`workspace.browseEmpty`))}</div>`;return}f.list.innerHTML=t.map(t=>{let r=p.selectedPath&&t.path===p.selectedPath,i=e?Ym(t.kind):`📁`,a=t.link?`<span class="wdb-link">${P(n(`workspace.browseLinkTag`))}</span>`:``,o=e?``:`<span class="wdb-pick" role="button" data-pick="1" title="${P(n(`workspace.browseChooseDir`))}" aria-label="${P(n(`workspace.browseChooseDir`))}">✓</span>`;return`<button type="button" class="wdb-item${r?` selected`:``}" role="option" aria-selected="${r?`true`:`false`}" data-path="${P(t.path)}" data-root="${e?`1`:`0`}" title="${P(t.path)}"><span class="wdb-item-icon">${i}</span><span class="wdb-item-name">${P(t.name)}</span>${a}${o}</button>`}).join(``),p.truncated&&f.list.insertAdjacentHTML(`beforeend`,`<div class="wdb-state wdb-truncated">${P(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(Jm(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 Zm(e){let t=e||C.activeSessionId;return t?!!(C.generatingSessionIds?.has(t)||fr(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 Qm(){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`),$m(),C.enableImageInput||(C.attachedImages=[]),th()}function $m(){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`)))),$m(),C.enableFileInput||Om()}function th(){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`,()=>{jp(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),th()}),i.appendChild(a),i.appendChild(o),e.appendChild(i)})}}async function nh(){if(!C.enableImageInput){F(r(`imageHelper.enableImageInputFirst`));return}try{let e=await chrome.runtime.sendMessage({type:`CAPTURE_TAB`});e?.dataUrl&&(zp(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 rh(){let e=await Ie();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 ih(n.dataUrl,t);if(!a){F(r(`imageHelper.cropFailed`));return}zp(await(await fetch(a)).blob())}catch(e){i.error(`[SidePanel] region screenshot failed:`,e),F(r(`imageHelper.regionScreenshotFailed`))}}function ih(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 ah(e,t,n){if(!C.enableImageInput){F(r(`imageHelper.enableImageInputFirst`));return}try{let i=e;t===`region`&&n&&(i=await ih(e,n)),zp(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:()=>hy,closePreview:()=>Z_,closeWorkspacePanel:()=>zv,closeWorkspacePreview:()=>Rv,initWorkspacePanel:()=>kh,locateFileInWorkspace:()=>Iv,openWorkspacePanel:()=>Xh,previewArtifactFile:()=>Lv,refreshWorkspacePanel:()=>kv,resetAndRefreshWorkspace:()=>Av,resolveWorkspaceAbsolutePath:()=>Bv,showSwitchWorkdirDialog:()=>ry,updateWorkspacePanelVisibility:()=>jv});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
|
+
|
|
774
|
+
路径: {path}
|
|
775
|
+
类型: 目录
|
|
776
|
+
|
|
777
|
+
删除后可在回收站中恢复(7天后自动清理)`,confirmDeleteFile:`确定要删除文件 "{name}" 吗?
|
|
778
|
+
|
|
779
|
+
路径: {path}
|
|
780
|
+
类型: 文件
|
|
781
|
+
|
|
782
|
+
删除后可在回收站中恢复(7天后自动清理)`,confirmDeleteTitle:`确认删除`,dirDeleted:`目录 已删除`,fileDeleted:`文件 已删除`,deleteFailedWithError:`删除失败: {error}`,deleteFailed:`删除失败`,confirmBatchDelete:`确定要删除选中的 {count} 个文件/目录吗?
|
|
783
|
+
|
|
784
|
+
{names}
|
|
785
|
+
|
|
786
|
+
删除后可在回收站中恢复(7天后自动清理)`,batchNamesMore:`
|
|
787
|
+
• ... 等共 {count} 项`,confirmBatchDeleteTitle:`确认批量删除`,deletedCount:`已删除 {success} 项{failed}`,deletedCountFailed:`,{count} 项失败`,fileDetailsTitle:`{name} - 文件详情`,getTypeDir:`目录`,getTypeSymlink:`符号链接`,getTypeFile:`文件`,bytes:`字节`,infoName:`名称`,infoType:`类型`,infoPath:`路径`,infoSize:`大小`,infoMime:`MIME 类型`,infoMtime:`修改时间`,infoCtime:`创建时间`,infoAtime:`访问时间`,infoPermission:`权限`,getDetailsFailed:`获取详情失败: {error}`,getWorkdirInfoFailed:`获取工作目录信息失败`,cannotConnectAgent:`无法连接 Agent,请确认代理已启动`,switchWorkdirTitle:`切换工作目录`,currentLabel:`当前: `,notSet:`未设置`,selectFromAllowed:`从允许的目录中选择(非当前目录可移除)`,orInputPath:`或输入绝对路径`,manualPathPlaceholder:`/Users/you/path 或 ~/path`,browseBtn:`浏览…`,browseUnavailable:`当前代理端环境不支持目录选择,请手动输入路径`,browseFailedWithError:`目录选择失败: {error}`,browseAgentOutdated:`当前代理端版本过旧,不支持目录选择,请更新代理端后重试`,browseBusy:`已有一个目录选择窗口在等待,请先完成或关闭它`,browseTimeout:`目录选择窗口未响应(可能被系统安全策略拦截或窗口不可见),请手动输入路径`,picking:`等待选择…`,browseAgentHost:`代理端: {platform} · {host}`,browseRoots:`位置`,browseLinkTag:`链接`,browseLoading:`正在读取…`,browseEmpty:`此目录下没有子目录`,browseTruncated:`目录项过多,仅显示前 5000 项`,browseNotFound:`目录不存在或已被删除`,browseNotDir:`该路径不是目录`,browsePermissionDenied:`无权访问该目录(当前 Agent 进程权限不足)`,browseBadPath:`目录路径无效,请使用 Agent 主机的原生绝对路径`,browseRateLimited:`操作过于频繁,请稍后重试`,browseLoadFailed:`读取目录失败: {error}`,browseUnsupported:`当前代理端版本过旧,暂不支持目录浏览,请手动输入路径或更新代理端`,browseBackToList:`返回列表`,browseUp:`上级`,browseChooseCurrent:`选择当前目录`,browseChooseDir:`选择此目录`,browseUseNative:`改用系统对话框`,switchBtn:`切换`,noAllowedPaths:`暂无允许的目录`,currentTag:`当前`,defaultTag:`默认`,removeFromAllowed:`从允许列表移除`,confirmRemovePath:`确定要从允许访问的目录列表中移除以下目录吗?
|
|
788
|
+
{path}
|
|
789
|
+
|
|
790
|
+
移除后 AI 将无法访问该目录,可重新切换工作目录再加回。`,confirmRemoveStillUsable:`确定要从允许访问的目录列表中移除以下目录吗?
|
|
791
|
+
{path}
|
|
792
|
+
|
|
793
|
+
它是当前会话的目录或代理默认目录,移出列表后仍照常可用(工作目录不受允许列表限制),只是不再作为「附加授权」显示。`,confirmRemovePathTitle:`确认移除允许目录`,removedFromAllowed:`已从允许列表移除`,removedStillUsable:`已从允许列表移除(它仍是工作目录/默认目录,照常可用)`,removeFailedWithError:`移除失败: {error}`,selectOrInputPath:`请选择或输入目标路径`,alreadyCurrentWorkdir:`该目录已是当前工作目录`,confirmSwitchToNewDefault:`该路径不在允许列表内。本次会把它设为代理默认目录,切换后自动创建目录并加入允许列表(影响未绑定的会话):
|
|
794
|
+
{path}`,confirmSwitchToNewTitle:`确认切换到新默认目录`,switchFailedWithError:`切换失败: {error}`,switchedTo:`已切换到: {path}`,switchedToAndSetDefault:`已切换到: {path},并设为代理默认目录`,setAsDefaultDone:`已设为代理默认目录: {path}`,renameDir:`重命名目录`,renameFile:`重命名文件`,inputNewName:`输入新名称`,renamedTo:`已重命名为 "{name}"`,renameFailedWithError:`重命名失败: {error}`,newFolderTitle:`新建文件夹`,inputFolderName:`输入文件夹名称`,folderCreated:`已创建文件夹 "{name}"`,createFailedWithError:`创建失败: {error}`,addedFilesToQuestion:`已添加 {count} 个文件到问答`,addedFilesToQuestionNoImage:`已添加 {count} 个文件到问答(图片识别未启用,图片作为文件附件)`,selectedCount:`已选 {count}`,unsavedChanges:`未保存的修改`,discardChangesPrompt:`有未保存的修改,确定要{action}吗?`,actionClosePreview:`关闭预览`,actionCancelEdit:`取消编辑`,saving:`保存中...`,saveSuccess:`保存成功`,saveFailedWithError:`保存失败: {error}`,agentNamePrefix:` · {name}`,agentNotPaired:`Agent 未配对`,fileDetailsLabel:`文件详情`,loadingLabel:`加载中...`,export:`导出`,exportDocx:`Word`,exportPdf:`PDF`,exportImage:`图片`,exportMd:`Markdown`,copyMarkdownHint:`按住 Ctrl/Cmd 点击复制富文本`}}),n(`en`,{workspace:{workDir:`Working Directory`,closePanel:`Close Panel`,embedMode:`Embed mode`,floatMode:`Floating mode`,openPanel:`Open workspace panel`,narrowViewportHint:`Viewport too narrow, switched back to floating mode`,switchWorkdir:`Switch Working Directory`,backToParent:`Back to Parent Directory`,uploadToCurrent:`Upload files to current directory`,newFolder:`New Folder`,askSelectedFiles:`Ask based on selected files`,downloadSelected:`Download selected files/directories (multi-select as ZIP)`,deleteSelected:`Delete selected files`,clearSearch:`Clear`,search:`Search`,searchPlaceholder:`Search...`,selectAllToggle:`Select All / Deselect All`,colName:`Name`,colSize:`Size`,colTime:`Modified`,noMatch:`No matching files found`,dirEmpty:`This directory is empty`,noWorkspace:`Unable to access working directory. Please confirm the Agent is connected.`,loadDirFailed:`Failed to load directory`,refreshFailed:`Unable to refresh. Please confirm the Agent is connected.`,agentNotConnected:`Agent not connected`,agentNotConnectedUpload:`Agent not connected, unable to upload`,unsupportedFileType:`Unsupported file type`,binaryFileNoPreview:`Looks like a binary file. Text preview is not supported. Please download directly.`,unknownError:`Unknown error`,copiedFileName:`Copied file name: {name}`,copiedPath:`Copied path: {path}`,copyFailed:`Copy failed`,copiedToClipboard:`Copied to clipboard`,copyFailedManual:`Copy failed, please select and copy manually`,getContentFailed:`Failed to get content`,codeCopiedToClipboard:`Code copied to clipboard`,copyUnsupportedType:`Copying text content is not supported for this file type`,copiedToClipboardShort:`Copied to clipboard`,clickToCopy:`Click to copy`,preview:`Preview`,previewBtn:`Preview`,details:`Details`,download:`Download`,downloadFile:`Download file`,rename:`Rename`,askFile:`Ask about file`,delete:`Delete`,copyAll:`Copy`,copyAllTitle:`Copy all content`,toggleRenderPreview:`Toggle rendered preview`,openInBrowser:`Open in browser`,openInBrowserBtn:`Open in browser`,fullscreenPreview:`Fullscreen preview`,exitFullscreen:`Exit fullscreen`,enterEditMode:`Enter edit mode`,edit:`Edit`,save:`Save`,saveChanges:`Save changes (Ctrl+S)`,cancelChanges:`Cancel changes (Esc)`,closePreview:`Close preview`,close:`Close`,confirm:`OK`,cancel:`Cancel`,switchToSourcePreview:`Switch to source preview`,switchToRenderPreview:`Switch to rendered preview`,markdownRendered:`Markdown rendered`,lineCount:`{count} lines`,linesModified:`{count} lines · Modified`,truncatedHint:`(Showing first {shown} of {total} lines. Download to view full content.)`,fileTooLargeNoPreview:`File too large ({size}). Preview not supported. Please download directly.`,fileTooLargeOpenInBrowser:`File too large ({size}) for built-in preview. Please click "Open in browser" above to view.`,previewFailed:`Preview failed: {error}`,openFailed:`Open failed: {error}`,documentEmpty:`(Empty document)`,pptxEmptyOrFailed:`PPTX file is empty or failed to parse`,pageCount:`{count} pages`,prevPage:`Previous page`,nextPage:`Next page`,zoomOut:`Zoom out`,zoomIn:`Zoom in`,fitPage:`Fit page`,originalSize:`Original size`,imageLoadFailed:`Image load failed`,parsingExcel:`Parsing Excel file...`,loadingData:`Loading data...`,requestFailed:`Request failed: {error}`,parseFailed:`Parse failed: {error}`,noSheetsInWorkbook:`No worksheets in the workbook`,sheetNotFound:`Worksheet data not found`,emptySheet:`(Empty sheet)`,xlsxTruncatedHint:`Showing first {shown} of {total} rows. Download to view full content.`,unsupportedMediaHint:`⚠ The browser cannot play this format ({ext}). Please download and use a local player.`,uploading:`Uploading...`,downloadInProgress:`Downloading`,uploadInProgress:`Uploading`,cancelUpload:`Cancel upload`,downloadCanceled:`Download canceled`,downloadFailed:`Download failed`,downloadFailedWithError:`Download failed: {error}`,savingToLocal:`Saving to local via browser...`,savedToLocal:`Saved to local`,downloaded:`Downloaded: {name}`,downloadedCount:`Downloaded {count} files`,downloadedZip:`Downloaded {count} files (ZIP archive)`,fileCount:`{count} files`,uploadCanceled:`Upload canceled`,uploadSuccessCount:`Success {count}`,uploadSkippedCount:`Skipped {count}`,uploadFailedCount:`Failed {count}`,uploadComplete:`Upload complete`,uploadCompleteWithStats:`Upload complete · {stats}`,uploadedFiles:`Successfully uploaded {count} files`,filesSkipped:`{count} file(s) already exist, skipped`,filesUploadFailed:`{count} file(s) failed to upload`,uploadFailed:`Upload failed`,uploadFailedWithStatus:`Upload failed ({status})`,parseResponseFailed:`Failed to parse response`,networkError:`Network error`,cannotMoveToSubdir:`Cannot move a directory into its own subdirectory`,moving:`Moving...`,movedToDir:`"{name}" moved to target directory`,movedToTarget:`"{name}" moved to "{target}"`,moveFailed:`Move failed: {error}`,searching:`Searching...`,confirmDeleteDir:`Are you sure you want to delete directory "{name}" and all its contents?
|
|
795
|
+
|
|
796
|
+
Path: {path}
|
|
797
|
+
Type: Directory
|
|
798
|
+
|
|
799
|
+
Deleted items can be restored from the trash (auto-cleaned after 7 days).`,confirmDeleteFile:`Are you sure you want to delete file "{name}"?
|
|
800
|
+
|
|
801
|
+
Path: {path}
|
|
802
|
+
Type: File
|
|
803
|
+
|
|
804
|
+
Deleted items can be restored from the trash (auto-cleaned after 7 days).`,confirmDeleteTitle:`Confirm Delete`,dirDeleted:`Directory deleted`,fileDeleted:`File deleted`,deleteFailedWithError:`Delete failed: {error}`,deleteFailed:`Delete failed`,confirmBatchDelete:`Are you sure you want to delete the selected {count} file(s)/directory(s)?
|
|
805
|
+
|
|
806
|
+
{names}
|
|
807
|
+
|
|
808
|
+
Deleted items can be restored from the trash (auto-cleaned after 7 days).`,batchNamesMore:`
|
|
809
|
+
• ... and {count} more`,confirmBatchDeleteTitle:`Confirm Batch Delete`,deletedCount:`Deleted {success} item(s){failed}`,deletedCountFailed:`, {count} failed`,fileDetailsTitle:`{name} - File Details`,getTypeDir:`Directory`,getTypeSymlink:`Symbolic link`,getTypeFile:`File`,bytes:`bytes`,infoName:`Name`,infoType:`Type`,infoPath:`Path`,infoSize:`Size`,infoMime:`MIME Type`,infoMtime:`Modified`,infoCtime:`Created`,infoAtime:`Accessed`,infoPermission:`Permission`,getDetailsFailed:`Failed to get details: {error}`,getWorkdirInfoFailed:`Failed to get working directory info`,cannotConnectAgent:`Cannot connect to Agent. Please confirm the agent is running.`,switchWorkdirTitle:`Switch Working Directory`,currentLabel:`Current: `,notSet:`Not set`,selectFromAllowed:`Select from allowed directories (non-current can be removed)`,orInputPath:`Or enter an absolute path`,manualPathPlaceholder:`/Users/you/path or ~/path`,browseBtn:`Browse…`,browseUnavailable:`The agent environment does not support directory selection. Please enter the path manually.`,browseFailedWithError:`Directory selection failed: {error}`,browseAgentOutdated:`The agent version is outdated and does not support directory selection. Please update the agent and try again.`,browseBusy:`A directory picker is already open. Please finish or close it first.`,browseTimeout:`The directory picker did not respond (it may be blocked by security policy or not visible). Please enter the path manually.`,picking:`Waiting…`,browseAgentHost:`Agent: {platform} · {host}`,browseRoots:`Locations`,browseLinkTag:`link`,browseLoading:`Loading…`,browseEmpty:`No subdirectories here`,browseTruncated:`Too many entries; showing the first 5000`,browseNotFound:`Directory does not exist or has been removed`,browseNotDir:`This path is not a directory`,browsePermissionDenied:`Access denied to this directory (insufficient Agent process permissions)`,browseBadPath:`Invalid directory path; use an absolute native path on the Agent host`,browseRateLimited:`Too many requests; please try again later`,browseLoadFailed:`Failed to read directory: {error}`,browseUnsupported:`The Agent version is too old to browse directories; enter the path manually or update the Agent`,browseBackToList:`Back to list`,browseUp:`Up`,browseChooseCurrent:`Choose this directory`,browseChooseDir:`Choose selected`,browseUseNative:`Use system dialog`,switchBtn:`Switch`,noAllowedPaths:`No allowed directories`,currentTag:`Current`,defaultTag:`Default`,removeFromAllowed:`Remove from allowed list`,confirmRemovePath:`Are you sure you want to remove the following directory from the allowed list?
|
|
810
|
+
{path}
|
|
811
|
+
|
|
812
|
+
After removal, the AI will no longer be able to access this directory. You can switch the working directory again to add it back.`,confirmRemoveStillUsable:`Remove the following directory from the allowed list?
|
|
813
|
+
{path}
|
|
814
|
+
|
|
815
|
+
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 J=null,sh=null,ch=[],lh=50,uh=240,dh=280,fh=520,ph=320,mh=`workspacePanelEmbedMode`,hh=`workspacePanelEmbedWidth`,gh=`workspacePanelExpanded`,_h=!1,vh=ph,yh=!1,bh=!1,xh=!1,Sh={field:`name`,asc:!0},Y=new Set,Ch=!1,wh=!1,Th=-1,Eh=!1,Dh=null;function Oh(e,t,n){e?.aborted||window.addEventListener(t,n,e?{signal:e}:void 0)}function kh(){if(xh)return;xh=!0;let e=document.createElement(`div`);e.className=`workspace-panel-container`,e.id=`workspacePanelContainer`,e.innerHTML=`
|
|
817
|
+
<button class="workspace-panel-toggle" id="workspacePanelToggle" title="${r(`workspace.workDir`)}">
|
|
818
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
819
|
+
<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"/>
|
|
820
|
+
</svg>
|
|
821
|
+
</button>
|
|
822
|
+
<div class="workspace-panel" id="workspacePanel">
|
|
823
|
+
<div class="workspace-panel-header">
|
|
824
|
+
<div class="workspace-panel-title-row">
|
|
825
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="width:16px;height:16px;color:var(--info-500);">
|
|
826
|
+
<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"/>
|
|
827
|
+
</svg>
|
|
828
|
+
<span>${r(`workspace.workDir`)}</span>
|
|
829
|
+
<span class="workspace-agent-name" id="workspaceAgentName"></span>
|
|
830
|
+
<button class="workspace-panel-mode-btn" id="workspacePanelModeBtn" title="${r(`workspace.embedMode`)}">
|
|
831
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
832
|
+
<rect x="3" y="3" width="18" height="18" rx="2"/>
|
|
833
|
+
<path d="M15 3v18"/>
|
|
834
|
+
</svg>
|
|
835
|
+
</button>
|
|
836
|
+
<button class="workspace-panel-close" id="workspacePanelClose" title="${r(`workspace.closePanel`)}">×</button>
|
|
837
|
+
</div>
|
|
838
|
+
<div class="workspace-panel-breadcrumb-row">
|
|
839
|
+
<button class="workspace-panel-switch-btn" id="workspaceSwitchBtn" title="${r(`workspace.switchWorkdir`)}">
|
|
840
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
841
|
+
<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"/>
|
|
842
|
+
<line x1="12" y1="11" x2="12" y2="17"/>
|
|
843
|
+
<polyline points="9 14 12 17 15 14"/>
|
|
844
|
+
</svg>
|
|
845
|
+
</button>
|
|
846
|
+
<div class="workspace-panel-breadcrumb" id="workspaceBreadcrumb"></div>
|
|
847
|
+
</div>
|
|
848
|
+
</div>
|
|
849
|
+
<div class="workspace-panel-toolbar" id="workspaceToolbar">
|
|
850
|
+
<button class="workspace-toolbar-btn" id="workspaceBackBtn" title="${r(`workspace.backToParent`)}" disabled>
|
|
851
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
852
|
+
<path d="M19 12H5M12 19l-7-7 7-7"/>
|
|
853
|
+
</svg>
|
|
854
|
+
</button>
|
|
855
|
+
<button class="workspace-toolbar-btn" id="workspaceRefreshBtn" title="${r(`common.refresh`)}">
|
|
856
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
857
|
+
<path d="M21.5 2v6h-6M2.5 22v-6h6M2 11.5a10 10 0 0 1 18.8-4.3M22 12.5a10 10 0 0 1-18.8 4.2"/>
|
|
858
|
+
</svg>
|
|
859
|
+
</button>
|
|
860
|
+
<button class="workspace-toolbar-btn" id="workspaceUploadBtn" title="${r(`workspace.uploadToCurrent`)}">
|
|
861
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
862
|
+
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12"/>
|
|
863
|
+
</svg>
|
|
864
|
+
</button>
|
|
865
|
+
<button class="workspace-toolbar-btn" id="workspaceNewFolderBtn" title="${r(`workspace.newFolder`)}">
|
|
866
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
867
|
+
<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"/>
|
|
868
|
+
<line x1="12" y1="11" x2="12" y2="17"/>
|
|
869
|
+
<line x1="9" y1="14" x2="15" y2="14"/>
|
|
870
|
+
</svg>
|
|
871
|
+
</button>
|
|
872
|
+
<button class="workspace-toolbar-btn" id="workspaceAskBtn" title="${r(`workspace.askSelectedFiles`)}" style="display:none;">
|
|
873
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
874
|
+
<circle cx="12" cy="12" r="10"/>
|
|
875
|
+
<path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/>
|
|
876
|
+
<line x1="12" y1="17" x2="12.01" y2="17"/>
|
|
877
|
+
</svg>
|
|
878
|
+
</button>
|
|
879
|
+
<button class="workspace-toolbar-btn" id="workspaceDownloadDirBtn" title="${r(`workspace.downloadSelected`)}" style="display:none;">
|
|
880
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
881
|
+
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/>
|
|
882
|
+
</svg>
|
|
883
|
+
</button>
|
|
884
|
+
<button class="workspace-toolbar-btn" id="workspaceBatchDeleteBtn" title="${r(`workspace.deleteSelected`)}" style="display:none;">
|
|
885
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
886
|
+
<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"/>
|
|
887
|
+
</svg>
|
|
888
|
+
</button>
|
|
889
|
+
<span class="workspace-toolbar-selected" id="workspaceSelectedCount" style="display:none;"></span>
|
|
890
|
+
<div class="workspace-search-box">
|
|
891
|
+
<input type="text" id="workspaceSearchInput" placeholder="${r(`workspace.searchPlaceholder`)}" />
|
|
892
|
+
<button id="workspaceSearchClear" title="${r(`workspace.clearSearch`)}" style="display:none;">×</button>
|
|
893
|
+
<button id="workspaceSearchBtn" title="${r(`workspace.search`)}">
|
|
894
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
|
|
895
|
+
<circle cx="11" cy="11" r="8"/>
|
|
896
|
+
<line x1="21" y1="21" x2="16.65" y2="16.65"/>
|
|
897
|
+
</svg>
|
|
898
|
+
</button>
|
|
899
|
+
</div>
|
|
900
|
+
</div>
|
|
901
|
+
<!-- 排序标题行 -->
|
|
902
|
+
<div class="workspace-file-header">
|
|
903
|
+
<div class="workspace-file-select" id="workspaceSelectAll" title="${r(`workspace.selectAllToggle`)}">
|
|
904
|
+
<span class="workspace-checkbox"></span>
|
|
905
|
+
</div>
|
|
906
|
+
<div class="workspace-file-header-name sortable" data-sort="name">
|
|
907
|
+
${r(`workspace.colName`)} <span class="sort-indicator" id="sortNameIndicator"></span>
|
|
908
|
+
</div>
|
|
909
|
+
<div class="workspace-file-header-size sortable" data-sort="size">
|
|
910
|
+
${r(`workspace.colSize`)} <span class="sort-indicator" id="sortSizeIndicator"></span>
|
|
911
|
+
</div>
|
|
912
|
+
<div class="workspace-file-header-time sortable" data-sort="time">
|
|
913
|
+
${r(`workspace.colTime`)} <span class="sort-indicator" id="sortTimeIndicator"></span>
|
|
914
|
+
</div>
|
|
915
|
+
</div>
|
|
916
|
+
<div class="workspace-panel-content" id="workspacePanelContent">
|
|
917
|
+
<div class="workspace-panel-loading">${r(`common.loading`)}</div>
|
|
918
|
+
</div>
|
|
919
|
+
<!-- 预览遮罩层 -->
|
|
920
|
+
<div class="workspace-preview-overlay" id="workspacePreviewArea" style="display:none;">
|
|
921
|
+
<div class="workspace-preview-header">
|
|
922
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="workspace-preview-icon">
|
|
923
|
+
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
924
|
+
<polyline points="14 2 14 8 20 8"/>
|
|
925
|
+
</svg>
|
|
926
|
+
<span class="workspace-preview-filename" id="workspacePreviewFilename"></span>
|
|
927
|
+
<span class="workspace-preview-linecount" id="workspacePreviewLineCount"></span>
|
|
928
|
+
<button class="workspace-preview-copy-btn workspace-preview-icon-btn" id="workspacePreviewCopyBtn" title="${r(`workspace.copyAllTitle`)}">
|
|
929
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
930
|
+
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
|
|
931
|
+
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
932
|
+
</svg>
|
|
933
|
+
</button>
|
|
934
|
+
<div class="workspace-preview-export-menu" id="workspacePreviewExportMenu" style="display:none;">
|
|
935
|
+
<button class="workspace-preview-export-btn workspace-preview-icon-btn ws-export-trigger-btn" id="workspacePreviewExportBtn" title="${r(`workspace.export`)}">
|
|
936
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
937
|
+
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
|
|
938
|
+
<polyline points="7 10 12 15 17 10"/>
|
|
939
|
+
<line x1="12" y1="15" x2="12" y2="3"/>
|
|
940
|
+
</svg>
|
|
941
|
+
</button>
|
|
942
|
+
<div class="ws-export-dropdown" id="workspacePreviewExportDropdown">
|
|
943
|
+
<button class="ws-export-dropdown-item" data-export-type="docx">
|
|
944
|
+
<svg viewBox="0 0 1024 1024" width="18" height="18"><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="#555"/><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="#555"/><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="#555"/></svg>
|
|
945
|
+
<span>${r(`workspace.export`)} ${r(`workspace.exportDocx`)}</span>
|
|
946
|
+
</button>
|
|
947
|
+
<button class="ws-export-dropdown-item" data-export-type="pdf">
|
|
948
|
+
<svg viewBox="0 0 1024 1024" width="18" height="18"><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="#555"/><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="#555"/></svg>
|
|
949
|
+
<span>${r(`workspace.export`)} ${r(`workspace.exportPdf`)}</span>
|
|
950
|
+
</button>
|
|
951
|
+
<button class="ws-export-dropdown-item" data-export-type="image">
|
|
952
|
+
<svg viewBox="0 0 1024 1024" width="18" height="18"><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="#555"/><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="#555"/><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="#555"/><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="#555"/></svg>
|
|
953
|
+
<span>${r(`workspace.export`)} ${r(`workspace.exportImage`)}</span>
|
|
954
|
+
</button>
|
|
955
|
+
<button class="ws-export-dropdown-item" data-export-type="md">
|
|
956
|
+
<svg viewBox="0 0 1024 1024" width="18" height="18"><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" fill="#555"/><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="#555"/></svg>
|
|
957
|
+
<span>${r(`workspace.export`)} ${r(`workspace.exportMd`)}</span>
|
|
958
|
+
</button>
|
|
959
|
+
</div>
|
|
960
|
+
</div>
|
|
961
|
+
<button class="workspace-preview-md-toggle-btn workspace-preview-icon-btn" id="workspacePreviewMdToggleBtn" title="${r(`workspace.toggleRenderPreview`)}" style="display:none;">
|
|
962
|
+
<svg class="workspace-preview-md-icon-preview" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
963
|
+
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
|
|
964
|
+
<circle cx="12" cy="12" r="3"/>
|
|
965
|
+
</svg>
|
|
966
|
+
<svg class="workspace-preview-md-icon-source" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14" style="display:none;">
|
|
967
|
+
<polyline points="16 18 22 12 16 6"/>
|
|
968
|
+
<polyline points="8 6 2 12 8 18"/>
|
|
969
|
+
</svg>
|
|
970
|
+
</button>
|
|
971
|
+
<button class="workspace-preview-download-btn workspace-preview-icon-btn" id="workspacePreviewDownloadBtn" title="${r(`workspace.downloadFile`)}">
|
|
972
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
973
|
+
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
|
|
974
|
+
<polyline points="7 10 12 15 17 10"/>
|
|
975
|
+
<line x1="12" y1="15" x2="12" y2="3"/>
|
|
976
|
+
</svg>
|
|
977
|
+
</button>
|
|
978
|
+
<button class="workspace-preview-download-btn workspace-preview-icon-btn" id="workspacePreviewOpenBrowserBtn" title="${r(`workspace.openInBrowser`)}" style="display:none">
|
|
979
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
980
|
+
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/>
|
|
981
|
+
<polyline points="15 3 21 3 21 9"/>
|
|
982
|
+
<line x1="10" y1="14" x2="21" y2="3"/>
|
|
983
|
+
</svg>
|
|
984
|
+
</button>
|
|
985
|
+
<button class="workspace-preview-fullscreen-btn" id="workspacePreviewFullscreenBtn" title="${r(`workspace.fullscreenPreview`)}" style="display:none;">
|
|
986
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
987
|
+
<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"/>
|
|
988
|
+
</svg>
|
|
989
|
+
</button>
|
|
990
|
+
<button class="workspace-preview-edit-btn workspace-preview-icon-btn" id="workspacePreviewEditBtn" title="${r(`workspace.enterEditMode`)}" style="display:none;">
|
|
991
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
992
|
+
<path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"/>
|
|
993
|
+
<path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"/>
|
|
994
|
+
</svg>
|
|
995
|
+
</button>
|
|
996
|
+
<button class="workspace-preview-save-btn workspace-preview-icon-btn" id="workspacePreviewSaveBtn" title="${r(`workspace.saveChanges`)}" style="display:none;">
|
|
997
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
998
|
+
<path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/>
|
|
999
|
+
<polyline points="17 21 17 13 7 13 7 21"/>
|
|
1000
|
+
<polyline points="7 3 7 8 15 8"/>
|
|
1001
|
+
</svg>
|
|
1002
|
+
</button>
|
|
1003
|
+
<button class="workspace-preview-cancel-btn workspace-preview-icon-btn" id="workspacePreviewCancelBtn" title="${r(`workspace.cancelChanges`)}" style="display:none;">
|
|
1004
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1005
|
+
<line x1="18" y1="6" x2="6" y2="18"/>
|
|
1006
|
+
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
1007
|
+
</svg>
|
|
1008
|
+
</button>
|
|
1009
|
+
<button class="workspace-preview-close" id="workspacePreviewClose" title="${r(`workspace.closePreview`)}">×</button>
|
|
1010
|
+
</div>
|
|
1011
|
+
<div class="workspace-preview-content" id="workspacePreviewContent"></div>
|
|
1012
|
+
<!-- 预览全屏内的目录导航挂载点:side-rail 被 fixed 全屏覆盖层遮挡,
|
|
1013
|
+
故在覆盖层内另设此 rail 承载 .message-toc-container(同消息全屏的做法) -->
|
|
1014
|
+
<div class="workspace-preview-rail" id="workspacePreviewRail"></div>
|
|
1015
|
+
</div>
|
|
1016
|
+
</div>
|
|
1017
|
+
`,hn(`workspace`).appendChild(e),Ah(),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))}),qv(),xv(),Wh(),Gh(),Jh(),i.debug(`[WorkspacePanel] workspace panelinitializing`)}function Ah(){document.getElementById(`workspacePanelContainer`);let e=document.getElementById(`workspacePanel`);document.getElementById(`workspacePanelToggle`).addEventListener(`click`,async t=>{t.stopPropagation(),e.classList.contains(`expanded`)?Zh():await Xh()}),document.getElementById(`workspacePanelClose`).addEventListener(`click`,e=>{e.stopPropagation(),Zh()}),document.getElementById(`workspacePanelModeBtn`).addEventListener(`click`,async e=>{e.stopPropagation(),await Uh()});let t=document.getElementById(`workspaceSwitchBtn`);t&&t.addEventListener(`click`,async e=>{e.stopPropagation(),await ry()}),document.getElementById(`workspaceBackBtn`).addEventListener(`click`,e=>{e.stopPropagation(),Cv()}),document.getElementById(`workspaceRefreshBtn`).addEventListener(`click`,e=>{e.stopPropagation(),wv()}),document.getElementById(`workspaceUploadBtn`).addEventListener(`click`,e=>{e.stopPropagation(),sv()}),document.getElementById(`workspaceNewFolderBtn`).addEventListener(`click`,e=>{e.stopPropagation(),py()}),document.getElementById(`workspaceAskBtn`).addEventListener(`click`,e=>{e.stopPropagation(),gy()}),document.getElementById(`workspaceDownloadDirBtn`).addEventListener(`click`,e=>{e.stopPropagation(),av()}),document.getElementById(`workspaceBatchDeleteBtn`).addEventListener(`click`,e=>{e.stopPropagation(),$v()});let n=document.getElementById(`workspaceSearchInput`),i=document.getElementById(`workspaceToolbar`),a=i.querySelector(`.workspace-search-box`);function o(){return i.clientWidth<188}function s(){n.value.trim()?(a.classList.add(`search-box-expanded`),o()&&i.classList.add(`search-focused`)):(a.classList.remove(`search-box-expanded`),i.classList.remove(`search-focused`))}n.addEventListener(`input`,e=>{Yv(e),s()}),n.addEventListener(`focus`,()=>{o()&&i.classList.add(`search-focused`)}),n.addEventListener(`blur`,()=>{n.value.trim()||i.classList.remove(`search-focused`)}),n.addEventListener(`keydown`,e=>{if(e.key===`Enter`)e.stopPropagation(),Xv();else if(e.key===`Escape`)e.stopPropagation(),Zv();else if(e.key===`ArrowUp`){if(e.preventDefault(),Gv.length===0)return;Kv===-1?Kv=Gv.length-1:Kv>0&&Kv--,n.value=Gv[Kv],Hv=n.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=Hv?``:`none`}else e.key===`ArrowDown`&&(e.preventDefault(),Kv===-1||Kv>=Gv.length-1?(Kv=-1,n.value=``,Hv=``,document.getElementById(`workspaceSearchClear`).style.display=`none`):(Kv++,n.value=Gv[Kv],Hv=n.value.trim(),document.getElementById(`workspaceSearchClear`).style.display=Hv?``:`none`))}),document.getElementById(`workspaceSearchBtn`).addEventListener(`click`,()=>{n.focus(),Xv()}),document.getElementById(`workspaceSearchClear`).addEventListener(`click`,Zv),document.getElementById(`workspacePanel`).querySelectorAll(`.workspace-file-header .sortable`).forEach(e=>{e.addEventListener(`click`,()=>{let t=e.dataset.sort;Sh.field===t?Sh.asc=!Sh.asc:(Sh.field=t,Sh.asc=!0),Dg(),hg()})}),document.getElementById(`workspaceSelectAll`).addEventListener(`click`,Tg),document.getElementById(`workspacePanelContent`).addEventListener(`click`,Sg),document.getElementById(`workspacePanelContent`).addEventListener(`dblclick`,Cg),document.getElementById(`workspacePanelContent`).addEventListener(`keydown`,xg),document.getElementById(`workspacePanelContent`).tabIndex=0,document.getElementById(`workspacePanelContent`).addEventListener(`dragstart`,bg);let c=null;document.getElementById(`workspacePanelContent`).addEventListener(`scroll`,()=>{dg&&(c&&cancelAnimationFrame(c),c=requestAnimationFrame(()=>{c=null,document.getElementById(`workspacePanelContent`).scrollTop!==fg&&mg()}))}),document.getElementById(`workspacePreviewClose`).addEventListener(`click`,()=>Z_()),document.getElementById(`workspacePreviewCopyBtn`).addEventListener(`click`,e=>R_(e)),document.getElementById(`workspacePreviewDownloadBtn`).addEventListener(`click`,V_),document.getElementById(`workspacePreviewOpenBrowserBtn`).addEventListener(`click`,H_),document.getElementById(`workspacePreviewFullscreenBtn`).addEventListener(`click`,K_),document.getElementById(`workspacePreviewMdToggleBtn`).addEventListener(`click`,q_),document.getElementById(`workspacePreviewEditBtn`).addEventListener(`click`,Q_),document.getElementById(`workspacePreviewSaveBtn`).addEventListener(`click`,$_),document.getElementById(`workspacePreviewCancelBtn`).addEventListener(`click`,ev),D_(),document.addEventListener(`keydown`,rv),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`)}}}}),bv(),chrome.storage.local.onChanged.addListener(Sv);let l=document.createElement(`input`);l.type=`file`,l.multiple=!0,l.id=`workspaceFileInput`,l.style.display=`none`,l.addEventListener(`change`,cv),document.body.appendChild(l)}var jh=[];function Mh(e){ch.push(e),ch.length>lh&&ch.shift()}function Nh(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 Ph(e,t){let n=Z(e);if(!t)return n;let r=t.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`);return n.replace(RegExp(`(${r})`,`gi`),`<mark class="search-highlight">$1</mark>`)}var Fh=`<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>`,Ih=`<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 Lh(){let e=document.getElementById(`mainRow`),t=e?e.clientWidth:window.innerWidth;return Math.max(uh,t-dh)}function Rh(e){return Math.max(uh,Math.min(e,Lh()))}function zh(e){let t=document.getElementById(`workspacePanelModeBtn`);t&&(t.title=r(e?`workspace.floatMode`:`workspace.embedMode`),t.innerHTML=e?Ih:Fh)}function Bh(){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`,`${vh}px`),zh(!0)}function Vh(){let e=document.getElementById(`workspacePanelContainer`);if(!e)return;e.classList.remove(`embedded`);let t=hn(`workspace`);t&&e.parentElement!==t&&t.appendChild(e),zh(!1)}async function Hh(){try{await chrome.storage.local.set({[mh]:_h,[hh]:vh})}catch(e){i.warn(`[WorkspacePanel] persist embed state failed`,e)}}async function Uh(){if(_h){_h=!1,bh=!1,yh=!1,Vh(),await Hh();return}let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<fh){F(r(`workspace.narrowViewportHint`),`error`);return}document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await Yh(),vh=Rh(vh),Bh(),_h=!0,bh=!0,yh=!1,await Hh()}function Wh(){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=vh;e.classList.add(`resizing`);function i(t){let i=Rh(r+(n-t.clientX));vh=i,e.style.setProperty(`--ws-embed-width`,`${i}px`)}function a(){document.removeEventListener(`mousemove`,i),document.removeEventListener(`mouseup`,a),e.classList.remove(`resizing`),Hh()}document.addEventListener(`mousemove`,i),document.addEventListener(`mouseup`,a)})}function Gh(){let e=document.getElementById(`mainRow`);!e||typeof ResizeObserver>`u`||new ResizeObserver(()=>{if(_h){e.clientWidth<fh&&(yh=!1,_h=!1,bh=!1,Vh(),Hh(),F(r(`workspace.narrowViewportHint`),`error`));return}yh&&e.clientWidth>=fh&&qh()}).observe(e)}async function Kh(){if(_h)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)<fh?!1:(vh=Rh(vh),document.getElementById(`workspacePanel`).classList.contains(`expanded`)||await Yh(),Bh(),_h=!0,!0)}function qh(){yh=!1,Kh().then(e=>{e||(yh=!0)}).catch(e=>{i.warn(`[WorkspacePanel] deferred embed restore failed`,e),yh=!0})}async function Jh(){try{let e=await chrome.storage.local.get([mh,hh,gh]);if(typeof e[hh]==`number`&&e[hh]>=uh&&(vh=Math.round(e[hh])),!e[mh]||(bh=!0,e[gh]===!1)||(await new Promise(e=>{let t=!1,n=()=>{t||(t=!0,e())};requestAnimationFrame(()=>requestAnimationFrame(n)),setTimeout(n,500)}),await Kh()))return;yh=!0}catch(e){i.warn(`[WorkspacePanel] restore embed state failed`,e)}}async function Yh(){let e=document.getElementById(`workspacePanel`);e.classList.contains(`expanded`)||(e.classList.add(`expanded`),Be(e),chrome.storage.local.set({[gh]:!0}).catch(()=>{}),await xv(),J||await Qh())}async function Xh(){let e=document.getElementById(`workspacePanel`);if(!(!e||e.classList.contains(`expanded`)))if(Eh=!1,bh){let e=document.getElementById(`mainRow`);if((e?e.clientWidth:window.innerWidth)<fh){await Yh(),F(r(`workspace.narrowViewportHint`),`error`);return}await Yh(),vh=Rh(vh),Bh(),_h=!0,yh=!1,await Hh()}else await Yh()}function Zh(){Vv()}async function Qh(){let e=await Kt();if(!e){Dv(r(`workspace.noWorkspace`));return}sh=e,ch=[],$h(e)}async function $h(e){J=e,Y.clear(),Tv(),Ev(),yy(),Dg(),Wv&&Hv?(Uv=await wt(e,Hv),hg()):await ag(e),Eg()}var eg=new Map,tg=3e4,ng=20;function rg(e){let t=eg.get(e);return t?Date.now()-t.timestamp>=tg?(eg.delete(e),null):(eg.delete(e),eg.set(e,t),t):null}function ig(e,t){eg.has(e)&&eg.delete(e),eg.set(e,t),eg.size>ng&&eg.delete(eg.keys().next().value)}async function ag(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-loading">${r(`common.loading`)}</div>`;let n=rg(e);if(n){jh=n.entries,hg();return}let i=await kt(e);if(!i.success){Dv(i.error||r(`workspace.loadDirFailed`));return}jh=(i.entries||[]).map(t=>({...t,path:og(`${e}/${t.name}`)})),ig(e,{entries:jh,timestamp:Date.now()}),hg()}function og(e){return(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`)}function sg(e){eg.delete(e)}var cg=200,lg=32,ug=5,dg=null,fg=0;function pg(e){let t=Vt(e.name,e.type),n=e.type===`directory`?`—`:Lt(e.size),i=Gt(e.mtime),a=e.type===`file`&&It(e.name),o=Wv?e.fullPath:og(`${J}/${e.name}`),s=Y.has(o),c=Wv&&e.matchPath!==J?og(e.matchPath).replace(og(sh),``).replace(/^\//,``)+`/`+e.name:``,l=Wv?Ph(e.name,Hv):Z(e.name);return`
|
|
1018
|
+
<div class="workspace-file-item ${e.type} ${s?`selected`:``}" data-path="${Z(o)}" data-type="${e.type}" data-name="${Z(e.name)}" draggable="true">
|
|
1019
|
+
<span class="workspace-file-select" data-action="select">
|
|
1020
|
+
<span class="workspace-checkbox ${s?`checked`:``}"></span>
|
|
1021
|
+
</span>
|
|
1022
|
+
<span class="workspace-file-icon">${t}</span>
|
|
1023
|
+
<span class="workspace-file-name" title="${Z(c||e.name)}">${l}</span>
|
|
1024
|
+
<span class="workspace-file-size">${n}</span>
|
|
1025
|
+
<span class="workspace-file-time">${i}</span>
|
|
1026
|
+
<span class="workspace-file-actions">
|
|
1027
|
+
${a?`<button class="workspace-file-btn preview" title="${r(`workspace.previewBtn`)}" data-action="preview"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="13" height="13"><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></button>`:``}
|
|
1028
|
+
<button class="workspace-file-btn info" title="${r(`workspace.details`)}" data-action="info"><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"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg></button>
|
|
1029
|
+
<button class="workspace-file-btn download" title="${r(`workspace.download`)}" data-action="download"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="13" height="13"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3"/></svg></button>
|
|
1030
|
+
<button class="workspace-file-btn rename" title="${r(`workspace.rename`)}" data-action="rename"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="13" height="13"><path d="M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"/></svg></button>
|
|
1031
|
+
<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
|
+
<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
|
+
</span>
|
|
1034
|
+
</div>`}function mg(){if(!dg)return;let{sorted:e}=dg,t=document.getElementById(`workspacePanelContent`),n=t.clientHeight,r=t.scrollTop,i=dg.itemHeight,a=Math.max(0,Math.floor(r/i)-ug),o=Math.min(e.length,Math.ceil((r+n)/i)+ug),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+=pg(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){dg.itemHeight=a;let i=Math.max(0,Math.floor(r/a)-ug),o=Math.min(e.length,Math.ceil((r+n)/a)+ug),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+=pg(e[t]);s+=`</div>`,t.innerHTML=s}}_g(),mv(),fg=t.scrollTop}function hg(){let e=document.getElementById(`workspacePanelContent`),t=[];if(t=Wv?Uv:[...jh],t.length===0){dg=null,e.innerHTML=Wv?`<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(Sh.field===`name`)n=e.name.localeCompare(t.name);else if(Sh.field===`size`){if(e.type===`directory`&&t.type!==`directory`)return Sh.asc?-1:1;if(e.type!==`directory`&&t.type===`directory`)return Sh.asc?1:-1;n=(e.size||0)-(t.size||0)}else n=(e.mtime||0)-(t.mtime||0);return Sh.asc?n:-n},o=n.sort(a),s=i.sort(a),c;if(c=Sh.field===`name`?Sh.asc?[...o,...s]:[...s.reverse(),...o.reverse()]:[...o,...s],Th=-1,c.length>cg){dg={sorted:c,itemHeight:lg},e.scrollTop=0,mg();return}dg=null;let l=`<div class="workspace-file-list">`;for(let e of c)l+=pg(e);l+=`</div>`,e.innerHTML=l}function gg(){let e=document.getElementById(`workspacePanelContent`);return e?Array.from(e.querySelectorAll(`.workspace-file-item`)):[]}function _g(){let e=document.getElementById(`workspacePanelContent`);if(dg&&Th>=0){let{sorted:t,itemHeight:n}=dg;if(Th>=t.length)return;let r=e.scrollTop,i=e.clientHeight,a=Th*n,o=a+n;if(a<r||o>r+i){e.scrollTop=Math.max(0,a-(i-n)/2),mg();return}}let t=gg();if(t.forEach(e=>e.classList.remove(`keyboard-focused`)),!(Th<0))if(dg){let e=dg.sorted[Th];if(!e)return;let n=Wv?e.fullPath:og(`${J}/${e.name}`),r=t.find(e=>e.dataset.path===n);r&&r.classList.add(`keyboard-focused`)}else Th<t.length&&(t[Th].classList.add(`keyboard-focused`),t[Th].scrollIntoView({block:`nearest`,behavior:`smooth`}))}function vg(e){let t=gg();t.length!==0&&(Th=Th===-1?e>0?0:t.length-1:Math.max(0,Math.min(t.length-1,Th+e)),_g())}function yg(){let e=gg();if(Th<0||Th>=e.length)return null;let t=e[Th];return{el:t,path:t.dataset.path,name:t.dataset.name,type:t.dataset.type}}function bg(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 xg(e){let t=e.target.tagName;if(!(t===`INPUT`||t===`TEXTAREA`))switch(e.key){case`ArrowDown`:e.preventDefault(),vg(1);break;case`ArrowUp`:e.preventDefault(),vg(-1);break;case`Enter`:{e.preventDefault();let t=yg();if(!t)return;t.type===`directory`?(Mh(J),await $h(t.path)):await zg(t.path,t.name);break}case`Delete`:{e.preventDefault();let t=yg();if(!t)return;await Qv(t.path,t.name,t.type);break}case`F2`:{e.preventDefault();let t=yg();if(!t)return;await fy(t.path,t.name,t.type);break}case` `:{e.preventDefault();let t=yg();if(!t)return;wg(t.path),vg(1);break}case`Escape`:Th=-1,_g();break}}async function Sg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;Eh=!1;let n=t.dataset.path,i=t.dataset.type,a=e.target.closest(`[data-action]`),o=gg(),s;if(dg){let e=t.dataset.path;s=dg.sorted.findIndex(t=>(Wv?t.fullPath:og(`${J}/${t.name}`))===e)}else s=o.indexOf(t);if(s>=0&&(Th=s,_g()),e.target.closest(`.workspace-file-select`)){e.stopPropagation(),wg(n);return}if(a){let r=a.dataset.action;e.stopPropagation(),r===`preview`?await zg(n,t.dataset.name):r===`info`?await ty(n,t.dataset.name,i):r===`download`?await iv(n,t.dataset.name):r===`ask`?await hy([n]):r===`delete`?await Qv(n,t.dataset.name,i):r===`rename`&&await fy(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(),Mh(J),await $h(n);return}}async function Cg(e){let t=e.target.closest(`.workspace-file-item`);if(!t)return;Eh=!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(),Mh(J),await $h(n);return}r===`file`&&It(i)&&(e.stopPropagation(),await zg(n,i))}}function wg(e){Y.has(e)?Y.delete(e):Y.add(e),yy(),Eg();let t=Array.from(document.querySelectorAll(`.workspace-file-item`)).find(t=>t.dataset.path===e);if(t){let n=Y.has(e);t.classList.toggle(`selected`,n);let r=t.querySelector(`.workspace-checkbox`);r&&r.classList.toggle(`checked`,n)}}function Tg(){let e=(Wv?Uv:jh).map(e=>Wv?e.fullPath:og(`${J}/${e.name}`));if(e.length>0&&e.every(e=>Y.has(e)))for(let t of e)Y.delete(t);else for(let t of e)Y.add(t);yy(),Eg();for(let e of document.querySelectorAll(`.workspace-file-item`)){let t=Y.has(e.dataset.path);e.classList.toggle(`selected`,t);let n=e.querySelector(`.workspace-checkbox`);n&&n.classList.toggle(`checked`,t)}}function Eg(){let e=(Wv?Uv:jh).map(e=>Wv?e.fullPath:og(`${J}/${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=>Y.has(e))?(n.classList.add(`checked`),n.classList.remove(`indeterminate`)):e.some(e=>Y.has(e))?(n.classList.remove(`checked`),n.classList.add(`indeterminate`)):(n.classList.remove(`checked`),n.classList.remove(`indeterminate`))}function Dg(){[`name`,`size`,`time`].forEach(e=>{let t=document.getElementById(`sort${e.charAt(0).toUpperCase()+e.slice(1)}Indicator`);t&&(Sh.field===e?t.textContent=Sh.asc?`▲`:`▼`:t.textContent=``)})}var Og=1024*1024,kg=50*1024*1024,Ag=20*1024*1024,jg=50*1024*1024,Mg=50*1024*1024,Ng=50*1024*1024,Pg=200*1024*1024,Fg=100*1024*1024,Ig=1e4,Lg=2e3;async function Rg(e){let t=await jt();if(!t)throw Error(r(`workspace.agentNotPaired`));let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...zt(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 zg(e,t){Dh&&Dh.abort(),Dh=new AbortController;let n=Dh.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`),U_(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 _=Dt(t),v=jh.find(t=>t.path===e)||Uv.find(t=>t.fullPath===e),y=v?v.size:0;if(_===`text`){if(l.style.display=``,y>Og){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.fileTooLargeNoPreview`,{size:Lt(y)})}</div>`;return}let n=(t.split(`.`).pop()||``).toLowerCase(),i=await qt(e);if(!i.success){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.previewFailed`,{error:Z(i.error||r(`workspace.unknownError`))})}</div>`;return}let s=i.size||0;if(s>Og){o.innerHTML=`<div class="workspace-panel-error">${r(`workspace.fileTooLargeNoPreview`,{size:Lt(s)})}</div>`;return}let h=i.content||``;if(!Yt(t)&&Jt(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`),U_(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">${et(h)}</div>`,Y_(o),X_(o),Ze(),c.textContent=``,J_(!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`),U_(p,!0),l.style.display=``,u.style.display=`none`,d.style.display=``,c.textContent=``,G_(o,h),J_(!0);return}let g=Ov(t),_=h.split(`
|
|
1035
|
+
`);c.textContent=r(`workspace.lineCount`,{count:_.length});let v=_.length>Ig,b=v?_.slice(0,Ig):_,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}">${Z(b[e])}</code></td></tr>`;v&&(x+=`<tr><td class="line-num">…</td><td class="line-content"><code>${r(`workspace.truncatedHint`,{shown:Ig,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:kg,docx:Ag,pptx:jg,xlsx:Mg,image:Ng,video:Pg,audio:Fg}[_]||Og)){o.innerHTML=`<div class="workspace-panel-error">${r(_===`pdf`||_===`image`?`workspace.fileTooLargeOpenInBrowser`:`workspace.fileTooLargeNoPreview`,{size:Lt(y)})}</div>`;return}if(_===`xlsx`){f.style.display=``,await v_(t,o,a);return}let i=await Rg(e);switch(_){case`pdf`:f.style.display=``,await e_(i,t,o,a,n);break;case`docx`:f.style.display=``,await t_(i,o);break;case`pptx`:f.style.display=``,await f_(i,t,o,a,n);break;case`image`:f.style.display=``,await x_(i,t,o,n);break;case`video`:case`audio`:f.style.display=``,await C_(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:Z((t instanceof Error?t.message:typeof t==`string`?t:String(t))||r(`workspace.unknownError`))})}</div>`}}var Bg=null,Vg=1,Hg=1,Ug=1,Wg=1,Gg=0,Kg=0,qg=!1,Jg=0,Yg=0,Xg=0,Zg=0,Qg=null,$g=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;Bg=c,Vg=1,Hg=1,Ug=1,Wg=1,$g=1,Gg=0,Kg=0,a.dataset.previewType=`pdf`;let l=c.numPages;document.getElementById(`workspacePreviewLineCount`).textContent=r(`workspace.pageCount`,{count:l}),i.innerHTML=`
|
|
1036
|
+
<div class="pdf-wrap">
|
|
1037
|
+
<div class="pdf-toolbar">
|
|
1038
|
+
<button class="pdf-toolbar-btn" id="pdfPrevPage" title="${r(`workspace.prevPage`)}" disabled>
|
|
1039
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><polyline points="15 18 9 12 15 6"/></svg>
|
|
1040
|
+
</button>
|
|
1041
|
+
<span class="pdf-page-info"><input type="number" class="pdf-page-input" id="pdfPageInput" value="1" min="1" max="${l}"> / ${l}</span>
|
|
1042
|
+
<button class="pdf-toolbar-btn" id="pdfNextPage" title="${r(`workspace.nextPage`)}">
|
|
1043
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><polyline points="9 18 15 12 9 6"/></svg>
|
|
1044
|
+
</button>
|
|
1045
|
+
<span class="pdf-toolbar-sep"></span>
|
|
1046
|
+
<button class="pdf-toolbar-btn" id="pdfZoomOut" title="${r(`workspace.zoomOut`)}">
|
|
1047
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><circle cx="11" cy="11" r="8"/><line x1="8" y1="11" x2="14" y2="11"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
|
|
1048
|
+
</button>
|
|
1049
|
+
<span class="pdf-zoom-info" id="pdfZoomInfo">100%</span>
|
|
1050
|
+
<button class="pdf-toolbar-btn" id="pdfZoomIn" title="${r(`workspace.zoomIn`)}">
|
|
1051
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><circle cx="11" cy="11" r="8"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
|
|
1052
|
+
</button>
|
|
1053
|
+
<span class="pdf-toolbar-sep"></span>
|
|
1054
|
+
<button class="pdf-toolbar-btn" id="pdfZoomFit" title="${r(`workspace.fitPage`)}">
|
|
1055
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/></svg>
|
|
1056
|
+
</button>
|
|
1057
|
+
</div>
|
|
1058
|
+
<div class="pdf-viewport" id="pdfViewport">
|
|
1059
|
+
<div class="pdf-pan" id="pdfPan">
|
|
1060
|
+
<canvas id="pdfCanvas"></canvas>
|
|
1061
|
+
</div>
|
|
1062
|
+
</div>
|
|
1063
|
+
</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(${Gg}px, ${Kg}px) scale(${Ug})`,p.textContent=Math.round(Hg*100)+`%`,qg||(u.style.cursor=Hg>Wg?`grab`:`default`)}function h(){Hg<=Wg&&(Gg=0,Kg=0)}function g(e,t,n){let r=Hg;if(Hg=Math.max(.05,Math.min(5,e)),Ug=Hg/$g,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=Hg/r;Gg=i-o*(i-Gg),Kg=a-o*(a-Kg)}h(),m(),_()}function _(){Qg&&clearTimeout(Qg),Qg=setTimeout(()=>{v()},180)}async function v(){if(!Bg)return;let e=await Bg.getPage(Vg),t=window.devicePixelRatio||1,n=Math.max(Hg,1);$g=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;Wg=o>0&&s>0&&a.width>0&&a.height>0?Math.min((o-24)/a.width,(s-24)/a.height):1,Ug=Hg/n,Hg<Wg*1.05&&Hg>Wg*.95&&(Hg=Wg,Ug=Wg/n,Gg=0,Kg=0),h(),m();let c=document.getElementById(`pdfPrevPage`),l=document.getElementById(`pdfNextPage`),d=document.getElementById(`pdfPageInput`);c&&(c.disabled=Vg<=1),l&&(l.disabled=Vg>=Bg.numPages),d&&(d.value=Vg)}await v(),u.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;g(Hg+t*Hg,e.clientX,e.clientY)},{passive:!1}),u.addEventListener(`mousedown`,e=>{e.button===0&&(qg=!0,Jg=e.clientX,Yg=e.clientY,Xg=Gg,Zg=Kg,u.style.cursor=`grabbing`,e.preventDefault())}),Oh(o,`mousemove`,e=>{qg&&(Gg=Xg+(e.clientX-Jg),Kg=Zg+(e.clientY-Yg),h(),m())}),Oh(o,`mouseup`,()=>{qg&&(qg=!1,u.style.cursor=Hg>Wg?`grab`:`default`)}),document.getElementById(`pdfPrevPage`).addEventListener(`click`,()=>{Vg>1&&(Vg--,v())}),document.getElementById(`pdfNextPage`).addEventListener(`click`,()=>{Vg<l&&(Vg++,v())}),document.getElementById(`pdfPageInput`).addEventListener(`change`,e=>{let t=parseInt(e.target.value,10);t>=1&&t<=l&&(Vg=t,v())}),document.getElementById(`pdfZoomIn`).addEventListener(`click`,()=>{let e=u.getBoundingClientRect();g(Hg*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pdfZoomOut`).addEventListener(`click`,()=>{let e=u.getBoundingClientRect();g(Hg/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pdfZoomFit`).addEventListener(`click`,()=>{Hg=Wg,Gg=0,Kg=0,v()}),u.addEventListener(`dblclick`,()=>{Hg=Wg,Gg=0,Kg=0,v()}),Oh(o,`resize`,()=>{Bg&&v()})}async function t_(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=ut.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">⚠ ${Z(e.message)}</div>`).join(``)}</div></div>`:n.innerHTML=`<div class="workspace-preview-docx">${o}</div>`}var n_=[],r_=0,X=1,i_=1,a_=0,o_=0,s_=!1,c_=0,l_=0,u_=0,d_=0;async function f_(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(n_=await o(e,{width:960,height:540,scaleToFit:!0,letterbox:!0}),r_=0,X=1,i_=1,a_=0,o_=0,!n_||n_.length===0){n.innerHTML=`<div class="workspace-panel-error">${r(`workspace.pptxEmptyOrFailed`)}</div>`;return}let s=n_.length;document.getElementById(`workspacePreviewLineCount`).textContent=r(`workspace.pageCount`,{count:s}),n.innerHTML=`
|
|
1065
|
+
<div class="pptx-wrap">
|
|
1066
|
+
<div class="pptx-toolbar">
|
|
1067
|
+
<button class="pptx-toolbar-btn" id="pptxPrevSlide" title="${r(`workspace.prevPage`)}" disabled>
|
|
1068
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><polyline points="15 18 9 12 15 6"/></svg>
|
|
1069
|
+
</button>
|
|
1070
|
+
<span class="pptx-page-info"><span id="pptxSlideNum">1</span> / ${s}</span>
|
|
1071
|
+
<button class="pptx-toolbar-btn" id="pptxNextSlide" title="${r(`workspace.nextPage`)}">
|
|
1072
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><polyline points="9 18 15 12 9 6"/></svg>
|
|
1073
|
+
</button>
|
|
1074
|
+
<span class="pptx-toolbar-sep"></span>
|
|
1075
|
+
<button class="pptx-toolbar-btn" id="pptxZoomOut" title="${r(`workspace.zoomOut`)}">
|
|
1076
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><circle cx="11" cy="11" r="8"/><line x1="8" y1="11" x2="14" y2="11"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
|
|
1077
|
+
</button>
|
|
1078
|
+
<span class="pptx-zoom-info" id="pptxZoomInfo">100%</span>
|
|
1079
|
+
<button class="pptx-toolbar-btn" id="pptxZoomIn" title="${r(`workspace.zoomIn`)}">
|
|
1080
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><circle cx="11" cy="11" r="8"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
|
|
1081
|
+
</button>
|
|
1082
|
+
<span class="pptx-toolbar-sep"></span>
|
|
1083
|
+
<button class="pptx-toolbar-btn" id="pptxZoomFit" title="${r(`workspace.fitPage`)}">
|
|
1084
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/></svg>
|
|
1085
|
+
</button>
|
|
1086
|
+
</div>
|
|
1087
|
+
<div class="pptx-viewport" id="pptxViewport">
|
|
1088
|
+
<div class="pptx-pan" id="pptxPan">
|
|
1089
|
+
<div class="pptx-slide-container" id="pptxSlideContainer"></div>
|
|
1090
|
+
</div>
|
|
1091
|
+
</div>
|
|
1092
|
+
</div>
|
|
1093
|
+
`,h_();let c=document.getElementById(`pptxViewport`),l=document.getElementById(`pptxPan`),u=document.getElementById(`pptxZoomInfo`);function d(){l.style.transform=`translate(${a_}px, ${o_}px) scale(${X})`,u.textContent=Math.round(X*100)+`%`,s_||(c.style.cursor=X>i_?`grab`:`default`)}function f(){X<=i_&&(a_=0,o_=0)}function p(e,t,n){let r=X;if(X=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=X/r;a_=i-o*(i-a_),o_=a-o*(a-o_)}X<i_*1.05&&X>i_*.95&&(X=i_,a_=0,o_=0),f(),d()}c.addEventListener(`wheel`,e=>{e.preventDefault();let t=-e.deltaY*.005;p(X+t*X,e.clientX,e.clientY)},{passive:!1}),c.addEventListener(`mousedown`,e=>{e.button===0&&(s_=!0,c_=e.clientX,l_=e.clientY,u_=a_,d_=o_,c.style.cursor=`grabbing`,e.preventDefault())}),Oh(a,`mousemove`,e=>{s_&&(a_=u_+(e.clientX-c_),o_=d_+(e.clientY-l_),f(),d())}),Oh(a,`mouseup`,()=>{s_&&(s_=!1,c.style.cursor=X>i_?`grab`:`default`)}),document.getElementById(`pptxPrevSlide`).addEventListener(`click`,()=>{r_>0&&(r_--,h_())}),document.getElementById(`pptxNextSlide`).addEventListener(`click`,()=>{r_<s-1&&(r_++,h_())}),document.getElementById(`pptxZoomIn`).addEventListener(`click`,()=>{let e=c.getBoundingClientRect();p(X*1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pptxZoomOut`).addEventListener(`click`,()=>{let e=c.getBoundingClientRect();p(X/1.25,e.left+e.width/2,e.top+e.height/2)}),document.getElementById(`pptxZoomFit`).addEventListener(`click`,()=>{requestAnimationFrame(()=>{p_(),X=i_,a_=0,o_=0,l.style.transform=`translate(0px, 0px) scale(${i_})`,u.textContent=Math.round(i_*100)+`%`,c.style.cursor=`default`})}),c.addEventListener(`dblclick`,()=>{requestAnimationFrame(()=>{p_(),X=i_,a_=0,o_=0,l.style.transform=`translate(0px, 0px) scale(${i_})`,u.textContent=Math.round(i_*100)+`%`,c.style.cursor=`default`})}),Oh(a,`resize`,()=>{!n_||n_.length===0||requestAnimationFrame(()=>{m_()})})}function p_(){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;i_=i>0&&a>0&&n>0&&r>0?Math.min((i-8)/n,(a-8)/r):1}function m_(){let e=document.getElementById(`pptxViewport`),t=document.getElementById(`pptxPan`),n=document.getElementById(`pptxZoomInfo`);if(!e||!t)return;let r=i_;p_(),X<=r*1.05&&(X=i_,a_=0,o_=0),t.style.transform=`translate(${a_}px, ${o_}px) scale(${X})`,n&&(n.textContent=Math.round(X*100)+`%`),s_||(e.style.cursor=X>i_?`grab`:`default`)}function h_(){let e=document.getElementById(`pptxSlideContainer`),t=document.getElementById(`pptxPan`);if(!e||!t||r_<0||r_>=n_.length)return;t.style.transform=`scale(1)`;let n=n_[r_],r=ut.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`),p_(),X=i_,a_=0,o_=0,t.style.transform=`translate(0px, 0px) scale(${i_})`;let a=document.getElementById(`pptxZoomInfo`);a&&(a.textContent=Math.round(X*100)+`%`);let o=document.getElementById(`pptxViewport`);o&&!s_&&(o.style.cursor=`default`);let s=document.getElementById(`pptxPrevSlide`),c=document.getElementById(`pptxNextSlide`),l=document.getElementById(`pptxSlideNum`);s&&(s.disabled=r_<=0),c&&(c.disabled=r_>=n_.length-1),l&&(l.textContent=r_+1)}var g_=[],__=0;async function v_(e,t,n){t.innerHTML=`<div class="workspace-panel-empty">${r(`workspace.parsingExcel`)}</div>`;let i=n.dataset.previewPath,a;try{let e=await jt();if(!e)throw Error(r(`workspace.agentNotPaired`));a=await(await fetch(`${e.url}/api/fs/preview-xlsx`,{method:`POST`,headers:{"Content-Type":`application/json`,...zt(e)},body:JSON.stringify({path:i,maxRows:500})})).json()}catch(e){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.requestFailed`,{error:Z(e.message)})}</div>`;return}if(!a.success){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.parseFailed`,{error:Z(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}g_=o,__=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}">${Z(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!==__&&(document.querySelectorAll(`.xlsx-sheet-tab`).forEach(e=>e.classList.remove(`active`)),t.classList.add(`active`),y_(n))}),await y_(0)}async function y_(e){let t=document.getElementById(`xlsxSheetContent`);if(!t)return;__=e;let n=g_[e];if(!n){t.innerHTML=`<div class="workspace-panel-error">${r(`workspace.sheetNotFound`)}</div>`;return}b_(n.rows,n.colCount,n.totalRows,t)}function b_(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>${Z(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>${Z(String(e[n][r]??``))}</td>`;s+=`</tr>`}s+=`</tbody></table></div>`,n>Lg&&(s+=`<div class="xlsx-truncated-msg">${r(`workspace.xlsxTruncatedHint`,{shown:Lg,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 x_(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
|
+
<div class="image-preview-wrap">
|
|
1095
|
+
<div class="image-preview-toolbar">
|
|
1096
|
+
<button class="image-preview-btn" id="imgZoomOut" title="${r(`workspace.zoomOut`)}">
|
|
1097
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><circle cx="11" cy="11" r="8"/><line x1="8" y1="11" x2="14" y2="11"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
|
|
1098
|
+
</button>
|
|
1099
|
+
<span class="image-preview-zoom-level" id="imgZoomLevel">100%</span>
|
|
1100
|
+
<button class="image-preview-btn" id="imgZoomIn" title="${r(`workspace.zoomIn`)}">
|
|
1101
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><circle cx="11" cy="11" r="8"/><line x1="11" y1="8" x2="11" y2="14"/><line x1="8" y1="11" x2="14" y2="11"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
|
|
1102
|
+
</button>
|
|
1103
|
+
<span class="image-preview-toolbar-sep"></span>
|
|
1104
|
+
<button class="image-preview-btn" id="imgZoomReset" title="${r(`workspace.originalSize`)}">
|
|
1105
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="16" height="16"><path d="M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7"/></svg>
|
|
1106
|
+
</button>
|
|
1107
|
+
</div>
|
|
1108
|
+
<div class="image-preview-viewport" id="imgViewport">
|
|
1109
|
+
<div class="image-preview-pan" id="imgPan">
|
|
1110
|
+
<img src="${s}" alt="${Z(t)}" id="imgPreviewImage">
|
|
1111
|
+
</div>
|
|
1112
|
+
</div>
|
|
1113
|
+
</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())}),Oh(i,`mousemove`,e=>{g&&(m=y+(e.clientX-_),h=b+(e.clientY-v),C(),S())}),Oh(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>`}),Oh(i,`resize`,()=>{l.isConnected&&(f=x(),C(),S())})}var S_=null;async function C_(e,t,n,i,a){S_&&=(URL.revokeObjectURL(S_),null);let o=Nt(t),s=new Blob([e],{type:o}),c=URL.createObjectURL(s);S_=c,a.dataset.previewType=n;let l=n===`video`,u=`<div class="workspace-panel-error" style="margin-top:10px;">${r(`workspace.unsupportedMediaHint`,{ext:Z((t.split(`.`).pop()||``).toUpperCase())})}</div>`;if(l){i.innerHTML=`
|
|
1115
|
+
<div class="media-preview-wrap" style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:12px;">
|
|
1116
|
+
<video controls autoplay style="max-width:100%;max-height:calc(100% - 24px);border-radius:8px;background:#000;">
|
|
1117
|
+
<source src="${c}" type="${Z(o)}">
|
|
1118
|
+
</video>
|
|
1119
|
+
<div id="mediaUnsupportedHint" style="display:none;">${u}</div>
|
|
1120
|
+
</div>`;let e=i.querySelector(`video`);e&&e.addEventListener(`dblclick`,()=>K_())}else i.innerHTML=`
|
|
1121
|
+
<div class="media-preview-wrap" style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;padding:12px;gap:16px;">
|
|
1122
|
+
<div style="font-size:14px;color:var(--text-secondary);">🎵 ${Z(t)}</div>
|
|
1123
|
+
<audio controls autoplay style="width:100%;max-width:560px;">
|
|
1124
|
+
<source src="${c}" type="${Z(o)}">
|
|
1125
|
+
</audio>
|
|
1126
|
+
<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 w_=!1;function T_(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 E_(e,t){T_(e,t),t.classList.add(`show`)}function D_(){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`):E_(t,n)});let r=null,i=null;e.addEventListener(`mouseenter`,()=>{i&&=(clearTimeout(i),null),r=setTimeout(()=>{E_(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`),k_(r)})}),document.addEventListener(`click`,t=>{!e.contains(t.target)&&!n.contains(t.target)&&n.classList.remove(`show`)});let a=()=>{n.classList.contains(`show`)&&T_(t,n)};document.getElementById(`workspacePreviewContent`)?.addEventListener(`scroll`,a),window.addEventListener(`resize`,a)}function O_(){return document.getElementById(`workspacePreviewArea`).dataset.markdownText||``}async function k_(e){if(w_)return;w_=!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 M_(a);break;case`pdf`:await P_(a);break;case`image`:await F_(a);break;case`md`:I_(a);break}}catch(e){i.error(`[WorkspacePanel] export failed:`,e),F(r(`chatExport.exportFailed`,{message:e.message}),`error`)}finally{w_=!1,t.innerHTML=o,t.disabled=!1,t.style.opacity=`1`,n.classList.remove(`show`)}}async function A_(e){if(typeof mermaid>`u`)return;let{renderMermaidInContainer:t,convertSvgsToImages:n}=await A(async()=>{let{renderMermaidInContainer:e,convertSvgsToImages:t}=await import(`./chat-export-Aojf945l.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([9,10,1,11,2,3,0]));await t(e),await n(e)}async function j_(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-Aojf945l.js`);return{renderMermaidInContainer:e,convertSvgsToImages:t}},__vite__mapDeps([9,10,1,11,2,3,0]));try{let r=et(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 M_(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-Aojf945l.js`);return{createDocxDocument:e}},__vite__mapDeps([9,10,1,11,2,3,0])),i=O_();if(!i){F(r(`chatExport.noContent`),`error`);return}i=await j_(i);let a=n(await N_(i)),o=await t.toBlob(a),s=`word-${new Date().getTime()}.docx`;L_(o,s),F(r(`workspace.downloaded`,{name:s}),`success`)}async function N_(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-Aojf945l.js`);return{createTextRuns:e,sanitizeDocxText:t,nextDocxImageId:n,isDocxEmbeddableImageType:r}},__vite__mapDeps([9,10,1,11,2,3,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
|
+
`),n=[];for(let e of t){if(/^[\s\|:\-]+$/.test(e.replace(/\|/g,``)))continue;let t=Xe(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
|
+
`);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
|
+
`).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 P_(e){let{jsPDF:t,html2canvas:n}=await Ne();if(!t||!n){F(r(`chatExport.pdfLibNotLoaded`),`error`);return}let a=O_();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">${et(a)}</div>`,document.body.appendChild(o),await A_(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 F_(e){let t=await He();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 A_(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 I_(e){let t=O_();if(!t){F(r(`chatExport.noContent`),`error`);return}let n=t.replace(/\r\n/g,`
|
|
1132
|
+
`).replace(/\n{3,}/g,`
|
|
1133
|
+
|
|
1134
|
+
`),i=new Blob([n],{type:`text/markdown;charset=utf-8`}),a=`md-${new Date().getTime()}.md`;L_(i,a),F(r(`workspace.downloaded`,{name:a}),`success`)}function L_(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 R_(e){let t=document.getElementById(`workspacePreviewArea`),n=t.dataset.previewPath;if(!n)return;if((t.dataset.previewType||Dt(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 z_();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 qt(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 z_(){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=B_(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 B_(e){return`<!DOCTYPE html><html><head>
|
|
1135
|
+
<style>
|
|
1136
|
+
h1 { font-size: 24px; font-weight: bold; margin: 16px 0 8px; }
|
|
1137
|
+
h2 { font-size: 20px; font-weight: bold; margin: 14px 0 6px; }
|
|
1138
|
+
h3 { font-size: 18px; font-weight: bold; margin: 12px 0 6px; }
|
|
1139
|
+
h4 { font-size: 16px; font-weight: bold; margin: 10px 0 6px; }
|
|
1140
|
+
p { margin: 6px 0; line-height: 1.6; }
|
|
1141
|
+
ul, ol { margin: 8px 0; padding-left: 24px; }
|
|
1142
|
+
li { margin: 4px 0; }
|
|
1143
|
+
blockquote { border-left: 4px solid #ddd; padding-left: 12px; margin: 8px 0; color: #666; }
|
|
1144
|
+
code { background: #f4f4f4; padding: 2px 6px; border-radius: 3px; font-family: monospace; }
|
|
1145
|
+
pre { background: #f6f8fa; border: 1px solid #e1e4e8; border-radius: 6px; padding: 14px 16px; margin: 12px 0; overflow-x: auto; font-family: monospace; font-size: 13px; line-height: 1.6; color: #24292f; white-space: pre-wrap; word-break: break-word; }
|
|
1146
|
+
pre code { background: none; padding: 0; border: none; border-radius: 0; }
|
|
1147
|
+
table { border-collapse: collapse; width: auto; margin: 8px 0; }
|
|
1148
|
+
th, td { border: 1px solid #ddd; padding: 6px 12px; text-align: left; }
|
|
1149
|
+
th { background: #f9f9f9; font-weight: bold; }
|
|
1150
|
+
strong { font-weight: bold; }
|
|
1151
|
+
em { font-style: italic; }
|
|
1152
|
+
a { color: #007bff; text-decoration: underline; }
|
|
1153
|
+
img { max-width: 100%; }
|
|
1154
|
+
</style>
|
|
1155
|
+
</head><body>${e}</body></html>`}async function V_(){let e=document.getElementById(`workspacePreviewArea`),t=e.dataset.previewPath,n=e.dataset.previewName;t&&await iv(t,n)}async function H_(){let e=document.getElementById(`workspacePreviewArea`).dataset.previewPath;if(e)try{let t=await Ot(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 U_(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 W_(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
|
+
<html>
|
|
1157
|
+
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></head>
|
|
1158
|
+
<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 G_(e,t){let n=W_(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 K_(){let e=document.getElementById(`workspacePreviewArea`),t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePreviewFullscreenBtn`),i=e.classList.toggle(`fullscreen`);if(Nn(),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 q_(){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`;Nn();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`),U_(n,!0),a.style.display=``,o&&(o.style.display=`none`),s&&(s.style.display=`none`),c&&(c.style.display=``),i.textContent=``,G_(t,l);else{n.classList.remove(`active`),n.title=r(`workspace.switchToRenderPreview`),U_(n,!1),a.style.display=``,o&&(o.style.display=``),s&&(s.style.display=`none`),c&&(c.style.display=`none`);let u=Ov(e.dataset.previewName||``),d=l.split(`
|
|
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}">${Z(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`),U_(n,!0),a.style.display=``,o&&(o.style.display=`none`),s&&(s.style.display=``),t.innerHTML=`<div class="markdown-body workspace-preview-markdown">${et(c)}</div>`,Y_(t),X_(t),Ze(),i.textContent=``;else{n.classList.remove(`active`),n.title=r(`workspace.switchToRenderPreview`),U_(n,!1),a.style.display=``,o&&(o.style.display=``),s&&(s.style.display=`none`);let l=Ov(e.dataset.previewName||``),u=(c||``).split(`
|
|
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}">${Z(u[e])}</code></td></tr>`;d+=`</tbody></table>`,t.innerHTML=d}}J_(u)}function J_(e){let t=document.getElementById(`workspacePreviewCopyBtn`);t&&(e?t.title=r(`workspace.copyAllTitle`)+`
|
|
1162
|
+
`+r(`workspace.copyMarkdownHint`):t.title=r(`workspace.copyAllTitle`))}async function Y_(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 X_(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&&rt(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 Z_(e=!1){let t=document.getElementById(`workspacePreviewArea`);if(!e&&t.dataset.editMode===`true`&&t.classList.contains(`has-unsaved`)&&!await nv(r(`workspace.actionClosePreview`)))return!1;tv(!1),Dh&&=(Dh.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`,U_(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`))}Nn();let o=document.getElementById(`workspacePreviewRail`);o&&o.querySelectorAll(`.message-toc-container`).forEach(e=>e.remove()),Bg&&=(Bg.destroy(),null),Vg=1,Ug=1,S_&&=(URL.revokeObjectURL(S_),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=``,Eh&&(Eh=!1,Vv(!1)),!0}function Q_(){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
|
+
`).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
|
+
`).length})):(e.classList.add(`has-unsaved`),l.textContent=r(`workspace.linesModified`,{count:p.value.split(`
|
|
1165
|
+
`).length}))})}async function $_(){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 Ct(n,a);if(t.success){i.info(`[WorkspacePanel] file save successful:`,n),F(r(`workspace.saveSuccess`)),e.dataset.origContent=a,tv(!1);let t=e.dataset.previewName;await zg(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 nv(r(`workspace.actionCancelEdit`)))return;tv(!0);let t=e.dataset.previewPath,n=e.dataset.previewName;t&&n&&await zg(t,n)}function tv(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 nv(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 rv(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(),$_()),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 iv(e,t){if(Ch)return;Ch=!0,lv(!0);let n=dv(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=hv(()=>i.abort());s.classList.add(`download-mode`),gv(s,{percent:0,fileName:t,loaded:0,totalBytes:0,speed:0});try{let c=await Bt(e,({loaded:e,total:r,percent:i})=>{fv(n,i);let c=Date.now();a.push({time:c,loaded:e}),a.length>8&&a.shift(),gv(s,{percent:i,fileName:t,loaded:e,totalBytes:r,speed:o()})},i.signal);if(c.aborted){_v(s,r(`workspace.downloadCanceled`),!0),F(r(`workspace.downloadCanceled`),`info`);return}if(!c.success){_v(s,r(`workspace.downloadFailed`),!0),F(r(`workspace.downloadFailedWithError`,{error:c.error}),`error`);return}ov(c.blob,c.name||t),gv(s,{percent:100,fileName:t,loaded:c.blob.size,totalBytes:c.blob.size,speed:0,statusText:r(`workspace.savingToLocal`)}),setTimeout(()=>{_v(s,r(`workspace.savedToLocal`),!1)},1500),F(r(`workspace.downloaded`,{name:c.name||t}),`success`)}catch(e){e.name===`AbortError`?(_v(s,r(`workspace.downloadCanceled`),!0),F(r(`workspace.downloadCanceled`),`info`)):(_v(s,r(`workspace.downloadFailed`),!0),F(r(`workspace.downloadFailedWithError`,{error:e.message}),`error`))}finally{setTimeout(()=>pv(n),600),Ch=!1,lv(!1)}}async function av(){if(Y.size===0||Ch)return;let e=Array.from(Y);if(e.length===1){let t=e[0].split(/[\\/]/).pop();await iv(e[0],t);return}Ch=!0,lv(!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=hv(()=>t.abort());o.classList.add(`download-mode`),gv(o,{percent:0,fileName:a,loaded:0,totalBytes:0,speed:0});try{let s=await At(e,({loaded:e,total:t,percent:r})=>{let s=Date.now();n.push({time:s,loaded:e}),n.length>8&&n.shift(),gv(o,{percent:r,fileName:a,loaded:e,totalBytes:t,speed:i()})},t.signal);if(s.aborted){_v(o,r(`workspace.downloadCanceled`),!0),F(r(`workspace.downloadCanceled`),`info`);return}s.success&&s.blob?(ov(s.blob,s.name||`workspace.zip`),_v(o,r(`workspace.downloadedCount`,{count:e.length}),!1),F(r(`workspace.downloadedZip`,{count:e.length}),`success`)):(_v(o,r(`workspace.downloadFailed`),!0),F(r(`workspace.downloadFailedWithError`,{error:s.error||r(`workspace.unknownError`)}),`error`))}catch(e){e.name===`AbortError`?(_v(o,r(`workspace.downloadCanceled`),!0),F(r(`workspace.downloadCanceled`),`info`)):(_v(o,r(`workspace.downloadFailed`),!0),F(r(`workspace.downloadFailedWithError`,{error:e.message}),`error`))}finally{Ch=!1,lv(!1)}}function ov(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 sv(){let e=document.getElementById(`workspaceFileInput`);e&&e.click()}async function cv(e){let t=e.target.files;if(!t||t.length===0)return;let n=Array.from(t);e.target.value=``,await yv(n)}function lv(e){document.querySelectorAll(`.workspace-file-btn.download`).forEach(t=>{t.disabled=e});let t=document.getElementById(`workspaceDownloadDirBtn`);t&&(t.disabled=e||Y.size===0);let n=document.getElementById(`workspacePreviewDownloadBtn`);n&&(n.disabled=e)}var uv=new Map;function dv(e){return uv.set(e,0),mv(),e}function fv(e,t){if(!e)return;let n=e;uv.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 pv(e){if(!e)return;let t=e;uv.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 mv(){for(let[e,t]of uv){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 hv(e){let t=document.createElement(`div`);t.className=`workspace-upload-progress`,t.innerHTML=`
|
|
1166
|
+
<div class="workspace-upload-progress-header">
|
|
1167
|
+
<span class="workspace-upload-progress-title">${r(`workspace.uploading`)}</span>
|
|
1168
|
+
<button class="workspace-upload-progress-cancel" title="${r(`workspace.cancelUpload`)}">
|
|
1169
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" width="14" height="14">
|
|
1170
|
+
<path d="M18 6L6 18M6 6l12 12"/>
|
|
1171
|
+
</svg>
|
|
1172
|
+
</button>
|
|
1173
|
+
</div>
|
|
1174
|
+
<div class="workspace-upload-progress-file"></div>
|
|
1175
|
+
<div class="workspace-upload-progress-track">
|
|
1176
|
+
<div class="workspace-upload-progress-bar"></div>
|
|
1177
|
+
</div>
|
|
1178
|
+
<div class="workspace-upload-progress-stats">
|
|
1179
|
+
<span class="workspace-upload-progress-bytes"></span>
|
|
1180
|
+
<span class="workspace-upload-progress-speed"></span>
|
|
1181
|
+
</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 gv(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=`${Lt(s)} / ${Lt(c)}`:s!=null&&(m.textContent=Lt(s))),h&&(h.textContent=l>0?`${Lt(l)}/s`:``)}function _v(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 vv(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 yv(e){let t=Array.from(e);if(t.length===0||wh)return;wh=!0,vv(!0);let n=await jt();if(!n){F(r(`workspace.agentNotConnectedUpload`),`error`),wh=!1,vv(!1);return}let i=new Set;try{let e=await kt(J);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=hv(()=>{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(),gv(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=Nh(t.name),c=og(`${J}/${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(zt(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}_v(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`),wh=!1,vv(!1),a>0&&(await wv(),_y(t[t.length-1].name))}function bv(){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 Tt(t,a);if(l.success){F(r(`workspace.movedToDir`,{name:o}),`success`),sg(J),sg(a);let e=a.split(/[\\/]/).pop();await wv(),_y(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(),Mh(J),J=e,await yv(n.dataTransfer.files),Tv(),Ev();return}if(n.dataTransfer.files&&n.dataTransfer.files.length>0){await yv(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 yv(n)})}async function xv(){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 Sv(e,t){if(t===`local`&&!(!e.pairedAgents&&!e.activeAgentId)&&(await xv(),e.activeAgentId?.newValue!==e.activeAgentId?.oldValue)){i.debug(`[WorkspacePanel] Agent changed,refreshworking directory`),xt(),sh=null,J=null,ch=[],Y.clear(),Hv=``,Uv=[],Wv=!1,eg.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await Qh()}}async function Cv(){if(ch.length===0)return;let e=ch.pop();Y.clear(),await $h(e)}async function wv(e){if(!J){let e=sh||await Kt();if(!e){F(r(`workspace.refreshFailed`),`error`);return}sh=e,J=e}if(sg(J),Y.clear(),yy(),Wv&&Hv?(Uv=await wt(J,Hv),hg()):await ag(J),Z_(),Eg(),e!==void 0){let t=document.getElementById(`workspacePanelContent`);t&&requestAnimationFrame(()=>{t.scrollTop=e})}}function Tv(){let e=document.getElementById(`workspaceBreadcrumb`);if(!J){e.innerHTML=``;return}let t=og(J).split(`/`).filter(Boolean),n=sh?og(sh).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">${Z(t[e])}</span>`:o?i+=`<span class="workspace-breadcrumb-link" data-path="${Z(a)}">${Z(t[e])}</span>`:i+=`<span class="workspace-breadcrumb-disabled">${Z(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=ch.findIndex(e=>e===n);ch=r>=0?ch.slice(0,r):[],Y.clear(),await $h(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 Tt(i,a);l.success?(F(r(`workspace.movedToTarget`,{name:o,target:a.split(/[\\/]/).pop()}),`success`),sg(J),sg(a),await wv()):F(r(`workspace.moveFailed`,{error:l.error}),`error`)}catch(e){F(r(`workspace.moveFailed`,{error:e.message}),`error`)}})})}function Ev(){let e=document.getElementById(`workspaceBackBtn`);e.disabled=!(sh&&J&&J!==sh)}function Dv(e){let t=document.getElementById(`workspacePanelContent`);t.innerHTML=`<div class="workspace-panel-error">${Z(e)}</div>`}function Z(e){return e?String(e).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`):``}function Ov(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 kv(){J&&await ag(J)}async function Av(){xt(),sh=null,J=null,ch=[],Y.clear(),Hv=``,Uv=[],Wv=!1,eg.clear();let e=document.getElementById(`workspacePanel`);e&&e.classList.contains(`expanded`)&&await Qh()}function jv(e){let t=document.getElementById(`workspacePanelContainer`);if(t)if(e){t.style.display=``;let e=document.getElementById(`workspacePanel`),n=!!(e&&e.classList.contains(`expanded`));_h&&e&&!n?Yh().catch(e=>i.warn(`[WorkspacePanel] reopen panel after reconnect failed`,e)):n&&!J&&Qh().catch(e=>i.warn(`[WorkspacePanel] navigate after reconnect failed`,e)),yh&&qh()}else t.style.display=`none`,Vv(!0)}function Mv(e,t){let n=t.toLowerCase(),r=e.toLowerCase();return r===n?``:r.startsWith(n+`/`)?e.substring(t.length+1):null}function Nv(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 Pv(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=Mv(r,n);return i===null&&(i=Nv(r,n)),i===null?null:i===``?n:n+`/`+i}async function Fv(e){if(!(e===`~`||e&&e.startsWith(`~/`)))return e;try{let t=await Pt();if(t)return og(e===`~`?t:t+`/`+e.slice(2))}catch{}return e}async function Iv(e){if(!e)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);if(!t||!n)return;if(t.classList.add(`expanded`),Be(t),n.classList.add(`click-opened`),sh||=await Kt(),!sh){Dv(r(`workspace.noWorkspace`));return}let i=Pv(await Fv(e),sh);if(!i){Dv(r(`artifacts.locateFailed`));return}let a=i.lastIndexOf(`/`),o=a>0?i.substring(0,a):sh,s=a>0?i.substring(a+1):i;sg(o),await $h(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||!dg)return n;let r=dg.sorted.findIndex(t=>t.name===e);if(r<0)return null;let i=document.getElementById(`workspacePanelContent`);if(!i)return null;let{itemHeight:a}=dg;return i.scrollTop=Math.max(0,r*a-i.clientHeight/2+a/2),mg(),t()};setTimeout(async()=>{let e=c(s);e||=(sg(o),await $h(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 Lv(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`),Be(n),i.classList.add(`click-opened`),sh||=await Kt(),!sh){Dv(r(`workspace.noWorkspace`));return}let o=Pv(await Fv(e),sh);if(!o){Dv(r(`artifacts.locateFailed`));return}await Z_(!0),await zg(o,t),Eh=!a}async function Rv(){await Z_(!0)}function zv(){Vv(!0)}async function Bv(e){return!e||(sh||=await Kt(),!sh)?null:Pv(await Fv(e),sh)}async function Vv(e=!1){if(e&&await Z_(!0)===!1)return;let t=document.getElementById(`workspacePanel`),n=document.getElementById(`workspacePanelContainer`);t&&(t.classList.remove(`expanded`),Re(t),e||chrome.storage.local.set({[gh]:!1}).catch(()=>{})),n&&(n.classList.remove(`hover-expanded`),n.classList.remove(`click-opened`),_h&&!e&&(_h=!1,yh=!1,n.classList.add(`closing-no-anim`),Vh(),requestAnimationFrame(()=>n.classList.remove(`closing-no-anim`))))}var Hv=``,Uv=[],Wv=!1,Gv=[],Kv=-1;function qv(){try{chrome.storage.local.get([`workspaceSearchHistory`],e=>{Gv=e.workspaceSearchHistory||[]})}catch{}}function Jv(e){if(!e.trim())return;let t=Gv.indexOf(e);t!==-1&&Gv.splice(t,1),Gv.push(e),Gv.length>20&&Gv.shift();try{chrome.storage.local.set({workspaceSearchHistory:Gv})}catch{}}function Yv(e){Hv=e.target.value.trim();let t=document.getElementById(`workspaceSearchClear`);t.style.display=Hv?``:`none`}async function Xv(){if(!Hv){Wv=!1,Uv=[],hg(),Eg();return}Jv(Hv),Kv=-1,F(r(`workspace.searching`),`info`),Uv=await wt(J,Hv),Wv=!0,hg(),Eg()}async function Zv(){let e=document.getElementById(`workspaceSearchInput`),t=document.getElementById(`workspaceToolbar`),n=t.querySelector(`.workspace-search-box`);e.value=``,Hv=``,Wv=!1,Uv=[],Y.clear(),document.getElementById(`workspaceSearchClear`).style.display=`none`,t.classList.remove(`search-focused`),n.classList.remove(`search-box-expanded`),e.blur(),await ag(J),Eg(),yy()}async function Qv(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 jt();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`,...zt(t)},body:JSON.stringify({path:e})})).json();n.success?(F(r(i?`workspace.dirDeleted`:`workspace.fileDeleted`),`success`),Y.delete(e),yy(),await wv(s)):F(r(`workspace.deleteFailedWithError`,{error:n.error||r(`workspace.unknownError`)}),`error`)}catch(e){F(r(`workspace.deleteFailedWithError`,{error:e.message}),`error`)}}async function $v(){if(Y.size===0)return;let e=Array.from(Y),t=e.map(e=>{let t=jh.find(t=>t.path===e)||Uv.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 jt();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`,...zt(t)},body:JSON.stringify({path:r})})).json()).success?(Y.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`),yy(),await wv(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 ty(e,t,n){let i=document.createElement(`div`);i.className=`modal-overlay show`,i.innerHTML=`
|
|
1184
|
+
<div class="modal-container file-info-modal">
|
|
1185
|
+
<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
|
+
<div class="modal-title">${Z(t)} - ${r(`workspace.fileDetailsLabel`)}</div>
|
|
1187
|
+
<div class="file-info-loading">${r(`workspace.loadingLabel`)}</div>
|
|
1188
|
+
<div class="modal-actions" style="display:flex;justify-content:flex-end;gap:8px;margin-top:12px;">
|
|
1189
|
+
<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
|
+
</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 Rt(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:Lt(o.size)+` (${o.size.toLocaleString()} ${r(`workspace.bytes`)})`,u=o.mimeType||null,d=ey(o.mode,o.isDirectory),f=[[r(`workspace.infoName`),Z(o.name),o.name],[r(`workspace.infoType`),c,c],[r(`workspace.infoPath`),`<span style="word-break:break-all;">${Z(o.path)}</span>`,o.path],[r(`workspace.infoSize`),l||`—`,l],[r(`workspace.infoMime`),u?Z(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`),Z(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="${Z(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 ny(e,t=``,n=``){return new Promise(i=>{let a=document.createElement(`div`);a.className=`modal-overlay show`,a.innerHTML=`
|
|
1192
|
+
<div class="modal-container input-dialog" style="min-width:320px;">
|
|
1193
|
+
<div class="modal-title">${Z(e)}</div>
|
|
1194
|
+
<input type="text" class="modal-input" value="${Z(t)}" placeholder="${Z(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;">
|
|
1195
|
+
<div class="modal-actions" style="display:flex;justify-content:flex-end;gap:8px;margin-top:12px;">
|
|
1196
|
+
<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
|
+
<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
|
+
</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 ry(e={}){let t=e.sessionId===void 0?C.activeSessionId||null:e.sessionId;if(Zm(t))return F(r(`workdirTag.lockedHint`),`warning`),!1;let n=null;try{n=await Mt(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 jt(),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
|
+
<div class="modal-container switch-workdir-dialog" style="max-width:480px;width:90%;box-sizing:border-box;position:relative;">
|
|
1201
|
+
<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
|
+
<div class="modal-title">${r(a?`workdirTag.switchTitle`:`workspace.switchWorkdirTitle`)}</div>
|
|
1203
|
+
<div style="display:flex;align-items:flex-start;gap:8px;font-size:12px;color:var(--text-tertiary);margin-bottom:10px;word-break:break-all;">
|
|
1204
|
+
<span style="flex:1;min-width:0;">${r(`workspace.currentLabel`)}<span style="color:var(--info-500);" title="${Z(c)}">${Z(c)||r(`workspace.notSet`)}</span><span>${s}</span></span>
|
|
1205
|
+
${o?`<button class="switch-workdir-restore" style="flex-shrink:0;padding:4px 10px;border:1px solid var(--border-default);border-radius:6px;background:var(--bg-surface);color:var(--text-primary);font-size:12px;cursor:pointer;white-space:nowrap;">${r(`workdirTag.restoreDefault`)}</button>`:``}
|
|
1206
|
+
</div>
|
|
1207
|
+
<div class="switch-workdir-list-label" style="font-size:12px;color:var(--text-tertiary);margin:6px 0;">${r(`workspace.selectFromAllowed`)}</div>
|
|
1208
|
+
<div class="switch-workdir-list" id="switchWorkdirList" style="max-height:180px;overflow-y:auto;border:1px solid var(--border-subtle);border-radius:8px;margin-bottom:10px;"></div>
|
|
1209
|
+
<div class="switch-workdir-browser" hidden></div>
|
|
1210
|
+
<div style="font-size:12px;color:var(--text-tertiary);margin:6px 0;">${r(`workspace.orInputPath`)}</div>
|
|
1211
|
+
<div style="display:flex;gap:8px;margin-bottom:12px;">
|
|
1212
|
+
<input type="text" class="switch-workdir-manual" placeholder="${r(`workspace.manualPathPlaceholder`)}" style="flex:1;min-width:0;padding:8px 12px;border:1px solid var(--border-default);border-radius:6px;font-size:13px;box-sizing:border-box;" autofocus>
|
|
1213
|
+
<button class="switch-workdir-browse" title="${r(`workspace.browseBtn`)}" style="flex-shrink:0;padding:6px 14px;border:1px solid var(--border-default);border-radius:6px;background:var(--bg-surface);color:var(--text-primary);font-size:13px;cursor:pointer;white-space:nowrap;">${r(`workspace.browseBtn`)}</button>
|
|
1214
|
+
</div>
|
|
1215
|
+
${a?`<label title="${r(`workdirTag.setAsAgentDefaultHint`)}" style="display:flex;align-items:flex-start;gap:6px;margin-bottom:10px;font-size:12px;color:var(--text-tertiary);cursor:pointer;"><input type="checkbox" class="switch-workdir-set-default" style="margin-top:1px;flex-shrink:0;"><span>${r(`workdirTag.setAsAgentDefault`)}</span></label>`:``}
|
|
1216
|
+
<div style="display:flex;justify-content:flex-end;gap:8px;">
|
|
1217
|
+
<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
|
+
<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
|
+
</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 bt();!e.success&&e.error===`busy`&&e.cancellable&&(await Ht(),e=await bt());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?Xm({container:v,t:r,platform:m,platformName:h,hostname:g,listDirs:Wt,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
|
+
<div class="switch-workdir-item${t?` current`:``}" data-path="${Z(e)}" title="${Z(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
|
+
<span style="flex-shrink:0;">📁</span>
|
|
1223
|
+
<span style="flex:1;">${Z(e)}</span>
|
|
1224
|
+
${t?a:``}${n?o:``}
|
|
1225
|
+
${i?`<button class="switch-workdir-remove" data-remove-path="${Z(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 Et(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 ly(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 uy(n,{sessionId:d,setAsDefault:s})))}w&&w.addEventListener(`click`,async()=>{w.disabled=!0,j(),e(await dy(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 iy(){sh=null,J=null,ch=[],Y.clear(),Hv=``,Uv=[],Wv=!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 ay=0;async function oy(){let e=++ay;if(C.agentPlatform?.connected!==!0){xt(),iy();return}await xv();let t=sh;xt();let n=null;try{n=await Kt()}catch(e){i.warn(`[WorkspacePanel] resolve root for session failed:`,e?.message||e)}if(e!==ay||t&&n&&t===n)return;iy();let r=document.getElementById(`workspacePreviewArea`);if(r&&r.dataset.previewPath&&(Eh=!1,await Z_(!0)),await Promise.resolve(),e!==ay)return;let a=document.getElementById(`workspacePanel`);!a||!a.classList.contains(`expanded`)||await Qh()}async function sy(e,t){document.dispatchEvent(new CustomEvent(`session-workdir-changed`,{detail:{sessionId:e,workdir:t}}))}async function cy(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 ly(e){let t=await yt(e,{sessionId:null});return t.success?(await cy(t.workdir),await sy(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 uy(e,t={}){let n=t.sessionId===void 0?C.activeSessionId||null:t.sessionId,a=t.setAsDefault===!0,o=await yt(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-owqj23pJ.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([12,1,2,3])),t=(await jt())?.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 yt(o.workdir,{sessionId:null});e.success?s=!0:F(r(`workspace.switchFailedWithError`,{error:e.error||r(`workspace.unknownError`)}),`error`)}return(!n||a)&&await cy(o.workdir),await sy(n,o.workdir),F(r(s?`workspace.switchedToAndSetDefault`:`workspace.switchedTo`,{path:o.workdir}),`success`),!0}async function dy(e,t={}){if(!e)return!1;let{unbindSessionWorkdirRemote:n}=await A(async()=>{let{unbindSessionWorkdirRemote:e}=await import(`./model-profiles-C3kJEHM6.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-owqj23pJ.js`).then(e=>e.g);return{setSessionWorkdirBinding:e}},__vite__mapDeps([12,1,2,3]));await t(e,null,null)}catch(e){i.warn(`[WorkspacePanel] clear session workdir failed:`,e)}return await sy(e,``),F(r(`workdirTag.restoredDefault`),`success`),!0}async function fy(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 ny(r(n===`directory`?`workspace.renameDir`:`workspace.renameFile`),i,r(`workspace.inputNewName`));if(!s||s===i)return;let c=s+a;try{let t=await St(e,c);t.success?(F(r(`workspace.renamedTo`,{name:c}),`success`),sg(J),await wv(),_y(c)):F(r(`workspace.renameFailedWithError`,{error:t.error}),`error`)}catch(e){F(r(`workspace.renameFailedWithError`,{error:e.message}),`error`)}}async function py(){if(!J)return;let e=await ny(r(`workspace.newFolderTitle`),``,r(`workspace.inputFolderName`));if(!e)return;let t=og(`${J}/${e}`);try{let n=await Ft(t);n.success?(F(r(`workspace.folderCreated`,{name:e}),`success`),sg(J),await wv(),_y(e)):F(r(`workspace.createFailedWithError`,{error:n.error}),`error`)}catch(e){F(r(`workspace.createFailedWithError`,{error:e.message}),`error`)}}async function my(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 hy(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=jh.find(e=>e.path===i),o||=Uv.find(e=>e.fullPath===i));let s=o?o.size:0,c=Nt(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 jt();if(t){let n=await fetch(`${t.url}/api/fs/download-stream`,{method:`POST`,headers:{"Content-Type":`application/json`,...zt(t)},body:JSON.stringify({path:e.path})});if(n.ok){let{originalUrl:e,compressedUrl:t}=await my(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);km(),th();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 gy(){Y.size!==0&&await hy(Array.from(Y))}function _y(e,t=0){let n=document.getElementById(`workspacePanelContent`);if(!n)return;if(dg){let t=dg.sorted.findIndex(t=>t.name===e);if(t>=0){let r=dg.itemHeight;n.scrollTop=Math.max(0,t*r-n.clientHeight/2+r/2),mg();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(()=>_y(e,t+1),150)}function vy(){let e=document.getElementById(`workspaceAskBtn`);Y.size===0?e.style.display=`none`:e.style.display=``}function yy(){let e=document.getElementById(`workspaceDownloadDirBtn`),t=document.getElementById(`workspaceBatchDeleteBtn`),n=document.getElementById(`workspaceSelectedCount`);Y.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:Y.size}),e.disabled=Ch),vy()}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 Q(e){let t=(e||``).replace(/\\/g,`/`).replace(/\/+/g,`/`),n=t.replace(/\/+$/,``);return n?/^[A-Za-z]:$/.test(n)?n+`/`:n:t?`/`:``}function by(e){if(!e)return``;let t=Q(e).replace(/\/+$/,``).split(`/`);return t[t.length-1]||``}function xy(e){if(!e)return``;let t=by(e),n=t.lastIndexOf(`.`);return n>0?t.substring(n+1).toLowerCase():``}function Sy(e){return String(e??``).replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function Cy(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 wy(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=Cy(a,`,`).map(e=>e.trim());if(s.length<=1)return[e];let c=[];for(let e of s)for(let t of wy(e))for(let e of wy(o))c.push(i+t+e);return c}function Ty(e,t){let n=[],r=new Set;for(let i of e)if(i)for(let e of wy(i)){if(!e)continue;let i=t(e);!i||r.has(i)||(r.add(i),n.push(i))}return n}function Ey(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 Dy(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=Oy(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 Oy(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 ky(e){let t=Q(e||``).replace(/\/$/,``);if(!t)return``;let n=t.lastIndexOf(`/`);return n>0?t.substring(0,n):``}var Ay=new Set([`du`,`df`,`stat`,`wc`,`file`,`cat`,`head`,`tail`,`grep`,`rg`]);function jy(e){if(!e||typeof e!=`string`)return!1;let t=Dy(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()),!Ay.has(n))return!1}return!0}function My(e,t){let n=t=>e===t||e.startsWith(t.endsWith(`/`)?t:t+`/`);return[...t].some(n)}function Ny(e,t){if(!e||typeof e!=`string`)return t||``;let n=t||``;for(let t of Dy(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?Q(n).replace(/\/[^/]+$/,``)||`/`:`..`:Q(n?n.replace(/\/$/,``)+`/`+r:r)}return n}function Py(e,t){if(!e||typeof e!=`string`)return[];let n=[],r=t||``,i=Dy(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?Q(r).replace(/\/[^/]+$/,``)||`/`:`..`:Q(r?r.replace(/\/$/,``)+`/`+e:e);continue}let o=e=>(e=e.replace(/^['"]|['"]$/g,``),!e.startsWith(`/`)&&!e.startsWith(`~/`)&&r&&(e=Q(r.replace(/\/$/,``)+`/`+e)),Q(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 Fy(t,r))e&&n.push({path:o(e),isDir:!1});continue}}let c=i.match(/^mkdir\s+(?:-[a-z]+\s+)*(.+?)$/);if(c){let e=Ty(Cy(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=Ty(Cy(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=Ty([u],o);for(let t of e)n.push({path:t,isDir:!1})}}return n}function Fy(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=Cy(i[1],` `).map(e=>e.trim()).filter(e=>e&&!e.startsWith(`-`));n.push(...e)}let a=t.match(/^touch\s+(.+)$/);if(a){let e=Cy(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 Iy(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(`/`)?Q(e):Q((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 Ly(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=xy(e);[`sh`,`bash`,`zsh`,`bat`,`cmd`,`ps1`,`py`].includes(n)&&t.push({path:Q(e),content:r[3],ext:n})}return t}function Ry(e,t){if(!e||typeof e!=`string`)return null;let n=e.trim();for(let e of t){let t=by(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 zy(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=Q(r.replace(/\/$/,``)+`/`+e)),Q(e)),a=Dy(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)?Q(e):e.startsWith(`~/`)?e:e===`..`?r?Q(r).replace(/\/[^/]+$/,``)||`/`:`..`:Q(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=Ty(Cy(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=Ty(Cy(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=Ty(Cy(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=Ty([...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 By(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=Q(t.path||t.filePath||``),r=xy(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 Ly(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=Ry(u,a);if(d&&e.status!==`failed`){let a=i.get(d);if(a){let i=Fy(a.content,a.ext);for(let a of i){if(!a)continue;let i=(a.startsWith(`/`),Q(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:by(i),toolName:r,action:`typeCreate`,size:0,timestamp:e.timestamp||null,status:e.status||`unknown`,type:`file`})}}}if(e.status!==`failed`){let t=zy(u,s.cwd);for(let n of t)o.set(n.path,{isDir:n.isDir,timestamp:e.timestamp})}let f=Py(u,s.cwd);for(let e of f)if(e&&e.path){let t=e.isDir?e.path:ky(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:by(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=Ny(u,s.cwd);/\bcd\s/.test(u)&&i&&(p||l)&&c.add(Q(i));let a=Iy(e.observation,i,u);a.length>0&&!p&&(a=jy(u)?[]:a.filter(e=>My(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:by(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=Q(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=Q(Ey(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=ky(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:by(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 Vy(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=Hy(e);!a||n.has(a)||(n.add(a),t.push({path:e,note:r}))}return t}function Hy(e){return Q(e).replace(/^\.\//,``)}function Uy(e,t){let n=(e||[]).map(e=>({...e,source:e.source||`static`})),r=n.map(e=>Hy(e.path));for(let e of t||[]){let t=Hy(e.path);if(!t)continue;let i=by(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 Wy(e,t){return Uy(By(e),Vy(t))}function Gy(e){try{return It(e)}catch{return!1}}var Ky=null,qy=null,Jy=null,Yy=1;function Xy(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 Zy(e){if(!Jy)return e;let t=Yy;return[...e].sort((e,n)=>{let r,i;return Jy===`name`?(r=(e.fileName||e.path||``).toLowerCase(),i=(n.fileName||n.path||``).toLowerCase()):Jy===`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 Qy(e,t){let n=Vt(e.fileName,e.type),i=r(`artifacts.${e.action}`),a=Xy(e.timestamp),o=Gy(e.fileName),s=`${Sy(e.path)} · ${r(`artifacts.dblClickHint`)}`;return`
|
|
1228
|
+
<tr class="artifacts-row" data-idx="${t}" data-path="${Sy(e.path)}" data-name="${Sy(e.fileName)}">
|
|
1229
|
+
<td class="col-index">${t+1}</td>
|
|
1230
|
+
<td class="col-file">
|
|
1231
|
+
<span class="artifact-icon">${n}</span>
|
|
1232
|
+
<span class="artifact-name" title="${s}">${Sy(e.fileName)}</span>
|
|
1233
|
+
<button class="artifact-copy-btn" title="${r(`artifacts.copyFileName`)}">
|
|
1234
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="13" height="13">
|
|
1235
|
+
<rect x="9" y="9" width="13" height="13" rx="2" ry="2"/>
|
|
1236
|
+
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
1237
|
+
</svg>
|
|
1238
|
+
</button>
|
|
1239
|
+
</td>
|
|
1240
|
+
<td class="col-type">${i}</td>
|
|
1241
|
+
<td class="col-time">${a}</td>
|
|
1242
|
+
<td class="col-action">
|
|
1243
|
+
<button class="artifact-action-btn download-btn" title="${r(`artifacts.download`)}">
|
|
1244
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1245
|
+
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
|
|
1246
|
+
<polyline points="7 10 12 15 17 10"/>
|
|
1247
|
+
<line x1="12" y1="15" x2="12" y2="3"/>
|
|
1248
|
+
</svg>
|
|
1249
|
+
</button>
|
|
1250
|
+
<button class="artifact-action-btn locate-btn" title="${r(`artifacts.locate`)}">
|
|
1251
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1252
|
+
<path d="M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0 1 18 0z"/>
|
|
1253
|
+
<circle cx="12" cy="10" r="3"/>
|
|
1254
|
+
</svg>
|
|
1255
|
+
</button>
|
|
1256
|
+
${o?`
|
|
1257
|
+
<button class="artifact-action-btn preview-btn" title="${r(`artifacts.preview`)}">
|
|
1258
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1259
|
+
<path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/>
|
|
1260
|
+
<circle cx="12" cy="12" r="3"/>
|
|
1261
|
+
</svg>
|
|
1262
|
+
</button>`:``}
|
|
1263
|
+
</td>
|
|
1264
|
+
</tr>
|
|
1265
|
+
`}function $y(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(qy),qy=setTimeout(()=>{qy=null,Rv().catch(()=>{}),Iv(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(qy),qy=null,Gy(n.fileName)&&Lv(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 Bv(n.path)||n.path),rt(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(),tb(n)}),e.querySelectorAll(`.locate-btn, .preview-btn`).forEach(e=>{e.addEventListener(`click`,async t=>{if(t.stopPropagation(),e.classList.contains(`locate-btn`)){Rv().catch(()=>{});try{await Iv(n.path)}catch(e){i.error(`[Artifacts] locate failed:`,e)}}else if(e.classList.contains(`preview-btn`))try{await Lv(n.path,n.fileName)}catch(e){i.error(`[Artifacts] preview failed:`,e)}})})})}function eb(e,t){let n=Zy(t),r=e.querySelector(`.artifacts-table tbody`);r.innerHTML=n.map((e,t)=>Qy(e,t)).join(``),e.querySelectorAll(`.artifacts-table th.sortable`).forEach(e=>{let t=e.dataset.sort;e.classList.toggle(`sorted-asc`,t===Jy&&Yy===1),e.classList.toggle(`sorted-desc`,t===Jy&&Yy===-1)}),$y(e,n)}async function tb(e){let t=null;try{t=e.type===`directory`?await Ut([e.path]):await Ot(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||by(e.path)||`workspace.zip`;if(e.type===`directory`){let t=by(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 nb(e,t){if(!t)return!0;let n=Q(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 rb(e,t){return!t||!(e===`~`||e&&e.startsWith(`~/`))?e:Q(e===`~`?t:t+`/`+e.slice(2))}function ib(e,t){let n=e.querySelector(`.artifacts-modal-count`);n&&(n.textContent=r(`artifacts.totalCount`,{count:t.length}))}async function ab(e){if(!e||e.length===0)return!1;let t=null;try{let e=await Kt();e&&(t=Q(e))}catch{}let n=null;try{n=await Pt()}catch{}let r=!1;if(t)for(let i=e.length-1;i>=0;i--){let a=e[i];nb(rb(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 Bv(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 ob(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 sb(e,t){!e||e.length===0||!t||ab(e).then(n=>{n&&ob(t,e.length)}).catch(()=>{})}function cb(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 lb(e,t){if(ub(),!e)return;for(let t=e.length-1;t>=0;t--)e[t].deleted&&e.splice(t,1);if(e.length===0){ob(t,0);return}Jy=null,Yy=1,Ky=document.createElement(`div`),Ky.className=`artifacts-modal-overlay`,Ky.id=`artifactsModalOverlay`;let n=document.createElement(`div`);n.className=`artifacts-modal`;let i=document.createElement(`div`);i.className=`artifacts-modal-header`,i.innerHTML=`
|
|
1266
|
+
<div class="artifacts-modal-title">
|
|
1267
|
+
<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
|
+
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
1269
|
+
<polyline points="14 2 14 8 20 8"/>
|
|
1270
|
+
<line x1="12" y1="18" x2="12" y2="12"/>
|
|
1271
|
+
<line x1="9" y1="15" x2="15" y2="15"/>
|
|
1272
|
+
</svg>
|
|
1273
|
+
<span>${r(`artifacts.modalTitle`)}</span>
|
|
1274
|
+
<span class="artifacts-modal-count">${r(`artifacts.totalCount`,{count:e.length})}</span>
|
|
1275
|
+
</div>
|
|
1276
|
+
<button class="artifacts-modal-close" id="artifactsModalClose" title="${r(`artifacts.closeBtn`)}">×</button>
|
|
1277
|
+
`;let a=document.createElement(`div`);a.className=`artifacts-modal-body`;let o=document.createElement(`table`);o.className=`artifacts-table`,o.innerHTML=`
|
|
1278
|
+
<thead>
|
|
1279
|
+
<tr>
|
|
1280
|
+
<th class="col-index" title="${r(`artifacts.serialCol`)}">${r(`artifacts.serialCol`)}</th>
|
|
1281
|
+
<th class="col-file sortable" data-sort="name" title="${r(`artifacts.sortHint`)}">${r(`artifacts.fileCol`)}<span class="sort-indicator"></span></th>
|
|
1282
|
+
<th class="col-type sortable" data-sort="type" title="${r(`artifacts.sortHint`)}">${r(`artifacts.typeCol`)}<span class="sort-indicator"></span></th>
|
|
1283
|
+
<th class="col-time sortable" data-sort="time" title="${r(`artifacts.sortHint`)}">${r(`artifacts.timeCol`)}<span class="sort-indicator"></span></th>
|
|
1284
|
+
<th class="col-action">${r(`artifacts.actionCol`)}</th>
|
|
1285
|
+
</tr>
|
|
1286
|
+
</thead>
|
|
1287
|
+
<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`,ub),s.appendChild(c),n.appendChild(i),n.appendChild(a),n.appendChild(s),Ky.appendChild(n);let l=document.body,u=document.getElementById(`workspacePanelContainer`);if(u&&u.classList.contains(`embedded`)){let e=document.getElementById(`mainLeft`);e&&(Ky.classList.add(`embedded-mode`),e.style.position=`relative`,l=e)}l.appendChild(Ky),document.getElementById(`artifactsModalClose`).addEventListener(`click`,ub);let d=e=>{e.key===`Escape`&&(ub(),document.removeEventListener(`keydown`,d))};document.addEventListener(`keydown`,d),o.querySelectorAll(`th.sortable`).forEach(t=>{t.addEventListener(`click`,()=>{let r=t.dataset.sort;Jy===r?Yy=-Yy:(Jy=r,Yy=1),eb(n,e)})}),eb(n,e),ab(e).then(i=>{if(!(!i||!Ky)){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>`),ib(n,e)}else ib(n,e),eb(n,e);ob(t,e.length)}}).catch(()=>{})}function ub(){qy&&=(clearTimeout(qy),null),Ky&&=(Ky.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} 分块`,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`,disabledBadge:`Disabled`,disabledTooltip:`Disabled (the model won't search this knowledge base autonomously); you can still reference it manually via @`,manualSuffix:`manual`}});var db=`pages`;async function fb(){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 pb=!1;async function mb(e=``,t=null){let n=document.getElementById(`agentAtSelector`),r=document.getElementById(`agentAtDropdown`);Je(),n.style.display=`block`,r.classList.add(`show`),_b(),t?await vb(t):await yb(e),hb()}async function hb(){try{let[e,t,n,i]=await Promise.all([gt(),Zb(),fb(),Gb()]),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&&db===`knowledge`&&vb(`pages`))}catch{}}function gb(){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 _b(){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`,()=>{vb(e.dataset.tab)})}),e.addEventListener(`click`,async e=>{if(e.target.closest(`#agentAddBtn`)){e.stopPropagation(),gb(),KT(null);return}if(e.target.closest(`#proxyAddBtn`)){e.stopPropagation(),gb(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`agent`});return}if(e.target.closest(`#knowledgeAddBtn`)){e.stopPropagation(),gb(),chrome.runtime.sendMessage({type:`OPEN_OPTIONS_PAGE`,hash:`knowledge`});return}if(e.target.closest(`#pageAddBtn`)){e.stopPropagation(),gb(),chrome.tabs.create({});return}let t=e.target.closest(`.agent-edit-btn`);if(t){e.stopPropagation();let n=t.dataset.agentId;gb(),KT(n);return}let n=e.target.closest(`.agent-delete-btn`);if(n){e.stopPropagation();let t=n.dataset.agentId;if(await fE(t)){let e=document.getElementById(`userInput`);await yb(e?bb(e.value):``)}}})}async function vb(e){db=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 yb(s?bb(s.value):``)}async function yb(e=``){let t=document.getElementById(`agentAtTabs`),n=document.getElementById(`agentPageList`),r=document.getElementById(`agentAtList`),i=document.getElementById(`agentProxyList`),a=document.getElementById(`agentKnowledgeList`);if(e){pb=!0,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 jb(e);let o=document.getElementById(`agentAtDropdown`);o&&o.setAttribute(`data-active-tab`,`merged`)}else{pb=!1,t&&t.classList.remove(`merged-mode`),t&&t.querySelectorAll(`.prompt-tab`).forEach(e=>{e.classList.toggle(`active`,e.dataset.tab===db)}),n&&(n.style.display=db===`pages`?``:`none`),r&&(r.style.display=db===`agents`?``:`none`),i&&(i.style.display=db===`proxies`?``:`none`),a&&(a.style.display=db===`knowledge`?``:`none`);let e=document.getElementById(`agentAtDropdown`);e&&e.setAttribute(`data-active-tab`,db),db===`pages`?await Qb(``):db===`proxies`?await Ab(``):db===`knowledge`?await Kb(``):await Cb(``)}}function bb(e){let t=e.lastIndexOf(`@`);return t===-1?``:e.substring(t+1)}function xb(e){return e.id==="default"?r(`agentMgr.defaultAgentName`):e.name}function Sb(e){return e.id==="default"?r(`agentMgr.defaultAgentDesc`):e.description}async function Cb(e=``){let t=document.getElementById(`agentAtList`);if(!t)return;let n=await gt(),i=(e||``).toLowerCase(),a=n.filter(t=>{if(!e)return!0;let n=xb(t),r=Sb(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=xb(e),s=Sb(e);return`
|
|
1289
|
+
<div class="prompt-item ${t===0?`selected`:``} ${n?`agent-at-active`:``}"
|
|
1290
|
+
data-index="${t}" data-agent-id="${P(e.id)}">
|
|
1291
|
+
<span class="prompt-item-index">${t+1}</span>
|
|
1292
|
+
<span class="agent-at-icon">${P(e.icon)}</span>
|
|
1293
|
+
<span class="prompt-item-content">${P(o)}</span>
|
|
1294
|
+
<span class="prompt-item-code">${P(s||a)}</span>
|
|
1295
|
+
<span class="agent-item-actions">
|
|
1296
|
+
<span class="agent-active-mark" style="${n?``:`display:none`}">✓</span>
|
|
1297
|
+
<span class="agent-edit-btn" data-agent-id="${P(e.id)}" title="${r(`promptSelector.editAgentTitle`)}">✎</span>
|
|
1298
|
+
${e.isBuiltin?``:`<span class="agent-delete-btn" data-agent-id="${P(e.id)}" title="${r(`promptSelector.deleteAgentTitle`)}">✕</span>`}
|
|
1299
|
+
</span>
|
|
1300
|
+
</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 Fb(e.dataset.agentId)})})}async function wb(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 Tb=new Map,Eb=1e4;function Db(e){let t=Tb.get(e.id);return t&&Date.now()-t.ts<Eb?t:null}function Ob(e,t){return e.isDisabled?`disabled`:e.isActive?t?`connected`:`disconnected`:t?`online`:`offline`}async function kb(e){if(Db(e))return;let t=await wb(e);Tb.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-${Ob(e,t.online)}`)}})}async function Ab(e=``){let t=document.getElementById(`agentProxyList`);if(!t)return;let n=await fb(),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=Db(e),i=e.isActive,a=e.isDisabled,o=Ob(e,n?n.online:!1),s=e.name||r(`promptSelector.unnamedProxy`);return`
|
|
1302
|
+
<div class="prompt-item ${t===0?`selected`:``} ${i?`agent-at-active`:``} ${a?`agent-disabled`:``} prompt-item-proxy"
|
|
1303
|
+
data-index="${t}" data-proxy-id="${P(e.id)}">
|
|
1304
|
+
<span class="prompt-item-index">${t+1}</span>
|
|
1305
|
+
<span class="agent-at-dot agent-at-dot-${o}"></span>
|
|
1306
|
+
<span class="prompt-item-content">${P(s)}</span>
|
|
1307
|
+
<span class="prompt-item-code" title="${P(e.url||``)}">${P(e.url||``)}</span>
|
|
1308
|
+
<span class="agent-item-actions">
|
|
1309
|
+
${i?`<span class="agent-active-mark">✓</span>`:``}
|
|
1310
|
+
</span>
|
|
1311
|
+
${a?`<span class="proxy-enable-btn" data-action="enable" data-id="${P(e.id)}" title="${r(`promptSelector.enableTitle`)}">▶</span>`:`<span class="proxy-disable-btn" data-action="disable" data-id="${P(e.id)}" title="${r(`promptSelector.disableTitle`)}">⏸</span>`}
|
|
1312
|
+
<span class="proxy-delete-btn" data-action="delete" data-id="${P(e.id)}" title="${r(`common.delete`)}">✕</span>
|
|
1313
|
+
</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 Xb(n.dataset.action,n.dataset.id);return}await qb(e.dataset.proxyId)})}),a.forEach(e=>kb(e))}async function jb(e=``){let t=document.getElementById(`agentAtList`);if(!t)return;let n=e.toLowerCase(),[i,a,o,s]=await Promise.all([gt(),Zb(),fb(),Gb()]),c=i.filter(e=>{let t=xb(e),r=Sb(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=xb(e),o=Sb(e);m+=`
|
|
1315
|
+
<div class="prompt-item${h===0?` selected`:``}${t?` agent-at-active`:``}"
|
|
1316
|
+
data-index="${h}" data-type="agent" data-agent-id="${P(e.id)}">
|
|
1317
|
+
<span class="prompt-item-index">${h+1}</span>
|
|
1318
|
+
<span class="agent-at-icon">${P(e.icon)}</span>
|
|
1319
|
+
<span class="prompt-item-content">${P(a)}</span>
|
|
1320
|
+
<span class="prompt-item-code">${P(o||i)}</span>
|
|
1321
|
+
<span class="agent-item-actions">
|
|
1322
|
+
<span class="agent-active-mark" style="${t?``:`display:none`}">✓</span>
|
|
1323
|
+
<span class="agent-edit-btn" data-agent-id="${P(e.id)}" title="${r(`promptSelector.editAgentTitle`)}">✎</span>
|
|
1324
|
+
${e.isBuiltin?``:`<span class="agent-delete-btn" data-agent-id="${P(e.id)}" title="${r(`promptSelector.deleteAgentTitle`)}">✕</span>`}
|
|
1325
|
+
</span>
|
|
1326
|
+
</div>`,h++});let g=C.selectedPage?C.selectedPage.id:null;l.forEach(e=>{let t=e.title||r(`promptSelector.noTitle`),n=e.url||``,i=e.favIconUrl?`<img src="${P(e.favIconUrl)}" width="16" height="16" style="flex-shrink:0;" class="favicon-img">`:`<span style="font-size:14px;flex-shrink:0;">🌐</span>`,a=e.id===g;m+=`
|
|
1327
|
+
<div class="prompt-item${h===0?` selected`:``} prompt-item-page"
|
|
1328
|
+
data-index="${h}" data-type="page" data-tab-id="${e.id}">
|
|
1329
|
+
<span class="prompt-item-index">${h+1}</span>
|
|
1330
|
+
${i}
|
|
1331
|
+
<span class="prompt-item-content" title="${P(t)}">${P(t)}</span>
|
|
1332
|
+
<span class="prompt-item-code" title="${P(n)}">${P(n)}</span>
|
|
1333
|
+
${a?`<span class="page-item-actions"><span class="page-selected-mark">✓</span></span>`:``}
|
|
1334
|
+
<span class="page-action-toolbar">
|
|
1335
|
+
<span class="page-action-btn" data-action="interpret" data-tab-id="${e.id}" title="${r(`pageSelector.interpretPage`)}">${r(`pageSelector.interpretPage`)}</span>
|
|
1336
|
+
<span class="page-action-btn" data-action="summarize" data-tab-id="${e.id}" title="${r(`pageSelector.summarizePage`)}">${r(`pageSelector.summarizePage`)}</span>
|
|
1337
|
+
<span class="page-action-btn" data-action="translate" data-tab-id="${e.id}" title="${r(`pageSelector.translatePage`)}">${r(`pageSelector.translatePage`)}</span>
|
|
1338
|
+
</span>
|
|
1339
|
+
</div>`,h++}),d.forEach(e=>{let t=C.knowledgeRefs.some(t=>t.id===e.id),n=r(`knowledgeSelector.docChunk`,{docs:e.documentCount||0,chunks:e.chunkCount||0}),i=e.enabled===!1;m+=`
|
|
1340
|
+
<div class="prompt-item${h===0?` selected`:``}${t?` agent-at-active picked`:``}${i?` knowledge-item-disabled`:``} prompt-item-knowledge"
|
|
1341
|
+
data-index="${h}" data-type="knowledge" data-kb-id="${P(e.id)}" data-kb-name="${P(e.name||``)}"
|
|
1342
|
+
data-kb-disabled="${i?`1`:`0`}"${i?` title="${P(r(`knowledgeSelector.disabledTooltip`))}"`:``}>
|
|
1343
|
+
<span class="prompt-item-index">${h+1}</span>
|
|
1344
|
+
<span class="agent-at-icon">📚</span>
|
|
1345
|
+
<span class="prompt-item-content">${P(e.name||``)}</span>
|
|
1346
|
+
${i?`<span class="knowledge-item-badge badge-disabled">${r(`knowledgeSelector.disabledBadge`)}</span>`:``}
|
|
1347
|
+
<span class="prompt-item-code">${P(n)}</span>
|
|
1348
|
+
</div>`,h++}),u.forEach(e=>{let t=e.isActive,n=e.isDisabled,i=Db(e),a=Ob(e,i?i.online:!1),o=e.name||r(`promptSelector.unnamedProxy`);m+=`
|
|
1349
|
+
<div class="prompt-item${h===0?` selected`:``}${t?` agent-at-active`:``}${n?` agent-disabled`:``} prompt-item-proxy"
|
|
1350
|
+
data-index="${h}" data-type="proxy" data-proxy-id="${P(e.id)}">
|
|
1351
|
+
<span class="prompt-item-index">${h+1}</span>
|
|
1352
|
+
<span class="agent-at-dot agent-at-dot-${a}"></span>
|
|
1353
|
+
<span class="prompt-item-content">${P(o)}</span>
|
|
1354
|
+
<span class="prompt-item-code" title="${P(e.url||``)}">${P(e.url||``)}</span>
|
|
1355
|
+
${t?`<span class="agent-item-actions"><span class="agent-active-mark">✓</span></span>`:``}
|
|
1356
|
+
${n?`<span class="proxy-enable-btn" data-action="enable" data-id="${P(e.id)}" title="${r(`promptSelector.enableTitle`)}">▶</span>`:`<span class="proxy-disable-btn" data-action="disable" data-id="${P(e.id)}" title="${r(`promptSelector.disableTitle`)}">⏸</span>`}
|
|
1357
|
+
<span class="proxy-delete-btn" data-action="delete" data-id="${P(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=>kb(e)),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,async t=>{let n=t.target.closest(`.page-action-btn`);if(n){t.stopPropagation(),rx(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 Xb(r.dataset.action,r.dataset.id);return}if(t.target.closest(`.agent-edit-btn`)||t.target.closest(`.agent-delete-btn`))return;let i=e.dataset.type;i===`agent`?await Fb(e.dataset.agentId):i===`page`?Ib(parseInt(e.dataset.tabId)):i===`knowledge`?(Rb({id:e.dataset.kbId,name:e.dataset.kbName,enabled:e.dataset.kbDisabled!==`1`}),(t.ctrlKey||t.metaKey)&&gb()):i===`proxy`&&await qb(e.dataset.proxyId)})})}function Mb(e){let t;t=pb?C.selectedAgentAtIndex:db===`proxies`?C.selectedProxyAtIndex:db===`knowledge`?C.selectedKnowledgeAtIndex:C.selectedAgentAtIndex,e.forEach((e,n)=>{n===t?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function Nb(){let e=document.getElementById(`userInput`);if(!e)return;let t=e.value,n=t.lastIndexOf(`@`);n!==-1&&(e.value=t.substring(0,n)),e.focus(),e.selectionStart=e.selectionEnd=e.value.length}function Pb(){let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)}async function Fb(e,{clearTrigger:t=!0}={}){t?Nb():Pb(),gb(),await MT(e),Ue()}function Ib(e){Nb(),chrome.tabs.get(e,e=>{if(chrome.runtime.lastError||!e){i.error(`[AgentAtSelector] getlabelpageinfo failed:`,chrome.runtime.lastError);return}ex(e),gb();let t=document.getElementById(`userInput`);t&&(t.focus(),Ue())})}function Lb(){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 Rb(e,{clearTrigger:t=!0}={}){t?Nb():Pb();let n=C.knowledgeRefs.findIndex(t=>t.id===e.id);n>=0?C.knowledgeRefs.splice(n,1):C.knowledgeRefs.push({id:e.id,name:e.name||e.id,enabled:e.enabled!==!1}),Lb(),Vb(),Ue()}function zb(e){C.knowledgeRefs=C.knowledgeRefs.filter(t=>t.id!==e),Lb(),Vb()}function Bb(){C.knowledgeRefs=[],Lb(),Vb()}function Vb(){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
|
+
<span class="knowledge-chip${t?` knowledge-chip-manual`:``}">
|
|
1360
|
+
<span class="knowledge-chip-name" title="${P(t?r(`knowledgeSelector.disabledTooltip`):e.name)}">📚 ${P(n)}</span>
|
|
1361
|
+
<button class="knowledge-chip-close" data-kb-id="${P(e.id)}" title="${r(`common.delete`)}">✕</button>
|
|
1362
|
+
</span>
|
|
1363
|
+
`}).join(``),e.querySelectorAll(`.knowledge-chip-close`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),zb(e.dataset.kbId)})}),e.style.display=`flex`}}var Hb={ok:!1,collections:[],ts:0},Ub=null,Wb=15e3;async function Gb(e=!1){let t=Date.now(),{ragEnabled:n}=await chrome.storage.local.get(`ragEnabled`);return n===!0?!e&&Hb.ts&&t-Hb.ts<Wb?Hb:Ub||(Ub=new Promise(e=>{try{chrome.runtime.sendMessage({type:`RAG_LIST_COLLECTIONS`},t=>{Hb=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(Hb)})}catch{Hb={ok:!1,collections:[],ts:Date.now()},e(Hb)}}).finally(()=>{Ub=null}),Ub):{ok:!1,disabled:!0,collections:[],ts:Date.now()}}async function Kb(e=``){let t=document.getElementById(`agentKnowledgeList`);if(!t)return;let n=await Gb();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=r(`knowledgeSelector.docChunk`,{docs:e.documentCount||0,chunks:e.chunkCount||0}),a=e.enabled===!1;return`
|
|
1364
|
+
<div class="prompt-item ${t===0?`selected`:``} ${n?`agent-at-active picked`:``} ${a?`knowledge-item-disabled`:``} prompt-item-knowledge"
|
|
1365
|
+
data-index="${t}" data-kb-id="${P(e.id)}" data-kb-name="${P(e.name||``)}"
|
|
1366
|
+
data-kb-disabled="${a?`1`:`0`}"${a?` title="${P(r(`knowledgeSelector.disabledTooltip`))}"`:``}>
|
|
1367
|
+
<span class="prompt-item-index">${t+1}</span>
|
|
1368
|
+
<span class="agent-at-icon">📚</span>
|
|
1369
|
+
<span class="prompt-item-content">${P(e.name||``)}</span>
|
|
1370
|
+
${a?`<span class="knowledge-item-badge badge-disabled">${r(`knowledgeSelector.disabledBadge`)}</span>`:``}
|
|
1371
|
+
<span class="prompt-item-code">${P(i)}</span>
|
|
1372
|
+
</div>
|
|
1373
|
+
`}).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{Rb({id:e.dataset.kbId,name:e.dataset.kbName,enabled:e.dataset.kbDisabled!==`1`}),(t.ctrlKey||t.metaKey)&&gb()})})}async function qb(e,{clearTrigger:t=!0}={}){t?Nb():Pb(),gb();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)}Ue()}var Jb=!1;function Yb(){Jb||(Jb=!0,chrome.tabs.onActivated.addListener(()=>{let e=document.getElementById(`agentAtSelector`);if(!e||e.style.display!==`block`||db!==`pages`&&!pb)return;let t=document.getElementById(`userInput`);yb(t?bb(t.value):``)}))}Yb();async function Xb(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 yb(a?bb(a.value):``)}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 Zb(){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 Qb(e=``){let t=document.getElementById(`agentPageList`);if(!t)return;let n=await Zb(),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="${P(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
|
+
<div class="prompt-item prompt-item-page ${t===0?`selected`:``}"
|
|
1375
|
+
data-index="${t}" data-tab-id="${e.id}">
|
|
1376
|
+
<span class="prompt-item-index">${t+1}</span>
|
|
1377
|
+
${a}
|
|
1378
|
+
<span class="prompt-item-content" title="${P(n)}">${P(n)}</span>
|
|
1379
|
+
${s}
|
|
1380
|
+
<span class="prompt-item-code" title="${P(i)}">${P(i)}</span>
|
|
1381
|
+
${c?`<span class="page-item-actions"><span class="page-selected-mark">✓</span></span>`:``}
|
|
1382
|
+
<span class="page-action-toolbar">
|
|
1383
|
+
<span class="page-action-btn" data-action="interpret" data-tab-id="${e.id}" title="${r(`pageSelector.interpretPage`)}">${r(`pageSelector.interpretPage`)}</span>
|
|
1384
|
+
<span class="page-action-btn" data-action="summarize" data-tab-id="${e.id}" title="${r(`pageSelector.summarizePage`)}">${r(`pageSelector.summarizePage`)}</span>
|
|
1385
|
+
<span class="page-action-btn" data-action="translate" data-tab-id="${e.id}" title="${r(`pageSelector.translatePage`)}">${r(`pageSelector.translatePage`)}</span>
|
|
1386
|
+
</span>
|
|
1387
|
+
</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(),rx(parseInt(n.dataset.tabId),n.dataset.action);return}nx(parseInt(e.dataset.tabId))})})}function $b(e){e.forEach((e,t)=>{t===C.selectedPageIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function ex(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 tx(){C.selectedPage=null,C.selectedPageIndex=-1;let e=document.getElementById(`pageIndicator`);e&&(e.style.display=`none`)}function nx(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}ex(e),gb(),t&&(t.focus(),Ue())})}function rx(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}ex(e),gb();let t=document.getElementById(`userInput`);t&&(t.value=n,Ue()),ew()})}function ix(){let e=document.getElementById(`pageIndicatorClose`);e&&e.addEventListener(`click`,()=>{tx()})}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`,ox=`messageFullscreenBody`,sx=`messageFullscreenTitle`,cx=`messageFullscreenCopyBtn`,lx=`messageFullscreenCloseBtn`,ux=`messageFullscreenExportBtn`,dx=`messageFullscreenExportDropdown`,fx=null,px=null,mx=null,hx=!1,gx=null,_x=!1;function vx(){return fx!==null}function yx(e){return!e||vx()?null:e.innerHTML}function bx(){let e=document.querySelectorAll(`#chatContainer .message.assistant`);return e.length?e[e.length-1]:null}function xx(){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 Sx(){let e=document.getElementById(ax),t=document.getElementById(ox);return!e||!t?(i.warn(`[MsgFullscreen] overlay/body element missing`),null):{overlay:e,body:t,title:document.getElementById(sx),copyBtn:document.getElementById(cx),closeBtn:document.getElementById(lx)}}function Cx(e){if(!e)return;let t=Sx();if(t&&fx!==e){if(!fx){let e=document.getElementById(`chatContainer`);gx=e?e.scrollTop:null}fx&&(_x=!0,wx(),_x=!1),px=document.createComment(`msg-fullscreen-anchor`),e.parentNode.insertBefore(px,e),e.dataset.fullscreen=`1`,t.body.appendChild(e),fx=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`)),Px(),Ex(t.body)}}function wx(){if(!fx)return;let e=Sx();if(Ox(),Fx(),px&&px.parentNode)px.parentNode.insertBefore(fx,px);else if(e){let e=document.getElementById(`chatContainer`);e&&e.appendChild(fx)}if(px&&px.parentNode&&px.parentNode.removeChild(px),delete fx.dataset.fullscreen,fx=null,px=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`),!_x&&gx!==null){let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=gx),gx=null}}function Tx(e){if(fx&&fx===e){wx();return}Cx(e||bx())}function Ex(e){Ox(),hx=!1,e.scrollTop=e.scrollHeight,e.addEventListener(`scroll`,Dx,{passive:!0}),typeof ResizeObserver<`u`&&(mx=new ResizeObserver(()=>{hx||(e.scrollTop=e.scrollHeight)}),mx.observe(e.firstElementChild||e))}function Dx(){let e=document.getElementById(ox);e&&(hx=e.scrollHeight-e.scrollTop-e.clientHeight>60)}function Ox(){let e=document.getElementById(ox);e&&e.removeEventListener(`scroll`,Dx),mx&&=(mx.disconnect(),null)}function kx(e){if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&e.code===`KeyF`){e.preventDefault(),fx?wx():Cx(bx());return}e.key===`Escape`&&fx&&(e.preventDefault(),e.stopImmediatePropagation(),wx())}function Ax(e){if(!e.altKey||e.ctrlKey||e.metaKey||e.shiftKey)return;let t=e.target.closest?.(`#chatContainer .message.assistant`);t&&(e.preventDefault(),Tx(t))}async function jx(e){if(!fx)return;let{copyAssistantMessage:t}=await A(async()=>{let{copyAssistantMessage:e}=await Promise.resolve().then(()=>Rx);return{copyAssistantMessage:e}},void 0);t(fx,document.getElementById(cx),e)}var Mx={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 Nx(){let e=document.createElement(`div`);e.className=`message-fullscreen-export`;let t=document.createElement(`button`);t.className=`message-fullscreen-icon-btn`,t.id=ux,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=dx;let i=e=>`<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round">${Mx[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(),fx&&(n.classList.remove(`show`),(await A(()=>import(`./chat-export-Aojf945l.js`),__vite__mapDeps([9,10,1,11,2,3,0])))[t](fx,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 Px(){if(document.getElementById(ux))return;let e=document.getElementById(lx),t=e?e.parentNode:document.querySelector(`.message-fullscreen-actions`);t&&t.insertBefore(Nx(),e||null)}function Fx(){let e=document.getElementById(dx);e&&e.classList.remove(`show`)}var Ix=!1;function Lx(){Ix||(Ix=!0,document.addEventListener(`click`,e=>{let t=document.getElementById(dx);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(),Tx(n.closest(`.message`));return}if(e.target.closest?.(`#messageFullscreenCloseBtn`)){e.stopPropagation(),wx();return}e.target.closest?.(`#messageFullscreenCopyBtn`)&&(e.stopPropagation(),jx(e))},!0),document.addEventListener(`keydown`,kx,!0),document.addEventListener(`dblclick`,Ax,!0))}var Rx=t({copyAssistantMessage:()=>Vx,copyMessage:()=>Bx,copyRichText:()=>Wx,fallbackCopyRichText:()=>Kx,fallbackCopyText:()=>Ux,quoteAndAsk:()=>Yx,setQuoteContextInjector:()=>Jx,showCopySuccess:()=>Hx,wrapHtmlWithStyles:()=>Gx});n(`zh`,{chatCopy:{copiedMarkdown:`已复制 Markdown`,copiedRich:`已复制富文本`,copyFailedManual:`复制失败,请手动复制`}}),n(`en`,{chatCopy:{copiedMarkdown:`Markdown copied`,copiedRich:`Rich text copied`,copyFailedManual:`Copy failed, please copy manually`}});function zx(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 Bx(e,t){try{let n=e.dataset.textContent_||e.dataset.rawContent||``;navigator.clipboard.writeText(n).then(()=>{let e=t.innerHTML;t.innerHTML=`
|
|
1390
|
+
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
|
|
1391
|
+
<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
|
+
</svg>
|
|
1393
|
+
`,t.classList.add(`copied`),setTimeout(()=>{t.innerHTML=e,t.classList.remove(`copied`)},2e3)}).catch(e=>{i.error(`[SidePanel] copy failed:`,e);let a=document.createElement(`textarea`);a.value=n,a.style.position=`fixed`,a.style.left=`-999999px`,document.body.appendChild(a),a.select();try{document.execCommand(`copy`);let e=t.innerHTML;t.innerHTML=`
|
|
1394
|
+
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
|
|
1395
|
+
<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
|
+
</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 Vx(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=et(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}=zx(e);Wx(r,n,t,a)}else navigator.clipboard.writeText(r).then(()=>{t&&Hx(t)}).catch(()=>{Ux(r,t)})}catch(e){i.error(`[SidePanel] copy failed:`,e),F(r(`chatCopy.copyFailed`),`error`)}}function Hx(e,t=!1){let n=e.innerHTML;e.innerHTML=`
|
|
1398
|
+
<svg viewBox="0 0 16 16" fill="currentColor">
|
|
1399
|
+
<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
|
+
</svg>
|
|
1401
|
+
<span>${r(t?`chatCopy.copiedRich`:`chatCopy.copiedMarkdown`)}</span>
|
|
1402
|
+
`,e.classList.add(`copied`),setTimeout(()=>{e.innerHTML=n,e.classList.remove(`copied`)},2e3)}function Ux(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`),Hx(t)}catch{F(r(`chatCopy.copyFailedManual`),`error`)}document.body.removeChild(n)}function Wx(e,t,n,r=null){let a=Gx(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(()=>{Hx(n,!0)}).catch(t=>{i.warn(`[SidePanel] Clipboard API write failed,using fallback plan:`,t.message),Kx(e,a,n)})}else Kx(e,a,n)}function Gx(e){return`<!DOCTYPE html><html><head>
|
|
1403
|
+
<style>
|
|
1404
|
+
h1 { font-size: 24px; font-weight: bold; margin: 16px 0 8px; }
|
|
1405
|
+
h2 { font-size: 20px; font-weight: bold; margin: 14px 0 6px; }
|
|
1406
|
+
h3 { font-size: 18px; font-weight: bold; margin: 12px 0 6px; }
|
|
1407
|
+
h4 { font-size: 16px; font-weight: bold; margin: 10px 0 6px; }
|
|
1408
|
+
p { margin: 6px 0; line-height: 1.6; }
|
|
1409
|
+
ul, ol { margin: 8px 0; padding-left: 24px; }
|
|
1410
|
+
li { margin: 4px 0; }
|
|
1411
|
+
blockquote { border-left: 4px solid #ddd; padding-left: 12px; margin: 8px 0; color: #666; }
|
|
1412
|
+
code { background: #f4f4f4; padding: 2px 6px; border-radius: 3px; font-family: monospace; }
|
|
1413
|
+
pre {
|
|
1414
|
+
background: #f6f8fa;
|
|
1415
|
+
border: 1px solid #e1e4e8;
|
|
1416
|
+
border-radius: 6px;
|
|
1417
|
+
padding: 14px 16px;
|
|
1418
|
+
margin: 12px 0;
|
|
1419
|
+
overflow-x: auto;
|
|
1420
|
+
font-family: 'SF Mono', 'JetBrains Mono', 'Fira Code', Consolas, Menlo, monospace;
|
|
1421
|
+
font-size: 13px;
|
|
1422
|
+
line-height: 1.6;
|
|
1423
|
+
color: #24292f;
|
|
1424
|
+
white-space: pre-wrap;
|
|
1425
|
+
word-break: break-word;
|
|
1426
|
+
}
|
|
1427
|
+
pre code {
|
|
1428
|
+
background: none;
|
|
1429
|
+
padding: 0;
|
|
1430
|
+
border: none;
|
|
1431
|
+
border-radius: 0;
|
|
1432
|
+
}
|
|
1433
|
+
table { border-collapse: collapse; width: auto; margin: 8px 0; }
|
|
1434
|
+
th, td { border: 1px solid #ddd; padding: 6px 12px; text-align: left; }
|
|
1435
|
+
th { background: #f9f9f9; font-weight: bold; }
|
|
1436
|
+
strong { font-weight: bold; }
|
|
1437
|
+
em { font-style: italic; }
|
|
1438
|
+
a { color: #007bff; text-decoration: underline; }
|
|
1439
|
+
img { max-width: 100%; }
|
|
1440
|
+
</style>
|
|
1441
|
+
</head><body>${e}</body></html>`}function Kx(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`),Hx(n,!0)}catch{Ux(e,n)}finally{a.removeAllRanges(),document.body.removeChild(r)}}var qx=null;function Jx(e){qx=e}function Yx(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:``;qx&&qx(t),a&&(a.innerHTML=`
|
|
1442
|
+
<svg viewBox="0 0 16 16" fill="currentColor">
|
|
1443
|
+
<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
|
+
</svg>
|
|
1445
|
+
<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 Xx(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
|
+
<div class="ri-section">
|
|
1448
|
+
<div class="ri-section-title">${r(`chatPanels.dimensionsTitle`)}</div>
|
|
1449
|
+
<div class="ri-dimensions">
|
|
1450
|
+
${Object.entries(o).map(([e,t])=>{let n=v[e]||e,r=t>=8?`#10b981`:t>=5?`#f59e0b`:`#ef4444`;return`
|
|
1451
|
+
<div class="ri-dim-item">
|
|
1452
|
+
<span class="ri-dim-label">${P(n)}</span>
|
|
1453
|
+
<span class="ri-dim-bar-bg"><span class="ri-dim-bar-fill" style="width:${t*10}%;background:${r}"></span></span>
|
|
1454
|
+
<span class="ri-dim-score" style="color:${r}">${t}/10</span>
|
|
1455
|
+
</div>
|
|
1456
|
+
`}).join(``)}
|
|
1457
|
+
</div>
|
|
1458
|
+
</div>
|
|
1459
|
+
`);let b=``;s&&s.length>0&&(b=`
|
|
1460
|
+
<div class="ri-section">
|
|
1461
|
+
<div class="ri-section-title">${r(`chatPanels.issuesTitle`)}</div>
|
|
1462
|
+
<ul class="ri-list">${s.map(e=>`<li>${P(e)}</li>`).join(``)}</ul>
|
|
1463
|
+
</div>
|
|
1464
|
+
`);let x=``;c&&c.length>0&&(x=`
|
|
1465
|
+
<div class="ri-section">
|
|
1466
|
+
<div class="ri-section-title">${r(`chatPanels.suggestionsTitle`)}</div>
|
|
1467
|
+
<ul class="ri-list">${c.map(e=>`<li>${P(e)}</li>`).join(``)}</ul>
|
|
1468
|
+
</div>
|
|
1469
|
+
`);let S=``;if(p>0||l||u!==null){let e=[];p>0&&e.push(`<span class="ri-tag">${r(`chatPanels.roundsEvaluated`,{rounds:p,revised:m?r(`chatPanels.revisedTag`):``})}</span>`),l&&e.push(`<span class="ri-tag">${r(`chatPanels.finalDecision`,{label:_})}</span>`),u!==null&&e.push(`<span class="ri-tag">${r(u?`chatPanels.resultUseful`:`chatPanels.resultNeedsImprovement`)}</span>`),d&&e.push(`<div class="ri-reasoning">📝 ${P(d)}</div>`),S=`
|
|
1470
|
+
<div class="ri-section">
|
|
1471
|
+
<div class="ri-section-title">${r(`chatPanels.processTitle`)}</div>
|
|
1472
|
+
<div class="ri-process">${e.join(``)}</div>
|
|
1473
|
+
</div>
|
|
1474
|
+
`}let C=r(a>=8?`chatPanels.scoreHighExplanation`:a>=5?`chatPanels.scoreMidExplanation`:`chatPanels.scoreLowExplanation`);i.innerHTML=`
|
|
1475
|
+
<div class="reflection-info-panel">
|
|
1476
|
+
<div class="ri-header">
|
|
1477
|
+
<div class="ri-title">${r(`chatPanels.reflectionTitle`)}</div>
|
|
1478
|
+
<button class="ri-close" title="${r(`common.close`)}">✕</button>
|
|
1479
|
+
</div>
|
|
1480
|
+
<div class="ri-body">
|
|
1481
|
+
<div class="ri-score-overview">
|
|
1482
|
+
<span class="ri-score-emoji">${g}</span>
|
|
1483
|
+
<span class="ri-score-value ${h}">${a}<span class="ri-score-max">/10</span></span>
|
|
1484
|
+
<span class="ri-score-label">${r(`chatPanels.overallScore`)}</span>
|
|
1485
|
+
</div>
|
|
1486
|
+
<div class="ri-section">
|
|
1487
|
+
<div class="ri-section-title">${r(`chatPanels.scoreExplanationTitle`)}</div>
|
|
1488
|
+
<p class="ri-text">${C}</p>
|
|
1489
|
+
</div>
|
|
1490
|
+
${y}
|
|
1491
|
+
${b}
|
|
1492
|
+
${x}
|
|
1493
|
+
${S}
|
|
1494
|
+
<div class="ri-section ri-about">
|
|
1495
|
+
<div class="ri-section-title">${r(`chatPanels.aboutTitle`)}</div>
|
|
1496
|
+
<p class="ri-text">${r(`chatPanels.aboutDesc`)}</p>
|
|
1497
|
+
<p class="ri-text ri-text-sm">${r(`chatPanels.scoreStandard`)}</p>
|
|
1498
|
+
</div>
|
|
1499
|
+
</div>
|
|
1500
|
+
</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 Zx(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=Pe(e);n.innerHTML=`
|
|
1502
|
+
<div class="log-container">
|
|
1503
|
+
<div class="log-header">
|
|
1504
|
+
<div class="log-title">
|
|
1505
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1506
|
+
<circle cx="12" cy="12" r="10"></circle>
|
|
1507
|
+
<polyline points="12 6 12 12 16 14"></polyline>
|
|
1508
|
+
</svg>
|
|
1509
|
+
<h3>${r(`chatPanels.executionLogTitle`)}</h3>
|
|
1510
|
+
${l>0?`<span class="log-badge">${r(`chatPanels.taskBreakdown`)}</span>`:``}
|
|
1511
|
+
</div>
|
|
1512
|
+
<div class="log-close">
|
|
1513
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1514
|
+
<line x1="18" y1="6" x2="6" y2="18"></line>
|
|
1515
|
+
<line x1="6" y1="6" x2="18" y2="18"></line>
|
|
1516
|
+
</svg>
|
|
1517
|
+
</div>
|
|
1518
|
+
</div>
|
|
1519
|
+
|
|
1520
|
+
<div class="log-summary">
|
|
1521
|
+
<div class="summary-item" title="${r(`chatPanels.totalDurationTitle`,{duration:Ve(i)})}">
|
|
1522
|
+
<svg class="summary-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1523
|
+
<circle cx="12" cy="12" r="10"></circle>
|
|
1524
|
+
<polyline points="12 6 12 12 16 14"></polyline>
|
|
1525
|
+
</svg>
|
|
1526
|
+
<span class="summary-label">${r(`chatPanels.totalDuration`)}</span>
|
|
1527
|
+
<span class="summary-value">${Ve(i)}</span>
|
|
1528
|
+
</div>
|
|
1529
|
+
${f?`
|
|
1530
|
+
<div class="summary-item token-summary" title="${r(`chatPanels.tokenUsageTitle`,{total:I(f.totalTokens),prompt:I(f.promptTokens),completion:I(f.completionTokens)})}">
|
|
1531
|
+
<span class="summary-icon token-summary-icon">⬤</span>
|
|
1532
|
+
<span class="summary-label">${r(`chatPanels.tokenUsage`)}</span>
|
|
1533
|
+
<span class="summary-value">${I(f.totalTokens)}</span>
|
|
1534
|
+
</div>
|
|
1535
|
+
`:``}
|
|
1536
|
+
<div class="summary-combo" title="${r(`chatPanels.totalNodesTitle`,{count:e.length})}">
|
|
1537
|
+
<div class="combo-main">
|
|
1538
|
+
<span class="combo-icon">◉</span>
|
|
1539
|
+
<span class="combo-label">${r(`chatPanels.totalNodes`)}</span>
|
|
1540
|
+
<span class="combo-value">${e.length}</span>
|
|
1541
|
+
</div>
|
|
1542
|
+
<div class="combo-stats">
|
|
1543
|
+
<div class="combo-stat success" data-status="success" title="${r(`chatPanels.successCountTitle`,{count:a})}">
|
|
1544
|
+
<span class="stat-icon">✓</span>
|
|
1545
|
+
<span class="stat-label">${r(`chatPanels.successLabel`)}</span>
|
|
1546
|
+
<span class="stat-value">${a}</span>
|
|
1547
|
+
</div>
|
|
1548
|
+
<div class="combo-stat failed" data-status="failed" title="${r(`chatPanels.failedCountTitle`,{count:o})}">
|
|
1549
|
+
<span class="stat-icon">✗</span>
|
|
1550
|
+
<span class="stat-label">${r(`chatPanels.failedLabel`)}</span>
|
|
1551
|
+
<span class="stat-value">${o}</span>
|
|
1552
|
+
</div>
|
|
1553
|
+
${s>0?`
|
|
1554
|
+
<div class="combo-stat subtask" data-status="subtask" title="${r(`chatPanels.subtaskCountTitle`,{completed:c,total:s})}">
|
|
1555
|
+
<span class="stat-icon">🔀</span>
|
|
1556
|
+
<span class="stat-label">${r(`chatPanels.subtaskLabel`)}</span>
|
|
1557
|
+
<span class="stat-value">${c}/${s}</span>
|
|
1558
|
+
</div>
|
|
1559
|
+
`:``}
|
|
1560
|
+
${u?`
|
|
1561
|
+
<div class="combo-stat reflection" title="${u.overallScore==null?r(`chatPanels.scoreLabel`):r(`chatPanels.scoreTitle`,{score:u.overallScore})}">
|
|
1562
|
+
<span class="stat-icon">🎯</span>
|
|
1563
|
+
<span class="stat-label">${r(`chatPanels.scoreLabel`)}</span>
|
|
1564
|
+
<span class="stat-value">${d}</span>
|
|
1565
|
+
</div>
|
|
1566
|
+
`:``}
|
|
1567
|
+
</div>
|
|
1568
|
+
</div>
|
|
1569
|
+
<div class="summary-actions">
|
|
1570
|
+
<button class="toggle-expand-btn" title="${r(`chatPanels.expandAll`)}">
|
|
1571
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1572
|
+
<polyline points="7 13 12 18 17 13"></polyline>
|
|
1573
|
+
<polyline points="7 6 12 11 17 6"></polyline>
|
|
1574
|
+
</svg>
|
|
1575
|
+
</button>
|
|
1576
|
+
</div>
|
|
1577
|
+
</div>
|
|
1578
|
+
|
|
1579
|
+
<div class="timeline">
|
|
1580
|
+
${Uf(e)}
|
|
1581
|
+
</div>
|
|
1582
|
+
</div>
|
|
1583
|
+
`,document.body.appendChild(n),If(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 Qx(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 $x(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&&MC()}async function eS(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,MC())}}catch{}}function tS(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
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1585
|
+
<polygon points="5 3 19 12 5 21 5 3"></polygon>
|
|
1586
|
+
</svg>
|
|
1587
|
+
<span>${r(`chatMsg.resumeTaskBtn`)}</span>
|
|
1588
|
+
`,o.addEventListener(`click`,async e=>{if(e.stopPropagation(),o.disabled)return;let t=await Qx({budgetEnded:a});t!==null&&(o.disabled=!0,o.style.opacity=`0.6`,o.style.cursor=`not-allowed`,rS(C.activeSessionId,t).finally(()=>{o.disabled=!1,o.style.opacity=``,o.style.cursor=``}))}),n.appendChild(o),e.dataset.resumable=String(t),eS(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,MC()),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}=cw(`assistant`,c,!0,[],null,!1,null,null,[],!0);t||(C.messageHistory.push({role:`assistant`,content:c,executionLog:[],messageId:u,resumable:!0,interrupted:!0}),MC()),eS(l,e)}}catch(e){i.warn(`[SidePanel] check abandoned checkpoint failed:`,e.message)}}async function rS(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}=cw(`assistant`,t,!0,[]);return C.messageHistory.push({role:`assistant`,content:t,executionLog:[],messageId:n,resumable:!1,resumed:!0}),MC(),$x(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=mw();C.isGenerating=!0;let o=``,s=[],c=null,l=!1,u=!1,d=!1,f=null,p=null;try{let e=await Cw(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?_i(n,{role:`assistant`,content:r(`chatResume.taskCancelled`),executionLog:e.executionLog||[],resumable:i,resumed:!0}):e.swRestarted?_i(n,{role:`assistant`,content:r(`chatResume.swRestarted`),executionLog:e.executionLog||[],resumable:i,resumed:!0}):_i(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}})),hw(a),!1}if(e.message===r(`chatMsg.errTaskStopped`)){hw(a);let{messageId:t}=cw(`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}),MC(),!1}if(e.swRestarted){hw(a);let t=!!e.checkpoint,{messageId:n}=cw(`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}),MC(),!1}hw(a);let t=r(`chatResume.resumeFailed`,{message:e.message||r(`chatResume.unknownError`)}),{element:i,messageId:o}=cw(`assistant`,t,!0,e.executionLog||[]);return C.messageHistory.push({role:`assistant`,content:t,executionLog:e.executionLog||[],messageId:o,resumable:!1,resumed:!0}),MC(),!1}finally{jl(n)}$x(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),_i(n,e),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:n}})),hw(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}),MC(),m&&tS(e?document.querySelector(`[data-message-id="${e}"]`):null,m),!0}hw(a);let{element:h,messageId:g}=cw(`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}),MC(),h&<(h),!0}var iS=300*1024,aS=typeof TextEncoder<`u`?new TextEncoder:null;function oS(e){return e?aS?aS.encode(e).length:e.length*3:0}var sS=`streamSnap|`,cS=e=>`${sS}${e}`,lS=new Map,uS=null;function dS(){return typeof chrome<`u`&&chrome.storage&&chrome.storage.session&&typeof chrome.storage.session.set==`function`}function fS(){if(uS||typeof window>`u`||!window.addEventListener||typeof document>`u`||!document.addEventListener)return;let e=()=>{gS()},t=()=>{document.visibilityState===`hidden`&&e()};uS={pagehide:e,onVisibility:t},window.addEventListener(`pagehide`,e),document.addEventListener(`visibilitychange`,t)}function pS(e,t,n){if(!e||!t||typeof n!=`function`||!dS())return;fS();let r=lS.get(e)||{};r.callId!==t&&(r.oversizeWarned=!1),r.callId=t,r.read=n,r.timer||=setTimeout(()=>{let t=lS.get(e);t&&(t.timer=null,mS(e).catch(()=>{}))},700),lS.set(e,r)}async function mS(e){let t=lS.get(e);if(!t||(t.timer&&=(clearTimeout(t.timer),null),!dS()))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=oS(r);s>307200&&(t.oversizeWarned||(t.oversizeWarned=!0,i.warn(`[StreamSnapshot] 快照 HTML ${s} 字节超过上限 ${iS},本次只存正文(接管后看不到工具卡片等富结构)`)),o=``),await chrome.storage.session.set({[cS(e)]:{sessionId:e,callId:t.callId,html:o,accumulated:a,ts:Date.now()}})}function hS(e){let t=lS.get(e);t&&(t.timer&&clearTimeout(t.timer),lS.delete(e))}function gS(){return Promise.all([...lS.keys()].map(e=>mS(e).catch(e=>{i.debug(`[StreamSnapshot] 卸载前刷盘失败(忽略):`,e?.message||e)})))}async function _S(e){if(!e||!dS())return null;try{let t=await chrome.storage.session.get(cS(e)),n=t&&t[cS(e)];return!n||!n.callId?null:Date.now()-(n.ts||0)>18e5?(await vS(e),null):n}catch(e){return i.debug(`[StreamSnapshot] 读取快照失败(忽略):`,e?.message||e),null}}async function vS(e){let t=lS.get(e);if(t&&t.timer&&clearTimeout(t.timer),lS.delete(e),dS())try{await chrome.storage.session.remove(cS(e))}catch(e){i.debug(`[StreamSnapshot] 清除快照失败(忽略):`,e?.message||e)}}var yS=t({addStreamingMessage:()=>nC,appendThinkingIndicator:()=>oC,appendToolCallItems:()=>dC,appendToolResult:()=>mC,applyStreamSnapshot:()=>iC,autoScrollToBottom:()=>DS,bindProcessHeaderClick:()=>NS,cancelStreamingTask:()=>_C,createAgentStreamOutput:()=>pC,createCodeBlockHtml:()=>fC,createPreSelectCard:()=>hC,createStreamingElementAccessor:()=>HS,deleteStreamingState:()=>US,finalizeCancelledStream:()=>vC,finalizeStreamingMessage:()=>gC,getPendingPreselectLog:()=>KS,getProcessStartTime:()=>XS,getReasoningContent:()=>QS,getStreamedContent:()=>WS,getThinkingStartTime:()=>JS,initScrollToBottomBtn:()=>AS,markStreamingRetrying:()=>aC,mountStreamingElement:()=>cC,notifyNonStreamContentArrived:()=>jS,reconnectStreamingElement:()=>lC,refreshAgentNames:()=>PS,resetScrollState:()=>kS,scrollStreamingToBottom:()=>OS,setPendingPreselectLog:()=>qS,setProcessStartTime:()=>ZS,setReasoningContent:()=>$S,setStreamedContent:()=>GS,setThinkingStartTime:()=>YS,updateScrollButtonState:()=>TS,updateStreamingMessage:()=>uC});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
|
+
... (点击展开查看完整输出)`,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
|
+
点击查看评估详情`,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
|
+
... (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 bS=new Map,xS=!1,SS=!1,CS=!1,wS=!1;function TS(){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`),wS=!1):e.classList.add(`visible`),t&&(wS&&!r?(t.classList.add(`active`),C.isGenerating?t.classList.add(`pulsing`):t.classList.remove(`pulsing`)):t.classList.remove(`active`,`pulsing`))}function ES(){if(CS)return;let e=document.getElementById(`chatContainer`);e&&(CS=!0,e.addEventListener(`scroll`,()=>{if(xS)return;let t=e.scrollHeight-e.scrollTop-e.clientHeight<80;SS=!t,t?wS=!1:C.isGenerating&&(wS=!0),TS()},{passive:!0}),document.addEventListener(`generating-state-changed`,()=>{C.isGenerating&&(wS=!0),requestAnimationFrame(()=>TS())}))}function DS(e,t={}){if(!e)return;ES();let{force:n=!1,smooth:r=!1}=t;if(!n&&SS){wS=!0,TS();return}if(xS=!0,r){e.scrollTo({top:e.scrollHeight,behavior:`smooth`}),requestAnimationFrame(()=>{xS=!1});return}e.scrollTop=e.scrollHeight,requestAnimationFrame(()=>{SS||(e.scrollTop=e.scrollHeight),requestAnimationFrame(()=>{xS=!1})})}function OS(e){if(!e||!e.isConnected)return;let t=document.getElementById(`chatContainer`);t&&DS(t)}function kS(){SS=!1,wS=!1,C.isGenerating&&(wS=!0),TS()}function AS(){ES();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&&(SS=!1,wS=!1,TS(),DS(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),TS()}function jS(){ES();let e=document.getElementById(`chatContainer`);e&&(e.scrollHeight-e.scrollTop-e.clientHeight<80||(wS=!0),TS())}function MS(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 NS(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=Pe(t?JSON.parse(t):[]);r&&qe(r,n)}catch{}return}n&&n.dataset.filter?MS(r,r.dataset.activeFilter===n.dataset.filter?`all`:n.dataset.filter):r.classList.toggle(`collapsed`)}});let n=e.closest(`.thinking-process`);n&&MS(n,n.dataset.activeFilter||`all`)}async function PS(){try{let{getAllAgents:e}=await A(async()=>{let{getAllAgents:e}=await import(`./agent-store-QTeMyM9O.js`).then(e=>e.t);return{getAllAgents:e}},__vite__mapDeps([0,1,2,3])),t=await e();bS.clear();for(let e of t)bS.set(e.id,e.name||e.id)}catch{}}function FS(e){return bS.get(e)||e}var IS=new Map,LS=new Map,RS=null,zS=0,BS=0,VS=``;function HS(e){return t=>t===void 0?IS.get(e)||null:(IS.set(e,t),t)}function US(e){IS.delete(e),LS.delete(e),vS(e)}function WS(e){return LS.get(e)||``}function GS(e,t){if(LS.set(e,t),!t){hS(e);return}rC(IS.get(e))}function KS(){return RS}function qS(e){RS=e}function JS(){return zS}function YS(e){zS=e}function XS(){return BS}function ZS(e){BS=e}function QS(){return VS}function $S(e){VS=e}function eC(){return`
|
|
1593
|
+
<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
|
+
<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
|
+
<circle cx="8" cy="12" r="1.5"/>
|
|
1596
|
+
<circle cx="16" cy="12" r="1.5"/>
|
|
1597
|
+
</svg>
|
|
1598
|
+
<div class="thinking-dots">
|
|
1599
|
+
<span></span><span></span><span></span>
|
|
1600
|
+
</div>
|
|
1601
|
+
<span class="thinking-label">${r(`chatStream.thinking`)}</span>
|
|
1602
|
+
<button class="streaming-stop-btn" title="${r(`chatStream.stopGenerating`)}">
|
|
1603
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1604
|
+
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
|
|
1605
|
+
</svg>
|
|
1606
|
+
</button>
|
|
1607
|
+
`}function tC(e){e&&e.querySelectorAll(`.streaming-stop-btn`).forEach(e=>{e.addEventListener(`click`,t=>{t.stopPropagation(),_C(e)})})}function nC(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
|
+
<div class="message-content">
|
|
1609
|
+
<div class="stream-content"></div>
|
|
1610
|
+
<div class="thinking-indicator">${eC()}</div>
|
|
1611
|
+
<div class="stream-status hidden"></div>
|
|
1612
|
+
</div>
|
|
1613
|
+
`,(!e||e===C.activeSessionId)&&t&&(t.appendChild(n),kS(),TS(),requestAnimationFrame(()=>{DS(t,{force:!0})})),tC(n),n}function rC(e){let t=e?.dataset?.sessionId,n=e?.dataset?.callId;!t||!n||pS(t,n,()=>({html:e.innerHTML,accumulated:WS(t)}))}function iC(e,t){return!e||!t?!1:(e.innerHTML=t,tC(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 aC(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 oC(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=eC(),t.appendChild(n),tC(n),n}function sC(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 cC(e){let t=IS.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 lC(e){let t=IS.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=LS.get(e)||``;if(i){uC(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`),sC(e,n,t)})}requestAnimationFrame(()=>{n.scrollTop=n.scrollHeight})}function uC(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`);if(e&&(e.textContent===r(`chatStream.thinking`)||e.dataset.retrying===`1`)&&(e.textContent=r(`chatStream.outputting`),delete e.dataset.retrying),n.contains(i)){let e=i.previousElementSibling;if(e&&e.classList.contains(`thinking-content`))e.innerHTML=$e(t);else{let e=document.createElement(`div`);e.className=`thinking-content`,e.innerHTML=$e(t),n.insertBefore(e,i)}}else{let e=n.querySelectorAll(`.thinking-content`);if(e.length===0){let e=document.createElement(`div`);e.className=`thinking-content`,e.innerHTML=$e(t),n.appendChild(e)}else{let r=e[e.length-1],i=r.nextElementSibling;if(!i||!i.classList.contains(`thinking-badge`))r.innerHTML=$e(t);else{let e=document.createElement(`div`);e.className=`thinking-content`,e.innerHTML=$e(t),n.appendChild(e)}}}}else{let e=n.querySelectorAll(`.thinking-badge`);if(e.length>0){let n=e[e.length-1],r=n.nextElementSibling;if(r&&r.classList.contains(`thinking-content`))r.innerHTML=$e(t);else{let e=document.createElement(`div`);e.className=`thinking-content`,e.innerHTML=$e(t),n.after(e)}}else{let e=document.createElement(`div`);e.className=`thinking-content`,e.innerHTML=$e(t),n.appendChild(e)}}rC(e),e.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&DS(e)})}function dC(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=zS>0?Ve(Date.now()-zS):``,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`,sC(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">$ ${P(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} ${P(e)||P(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">${P(i.action)}: ${P(e)||P(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">🔍 ${P(e)||P(t)}</span>`}else if(i.metaType===`subagent`){let e=o.subAgentId||o.agent_id||``,t=e?FS(e):``,n=(o.task||``).substring(0,80);t&&t!==e?(l=`${t} (${e}): ${n}`,c=`<span class="tool-call-subagent">🤖 <strong>${P(t)}</strong> <span class="tool-call-subagent-id">(${P(e)})</span>: ${P(n)}</span>`):(l=`${e}: ${n}`,c=`<span class="tool-call-subagent">🤖 <strong>${P(e)}</strong>: ${P(n)}</span>`)}else{let e=Object.keys(o);if(e.length===0)l=t,c=`<span>${P(t)}</span>`;else if(e.length===1){let t=JSON.stringify(o[e[0]]);l=`${e[0]}: ${t}`,c=`<span>${P(e[0])}: ${P(t.substring(0,80))}</span>`}else l=e.map(e=>`${e}=${JSON.stringify(o[e])}`).join(`, `),c=`<span>${e.slice(0,2).map(e=>`${P(e)}=${P(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">
|
|
1614
|
+
<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>
|
|
1615
|
+
</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">
|
|
1616
|
+
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
1617
|
+
<polyline points="14 2 14 8 20 8"/>
|
|
1618
|
+
</svg>`:`<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1619
|
+
<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"/>
|
|
1620
|
+
</svg>`,d=document.createElement(`div`);d.className=`tool-call-item`+(C.chatConfig?.streamExpandTools?` expanded`:``),d.setAttribute(`data-tool-call-id`,e.id||``),d.setAttribute(`data-meta-type`,i.metaType),d.setAttribute(`data-created-at`,Date.now());let f=t===`agent_exec`,p=f?`
|
|
1621
|
+
<button class="tool-call-terminate-btn" title="${r(`chatStream.terminateCommand`)}">
|
|
1622
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
|
|
1623
|
+
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
|
|
1624
|
+
</svg>
|
|
1625
|
+
</button>`:``,m=f?``:`
|
|
1626
|
+
<button class="tool-call-abort-btn" title="${r(`chatStream.abortWaiting`)}">
|
|
1627
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" width="14" height="14">
|
|
1628
|
+
<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
|
|
1629
|
+
</svg>
|
|
1630
|
+
</button>`;if(d.innerHTML=`
|
|
1631
|
+
<div class="tool-call-header">
|
|
1632
|
+
${u}
|
|
1633
|
+
<span class="tool-call-name">${P(t)}</span>
|
|
1634
|
+
<div class="tool-call-summary">${c}</div>
|
|
1635
|
+
<span class="tool-call-executing">${r(`chatStream.executing`)}</span>
|
|
1636
|
+
${p}
|
|
1637
|
+
${m}
|
|
1638
|
+
<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>
|
|
1639
|
+
</div>
|
|
1640
|
+
<div class="tool-call-body">
|
|
1641
|
+
${fC(P(s))}
|
|
1642
|
+
</div>
|
|
1643
|
+
`,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(),yw(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)}),rC(e),e.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&DS(e)})}function fC(e,t=``){let n=t?` class="${t}"`:``;return`<div class="code-block-container" style="position: relative;">
|
|
1644
|
+
<button class="code-copy-btn" title="${r(`chatStream.copyCode`)}">
|
|
1645
|
+
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
|
1646
|
+
<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"/>
|
|
1647
|
+
</svg>
|
|
1648
|
+
</button>
|
|
1649
|
+
<pre${n}><code>${e}</code></pre>
|
|
1650
|
+
</div>`}function pC(e,t){let n=document.createElement(`div`);n.className=`agent-stream-output`,n.innerHTML=`
|
|
1651
|
+
<div class="tool-result-title">${r(`chatMsg.toolResultTitle`)}</div>
|
|
1652
|
+
${fC(``,`agent-stream-content`)}
|
|
1653
|
+
`;let i=(e?e.querySelector(`.tool-call-body`)||e:null)||t;return i&&i.appendChild(n),n}function mC(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`;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=`
|
|
1654
|
+
<span class="tool-result-status ${e.success?`success`:`fail`}">
|
|
1655
|
+
${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>`}
|
|
1656
|
+
</span>
|
|
1657
|
+
${e.duration?`<span class="tool-result-duration">${Ve(e.duration)}</span>`:``}
|
|
1658
|
+
${c}
|
|
1659
|
+
`,f=u.querySelector(`.tool-call-chevron`);if(f?f.insertAdjacentHTML(`beforebegin`,d):u.insertAdjacentHTML(`beforeend`,d),!l||!e.success){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=`
|
|
1660
|
+
<div class="tool-result-title">${r(`chatStream.execResult`)}</div>
|
|
1661
|
+
<div class="tool-result-content">
|
|
1662
|
+
${fC(P(n))}
|
|
1663
|
+
</div>
|
|
1664
|
+
`,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(),rC(t),t.isConnected&&requestAnimationFrame(()=>{let e=document.getElementById(`chatContainer`);e&&DS(e)})};s>0?setTimeout(c,s):c()}function hC(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>${P(e)}</code>`).join(r(`chatStream.listSeparator`))}</span>`}else e.action?.name===`all_tools`?(i=`<div class="tool-call-summary"><span>${P(e.action.params.reason||``)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectSkippedAll`,{reason:P(e.action.params.reason||``)})}</span>`):e.action?.name===`skip`?(i=`<div class="tool-call-summary"><span>${P(e.action.params.reason||``)}</span></div>`,a=`<span class="preselect-summary">${r(`chatStream.preselectSkippedCount`,{reason:P(e.action.params.reason||``),count:e.action.params.toolCount||`?`})}</span>`):e.error?(i=`<div class="tool-call-summary"><span style="color:var(--danger-500);">${P(e.error)}</span></div>`,a=`<span class="preselect-summary" style="color:var(--danger-500);">${P(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`)}${P(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=`
|
|
1665
|
+
<div class="tool-call-header">
|
|
1666
|
+
<svg class="tool-call-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1667
|
+
<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>
|
|
1668
|
+
</svg>
|
|
1669
|
+
<span class="tool-call-name">${r(`chatStream.toolPreselect`)}</span>
|
|
1670
|
+
${i}
|
|
1671
|
+
<span class="tool-result-status ${n?`fail`:`success`}">${s}</span>
|
|
1672
|
+
${o?`<span class="tool-result-duration">${o}</span>`:``}
|
|
1673
|
+
<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>
|
|
1674
|
+
</div>
|
|
1675
|
+
<div class="tool-call-body">
|
|
1676
|
+
${a}
|
|
1677
|
+
${e.apiResponse?.toolCountAfter===void 0?``:`<div class="preselect-meta">${r(`chatStream.toolsAfterFilter`,{count:e.apiResponse.toolCountAfter})}</div>`}
|
|
1678
|
+
</div>
|
|
1679
|
+
`,t.querySelector(`.tool-call-header`).addEventListener(`click`,e=>{e.ctrlKey||e.metaKey||t.classList.toggle(`expanded`)}),t}function gC(e,t,n=[],a=null,o=null,s=!1){if(!e)return;e.dataset.sessionId&&vS(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=zS>0?Ve(Date.now()-zS):``,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=BS>0?Ve(Date.now()-BS):``,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=Pe(n),p=document.createElement(`div`);p.className=`thinking-process collapsed`;let m=document.createElement(`div`);m.className=`thinking-process-header`;let h=d>0?`
|
|
1680
|
+
<span class="thinking-process-stat">
|
|
1681
|
+
<span class="stat-icon node-icon">◉</span>
|
|
1682
|
+
<span class="stat-label">${r(`chatStream.totalNodes`)}</span>
|
|
1683
|
+
<span class="stat-value">${d}</span>
|
|
1684
|
+
</span>
|
|
1685
|
+
<span class="thinking-process-divider">|</span>
|
|
1686
|
+
<span class="thinking-process-stat success">
|
|
1687
|
+
<span class="stat-icon success-icon">✓</span>
|
|
1688
|
+
<span class="stat-label">${r(`chatStream.successLabel`)}</span>
|
|
1689
|
+
<span class="stat-value">${o}</span>
|
|
1690
|
+
</span>
|
|
1691
|
+
<span class="thinking-process-stat failed">
|
|
1692
|
+
<span class="stat-icon failed-icon">✗</span>
|
|
1693
|
+
<span class="stat-label">${r(`chatStream.failedLabel`)}</span>
|
|
1694
|
+
<span class="stat-value">${u}</span>
|
|
1695
|
+
</span>
|
|
1696
|
+
`:``,g=f?`
|
|
1697
|
+
${d>0?`<span class="thinking-process-divider">|</span>`:``}
|
|
1698
|
+
<span class="thinking-process-stat token-stat" title="${r(`chatStream.tokenUsageTitle`,{total:I(f.totalTokens),prompt:I(f.promptTokens),completion:I(f.completionTokens)})}">
|
|
1699
|
+
<span class="stat-icon token-icon">⬤</span>
|
|
1700
|
+
<span class="stat-label">${r(`chatStream.tokenLabel`)}</span>
|
|
1701
|
+
<span class="stat-value">${I(f.totalTokens)}</span>
|
|
1702
|
+
</span>
|
|
1703
|
+
`:``;if(m.innerHTML=`
|
|
1704
|
+
<svg class="thinking-process-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1705
|
+
<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"/>
|
|
1706
|
+
<circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/>
|
|
1707
|
+
</svg>
|
|
1708
|
+
<span class="thinking-process-title">${r(`chatStream.thinkingProcess`)}</span>
|
|
1709
|
+
<div class="thinking-process-stats">${h}${g}</div>
|
|
1710
|
+
<span class="thinking-process-duration">${e}</span>
|
|
1711
|
+
<svg class="thinking-process-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1712
|
+
<polyline points="6 9 12 15 18 9"/>
|
|
1713
|
+
</svg>
|
|
1714
|
+
`,f){let e=m.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),qe(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=hC(e);v.insertBefore(t,v.firstChild)});let b=v.querySelectorAll(`.thinking-content`),x=CC(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=CC(t);n&&n.trim()&&(e.innerHTML=$e(n));let r=c.querySelector(`.thinking-indicator`);r&&r.remove(),l&&(l.innerHTML=``),c.appendChild(p),c.appendChild(e),NS(m)}else{let e=c.querySelector(`.thinking-indicator`);if(e&&e.remove(),l){let e=CC(t);e&&e.trim()&&(l.innerHTML=$e(e))}}}else if(l){let e=CC(t);if(l.querySelector(`.thinking-content`)){let t=BS>0?Ve(Date.now()-BS):``,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=Pe(n),f=document.createElement(`div`);f.className=`thinking-process collapsed`;let p=document.createElement(`div`);p.className=`thinking-process-header`;let m=u>0?`
|
|
1715
|
+
<span class="thinking-process-stat">
|
|
1716
|
+
<span class="stat-icon node-icon">◉</span>
|
|
1717
|
+
<span class="stat-label">${r(`chatStream.totalNodes`)}</span>
|
|
1718
|
+
<span class="stat-value">${u}</span>
|
|
1719
|
+
</span>
|
|
1720
|
+
<span class="thinking-process-divider">|</span>
|
|
1721
|
+
<span class="thinking-process-stat success">
|
|
1722
|
+
<span class="stat-icon success-icon">✓</span>
|
|
1723
|
+
<span class="stat-label">${r(`chatStream.successLabel`)}</span>
|
|
1724
|
+
<span class="stat-value">${a}</span>
|
|
1725
|
+
</span>
|
|
1726
|
+
<span class="thinking-process-stat failed">
|
|
1727
|
+
<span class="stat-icon failed-icon">✗</span>
|
|
1728
|
+
<span class="stat-label">${r(`chatStream.failedLabel`)}</span>
|
|
1729
|
+
<span class="stat-value">${o}</span>
|
|
1730
|
+
</span>
|
|
1731
|
+
`:``,h=d?`
|
|
1732
|
+
${u>0?`<span class="thinking-process-divider">|</span>`:``}
|
|
1733
|
+
<span class="thinking-process-stat token-stat" title="${r(`chatStream.tokenUsageTitle`,{total:I(d.totalTokens),prompt:I(d.promptTokens),completion:I(d.completionTokens)})}">
|
|
1734
|
+
<span class="stat-icon token-icon">⬤</span>
|
|
1735
|
+
<span class="stat-label">${r(`chatStream.tokenLabel`)}</span>
|
|
1736
|
+
<span class="stat-value">${I(d.totalTokens)}</span>
|
|
1737
|
+
</span>
|
|
1738
|
+
`:``;if(p.innerHTML=`
|
|
1739
|
+
<svg class="thinking-process-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1740
|
+
<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"/>
|
|
1741
|
+
<circle cx="8" cy="12" r="1.5"/><circle cx="16" cy="12" r="1.5"/>
|
|
1742
|
+
</svg>
|
|
1743
|
+
<span class="thinking-process-title">${r(`chatStream.thinkingProcess`)}</span>
|
|
1744
|
+
<div class="thinking-process-stats">${m}${h}</div>
|
|
1745
|
+
<span class="thinking-process-duration">${t}</span>
|
|
1746
|
+
<svg class="thinking-process-chevron" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
1747
|
+
<polyline points="6 9 12 15 18 9"/>
|
|
1748
|
+
</svg>
|
|
1749
|
+
`,d){let e=p.querySelector(`.token-stat`);e&&(e.style.cursor=`pointer`,e.addEventListener(`click`,t=>{t.stopPropagation(),qe(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=$e(e));let n=c.querySelector(`.thinking-indicator`);n&&n.remove(),c.appendChild(f),c.appendChild(t),NS(p)}else{let t=c.querySelector(`.thinking-indicator`);t&&t.remove(),e&&e.trim()&&(l.innerHTML=$e(e))}}else e&&e.trim()&&(l.innerHTML=$e(e))}e.classList.add(`assistant`,`message`),e.dataset.rawContent=typeof t==`string`?dt(t):JSON.stringify(t),e.dataset.textContent_=dt(CC(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(),Vx(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(),Yx(e)}),f.appendChild(m),f.appendChild(xx());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-Aojf945l.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,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-Aojf945l.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,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-Aojf945l.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,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-Aojf945l.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,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=Pe(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(),qe(T,e)}),w.appendChild(e)}let E=Vy(t),D=Wy(n,t);if(E.length&&(e.dataset.declaredArtifacts=JSON.stringify(E)),cb(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=`
|
|
1750
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1751
|
+
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
1752
|
+
<polyline points="14 2 14 8 20 8"/>
|
|
1753
|
+
<line x1="12" y1="18" x2="12" y2="12"/>
|
|
1754
|
+
<line x1="9" y1="15" x2="15" y2="15"/>
|
|
1755
|
+
</svg>
|
|
1756
|
+
<span class="artifacts-btn-count">${D.length}</span>
|
|
1757
|
+
`,e.addEventListener(`click`,t=>{t.stopPropagation(),lb(D,e)}),w.appendChild(e),sb(D,e)}if(Qe(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=oc,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?Cc(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=`
|
|
1758
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1759
|
+
<path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>
|
|
1760
|
+
</svg>
|
|
1761
|
+
`,Mm(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 Pm(n,r),Km(N,n,r);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e}},void 0);e()}else{await Nm(n,r,e.dataset.textContent_||``,C.sessions.find(e=>e.id===n)?.title||``),Km(N,n,r);let{refreshBookmarkPanel:t}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Rm);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=`
|
|
1762
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1763
|
+
<circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/>
|
|
1764
|
+
<path d="M6 8.5v7"/><path d="M6 12h8a4 4 0 0 0 4-4V6"/>
|
|
1765
|
+
</svg>
|
|
1766
|
+
`,ee.addEventListener(`click`,async t=>{t.stopPropagation();let n=e.dataset.messageId;n&&await Xs(C.activeSessionId,n)}),w.appendChild(ee);let te=document.createElement(`button`);te.className=`delete-btn`,te.title=r(`chatStream.deleteMessage`),te.innerHTML=`
|
|
1767
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1768
|
+
<polyline points="3 6 5 6 21 6"></polyline>
|
|
1769
|
+
<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>
|
|
1770
|
+
</svg>
|
|
1771
|
+
`,te.addEventListener(`click`,t=>{t.stopPropagation(),xw(e)}),w.appendChild(te),f.appendChild(w),e.querySelector(`.message-content`).appendChild(f),dw(),pw(),it(),lt(e),requestAnimationFrame(()=>{if(ES(),!SS){let t=document.getElementById(`chatContainer`);t&&e.offsetHeight>t.clientHeight*.6&&e.scrollIntoView({behavior:`smooth`,block:`start`})}TS()})}function _C(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 vC(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 yC=t({_checkForAbandonedCheckpoint:()=>nS,addContextBubble:()=>iw,addLoadingMessage:()=>mw,addMessage:()=>cw,applyNodeFilter:()=>WC,bindExecutionLogDelegate:()=>dw,bindReflectionBadgeDelegate:()=>pw,bindSubtaskProgressClicks:()=>YC,buildKnowledgeContextText:()=>RC,buildUserContent:()=>Vp,callApi:()=>Cw,cancelStreamingTask:()=>_C,classifySubtaskNodeStats:()=>VC,classifySubtaskOutcome:()=>BC,clearChatHistory:()=>PC,clearSelectedContext:()=>EC,deleteMessage:()=>xw,directSend:()=>rw,editAndResendMessage:()=>ww,extractSubtaskPlan:()=>qC,extractTextContent:()=>CC,fillSidePanelInput:()=>nw,hideModal:()=>IC,insertSubtaskRowInOrder:()=>XC,isSubtaskReplaySkipped:()=>HC,loadChatHistory:()=>AC,mapApiErrorToUserMessage:()=>ZC,openImagePreview:()=>jp,rebindAllMessages:()=>vw,refreshSelectionIndicatorFromState:()=>TC,removeLoadingMessage:()=>hw,renderImagePreviewsFromChat:()=>Bp,renderKnowledgeContextBubbles:()=>zC,renderMessageMermaid:()=>lt,renderPendingSubtaskRow:()=>JC,restoreMessageFromHtml:()=>_w,restorePendingSessionsFromStorage:()=>SC,saveChatHistory:()=>MC,saveChatHistoryAsync:()=>NC,sendMessage:()=>ew,setMessageTimestampVisible:()=>lw,setQuoteContext:()=>wC,showCommandTerminateDialog:()=>yw,showModal:()=>FC,stripImagesFromContent:()=>Hp,syncPendingSessionsToStorage:()=>xC,toggleNodeFilter:()=>UC,triggerSelectionSearch:()=>tw});Jx(wC),n(`zh`,{chatMsg:{searchPrompt:`搜索一下`,exportWord:`导出 Word`,exportPdf:`导出 PDF`,exportImage:`导出图片`,exportMarkdown:`导出 Markdown`,executionLogTitle:`执行日志`,revisedTag:`已修订`,roundsTag:` ({count}轮)`,revisedSuffix:`(已修订)`,scoreBadgeTitle:`AI 质量评估: {score}/10{rounds}{revised}
|
|
1772
|
+
点击查看评估详情`,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}
|
|
1773
|
+
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 bC=`pendingCallApiSessions`;function xC(){chrome.storage.session.set({[bC]:[...C.pendingCallApiSessionIds]}).catch(()=>{})}async function SC(){try{let e=await chrome.storage.session.get([bC]);e[bC]&&Array.isArray(e[bC])&&(C.pendingCallApiSessionIds=new Set(e[bC]))}catch{}}function CC(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 wC(e){let t=CC(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 TC(){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 EC(){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(`
|
|
1774
|
+
`),n=e.findIndex(e=>e.startsWith(`[用户问题]`));n===-1?t.value=``:t.value=e.slice(n+1).join(`
|
|
1775
|
+
`).trim()}}var DC,OC=new Promise(e=>{DC=e});function kC(){C.activeSessionId&&document.dispatchEvent(new CustomEvent(`session-hydrated`,{detail:{sessionId:C.activeSessionId,workdir:C.sessionWorkdir||null}}))}async function AC(){try{await jC()}finally{DC(),document.dispatchEvent(new CustomEvent(`chat-history-rendered`,{detail:{sessionId:C.activeSessionId||null}}))}}async function jC(){let e=await ti();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,ri(t),kC(),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-QTeMyM9O.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} (${fm(e.size||0)})`;break;case`knowledge`:{let t=Array.isArray(e.refs)?e.refs:[];t.length>0&&zC(t,e.failed===!0);break}}t&&e.type!==`file`&&iw(e.type,t,!1)}),e.htmlContent)_w(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||``}));cw(e.role,e.content,!1,e.executionLog||[],e.reflectionScore,t,null,e.messageId,n,e.resumable,e.timestamp??null)}}),dw(),pw(),st();let i=document.querySelector(`.welcome-message`);i&&C.messageHistory.length>0&&i.remove(),Ye(),it(),LE(),e.activeSessionId===C.activeSessionId?yo(e):yo(),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 ai();let e=await ti();e.activeSessionId&&(C.activeSessionId=e.activeSessionId,C.sessions=e.list,ri(e.list.find(t=>t.id===e.activeSessionId)),kC()),yo(e)}}function MC(){try{ni().catch(e=>{i.error(`[SidePanel] save currentsession failed:`,e)})}catch(e){i.error(`[SidePanel] save conversationhistory exception:`,e)}}async function NC(){try{await ni()}catch(e){i.error(`[SidePanel] save conversationhistory exception:`,e)}}function PC(){C.messageHistory&&C.messageHistory.length>0&&ui().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=`
|
|
1776
|
+
<div class="icon-wrapper">
|
|
1777
|
+
<div class="icon">💬</div>
|
|
1778
|
+
</div>
|
|
1779
|
+
<h2>${r(`chat.welcomeTitle`)}</h2>
|
|
1780
|
+
<p>${r(`chat.welcomeSubtitle`)}</p>
|
|
1781
|
+
`,e.appendChild(t)}chrome.storage.local.remove(`scrollPosition_`+(C.activeSessionId||`default`)),yo()})}function FC(){document.getElementById(`confirmModal`).classList.add(`show`)}function IC(){document.getElementById(`confirmModal`).classList.remove(`show`)}var LC=1500;async function RC(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,LC),truncated:t.length>LC,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,LC)),m.push(``)})}),m.push(`[/知识库检索结果]`),{text:m.join(`
|
|
1782
|
+
`)+`
|
|
1783
|
+
|
|
1784
|
+
`,refs:p,failed:o}}function zC(e,t=!1){if(!Array.isArray(e)||e.length===0)return;let n=e.reduce((e,t)=>e+(t.hitCount||0),0);if(t){iw(`knowledge`,r(`contextBubble.bubbleKnowledgeFailed`,{name:e.map(e=>e.name).join(`、`)}),!1);return}if(n===0){iw(`knowledge`,r(`contextBubble.bubbleKnowledgeMiss`,{name:e.map(e=>e.name).join(`、`)}),!1);return}e.forEach(e=>{(e.hitCount||0)>0?iw(`knowledge`,r(`contextBubble.bubbleKnowledge`,{name:e.name,count:e.hitCount}),!1,Array.isArray(e.hits)?e.hits:null):iw(`knowledge`,r(`contextBubble.bubbleKnowledgeMiss`,{name:e.name}),!1)})}function BC(e,t,n,r=.8){return e===`failed`?!n||n<=0?`failed`:t/n>=r?`partial`:`failed`:e}function VC(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 HC(e,t){return(Array.isArray(e)?e:[]).some(e=>!!e&&e.nodeType===`subtask`&&e.subtaskIndex===t&&e.skippedReplay===!0)}function UC(e,t){return t!==`success`&&t!==`failed`&&t!==`other`?e||null:e===t?null:t}function WC(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 GC=`<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>`,KC=`<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 qC(e){let t=Array.isArray(e)?e:[],n=null;for(let e of t)!e||e.nodeType!==`subtask_plan`||!Array.isArray(e.items)||(!n||new Date(e.timestamp||0)>=new Date(n.timestamp||0))&&(n=e);if(!n)return null;let r=n.items,i=r.filter(e=>e&&typeof e.index==`number`);return{total:n.subtaskTotal||r.length,items:i,timestamp:n.timestamp}}function JC(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>${P(n)}</div>`:``;return`
|
|
1785
|
+
<div class="subtask-header">
|
|
1786
|
+
${KC}${GC}${`<span class="subtask-badge">${e.index+1}/${t}</span>`}<span class="subtask-name" title="${nt(n)}">${P(e.name||``)}</span><span class="subtask-status-pending">${r(`chatMsg.subtaskPending`)}</span>
|
|
1787
|
+
</div>
|
|
1788
|
+
<div class="subtask-detail-body">${i}</div>
|
|
1789
|
+
`}function YC(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=UC(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 XC(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 ZC(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 QC=Object.freeze({quotedContextText:``,selectedContextText:``,selectedSkills:[],selectedMcpServices:[],knowledgeRefs:[],selectedPage:null,attachedFiles:[],attachedImages:[]});function $C(){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 ew(e={}){await OC;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?$C():QC),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||od(d);if(!x)return{ok:!1,reason:`empty`};if(o&&f&&dd())return F(r(`queue.filesStillExtracting`),`warning`,4e3),{ok:!1,reason:`files_extracting`};if(e.fromQueue||Uu(),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($x(a),chrome.runtime.sendMessage({type:`DELETE_CHECKPOINT`,sessionId:a}),o&&await Xc({state:C,getRatio:()=>SE().usage?.ratio??0,compact:jE}),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&&iw(`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&&iw(`selected`,e,!1),D.push({type:`selected`,text:e}),o&&f&&C.selectedContextText===d.selectedContextText&&(C.selectedContextText=``)}let O=await pT(d.selectedSkills);if(O){S=O+S;for(let e of d.selectedSkills||[])o&&iw(`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,sT(),cT())}}let k=null,A=bT(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&&iw(`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,xT(),ST())}}if((d.knowledgeRefs||[]).length>0){let e=d.knowledgeRefs.slice();o&&(C.isGenerating=!0);let t=o?iw(`knowledge`,r(`contextBubble.bubbleKnowledgeSearching`),!0):null,n=null;try{n=await RC(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&&zC(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,Lb(),Vb())}}if(d.selectedPage){let e=d.selectedPage;S=`[网页上下文]\n标题: ${e.title}\nURL: ${e.url}\ntabId: ${e.id}\n`+S,o&&iw(`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&&tx()}let M=!1,N=(d.attachedFiles||[]).slice();if(N.length>0){let e=Am(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=Te(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:Vp(S,d.attachedImages),messageId:re,timestamp:ie,contextBubbles:D};o?(cw(`user`,Vp(x,d.attachedImages),!0,[],null,!1,S,re,N,!1,ie),C.messageHistory.push(ae),MC(),y&&cn(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?EC():TC()),C.generatingSessionIds.add(a),document.dispatchEvent(new CustomEvent(`generating-state-changed`));let oe=o?mw():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,Bp())}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,km()}}let ce=e=>{if(!o){u.push(e);return}if(C.activeSessionId!==a){_i(a,e);return}C.messageHistory.push(e)};try{await je();let e=await pE(o?C.activeAgentId:l.agentId||null),t=mE(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=nn(u.slice(0,-1),{isolateChat:!0,maxMemoryMessages:C.chatConfig.maxMemoryMessages,compaction:v,currentMessage:n});an(m,r,v,i),r.historySummaryText&&(m[0]={...m[0],content:m[0].content+`
|
|
1790
|
+
|
|
1791
|
+
`+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:Hp(m[e].content)}}else{let e=Vp(S,d.attachedImages);m.push({role:`user`,content:e})}let h=await Ge(o?null:{temperature:l.temperature,topP:l.topP});if(o&&(h._loadingId=oe),o)try{let e=await xf({sessionId:a,text:x,attachments:Sf(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 Sw(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 Cw(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`):ZC(e.message),executionLog:e.executionLog||[],resumable:t}),document.dispatchEvent(new CustomEvent(`session-cache-invalidate`,{detail:{sessionId:a}})),oe&&hw(oe),C.substituteLoadingIds.delete(a),{ok:!1,delivered:!0,reason:`inactive`}}if(e.message===r(`chatMsg.errTaskStopped`)){oe&&hw(oe),C.substituteLoadingIds.delete(a);let{messageId:t}=cw(`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}),MC(),{ok:!1,delivered:!0,reason:`cancelled`}}if(e.swRestarted){oe&&hw(oe),C.substituteLoadingIds.delete(a);let t=!!e.checkpoint,{messageId:n}=cw(`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}),MC(),Ol(a,r(`chat.taskInterruptedSwRestart`),x),{ok:!1,delivered:!0,reason:`sw_restarted`}}oe&&hw(oe),C.substituteLoadingIds.delete(a),D=ZC(e.message),O=e.executionLog||[];let{messageId:t}=cw(`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}),Ol(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&&hw(oe),C.substituteLoadingIds.delete(a),{ok:!0,delivered:!0}}let re=null;if(!M||!N)if(oe&&hw(oe),C.substituteLoadingIds.has(a)&&(hw(C.substituteLoadingIds.get(a)),C.substituteLoadingIds.delete(a)),M)C.substituteLoadingIds.has(a)&&(hw(C.substituteLoadingIds.get(a)),C.substituteLoadingIds.delete(a)),re=te;else{let{element:e,messageId:t}=cw(`assistant`,D,!0,O,A,j,null,null,[],ne?`budget`:!1);re=t,await lt(e),jS()}else re=te;ne&&tS(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}"]`))){_w(N,re,ne?`budget`:!1),dw(),pw();let e=document.getElementById(`chatContainer`);e&&(e.scrollTop=e.scrollHeight)}return C.messageHistory.push(ie),Dl(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?MC():(await ii(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}}))),jl(a),o&&t.focus()}}function tw(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`)),ew()}function nw(e){let t=document.getElementById(`userInput`);!t||!e||(t.value=e,t.dispatchEvent(new Event(`input`)),t.focus())}async function rw(e,t=``){await OC;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 hd();return}n.value=e,n.dispatchEvent(new Event(`input`)),n.focus(),ew()}}function iw(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=P(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:LC})}</span>`:``;return`<div class="kb-bubble-hit"><div class="kb-bubble-hit-text" title="${r(`contextBubble.kbHitToggle`)}">${n}${P(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">${P(t)}${a}</div>${e}`}o.innerHTML=`
|
|
1792
|
+
<div class="context-bubble-inner">
|
|
1793
|
+
<div class="context-bubble-header" title="${r(`contextBubble.clickToExpand`)}">
|
|
1794
|
+
<span class="context-icon">${s}</span>
|
|
1795
|
+
<span class="context-type">${c}</span>
|
|
1796
|
+
</div>
|
|
1797
|
+
<div class="context-bubble-content">${l}</div>
|
|
1798
|
+
</div>
|
|
1799
|
+
`;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 aw(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 ow(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 sw=e=>!!e&&e.dataset.resumable===`budget`;function cw(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`?fe(_):_,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`?fe(c||v):c||v);let b=v;if(m.dataset.executionLog=JSON.stringify(a),s&&(m.dataset.wasRevised=`true`),e===`assistant`){m.innerHTML=$e(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(),Vx(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(),Yx(m)}),e.appendChild(c),e.appendChild(xx());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-Aojf945l.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,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-Aojf945l.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,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-Aojf945l.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,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-Aojf945l.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,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=Pe(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(),qe(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;dw(),pw(),st();let E=a?.find(e=>e.nodeType===`reflection`&&e.reflectionType===`post`),D=Vy(t),O=Wy(a,t);if(D.length&&(m.dataset.declaredArtifacts=JSON.stringify(D)),cb(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=`
|
|
1800
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1801
|
+
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
1802
|
+
<polyline points="14 2 14 8 20 8"/>
|
|
1803
|
+
<line x1="12" y1="18" x2="12" y2="12"/>
|
|
1804
|
+
<line x1="9" y1="15" x2="15" y2="15"/>
|
|
1805
|
+
</svg>
|
|
1806
|
+
<span class="artifacts-btn-count">${O.length}</span>
|
|
1807
|
+
`,e.addEventListener(`click`,t=>{t.stopPropagation(),lb(O,e)}),b.appendChild(e),sb(O,e)}if(Qe(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=oc,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?Cc(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=`
|
|
1808
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1809
|
+
<path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"/>
|
|
1810
|
+
</svg>
|
|
1811
|
+
`,Mm(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 Pm(t,n),Km(j,t,n);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e}},void 0);e()}else{await Nm(t,n,m.dataset.textContent_||``,C.sessions.find(e=>e.id===t)?.title||``),Km(j,t,n);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Rm);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=`
|
|
1812
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1813
|
+
<circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/>
|
|
1814
|
+
<path d="M6 8.5v7"/><path d="M6 12h8a4 4 0 0 0 4-4V6"/>
|
|
1815
|
+
</svg>
|
|
1816
|
+
`,M.addEventListener(`click`,async e=>{e.stopPropagation();let t=m.dataset.messageId;t&&await Xs(C.activeSessionId,t)}),b.appendChild(M);let N=document.createElement(`button`);N.className=`delete-btn`,N.title=r(`chatMsg.deleteMessageTitle`),N.innerHTML=`
|
|
1817
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1818
|
+
<polyline points="3 6 5 6 21 6"></polyline>
|
|
1819
|
+
<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>
|
|
1820
|
+
</svg>
|
|
1821
|
+
`,N.addEventListener(`click`,e=>{e.stopPropagation(),xw(m)}),b.appendChild(N),e.appendChild(b),m.appendChild(e),d&&tS(m,d)}else{let e=b;e=e.replace(/^\[网页上下文\]\n标题: .+\nURL: .+\ntabId: \d+\n/,``),e=e.replace(/\[知识库检索结果\][^\n]*\n[\s\S]*?\[\/知识库检索结果\]\n\n?/,``),e=ow(e),e=aw(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=ow(r),r=aw(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=ow(e),e=aw(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`,()=>{jp(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=`${dm(t.name)} ${t.name} (${fm(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(),Bx(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(),ww(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=`
|
|
1822
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1823
|
+
<polyline points="3 6 5 6 21 6"></polyline>
|
|
1824
|
+
<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>
|
|
1825
|
+
</svg>
|
|
1826
|
+
`,l.addEventListener(`click`,e=>{e.stopPropagation(),xw(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=ze(h),m.appendChild(e)}}if(p.appendChild(m),m._pendingContext){let{type:e,contextText:t}=m._pendingContext,n=iw(e,t,!1);p.insertBefore(n,m),delete m._pendingContext}return n&&DS(p,{smooth:!0}),e===`assistant`&&it(),{element:m,messageId:g,timestamp:h}}function lw(e){let t=document.getElementById(`chatContainer`);t&&t.classList.toggle(`timestamps-hidden`,e===!1)}var uw=!1;function dw(){if(uw)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),Zx(e)}catch(e){i.error(`[chat-manager] parse executionLog failed:`,e)}}),uw=!0)}var fw=!1;function pw(){if(fw)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{Xx(JSON.parse(n),t)}catch(e){i.error(`[chat-manager] parse reflectionData failed:`,e)}}),fw=!0)}function mw(){let e=document.getElementById(`chatContainer`),t=`loading-`+Date.now(),n=document.createElement(`div`);n.className=`loading-message`,n.id=t,n.innerHTML=`
|
|
1827
|
+
<div class="loading-content">
|
|
1828
|
+
<div class="loading-dots">
|
|
1829
|
+
<span></span>
|
|
1830
|
+
<span></span>
|
|
1831
|
+
<span></span>
|
|
1832
|
+
</div>
|
|
1833
|
+
<span class="loading-text">${r(`chatMsg.thinking`)}</span>
|
|
1834
|
+
<button class="stop-task-btn" title="${r(`chatMsg.stopTask`)}">
|
|
1835
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1836
|
+
<circle cx="12" cy="12" r="10"></circle>
|
|
1837
|
+
<line x1="15" y1="9" x2="9" y2="15"></line>
|
|
1838
|
+
<line x1="9" y1="9" x2="15" y2="15"></line>
|
|
1839
|
+
</svg>
|
|
1840
|
+
</button>
|
|
1841
|
+
<div class="execution-status-container" style="display: none;">
|
|
1842
|
+
<button class="execution-log-toggle-btn" title="${r(`chatMsg.viewExecutionLog`)}">
|
|
1843
|
+
<svg viewBox="0 0 1024 1024">
|
|
1844
|
+
<path d="M512 5.12C230.4 5.12 5.12 230.4 5.12 512s225.28 506.88 506.88 506.88 506.88-225.28 506.88-506.88S793.6 5.12 512 5.12z m0 92.16c107.52 0 215.04 46.08 291.84 122.88s122.88 184.32 122.88 291.84-46.08 215.04-122.88 291.84-184.32 122.88-291.84 122.88-215.04-46.08-291.84-122.88-122.88-184.32-122.88-291.84 46.08-215.04 122.88-291.84S404.48 97.28 512 97.28zM430.08 327.68h-5.12c-5.12 0-5.12 5.12-5.12 5.12v353.28l5.12 5.12h20.48l250.88-168.96s5.12 0 5.12-5.12V512v-5.12s0-5.12-5.12-5.12l-256-168.96c-5.12 0-5.12 0-10.24-5.12z" fill="#707070"></path>
|
|
1845
|
+
</svg>
|
|
1846
|
+
</button>
|
|
1847
|
+
<span class="current-node-name">${r(`chatMsg.preparing`)}</span>
|
|
1848
|
+
</div>
|
|
1849
|
+
</div>
|
|
1850
|
+
`,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),Zf(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(),Xf(t)}),t}function hw(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 gw(e){if(!e)return;let t=By((()=>{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?Uy(t,n):t;if(cb(i),Qe(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=`
|
|
1851
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" width="14" height="14">
|
|
1852
|
+
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
|
1853
|
+
<polyline points="14 2 14 8 20 8"/>
|
|
1854
|
+
<line x1="12" y1="18" x2="12" y2="12"/>
|
|
1855
|
+
<line x1="9" y1="15" x2="15" y2="15"/>
|
|
1856
|
+
</svg>
|
|
1857
|
+
<span class="artifacts-btn-count">${i.length}</span>
|
|
1858
|
+
`;let n=t.querySelector(`.execution-log-btn`);n?t.insertBefore(a,n):t.prepend(a)}a._artifactsBound||(a.addEventListener(`click`,e=>{e.stopPropagation(),lb(i,a)}),a._artifactsBound=!0,sb(i,a))}function _w(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&&tS(s,n),s.classList.remove(`streaming`);let c=s.querySelector(`.thinking-process-header`);c&&NS(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`)}">
|
|
1859
|
+
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
|
1860
|
+
<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"/>
|
|
1861
|
+
</svg>
|
|
1862
|
+
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),s.querySelectorAll(`.subtask-progress`).forEach(e=>{YC(e)}),s.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),yw(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(),Vx(s,e,t)});let t=l.querySelector(`.quote-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),Yx(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-Aojf945l.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,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-Aojf945l.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,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-Aojf945l.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,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-Aojf945l.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,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?Cc(t):i.error(`[SidePanel] not found prototypeId,entry keys:`,Object.keys(e),`observation:`,e.observation)})}let o=l.querySelector(`.bookmark-btn`);o&&(Km(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 Pm(t,n),Km(o,t,n);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e}},void 0);e()}else{await Nm(t,n,s.dataset.textContent_||``,C.sessions.find(e=>e.id===t)?.title||``),Km(o,t,n);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=l.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),xw(s)});let u=l.querySelector(`.fork-btn`);u&&u.addEventListener(`click`,async e=>{e.stopPropagation();let t=s.dataset.messageId;t&&await Xs(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 Qx({budgetEnded:sw(s)});t!==null&&(d.disabled=!0,d.style.opacity=`0.6`,d.style.cursor=`not-allowed`,rS(C.activeSessionId,t).finally(()=>{d.disabled=!1,d.style.opacity=``,d.style.cursor=``}))}),gw(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=Pe(e?JSON.parse(e):[]);t&&qe(t,f)}catch{}}))}let u=s.querySelector(`.message-toolbar`);if(u){let e=u.querySelector(`.edit-btn`);e&&e.addEventListener(`click`,e=>{e.stopPropagation(),ww(s)});let t=u.querySelector(`.copy-btn`);t&&t.addEventListener(`click`,e=>{e.stopPropagation(),Bx(s,t)});let n=u.querySelector(`.delete-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),xw(s)})}s.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{jp(e.src,e)})}),a.appendChild(s),LE()}function vw(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`)}">
|
|
1863
|
+
<svg width="16" height="16" viewBox="0 0 16 16" fill="currentColor">
|
|
1864
|
+
<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"/>
|
|
1865
|
+
</svg>
|
|
1866
|
+
</button>`,e.parentElement.insertBefore(t,e),t.appendChild(e)}),e.querySelectorAll(`.thinking-process-header`).forEach(e=>{NS(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=>{YC(e)}),e.querySelectorAll(`.tool-call-terminate-btn, .agent-stream-terminate-btn`).forEach(e=>{e.addEventListener(`click`,e=>{e.stopPropagation(),yw(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(),Vx(t,n,e)});let r=e.querySelector(`.quote-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),Yx(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-Aojf945l.js`);return{exportAssistantMessageToDocx:e}},__vite__mapDeps([9,10,1,11,2,3,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-Aojf945l.js`);return{exportAssistantMessageToMarkdown:e}},__vite__mapDeps([9,10,1,11,2,3,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-Aojf945l.js`);return{exportAssistantMessageToPdf:e}},__vite__mapDeps([9,10,1,11,2,3,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-Aojf945l.js`);return{exportAssistantMessageToImage:e}},__vite__mapDeps([9,10,1,11,2,3,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&&Cc(t)})}let s=e.querySelector(`.bookmark-btn`);s&&(Km(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 Pm(n,r),Km(s,n,r);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e}},void 0);e()}else{await Nm(n,r,t.dataset.textContent_||``,C.sessions.find(e=>e.id===n)?.title||``),Km(s,n,r);let{refreshBookmarkPanel:e}=await A(async()=>{let{refreshBookmarkPanel:e}=await Promise.resolve().then(()=>Rm);return{refreshBookmarkPanel:e}},void 0);e()}}));let c=e.querySelector(`.delete-btn`);c&&c.addEventListener(`click`,e=>{e.stopPropagation(),xw(t)});let l=e.querySelector(`.fork-btn`);l&&l.addEventListener(`click`,async e=>{e.stopPropagation();let n=t.dataset.messageId;n&&await Xs(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 Qx({budgetEnded:sw(t)});n!==null&&(u.disabled=!0,u.style.opacity=`0.6`,u.style.cursor=`not-allowed`,rS(C.activeSessionId,n).finally(()=>{u.disabled=!1,u.style.opacity=``,u.style.cursor=``}))}),gw(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=Pe(e?JSON.parse(e):[]);n&&qe(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(),ww(t)});let r=e.querySelector(`.copy-btn`);r&&r.addEventListener(`click`,e=>{e.stopPropagation(),Bx(t,r)});let i=e.querySelector(`.delete-btn`);i&&i.addEventListener(`click`,e=>{e.stopPropagation(),xw(t)})}),e.querySelectorAll(`.user-message-image`).forEach(e=>{e.addEventListener(`click`,()=>{jp(e.src,e)})}),e.querySelectorAll(`.mermaid-controls`).forEach(e=>e.remove()),Ze(),dw(),pw(),LE()}function yw(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=`
|
|
1867
|
+
<div class="command-terminate-modal">
|
|
1868
|
+
<div class="command-terminate-header">
|
|
1869
|
+
<div class="command-terminate-icon">⏹</div>
|
|
1870
|
+
<div class="command-terminate-title">${r(`chatMsg.terminateCommandTitle`)}</div>
|
|
1871
|
+
</div>
|
|
1872
|
+
<div class="command-terminate-body">
|
|
1873
|
+
<p>${r(`chatMsg.terminateCommandPrompt`)}</p>
|
|
1874
|
+
<div class="command-terminate-options">
|
|
1875
|
+
<button class="command-terminate-option wait-btn">
|
|
1876
|
+
<div class="option-icon">🔌</div>
|
|
1877
|
+
<div class="option-text">
|
|
1878
|
+
<div class="option-title">${r(`chatMsg.terminateWaitTitle`)}</div>
|
|
1879
|
+
<div class="option-desc">${r(`chatMsg.terminateWaitDesc`)}</div>
|
|
1880
|
+
</div>
|
|
1881
|
+
</button>
|
|
1882
|
+
<button class="command-terminate-option kill-btn">
|
|
1883
|
+
<div class="option-icon">💀</div>
|
|
1884
|
+
<div class="option-text">
|
|
1885
|
+
<div class="option-title">${r(`chatMsg.terminateCommandBtnTitle`)}</div>
|
|
1886
|
+
<div class="option-desc">${r(`chatMsg.terminateCommandBtnDesc`)}</div>
|
|
1887
|
+
</div>
|
|
1888
|
+
</button>
|
|
1889
|
+
</div>
|
|
1890
|
+
</div>
|
|
1891
|
+
<div class="command-terminate-footer">
|
|
1892
|
+
<button class="command-terminate-cancel">${r(`common.cancel`)}</button>
|
|
1893
|
+
</div>
|
|
1894
|
+
</div>
|
|
1895
|
+
`,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 bw(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=`
|
|
1896
|
+
<div class="delete-confirm-modal">
|
|
1897
|
+
<div class="delete-confirm-header">
|
|
1898
|
+
<div class="delete-confirm-icon">🗑️</div>
|
|
1899
|
+
<div class="delete-confirm-title">${r(`chatMsg.confirmDeleteMessage`)}</div>
|
|
1900
|
+
</div>
|
|
1901
|
+
<div class="delete-confirm-body">
|
|
1902
|
+
<p>${r(`chatMsg.deleteMessageWarning`)}</p>
|
|
1903
|
+
<div class="delete-confirm-preview">${a}</div>
|
|
1904
|
+
</div>
|
|
1905
|
+
<div class="delete-confirm-footer">
|
|
1906
|
+
<button class="delete-confirm-cancel">${r(`common.cancel`)}</button>
|
|
1907
|
+
<button class="delete-confirm-confirm">${r(`chatMsg.confirmDelete`)}</button>
|
|
1908
|
+
</div>
|
|
1909
|
+
</div>
|
|
1910
|
+
`,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 xw(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 bw(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=`
|
|
1911
|
+
<div class="welcome-message">
|
|
1912
|
+
<div class="icon-wrapper">
|
|
1913
|
+
<div class="icon">💬</div>
|
|
1914
|
+
</div>
|
|
1915
|
+
<h2>${r(`chat.welcomeTitle`)}</h2>
|
|
1916
|
+
<p>${r(`chat.welcomeSubtitle`)}</p>
|
|
1917
|
+
</div>
|
|
1918
|
+
`),await NC(),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 Sw(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}}async function Cw(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 We(),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),xC());let w=HS(x),T=chrome.runtime.connect({name:`keepalive-`+x});i.debug(`[SidePanel] keepalive portconnected, sessionId:`,x),nl(x);try{let e=tl();T.postMessage({type:`KEEPALIVE_IDENTITY`,identity:e==null?null:{windowId:e}})}catch{}let E={restarted:!1,rejectFn:null,cleanup:null,checkpoint:null};T.onMessage.addListener(e=>{if(e.type===`HOST_TAB_RESOLVED`&&e.sessionId===x){rl(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`),E.restarted=!0,E.checkpoint=e.checkpoint||null,E.rejectFn&&E.cleanup&&(E.cleanup(),E.rejectFn({message:r(`chatMsg.errSwRestarted`),executionLog:[],checkpoint:E.checkpoint,swRestarted:!0}))),e.type===`SHOW_CLARIFY_DIALOG`?za(e.data):e.type===`CLARIFY_TIMEOUT`?Ga(e):e.type===`CLARIFY_EXTENDED`?ka(e):e.type===`SHOW_CONFIRM_DIALOG`?co(e.data):e.type===`DISMISS_CONFIRM_DIALOG`&&fo(e.data)});let D={timeoutId:null,removeListener:()=>{}},O=()=>{try{T.disconnect()}catch{}D.timeoutId&&=(clearTimeout(D.timeoutId),null),D.removeListener(),C.pendingCancelApiMap.delete(x),C.pendingCallApiSessionIds.delete(x),US(x),xC()};return new Promise((o,l)=>{if(E.cleanup=O,E.rejectFn=l,E.restarted){O(),l({message:r(`chatMsg.errSwRestarted`),executionLog:[],checkpoint:E.checkpoint,swRestarted:!0});return}let d=[],f=Math.round(_.loopTimeout/1e3);w(null),qS(null),ZS(0);let v=``,T={},k=e=>{w()&&vC(w()),O(),(!e.executionLog||e.executionLog.length===0||d.length>0)&&(e.executionLog=d),l(e)};C.pendingCancelApiMap.set(x,k),C.pendingCallApiSessionIds.add(x),xC(),i.debug(`[SidePanel] callApi: add pendingCallApiSessionIds, mySessionId =`,x,`, set:`,[...C.pendingCallApiSessionIds]),D.timeoutId=setTimeout(()=>{k({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 A=Date.now(),j=0,M=null,N=()=>{M===null&&D.timeoutId!==null&&(M=Date.now(),clearTimeout(D.timeoutId),D.timeoutId=null,i.debug(`[SidePanel] before sidetimeoutpaused (waitinguser response:clarification/sensitive toolconfirm)`))},ee=()=>{if(M!==null){let e=Date.now()-M;j+=e,M=null;let t=Date.now()-A,n=y+j-t;if(n<=0){k({message:r(`chatMsg.errTimeout`,{seconds:f}),executionLog:d});return}D.timeoutId=setTimeout(()=>{k({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`)}},te=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]={...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=qC(d);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=JC(r,i.total||e.subtaskTotal),XC(n,o),YC(o)});let a=`.subtask-progress[data-subtask-index="${t}"]`,o=n.querySelector(a),s=o?o.classList.contains(`subtask-expanded`):!1;o||(o=document.createElement(`div`),o.className=`subtask-progress`,o.dataset.subtaskIndex=t,XC(n,o));let c=GC,l=t+1,u=e.subtaskTotal,f=e.subtaskName||``,p=`<span class="subtask-badge">${l}/${u}</span>`,m=KC,h=e.status!==`success`&&e.status!==`failed`,g=d.filter(e=>e.subtaskIndex===t&&e.nodeType!==`subtask`),_=VC(g),v=_.total,y=_.success,b=_.failed,x=_.other,S=g.find(e=>e.status===`processing`),C=BC(e.status,y,v),w=i?i.items.find(e=>e.index===t):null,T=w&&w.description?String(w.description).replace(/\s+/g,` `).trim():``,E=d.find(e=>e.subtaskIndex===t&&e.nodeType===`subtask`),D=HC(d,t)?`<span class="subtask-replay-skipped" title="${nt(r(`chatMsg.subtaskReplaySkippedHint`))}">${r(`chatMsg.subtaskReplaySkipped`)}</span>`:``;o.classList.remove(`subtask-progress-pending`);let O=``;e.status===`success`?(O=`<span class="subtask-status-done">${r(`chatMsg.subtaskDone`)}</span>`,o.classList.add(`subtask-progress-done`),o.classList.remove(`subtask-progress-active`)):C===`partial`?(O=`<span class="subtask-status-partial">${r(`chatMsg.subtaskPartial`)}</span>`,o.classList.add(`subtask-progress-failed`),o.classList.remove(`subtask-progress-active`)):e.status===`failed`?(O=`<span class="subtask-status-failed">${r(`chatMsg.subtaskFailed`)}</span>`,o.classList.add(`subtask-progress-failed`),o.classList.remove(`subtask-progress-active`)):(O=`<span class="subtask-status-label"><span class="subtask-spinner"></span>${r(`chatMsg.subtaskExecuting`)}</span>`,o.classList.add(`subtask-progress-active`));let k=``;if(h&&v>0){let e=S?S.nodeType===`tool_exec`?`🔧`:S.nodeType===`api_call`?`📡`:S.nodeType===`reflection`?`🎯`:S.nodeType===`preselect`?`🔍`:`○`:`○`,t=S?P(S.nodeName||``):r(`chatMsg.preparing`),n=S?Rf(S):``;k=`<div class="subtask-progress-line">
|
|
1919
|
+
<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="${nt(n)}">${P(n)}</span>`:``}</span>
|
|
1920
|
+
<span class="subtask-node-stats">
|
|
1921
|
+
<span class="subtask-stat-total">${v}</span>
|
|
1922
|
+
<span class="subtask-stat-done${o._nodeFilter===`success`?` subtask-stat-active`:``}" data-node-filter="success" title="${r(`chatMsg.subtaskFilterHint`)}">✓${y}</span>
|
|
1923
|
+
${b>0?`<span class="subtask-stat-fail${o._nodeFilter===`failed`?` subtask-stat-active`:``}" data-node-filter="failed" title="${r(`chatMsg.subtaskFilterHint`)}">✗${b}</span>`:``}
|
|
1924
|
+
${x>0?`<span class="subtask-stat-other${o._nodeFilter===`other`?` subtask-stat-active`:``}" data-node-filter="other" title="${r(`chatMsg.subtaskStatOtherHint`)}">⊘${x}</span>`:``}
|
|
1925
|
+
</span>
|
|
1926
|
+
</div>`}else if(!h){if(e.status===`success`)k=`<div class="subtask-progress-line done">
|
|
1927
|
+
<span>${r(`chatMsg.subtaskAllDone`)}</span>
|
|
1928
|
+
<span class="subtask-node-stats">
|
|
1929
|
+
<span class="subtask-stat-done${o._nodeFilter===`success`?` subtask-stat-active`:``}" data-node-filter="success" title="${r(`chatMsg.subtaskFilterHint`)}">✓ ${y}</span>
|
|
1930
|
+
<span class="subtask-stat-fail${o._nodeFilter===`failed`?` subtask-stat-active`:``}" data-node-filter="failed" title="${r(`chatMsg.subtaskFilterHint`)}">✗ ${b}</span>
|
|
1931
|
+
${x>0?`<span class="subtask-stat-other${o._nodeFilter===`other`?` subtask-stat-active`:``}" data-node-filter="other" title="${r(`chatMsg.subtaskStatOtherHint`)}">⊘ ${x}</span>`:``}
|
|
1932
|
+
</span>
|
|
1933
|
+
</div>`;else if(e.status===`failed`){let e=E&&E.error?String(E.error).replace(/\s+/g,` `).trim().slice(0,120):``,t=e?`<span class="subtask-fail-reason">${P(r(`chatMsg.subtaskFailReason`,{error:e}))}</span>`:``;k=`<div class="subtask-progress-line failed">
|
|
1934
|
+
<span>${r(`chatMsg.subtaskPartialFail`,{success:y,total:v,fail:b})}</span>
|
|
1935
|
+
<span class="subtask-node-stats">
|
|
1936
|
+
<span class="subtask-stat-done${o._nodeFilter===`success`?` subtask-stat-active`:``}" data-node-filter="success" title="${r(`chatMsg.subtaskFilterHint`)}">✓ ${y}</span>
|
|
1937
|
+
<span class="subtask-stat-fail${o._nodeFilter===`failed`?` subtask-stat-active`:``}" data-node-filter="failed" title="${r(`chatMsg.subtaskFilterHint`)}">✗ ${b}</span>
|
|
1938
|
+
${x>0?`<span class="subtask-stat-other${o._nodeFilter===`other`?` subtask-stat-active`:``}" data-node-filter="other" title="${r(`chatMsg.subtaskStatOtherHint`)}">⊘ ${x}</span>`:``}
|
|
1939
|
+
</span>${t}
|
|
1940
|
+
</div>`}}o.innerHTML=`
|
|
1941
|
+
<div class="subtask-header">
|
|
1942
|
+
${m}${c}${p}<span class="subtask-name" title="${nt(T)}">${f}</span>${D}${O}
|
|
1943
|
+
</div>
|
|
1944
|
+
${k}
|
|
1945
|
+
<div class="subtask-detail-body"></div>
|
|
1946
|
+
`,s&&o.classList.add(`subtask-expanded`);let A=o.querySelector(`.subtask-detail-body`);o._renderNodes=()=>{if(!A)return;let e=[];T&&e.push(`<div class="subtask-detail-desc"><span class="subtask-detail-label">${r(`chatMsg.subtaskDescLabel`)}</span>${P(T)}</div>`);let n=E&&E.result?String(E.result).trim():``;n&&e.push(`<div class="subtask-detail-result"><span class="subtask-detail-label">${r(`chatMsg.subtaskResultLabel`)}</span>${P(n)}</div>`);let i=d.filter(e=>e.subtaskIndex===t&&e.nodeType!==`subtask`),a=WC(i,o._nodeFilter),s=``;i.length>0&&a.length===0?s=`<div class="subtask-node-empty">${P(r(`chatMsg.subtaskFilterEmpty`))}</div>`:a.length>0&&(s=a.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`?`✗`:h?`<span class="subtask-node-spinner"></span>`:`○`,i=e.status===`success`?`done`:e.status===`failed`?`failed`:`processing`,a=e.duration?Ve(e.duration):``,o=P(e.nodeName||r(`chatMsg.unknownNode`)),s=``;if(e.nodeType===`tool_exec`){let t=Rf(e);t&&(s=`<span class="subtask-node-cmd" title="${nt(t)}">${P(t)}</span>`)}return`<div class="subtask-node ${i}">
|
|
1947
|
+
<span class="subtask-node-icon">${t}</span>
|
|
1948
|
+
<span class="subtask-node-status">${n}</span>
|
|
1949
|
+
<span class="subtask-node-name">${o}${s}</span>
|
|
1950
|
+
${a?`<span class="subtask-node-dur">${a}</span>`:``}
|
|
1951
|
+
</div>`}).join(``)),A.innerHTML=e.join(``)+s},o._renderNodes(),YC(o),e.status===`success`&&l>=u&&n.querySelectorAll(`.subtask-progress`).forEach(e=>e.classList.add(`subtask-progress-all-done`))}}}return!1}if(e.type===`CLARIFY_START`)return N(),!1;if(e.type===`CLARIFY_END`)return ee(),!1;if(e.type===`TOOL_CONFIRM_START`)return N(),!1;if(e.type===`TOOL_CONFIRM_END`)return ee(),!1;if(e.type===`STREAM_PRESELECT`){if(i.debug(`[SidePanel] received pre-filterlog,:`,e.preselectLog?.length),qS(e.preselectLog||null),w()&&KS()&&KS().length>0){let e=w().querySelector(`.message-content`);e&&(KS().forEach(t=>{let n=hC(t);e.insertBefore(n,e.firstChild)}),qS(null),i.debug(`[SidePanel] pre-filtercard imageappended to existingstreamingelement`))}return!1}if(e.type===`API_RETRYING`){let t=w();if(t)aC(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=`
|
|
1952
|
+
<svg class="thinking-icon pulse-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1953
|
+
<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"/>
|
|
1954
|
+
<circle cx="8" cy="12" r="1.5"/>
|
|
1955
|
+
<circle cx="16" cy="12" r="1.5"/>
|
|
1956
|
+
</svg>
|
|
1957
|
+
<div class="thinking-dots"><span></span><span></span><span></span></div>
|
|
1958
|
+
<span class="thinking-label">${r(`chatMsg.thinking`)}</span>
|
|
1959
|
+
<button class="streaming-stop-btn" title="${r(`chatMsg.stopGeneration`)}">
|
|
1960
|
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1961
|
+
<rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
|
|
1962
|
+
</svg>
|
|
1963
|
+
</button>
|
|
1964
|
+
`;let n=t.querySelector(`.streaming-stop-btn`);n&&n.addEventListener(`click`,e=>{e.stopPropagation(),_C(n)}),e.appendChild(t)}}}else if(w(nC(x)),ZS(Date.now()),KS()&&KS().length>0){let e=w().querySelector(`.message-content`);KS().forEach(t=>{let n=hC(t);e.insertBefore(n,e.firstChild)}),qS(null)}return w().dataset.callId=S,v=``,GS(x,``),YS(Date.now()),$S(``),OS(w()),!1}if(e.type===`STREAM_CHUNK`)return w()&&(v+=e.delta,GS(x,v),w().isConnected&&uC(w(),v)),!1;if(e.type===`STREAM_TOOL_CALL`)return w()||(w(nC(x)),ZS(Date.now())),w()&&e.toolCalls?.length>0&&dC(w(),e.toolCalls),!1;if(e.type===`STREAM_TOOL_RESULT`)return w()&&e.result&&mC(e.result,w()),!1;if(e.type===`AGENT_STREAM`){if(w()&&e.execId){let t=T[e.execId];if(!t){let n=w();t={element:pC(e.toolCallId?n.querySelector(`.tool-call-item[data-tool-call-id="${e.toolCallId}"]`):null,n.querySelector(`.stream-content`)),stdout:``,stderr:``},T[e.execId]=t,it()}let n=t.element.querySelector(`code`);n&&(e.streamType===`stderr`?t.stderr+=e.data:t.stdout+=e.data,n.textContent=t.stdout+(t.stderr?`
|
|
1965
|
+
`+t.stderr:``),n.parentElement.scrollTop=n.parentElement.scrollHeight)}return!1}if(e.type===`AGENT_STREAM_DONE`){if(e.execId){let t=T[e.execId];t&&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()&&gC(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 O(),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(),O(),l({message:e.error,executionLog:e.executionLog||d}),!1}return!1};if(chrome.runtime.onMessage.addListener(te),D.removeListener=()=>{chrome.runtime.onMessage.removeListener(te)},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 ww(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,Bp());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(()=>cm).then(e=>{e.renderFilePreviews()}),void 0));let s=n.match(/^\[网页上下文\]\n标题: (.+)\nURL: (.+)\ntabId: (\d+)\n/);if(s){tx(),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&&(Bb(),C.knowledgeRefs=e.map(e=>({id:``,name:e})),Vb(),Gb().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}}),Vb()}}).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&&(oT(),C.selectedSkills=l.map(e=>({name:e,description:``,type:`agent`})),sT());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&&(yT(),C.selectedMcpServices=u.map(e=>({serverId:``,serverName:e,toolCount:0})),xT(),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)}),xT()}));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=ow(d)),l.length>0&&(d=aw(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=_,Ue(),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:`暂无提示词,请添加`,menuDisplayTitle:`菜单显示`,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 · Ctrl+Enter to insert/select & close · Esc to cancel`,noMatchResult:`No matching results`,requestFailed:`❌ Request failed: {message}`,emptyPromptHint:`No prompts yet, please add one`,menuDisplayTitle:`Show in 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 Tw=`<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 Ew(){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(`
|
|
1966
|
+
`),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(`
|
|
1967
|
+
`),t.dispatchEvent(new Event(`input`)),i.debug(`[SidePanel] removedinput box selected content before suffix`))}C.lastSelectedText=``,C.currentSelectionRange=null}function Dw(){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}),Bw()}t.classList.remove(`drag-over`)})})}function Ow(){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(),Rw()}),e.appendChild(t)}async function kw(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 $w():!1,s=a?await mT():!1;if(i&&(i.style.display=o?`block`:`none`),a&&(a.style.display=s?`block`:`none`),jw(o,s),e)await Pw(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 uT(i),Nw(e)}}function Aw(){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 jw(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 tT(),t=document.getElementById(`skillsTab`);t&&(t.textContent=r(`promptMgr.skillsTabCount`,{count:e.length}))}if(t){let e=await hT(),t=document.getElementById(`mcpTab`);t&&(t.textContent=r(`promptMgr.mcpTabCount`,{count:e.length}))}}catch{}}function Mw(e=``){e?Pw(e):Nw(e)}function Nw(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)=>`
|
|
1968
|
+
<div class="prompt-item ${t===C.selectedPromptIndex?`selected`:``}" data-index="${t}" data-code="${e.code}">
|
|
1969
|
+
<span class="prompt-item-index">${t+1}</span>
|
|
1970
|
+
<span class="prompt-item-icon">${Tw}</span>
|
|
1971
|
+
<span class="prompt-item-content">${e.content}</span>
|
|
1972
|
+
<span class="prompt-item-code">/${e.code}</span>
|
|
1973
|
+
</div>
|
|
1974
|
+
`).join(``),t.querySelectorAll(`.prompt-item`).forEach(e=>{e.addEventListener(`click`,t=>{let n=e.dataset.code;t.ctrlKey||t.metaKey?Iw(n):Lw(n)})})}async function Pw(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 $w()&&(f=(await tT()).filter(t=>e?(t.name||``).toLowerCase().includes(u)||(t.description||``).toLowerCase().includes(u):!0));let p=[];await mT()&&(p=(await hT()).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=`
|
|
1975
|
+
<div class="prompt-item ${g===0?`selected`:``}" data-index="${g}" data-type="prompt" data-code="${e.code}">
|
|
1976
|
+
<span class="prompt-item-index">${g+1}</span>
|
|
1977
|
+
<span class="prompt-item-icon">📋</span>
|
|
1978
|
+
<span class="prompt-item-content">${e.content}</span>
|
|
1979
|
+
<span class="prompt-item-code">/${e.code}</span>
|
|
1980
|
+
</div>`;return g++,t}).join(``),v=f.map(e=>{let t=e.enabled===!1,n=t?`${e.name}\n${r(`skillSelector.disabledTooltip`)}`:e.name,i=`
|
|
1981
|
+
<div class="prompt-item merged-skill-item ${g===0?`selected`:``} ${t?`merged-skill-item-disabled`:``}" data-index="${g}" data-type="skill" data-skill-name="${P(e.name)}" title="${nt(n)}">
|
|
1982
|
+
<span class="prompt-item-index">${g+1}</span>
|
|
1983
|
+
<span class="prompt-item-content">🧩 ${P(e.name)}${e.description?` - `+P(e.description):``}</span>
|
|
1984
|
+
<span class="merged-item-badge badge-skill">${r(`promptSelector.skills`)}</span>
|
|
1985
|
+
${t?`<span class="merged-item-badge badge-disabled">${r(`skillSelector.disabledBadge`)}</span>`:``}
|
|
1986
|
+
</div>`;return g++,i}).join(``),y=p.map(e=>{let t=e.effectiveOpen===!1,n=`
|
|
1987
|
+
<div class="prompt-item merged-mcp-item ${g===0?`selected`:``} ${t?`merged-mcp-item-inactive`:``}" data-index="${g}" data-type="mcp" data-server-id="${P(e.serverId)}" data-server-name="${P(e.serverName)}">
|
|
1988
|
+
<span class="prompt-item-index">${g+1}</span>
|
|
1989
|
+
<span class="prompt-item-content">🔌 ${P(e.serverName)}</span>
|
|
1990
|
+
${t?`<span class="merged-item-badge badge-mcp-inactive">${r(`skillSelector.mcpInactiveBadge`)}</span>`:``}
|
|
1991
|
+
<span class="merged-item-badge badge-mcp">MCP</span>
|
|
1992
|
+
</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;aT(n,await tT()),(t.ctrlKey||t.metaKey)&&Aw()}else if(n===`mcp`){let n=e.dataset.serverId,r=e.dataset.serverName;vT(n,r,await hT()),(t.ctrlKey||t.metaKey)&&Aw()}else{let n=e.dataset.code;t.ctrlKey||t.metaKey?Iw(n):Lw(n)}})}),cT(),ST()}function Fw(e){e.forEach((e,t)=>{t===C.selectedPromptIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function Iw(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=a.lastIndexOf(`/`),s=a;if(!t&&o!==-1){let e=-1;for(let t=o-1;t>=0;t--)if(a[t]===`
|
|
1993
|
+
`){e=t;break}s=e===-1?a.substring(0,o).trimEnd():a.substring(0,e+1).trimEnd()}r.value=s+(s&&!s.endsWith(`
|
|
1994
|
+
`)?`
|
|
1995
|
+
|
|
1996
|
+
`:``)+n.content,r.focus(),r.selectionStart=r.selectionEnd=r.value.length,Aw(),Ue(),i.debug(`[SidePanel] trackaddpromptword to input box:`,n.code,n.content)}async function Lw(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 Xc({state:C,getRatio:()=>SE().usage?.ratio??0,compact:jE}),Aw();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}`,iw(`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}`,iw(`selected`,e,!1),u.push({type:`selected`,text:e}),C.selectedContextText===a.selectedContextText&&(C.selectedContextText=``)}let d=a.selectedSkills,f=await pT(d);if(f){s=f+s;for(let e of d)iw(`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,sT(),cT())}let p=null,h=a.selectedMcpServices,_=bT(h);if(_){let e=h.map(e=>e.serverId).filter(Boolean);p=e.length>0?e:null,s=_+s;for(let e of h)iw(`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,xT(),ST())}let v=a.knowledgeRefs;if(v.length>0){let e=iw(`knowledge`,r(`contextBubble.bubbleKnowledgeSearching`),!1),n=null;try{n=await RC(t.content,v)}catch(e){i.warn(`[SidePanel] knowledge search failed:`,e)}e&&e.parentNode&&e.remove(),n&&(s=n.text+s,zC(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,Lb(),Vb())}let y=a.selectedPage;y&&(s=`[网页上下文]\n标题: ${y.title}\nURL: ${y.url}\ntabId: ${y.id}\n`+s,iw(`page`,r(`contextBubble.bubblePage`,{title:y.title,url:y.url}),!1),u.push({type:`page`,title:y.title,url:y.url}),C.selectedPage===y&&tx()),(c||l)&&(!C.quotedContextText&&!C.selectedContextText?Ew():TC());let b=a.attachedFiles,x=(a.attachedImages||[]).slice();if(b.length>0){let e=Am(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=Te(S?.chatStart,S?.chatCount);w&&(s+=w);let T=Vp(s,x),{messageId:E,timestamp:D}=cw(`user`,Vp(t.content,x),!0,[],null,!1,s,null,b);C.messageHistory.push({role:`user`,content:T,messageId:E,timestamp:D,contextBubbles:u}),MC(),cn(t.content);let O=document.getElementById(`userInput`);O.value===n&&(O.value=``,O.style.height=`auto`),C.isGenerating=!0;let k=mw(),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,Bp())}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,km()}}try{await je(),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=nn(C.messageHistory.slice(0,-1),{isolateChat:!0,maxMemoryMessages:C.chatConfig.maxMemoryMessages,compaction:C.activeCompaction,historyBudget:n,currentMessage:r});an(e,a,C.activeCompaction,i),a.historySummaryText&&(e[0]={...e[0],content:e[0].content+`
|
|
1997
|
+
|
|
1998
|
+
`+a.historySummaryText}),e=[...e,...a.messages];for(let t=0;t<e.length-1;t++)e[t]={...e[t],content:Hp(e[t].content)}}else e.push({role:`user`,content:T});let n=await Ge(),a,o,s=!1,c=null,l=null;try{let t=await Cw(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){hw(k),a=r(`promptMgr.requestFailed`,{message:e.message||r(`agentConfig.unknownError`)}),o=e.executionLog||[];let{element:n,messageId:i}=cw(`assistant`,a,!0,o);throw C.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:i}),MC(),e.message!==r(`chatMsg.errTaskStopped`)&&Ol(A,a,t.content),e}let u=null;if(!s||!c)if(hw(k),s)u=l;else{let{element:e,messageId:t}=cw(`assistant`,a,!0,o);u=t,await lt(e)}else u=l;C.messageHistory.push({role:`assistant`,content:a,executionLog:o,messageId:u}),MC(),Dl(A,t.content)}catch{}finally{jl(A),O.focus()}}function Rw(){document.getElementById(`promptManageModal`).classList.add(`show`),Bw()}function zw(){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 Bw(){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)=>`
|
|
1999
|
+
<div class="prompt-manage-item" draggable="true" data-index="${t}">
|
|
2000
|
+
<div class="prompt-manage-item-left">
|
|
2001
|
+
<span class="prompt-drag-handle" title="${r(`toolbar.dragSort`)}">⋮⋮</span>
|
|
2002
|
+
<span class="prompt-manage-item-content">${e.content}</span>
|
|
2003
|
+
</div>
|
|
2004
|
+
<span class="prompt-manage-item-code">/${e.code}</span>
|
|
2005
|
+
<div class="prompt-manage-item-actions">
|
|
2006
|
+
<button class="prompt-sort-btn move-up-btn" data-index="${t}" title="${r(`toolbar.moveUp`)}" ${t===0?`disabled`:``}>↑</button>
|
|
2007
|
+
<button class="prompt-sort-btn move-down-btn" data-index="${t}" title="${r(`toolbar.moveDown`)}" ${t===C.customPrompts.length-1?`disabled`:``}>↓</button>
|
|
2008
|
+
<button class="prompt-sort-btn menu-toggle-btn ${e.enabledInMenu===!0?`active`:``}" data-index="${t}" title="${r(`promptMgr.menuDisplayTitle`)}">
|
|
2009
|
+
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
|
|
2010
|
+
<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"/>
|
|
2011
|
+
</svg>
|
|
2012
|
+
</button>
|
|
2013
|
+
<button class="edit-btn" data-index="${t}" title="${r(`common.edit`)}">
|
|
2014
|
+
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
|
|
2015
|
+
<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"/>
|
|
2016
|
+
</svg>
|
|
2017
|
+
</button>
|
|
2018
|
+
<button class="delete-btn" data-index="${t}" title="${r(`common.delete`)}">
|
|
2019
|
+
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor">
|
|
2020
|
+
<path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5m3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0z"/>
|
|
2021
|
+
<path d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1zM4.118 4 4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4zM2.5 3h11V2h-11z"/>
|
|
2022
|
+
</svg>
|
|
2023
|
+
</button>
|
|
2024
|
+
</div>
|
|
2025
|
+
</div>
|
|
2026
|
+
`).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}),Bw()}})}),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}),Bw()}})}),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}),Bw()})}),e.querySelectorAll(`.edit-btn`).forEach(e=>{e.addEventListener(`click`,()=>{Ww(parseInt(e.dataset.index))})}),e.querySelectorAll(`.delete-btn`).forEach(e=>{e.addEventListener(`click`,()=>{Gw(parseInt(e.dataset.index))})}),Dw()}function Vw(e){let t=document.getElementById(`promptErrorModal`),n=document.getElementById(`promptErrorMessage`);n.textContent=e,t.classList.add(`show`)}function Hw(){document.getElementById(`promptErrorModal`).classList.remove(`show`)}function Uw(){let e=document.getElementById(`editPromptIndex`),t=document.getElementById(`newPromptCode`),n=document.getElementById(`newPromptContent`),i=t.value.trim(),a=n.value.trim();if(!i||!a){Vw(r(`promptMgr.codeAndContentRequired`));return}let o=e?parseInt(e.value):-1,s=C.customPrompts.findIndex(e=>e.code===i);if(s!==-1&&s!==o){Vw(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)`,Bw()}function Ww(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 Gw(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 Kw(){document.getElementById(`deleteConfirmModal`).classList.remove(`show`),C.pendingDeleteIndex=-1}function qw(e){C.customPrompts.splice(e,1),chrome.storage.local.set({customPrompts:C.customPrompts}),Bw()}function Jw(){let e=document.getElementById(`promptManageCancelBtn`),t=document.getElementById(`promptManageAddBtn`),n=document.getElementById(`promptModalCloseBtn`);e&&e.addEventListener(`click`,zw),t&&t.addEventListener(`click`,Uw),n&&n.addEventListener(`click`,zw);let r=document.getElementById(`deleteCancelBtn`),i=document.getElementById(`deleteConfirmBtn`);r&&r.addEventListener(`click`,Kw),i&&i.addEventListener(`click`,()=>{C.pendingDeleteIndex>=0&&qw(C.pendingDeleteIndex),Kw()});let a=document.getElementById(`deleteConfirmModal`);a&&a.addEventListener(`click`,e=>{e.target===a&&Kw()});let o=document.getElementById(`promptErrorConfirmBtn`);o&&o.addEventListener(`click`,Hw);let s=document.getElementById(`promptErrorModal`);s&&s.addEventListener(`click`,e=>{e.target===s&&Hw()});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:`请根据上述技能说明,使用相关工具处理以下问题:
|
|
2027
|
+
`,loadSkillHint:"请使用 `agent_skill`(action=load)加载「{name}」的完整说明,然后根据说明自主调用相关工具处理以下问题。\n",runSkillHint:"请使用 `agent_skill`(action=run)执行「{name}」技能来处理以下问题",requiredParam:`必填`,optionalParam:`可选`,callParamsPrefix:`,调用参数:`,paramItem:`({flag},{type}:{desc})`,paramJoin:`、`,sentenceEnd:`。
|
|
2028
|
+
`,selectedMcpContext:`[已选MCP服务: {name}]
|
|
2029
|
+
请使用「{name}」MCP服务来处理以下问题:
|
|
2030
|
+
`,disabledBadge:`未启用`,disabledTooltip:`未启用(不会自动注入 AI 提示词),仍可手动选择使用`,mcpInactiveBadge:`未开放`,mcpInactiveTooltip:`该服务当前未开放(已关闭或被当前助手排除),选中后将随本次请求强制启用`,manualUseSuffix:`手动使用`}}),n(`en`,{skillSelector:{selectedSkillStart:`[Selected skill: {name}`,useSkillToolsHint:`Please use the relevant tools to handle the following problem based on the skill description above:
|
|
2031
|
+
`,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:`.
|
|
2032
|
+
`,selectedMcpContext:`[Selected MCP service: {name}]
|
|
2033
|
+
Please use the "{name}" MCP service to handle the following problem:
|
|
2034
|
+
`,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 Yw=[],Xw=0,Zw=3e4;async function Qw(e=!1){let t=Date.now();return!e&&Yw.length>0&&t-Xw<Zw?Yw:new Promise(e=>{chrome.runtime.sendMessage({type:`GET_SKILL_LIST`},t=>{if(chrome.runtime.lastError||!t?.success){e(Yw);return}Yw=t.skills||[],Xw=Date.now(),e(Yw)})})}async function $w(){if(!C.agentPlatform?.connected||(await new Promise(e=>{chrome.storage.local.get([`skillsEnabled`],e)})).skillsEnabled===!1)return!1;try{return(await tT()).length>0}catch{return!1}}async function eT(e=!1){return(await Qw(e)).filter(e=>e.enabled!==!1)}async function tT(e=!1){let t=[...await Qw(e)];return t.sort((e,t)=>(e.enabled===!1)-+(t.enabled===!1)),t}async function nT(e=``){let t=document.getElementById(`skillList`);if(!t)return;let n=await tT(!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`
|
|
2035
|
+
<div class="skill-list-item ${t===0?`selected`:``} ${a?`skill-list-item-disabled`:``}" data-index="${t}" data-skill-name="${P(e.name)}" title="${nt(o)}">
|
|
2036
|
+
<span class="skill-list-item-index">${t+1}</span>
|
|
2037
|
+
<span class="skill-list-item-icon">🧩</span>
|
|
2038
|
+
<div class="skill-list-item-info">
|
|
2039
|
+
<div class="skill-list-item-name">${P(e.name)}</div>
|
|
2040
|
+
${i?`<div class="skill-list-item-desc" title="${nt(i)}">${P(i)}</div>`:``}
|
|
2041
|
+
</div>
|
|
2042
|
+
<span class="skill-list-item-badge">${n}</span>
|
|
2043
|
+
${a?`<span class="skill-list-item-badge badge-disabled">${r(`skillSelector.disabledBadge`)}</span>`:``}
|
|
2044
|
+
</div>
|
|
2045
|
+
`}).join(``),t.querySelectorAll(`.skill-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.skillName;aT(r,n),(t.ctrlKey||t.metaKey)&&Aw()})}),cT()}function rT(e){e.forEach((e,t)=>{t===C.selectedSkillIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function iT(){let e=document.getElementById(`userInput`);if(!e)return;let t=e.value,n=t.lastIndexOf(`/`);n!==-1&&(e.value=t.substring(0,n)),e.focus(),e.selectionStart=e.selectionEnd=e.value.length,Ue()}function aT(e,t,{clearTrigger:n=!0}={}){let r=t.find(t=>t.name===e);if(!r)return;let a=C.selectedSkills.findIndex(t=>t.name===e);if(a>=0?C.selectedSkills.splice(a,1):C.selectedSkills.push({name:r.name,description:r.description||``,type:r.type||`agent`,stepCount:r.stepCount||0,parameters:r.parameters||{},enabled:r.enabled!==!1}),cT(),sT(),n)iT();else{let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length),Ue()}i.debug(`[SidePanel] skill toggled:`,r.name,`count:`,C.selectedSkills.length)}function oT(){C.selectedSkills=[],C.selectedSkillIndex=-1,sT(),cT(),i.debug(`[SidePanel] skill clearedselect`)}function sT(){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`
|
|
2046
|
+
<span class="ref-chip skill-ref-chip${t?` skill-ref-chip-manual`:``}">
|
|
2047
|
+
<span class="ref-chip-name" title="${nt(i)}">🧩 ${P(n)}</span>
|
|
2048
|
+
<button class="ref-chip-close" data-skill-name="${nt(e.name)}" title="${r(`common.delete`)}">✕</button>
|
|
2049
|
+
</span>
|
|
2050
|
+
`}).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),sT(),cT()})}),e.style.display=`flex`}}function cT(){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 lT(){let e=document.getElementById(`skillIndicatorClose`);e&&e.addEventListener(`click`,oT)}async function uT(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.switchHintSelect`)),C.selectedPromptIndex=-1,C.selectedMcpServiceIndex=-1,await nT()):e===`mcp`?(t&&(t.style.display=`none`),n&&(n.style.display=`none`),i&&(i.style.display=`block`),s&&(s.textContent=r(`promptSelector.switchHintSelect`)),C.selectedPromptIndex=-1,C.selectedSkillIndex=-1,await gT()):(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 dT(){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 fT(){let e=document.getElementById(`promptDropdownTabs`);e&&(dT(),wT(),e.addEventListener(`click`,e=>{let t=e.target.closest(`.prompt-tab`);if(!t)return;let n=t.dataset.tab;n!==C.activeDropdownTab&&uT(n)}))}async function pT(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+=`]
|
|
2051
|
+
`,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(`
|
|
2052
|
+
|
|
2053
|
+
`)}async function mT(){return!C.agentPlatform?.connected||!await new Promise(e=>{chrome.storage.local.get([`mcpEnabled`],t=>e(t.mcpEnabled))})?!1:(await hT()).length>0}async function hT(){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 gT(e=``){let t=document.getElementById(`mcpList`);if(!t)return;let n=await hT(),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`
|
|
2054
|
+
<div class="mcp-list-item ${t===0?`selected`:``} ${n?`mcp-list-item-inactive`:``}" data-index="${t}" data-server-id="${P(e.serverId)}" data-server-name="${P(e.serverName)}" title="${nt(i)}">
|
|
2055
|
+
<span class="mcp-list-item-index">${t+1}</span>
|
|
2056
|
+
<span class="mcp-list-item-icon">🔌</span>
|
|
2057
|
+
<div class="mcp-list-item-info">
|
|
2058
|
+
<div class="mcp-list-item-name">${P(e.serverName)}</div>
|
|
2059
|
+
<div class="mcp-list-item-desc">${P(e.serverId)}</div>
|
|
2060
|
+
</div>
|
|
2061
|
+
${n?`<span class="mcp-list-item-badge mcp-badge-inactive">${r(`skillSelector.mcpInactiveBadge`)}</span>`:``}
|
|
2062
|
+
<span class="mcp-list-item-badge">${r(`promptSelector.toolCount`,{count:e.toolCount})}</span>
|
|
2063
|
+
</div>
|
|
2064
|
+
`}).join(``),t.querySelectorAll(`.mcp-list-item`).forEach(e=>{e.addEventListener(`click`,t=>{let r=e.dataset.serverId,i=e.dataset.serverName;vT(r,i,n),(t.ctrlKey||t.metaKey)&&Aw()})}),ST()}function _T(e){e.forEach((e,t)=>{t===C.selectedMcpServiceIndex?(e.classList.add(`selected`),e.scrollIntoView({block:`nearest`})):e.classList.remove(`selected`)})}function vT(e,t,n,{clearTrigger:r=!0}={}){let a=n?.find(t=>t.serverId===e)?.toolCount||0,o=t||e,s=C.selectedMcpServices.findIndex(e=>e.serverName===o);if(s>=0?C.selectedMcpServices.splice(s,1):C.selectedMcpServices.push({serverId:e,serverName:o,toolCount:a}),ST(),xT(),r)iT();else{let e=document.getElementById(`userInput`);e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length),Ue()}i.debug(`[SidePanel] MCP service toggled:`,o,`count:`,C.selectedMcpServices.length)}function yT(){C.selectedMcpServices=[],C.selectedMcpServiceIndex=-1,xT(),ST(),i.debug(`[SidePanel] cleared MCP serviceselect`)}function bT(e){let t=e||C.selectedMcpServices||[];return t.length===0?``:t.map(e=>r(`skillSelector.selectedMcpContext`,{name:e.serverName})).join(`
|
|
2065
|
+
`)}function xT(){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=>`
|
|
2066
|
+
<span class="ref-chip mcp-ref-chip">
|
|
2067
|
+
<span class="ref-chip-name" title="${nt(e.serverName)}">🔌 ${P(e.serverName)}</span>
|
|
2068
|
+
<button class="ref-chip-close" data-server-name="${nt(e.serverName)}" title="${r(`common.delete`)}">✕</button>
|
|
2069
|
+
</span>
|
|
2070
|
+
`).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),xT(),ST()})}),e.style.display=`flex`}}function ST(){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 CT(){let e=document.getElementById(`mcpIndicatorClose`);e&&e.addEventListener(`click`,yT)}function wT(){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)}var TT=[[`🀄`,`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}" 吗?
|
|
2071
|
+
正在使用该助手的会话将恢复为默认助手。`,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}"?
|
|
2072
|
+
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 ET(){await DT(),await OT(),jT(),NT(),i.debug(`[AgentMgr] Agent managerinitialization complete, activeAgentId:`,C.activeAgentId)}async function DT(){let[e,t]=await Promise.all([mt(),gt()]);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 OT(){let e=document.getElementById(`agentListItems`),t=document.getElementById(`agentDropdownFooter`);if(!e)return;let n=await gt(),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+=`
|
|
2073
|
+
<div class="agent-item ${t?`active`:``} ${e.isBuiltin?``:`is-editable`}" data-agent-id="${$(e.id)}">
|
|
2074
|
+
<span class="agent-item-icon">${hE(e.icon)}</span>
|
|
2075
|
+
<div class="agent-item-info">
|
|
2076
|
+
<span class="agent-item-name">${hE(o)}</span>
|
|
2077
|
+
<span class="agent-item-desc" title="${$(s)}">${hE(s)}</span>
|
|
2078
|
+
</div>
|
|
2079
|
+
<div class="agent-item-actions">
|
|
2080
|
+
${e.isBuiltin?``:`<button class="agent-item-edit" data-action="edit" data-agent-id="${$(e.id)}" title="${$(r(`common.edit`))}">✎</button>`}
|
|
2081
|
+
${e.isBuiltin?``:`<button class="agent-item-delete" data-action="delete" data-agent-id="${$(e.id)}" title="${$(r(`common.delete`))}">✕</button>`}
|
|
2082
|
+
${t?`<span class="agent-item-check">✓</span>`:``}
|
|
2083
|
+
</div>
|
|
2084
|
+
</div>`}e.innerHTML=a,t&&(t.innerHTML=`
|
|
2085
|
+
<div class="agent-item" id="agentAddBtn" style="color:var(--brand-500);">
|
|
2086
|
+
<span class="agent-item-icon" style="color:var(--brand-500);">+</span>
|
|
2087
|
+
<span class="agent-item-name">${r(`agentEditor.createNew`)}</span>
|
|
2088
|
+
</div>`),kT(n,i)}function kT(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 AT(){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 jT(){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`,AT();try{await OT()}catch{}AT()}}),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;KT(t);return}if(r&&r.dataset.action===`delete`){e.stopPropagation(),await fE(r.dataset.agentId);return}if(n.id===`agentAddBtn`){KT(null);return}let i=n.dataset.agentId;i&&(await MT(i),t.style.display=`none`)}))}async function MT(e){let t=e?await ft(e):null;if(C.activeAgentId=e,C.activeAgentToolIds=t?t.toolIds:null,C.activeAgentMcpExcludedServerIds=t?t.mcpExcludedServerIds??null:null,await vt(e),ni().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 OT();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=ta(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=ea(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=ea(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`)&&(Bi(),Ji(),Yi()),Qi();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 NT(){let e=document.getElementById(`agentEditModal`);if(!e)return;e.querySelector(`#agentModalCloseBtn`)?.addEventListener(`click`,qT),e.querySelector(`#agentSaveBtn`)?.addEventListener(`click`,uE),e.querySelector(`#agentDeleteBtn`)?.addEventListener(`click`,dE),e.querySelector(`#agentTemplateSelect`)?.addEventListener(`change`,YT),RT();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`?zT():n===`deselectAll`?BT():n===`toggleSelectedOnly`&&(XT.selectedOnly=!XT.selectedOnly,QT())});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(()=>{XT.searchText=n.value,QT()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),n.value=``,r(),XT.searchText=``,QT(),n.focus()}),r()}let r=document.getElementById(`agentSkillActions`);r&&r.addEventListener(`click`,e=>{let t=e.target.closest(`button`);if(!t)return;let n=t.dataset.action;n===`selectAllSkills`?VT():n===`deselectAllSkills`?HT():n===`toggleSelectedOnlySkills`&&(nE.selectedOnly=!nE.selectedOnly,iE())});let i=document.getElementById(`agentSkillSearchInput`);if(i){let e=null,t=document.getElementById(`agentSkillSearchClear`),n=()=>{t&&(t.style.display=i.value?`block`:`none`)};i.addEventListener(`input`,()=>{n(),clearTimeout(e),e=setTimeout(()=>{nE.searchText=i.value,iE()},150)}),t&&t.addEventListener(`click`,()=>{clearTimeout(e),i.value=``,n(),nE.searchText=``,iE(),i.focus()}),n()}let a=document.getElementById(`agentToolList`);a&&(a.addEventListener(`click`,e=>{let t=e.target.closest(`.agent-mcp-expand-btn`);if(t){e.preventDefault(),$T(t.dataset.serverId,t);return}let n=e.target.closest(`.agent-mcp-service-item`);if(n&&!e.target.closest(`input[type="checkbox"]`)){e.preventDefault(),$T(n.dataset.mcpServerId,n.querySelector(`.agent-mcp-expand-btn`));return}let r=e.target.closest(`.agent-tool-category-clickable`);r&&UT(r.dataset.category)}),a.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=XT,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?QT():WT()}));let o=document.getElementById(`agentSkillList`);o&&o.addEventListener(`change`,e=>{if(!e.target.matches(`input[type="checkbox"]`))return;let t=nE;t.inheritMode=!1,e.target.checked?t.selectedSet.add(e.target.value):t.selectedSet.delete(e.target.value),t.selectedOnly&&!e.target.checked?iE():GT()}),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 PT=[[`smileys`,`emojiCatSmileys`],[`people`,`emojiCatPeople`],[`animals`,`emojiCatAnimals`],[`food`,`emojiCatFood`],[`travel`,`emojiCatTravel`],[`activity`,`emojiCatActivity`],[`objects`,`emojiCatObjects`],[`symbols`,`emojiCatSymbols`],[`flags`,`emojiCatFlags`]];function FT(e,t){return!!(e[1].includes(t)||e[3]&&e[3].includes(t))}function IT(e){let t=``;for(let[e,n]of PT){let i=TT.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 LT(e,t){let n=TT.filter(e=>FT(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 RT(){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?LT(a,e):IT(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 zT(){let e=XT;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.add(t.id)),e.mcpServices.forEach(t=>e.excludedSet.delete(t.serverId)),QT()}function BT(){let e=XT;e.inheritMode=!1,e.allTools.forEach(t=>e.selectedSet.delete(t.id)),e.mcpServices.forEach(t=>e.excludedSet.add(t.serverId)),QT()}function VT(){let e=nE;e.inheritMode=!1,e.skills.forEach(t=>e.selectedSet.add(t.name)),iE()}function HT(){let e=nE;e.inheritMode=!1,e.selectedSet.clear(),iE()}function UT(e){let t=XT;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?QT():WT()}function WT(){let e=XT,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 GT(){let e=document.getElementById(`agentSkillCount`);if(!e)return;let t=nE,n=t.skills.length;e.textContent=r(`agentConfig.selectedTotalCount`,{selected:t.inheritMode?n:t.selectedSet.size,total:n})}async function KT(e){let t=document.getElementById(`agentEditModal`);if(!t)return;await oE(),sE(-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`);if(e){let n=await ft(e);if(!n||n.isBuiltin)return;a.textContent=r(`agentMgr.editAgent`),t.querySelector(`#agentEditId`).value=n.id,t.querySelector(`#agentEditName`).value=n.name,t.querySelector(`#agentEditIcon`).value=n.icon||`🤖`;let o=t.querySelector(`#agentEditIconBtn`);o&&(o.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||``,sE(lE(n.temperature,n.topP)),i.style.display=`block`,ZT(n.toolIds,n.mcpExcludedServerIds??[]),rE(n.skillIds)}else a.textContent=r(`agentEditor.createNew`),i.style.display=`none`,ZT(null,[]),rE(null);JT(),t.style.display=`flex`;let o=t.querySelector(`#agentEditModel`);if(o){let e=o.value,t=o.cloneNode(!0);o.parentNode.replaceChild(t,o),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 qT(){let e=document.getElementById(`agentEditModal`);e&&(e.style.display=`none`)}function JT(){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 YT(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||``,sE(lE(n.temperature,n.topP)),ZT(n.toolIds,[]),rE(n.skillIds||null),F(r(`agentMgr.templateLoaded`,{name:n.name}),`info`,2e3)}var XT={allTools:[],mcpServices:[],selectedSet:new Set,excludedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function ZT(e,t){if(!document.getElementById(`agentToolList`))return;let n=[];try{n=(await chrome.storage.local.get([`mcpTools`])).mcpTools||[]}catch{}let{mcpEnabled:r,skillsEnabled:i,ragTools:a}=await chrome.storage.local.get([`mcpEnabled`,`skillsEnabled`,`ragTools`]),o=C.agentPlatform?.connected===!0,s=[...f,...a||[]];o||(s=s.filter(e=>!e.id.startsWith(`agent_`)&&!e.id.startsWith(`knowledge_`))),i===!1&&(s=s.filter(e=>e.id!==`agent_skill`));let c=[];if(r===!0&&o){let e=new Map;for(let t of n){let n=t.serverId||`unknown`;e.has(n)||e.set(n,{serverId:n,serverName:t.serverName||n,tools:[]}),e.get(n).tools.push(t)}c=Array.from(e.values())}let l=new Set(Array.isArray(t)?t:[]),u=XT;u.allTools=s,u.mcpServices=c,u.selectedSet=new Set(e||[]),u.excludedSet=l,u.searchText=``,u.selectedOnly=!1,u.inheritMode=!e;let d=document.getElementById(`agentToolSearchInput`);d&&(d.value=``);let p=document.getElementById(`agentToolSearchClear`);p&&(p.style.display=`none`),QT()}function QT(){let e=document.getElementById(`agentToolList`);if(!e)return;let t=XT,n=aa({tools:t.allTools,services:t.mcpServices,selectedSet:t.selectedSet,excludedSet:t.excludedSet,query:t.searchText,selectedOnly:t.selectedOnly,getDesc:xi}),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=xi(r),a=i.length>40?i.substring(0,40)+`...`:i;o+=`
|
|
2089
|
+
<label class="agent-tool-item" data-category="${$(e)}">
|
|
2090
|
+
<input type="checkbox" value="${$(r.id)}" ${n} data-tool-id="${$(r.id)}">
|
|
2091
|
+
<span class="agent-tool-name" title="${$(r.name)}">${hE(r.name)}</span>
|
|
2092
|
+
<span class="agent-tool-desc" title="${$(i)}">${hE(a)}</span>
|
|
2093
|
+
</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=Si(e);return`<div class="agent-mcp-tool-row" title="${$(n?`${t}:${n}`:t)}"><div class="agent-mcp-tool-name">${hE(t)}</div>`+(n?`<div class="agent-mcp-tool-desc">${hE(n)}</div>`:``)+`</div>`}).join(``);o+=`
|
|
2094
|
+
<label class="agent-tool-item agent-mcp-service-item" data-category="mcp" data-mcp-server-id="${$(e.serverId)}">
|
|
2095
|
+
<input type="checkbox" ${n} data-mcp-server-id="${$(e.serverId)}">
|
|
2096
|
+
<span class="agent-tool-name" title="${$(e.serverName)}">${hE(e.serverName)}</span>
|
|
2097
|
+
<span class="agent-tool-desc" title="${$(a)}">${hE(i)}</span>
|
|
2098
|
+
<span class="agent-mcp-service-id" title="ID: ${$(e.serverId)}">ID: ${hE(e.serverId)}</span>
|
|
2099
|
+
<button type="button" class="agent-mcp-expand-btn" data-server-id="${$(e.serverId)}" title="${$(r(`toolPanel.mcpServiceExpand`))}">▶</button>
|
|
2100
|
+
</label>
|
|
2101
|
+
<div class="agent-mcp-tool-list collapsed" data-server-id="${$(e.serverId)}">${s}</div>`}}o||=`<div class="agent-tool-empty">${hE(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})}WT()}function $T(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 eE(){let e=XT,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 tE(){let e=XT;if(e.mcpServices.length!==0)return e.mcpServices.filter(t=>e.excludedSet.has(t.serverId)).map(e=>e.serverId)}var nE={skills:[],selectedSet:new Set,searchText:``,selectedOnly:!1,inheritMode:!1};async function rE(e){if(!document.getElementById(`agentSkillList`))return;let t=[];try{t=await eT()}catch{}let n=nE;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`),iE()}function iE(){let e=document.getElementById(`agentSkillList`);if(!e)return;let t=nE;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=aa({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">${hE(r(`toolPanel.noMatch`))}</div>`:e.innerHTML=n.map(e=>{let n=t.selectedSet.has(e.name)?`checked`:``,r=e.description||``;return`
|
|
2102
|
+
<label class="agent-tool-item">
|
|
2103
|
+
<input type="checkbox" value="${$(e.name)}" ${n}>
|
|
2104
|
+
<span class="agent-tool-name" title="${$(e.name)}">${hE(e.name)}</span>
|
|
2105
|
+
<span class="agent-tool-desc" title="${$(r)}">${hE(r.substring(0,40))}${r.length>40?`...`:``}</span>
|
|
2106
|
+
</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})),GT()}function aE(){let e=nE,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 oE(){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 sE(e){let t=document.getElementById(`agentEditTempPreset`);if(t){for(;t.options.length>1;)t.remove(1);Qt.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 cE(){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>=Qt.length)return{temperature:null,topP:null};let n=Qt[t];return{temperature:n.temp,topP:n.topP}}function lE(e,t){if(e==null)return-1;for(let n=0;n<Qt.length;n++){let r=Qt[n];if(Math.abs(r.temp-e)<.001&&Math.abs(r.topP-(t||1))<.001)return n}return-1}async function uE(){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=eE(),u=tE(),d=aE(),f=e.querySelector(`#agentEditModel`).value.trim()||null,{temperature:p,topP:m}=cE();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 pt(t,h),t===C.activeAgentId&&u!==void 0&&(C.activeAgentMcpExcludedServerIds=u),F(r(`agentMgr.agentUpdated`),`success`)):F(r(`agentMgr.agentCreated`,{name:(await ht(h)).name}),`success`),await DT(),await OT(),qT(),Qi()}catch(e){i.error(`[AgentMgr] save Agent failed:`,e),F(r(`agentMgr.saveFailed`,{message:e.message}),`error`)}}async function dE(){let e=document.getElementById(`agentEditModal`);if(!e)return;let t=e.querySelector(`#agentEditId`)?.value;if(!t)return;let n=await ft(t);if(await gE(r(`agentMgr.confirmDeleteAgentMessage`,{name:n?n.name:``}),r(`agentMgr.deleteAgentTitle`)))try{await _t(t),F(r(`agentMgr.agentDeleted`),`success`),await DT(),await OT(),qT()}catch(e){i.error(`[AgentMgr] delete Agent failed:`,e),F(r(`agentMgr.deleteFailed`,{message:e.message}),`error`)}}async function fE(e){if(!e)return!1;let t=await ft(e);if(!t||t.isBuiltin)return F(r(`agentMgr.cannotDeleteDefault`),`warning`),!1;if(!await gE(r(`agentMgr.confirmDeleteAgentMessage`,{name:t.name}),r(`agentMgr.deleteAgentTitle`)))return!1;try{return await _t(e),F(r(`agentMgr.agentDeleted`),`success`),await DT(),await OT(),!0}catch(e){return i.error(`[AgentMgr] delete Agent failed:`,e),F(r(`agentMgr.deleteFailed`,{message:e.message}),`error`),!1}}async function pE(e=C.activeAgentId){return e?await ft(e):null}function mE(e){return e?e.toolIds:null}function hE(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 gE(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 _E=300,vE=``,yE=0,bE=null;async function xE(){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 SE(){let e=document.getElementById(`userInput`)?.value||``;return{usage:on({model:C.currentModel,customModelMap:C.customModelMap,systemPromptText:vE,toolCount:(C.useTools?C.enabledTools.length:0)+yE,history:C.messageHistory,inputText:e,maxMemoryMessages:C.chatConfig?.maxMemoryMessages??null,compaction:C.activeCompaction,isolateChat:C.isolateChat}),inputText:e}}function CE(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 wE(){try{let{usage:e}=SE();return CE(e),IE(),e}catch(e){return i.warn(`[ContextIndicator] update failed:`,e?.message),null}}function TE(){clearTimeout(bE),bE=setTimeout(()=>wE(),_E)}async function EE(e=null){let t=e===null?C.activeSessionId:e;try{vE=await Ke(await pE(),{sessionId:t})}catch(e){i.warn(`[ContextIndicator] refresh system prompt failed:`,e?.message)}try{yE=await xE()}catch{yE=0}wE()}function DE(){let e=document.getElementById(`contextUsageIndicator`);e&&(e.addEventListener(`click`,()=>BE()),document.getElementById(`userInput`)?.addEventListener(`input`,TE),document.addEventListener(`generating-state-changed`,()=>{EE()}),document.addEventListener(`agent-model-changed`,()=>{EE()}),document.addEventListener(`session-switched`,()=>{EE()}),document.addEventListener(`session-workdir-changed`,()=>{EE()}),chrome.storage.onChanged.addListener((e,t)=>{t===`local`&&((e.chatMaxMemoryMessages||e.isolateChat)&&TE(),(e.modelName||e.customModels)&&TE(),(e.isolateChat||e.mcpTools||e.mcpEnabled||e.enabledTools||e.enableTools)&&EE())}),EE())}function OE({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=`
|
|
2107
|
+
<div class="modal-container">
|
|
2108
|
+
<div class="modal-title"></div>
|
|
2109
|
+
<div class="modal-message"></div>
|
|
2110
|
+
<div class="modal-actions">
|
|
2111
|
+
<button class="modal-btn cancel">${r(`common.cancel`)}</button>
|
|
2112
|
+
</div>
|
|
2113
|
+
</div>
|
|
2114
|
+
`,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 kE(){let e=document.createElement(`div`);return e.className=`modal-overlay show context-usage-compacting-overlay`,e.style.zIndex=`10200`,e.innerHTML=`
|
|
2115
|
+
<div class="modal-container context-usage-compacting-modal">
|
|
2116
|
+
<div class="context-usage-compacting-spinner"></div>
|
|
2117
|
+
<div class="modal-title"></div>
|
|
2118
|
+
<div class="modal-message"></div>
|
|
2119
|
+
</div>
|
|
2120
|
+
`,e.querySelector(`.modal-title`).textContent=r(`contextUsage.compactingTitle`),e.querySelector(`.modal-message`).textContent=r(`contextUsage.compactingHint`),document.body.appendChild(e),{close:()=>e.remove()}}function AE(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 jE({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}=sn(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 OE({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:kE();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=AE(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 ni(),LE(),wE(),Yc(),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=AE(t?.message);F(`${r(`contextUsage.compactErrFailed`)}${e?`(${e})`:``}`,`error`)}return{success:!1,reason:`exception`}}finally{u?.close()}}async function ME(){await jE({silent:!1})}function NE(){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 PE(e=!1){if(C.activeCompaction){if(NE()){F(r(`contextUsage.undoExpiredToast`),`warning`);return}!e&&!await OE({title:r(`contextUsage.undoTitle`),message:r(`contextUsage.undoMessage`),okText:r(`contextUsage.undoOk`)})||(C.activeCompaction=null,await ni(),FE(),wE(),F(r(`contextUsage.undoDone`),`success`))}}function FE(){document.querySelectorAll(`.compaction-divider`).forEach(e=>e.remove())}function IE(){let e=NE();document.querySelectorAll(`.compaction-divider [data-action="undo"]`).forEach(t=>{t.style.display=e?`none`:``})}function LE(){FE();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=!NE();i.innerHTML=`
|
|
2121
|
+
<span class="compaction-divider-text">${r(`contextUsage.dividerText`,{count:e.compressedCount})}</span>
|
|
2122
|
+
<button class="compaction-divider-btn" data-action="view">${r(`contextUsage.dividerView`)}</button>
|
|
2123
|
+
${a?`<button class="compaction-divider-btn" data-action="undo">${r(`contextUsage.dividerUndo`)}</button>`:``}
|
|
2124
|
+
`,i.querySelector(`[data-action="view"]`).addEventListener(`click`,()=>VE(e)),i.querySelector(`[data-action="undo"]`)?.addEventListener(`click`,()=>PE()),n.after(i)}var RE=null;function zE(){document.querySelectorAll(`.context-usage-popup`).forEach(e=>e.remove());let e=document.getElementById(`contextUsageIndicator`);e&&(e._ctxPopupOpen=!1),RE&&=(document.removeEventListener(`click`,RE),null)}function BE(){let e=document.getElementById(`contextUsageIndicator`);if(!e)return;if(e._ctxPopupOpen){zE();return}zE(),e._ctxPopupOpen=!0;let{usage:t}=SE(),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?`
|
|
2125
|
+
<div class="context-usage-compaction">
|
|
2126
|
+
<div class="context-usage-dim">${r(`contextUsage.compactionActive`,{count:o.compressedCount,tokens:I(o.summaryTokens)})}</div>
|
|
2127
|
+
${NE()?`<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>`}
|
|
2128
|
+
</div>`:n.compactionInvalid?`
|
|
2129
|
+
<div class="context-usage-compaction">
|
|
2130
|
+
<div class="context-usage-warn">${r(`contextUsage.compactionInvalidHint`)}</div>
|
|
2131
|
+
<button class="context-usage-btn danger-ghost" data-action="remove-invalid">${r(`contextUsage.removeInvalid`)}</button>
|
|
2132
|
+
</div>`:`
|
|
2133
|
+
<div class="context-usage-compaction">
|
|
2134
|
+
<button class="context-usage-btn primary" data-action="compact">${r(`contextUsage.btnCompact`)}</button>
|
|
2135
|
+
</div>`;let c=r(`contextUsage.historyMeta`,{selected:n.selectedCount,total:n.totalCount}),l=n.trimmedCount>0?`<div class="context-usage-dim">${r(`contextUsage.historyTrimmed`,{count:n.trimmedCount})}</div>`:``,u=document.createElement(`div`);u.className=`context-usage-popup`,u.dataset.level=t.level,u.innerHTML=`
|
|
2136
|
+
<div class="context-usage-popup-header">
|
|
2137
|
+
<span class="context-usage-popup-title">${r(`contextUsage.popupTitle`)}</span>
|
|
2138
|
+
<button class="context-usage-popup-close" aria-label="${r(`common.close`)}">×</button>
|
|
2139
|
+
</div>
|
|
2140
|
+
<div class="context-usage-popup-body">
|
|
2141
|
+
<div class="context-usage-total">
|
|
2142
|
+
<span class="context-usage-total-percent">${i}%</span>
|
|
2143
|
+
<span class="context-usage-total-detail">${Me(t.usedTokens)} / ${Me(t.contextWindow)}</span>
|
|
2144
|
+
</div>
|
|
2145
|
+
<div class="context-usage-bar"><div class="context-usage-bar-fill" style="width:${Math.min(i,100)}%"></div></div>
|
|
2146
|
+
<div class="context-usage-section">
|
|
2147
|
+
<div class="context-usage-row"><span>${r(`contextUsage.rowSystem`)}</span><span>${Me(n.system)}</span></div>
|
|
2148
|
+
<div class="context-usage-row"><span>${r(`contextUsage.rowTools`)}</span><span>${Me(n.tools)}</span></div>
|
|
2149
|
+
<div class="context-usage-row"><span>${r(`contextUsage.rowHistory`)}</span><span>${Me(n.history)}</span></div>
|
|
2150
|
+
<div class="context-usage-dim">${c}</div>
|
|
2151
|
+
${l}
|
|
2152
|
+
<div class="context-usage-row"><span>${r(`contextUsage.rowInput`)}</span><span>${Me(n.input)}</span></div>
|
|
2153
|
+
</div>
|
|
2154
|
+
<div class="context-usage-section context-usage-dim">${r(`contextUsage.refInfo`,{output:Me(n.outputReserve),safety:Me(n.safetyMargin)})}</div>
|
|
2155
|
+
<div class="context-usage-section">
|
|
2156
|
+
<div class="context-usage-row"><span>${r(`contextUsage.memoryLabel`)}</span><span>${a}</span></div>
|
|
2157
|
+
</div>
|
|
2158
|
+
${s}
|
|
2159
|
+
</div>
|
|
2160
|
+
`,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`,()=>zE()),u.querySelector(`[data-action="compact"]`)?.addEventListener(`click`,()=>{zE(),ME()}),u.querySelector(`[data-action="undo"]`)?.addEventListener(`click`,()=>{zE(),PE(!0)}),u.querySelector(`[data-action="remove-invalid"]`)?.addEventListener(`click`,async()=>{zE(),C.activeCompaction=null,await ni(),FE(),wE()}),RE=e=>{e.target.closest(`.context-usage-popup, #contextUsageIndicator`)||zE()},setTimeout(()=>document.addEventListener(`click`,RE),0)}function VE(e=C.activeCompaction){if(!e?.summary)return;let t=document.createElement(`div`);t.className=`modal-overlay show`,t.style.zIndex=`10200`,t.innerHTML=`
|
|
2161
|
+
<div class="modal-container context-usage-summary-modal">
|
|
2162
|
+
<button type="button" class="context-usage-summary-close" title="${r(`common.close`)}">×</button>
|
|
2163
|
+
<div class="modal-title">${r(`contextUsage.summaryTitle`,{count:e.compressedCount})}
|
|
2164
|
+
</div>
|
|
2165
|
+
<div class="context-usage-summary-tabs">
|
|
2166
|
+
<button class="context-usage-summary-tab active" data-mode="preview">${r(`contextUsage.summaryTabPreview`)}</button>
|
|
2167
|
+
<button class="context-usage-summary-tab" data-mode="source">${r(`contextUsage.summaryTabSource`)}</button>
|
|
2168
|
+
</div>
|
|
2169
|
+
<div class="context-usage-summary-body"></div>
|
|
2170
|
+
</div>
|
|
2171
|
+
`,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=et(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{SC as $,Ys as $n,mb as $t,Lw as A,hd as An,pr as Ar,yx as At,Cw as B,Sd as Bn,cn as Br,Gb as Bt,_T as C,ip as Cn,hr as Cr,$S as Ct,Aw as D,Df as Dn,ur as Dr,_S as Dt,Ow as E,rp as En,fr as Er,uC as Et,iw as F,Nd as Fn,Tr as Fr,ix as Ft,ww as G,jl as Gn,Ob as Gt,PC as H,qu as Hn,nn as Hr,xb as Ht,mw as I,bd as In,cr as Ir,ex as It,AC as J,el as Jn,kb as Jt,nw as K,Dl as Kn,gb as Kt,cw as L,md as Ln,wn as Lr,$b as Lt,kw as M,xd as Mn,Er as Mr,vx as Mt,Mw as N,Yd as Nn,yr as Nr,tx as Nt,Jw as O,td as On,or as Or,nS as Ot,Fw as P,Fd as Pn,br as Pr,Zb as Pt,_w as Q,ac as Qn,qb as Qt,dw as R,pd as Rn,hn as Rr,db as Rt,uT as S,Lp as Sn,L as Sr,ZS as St,Tw as T,Qf as Tn,lr as Tr,YS as Tt,EC as U,au as Un,Qt as Ur,Db as Ut,yC as V,Hu as Vn,an as Vr,Sb as Vt,rw as W,Bu as Wn,fb as Wt,TC as X,Hc as Xn,Fb as Xt,vw as Y,Xc as Yn,Vb as Yt,hw as Z,Tc as Zn,Rb as Zt,sT as _,jm as _n,Qi as _r,gC as _t,ET as a,Av as an,zi as ar,tw as at,mT as b,km as bn,Yr as br,lC as bt,oT as c,nh as cn,Ri as cr,dC as ct,CT as d,th as dn,Xi as dr,_C as dt,vb as en,xo as er,MC as et,lT as f,eh as fn,Zi as fr,yS as ft,xT as g,zm as gn,Yi as gr,US as gt,cT as h,Rm as hn,$i as hr,HS as ht,wE as i,Xh as in,ea as ir,FC as it,Rw as j,id as jn,mr as jr,Lx as jt,Iw as k,ad as kn,gr as kr,wx as kt,hT as l,rh as ln,na as lr,mC as lt,ST as m,Zm as mn,Ji as mr,hC as mt,DE as n,hy as nn,po as nr,lw as nt,KT as o,jv as on,ta as or,nC as ot,fT as p,Qm as pn,qi as pr,pC as pt,IC as q,Ol as qn,Lb as qt,jE as r,kh as rn,qa as rr,wC as rt,yT as s,oh as sn,Ki as sr,oC as st,SE as t,Mb as tn,mo as tr,ew as tt,tT as u,ah as un,Bi as ur,iC as ut,vT as v,Em as vn,$r as vr,aC as vt,rT as w,np as wn,dr as wr,GS as wt,$w as x,zp as xn,oi as xr,OS as xt,aT as y,Om as yn,Zr as yr,cC as yt,pw as z,Xd as zn,mn as zr,Bb as zt};
|